context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Scheduler; using Microsoft.WindowsAzure.Scheduler.Models; namespace Microsoft.WindowsAzure { public static partial class JobOperationsExtensions { /// <summary> /// Creates a new Job, allowing the service to generate a job id. Use /// CreateOrUpdate if a user-chosen job id is required. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters specifying the job definition for a Create Job /// operation. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobCreateResponse Create(this IJobOperations operations, JobCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).CreateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Job, allowing the service to generate a job id. Use /// CreateOrUpdate if a user-chosen job id is required. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters specifying the job definition for a Create Job /// operation. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobCreateResponse> CreateAsync(this IJobOperations operations, JobCreateParameters parameters) { return operations.CreateAsync(parameters, CancellationToken.None); } /// <summary> /// Creates a new Job with a user-provided job id, or updates an /// existing job, replacing its definition with that specified. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to create or update. /// </param> /// <param name='parameters'> /// Required. Parameters specifying the job definition for a /// CreateOrUpdate Job operation. /// </param> /// <returns> /// The CreateOrUpdate Job operation response. /// </returns> public static JobCreateOrUpdateResponse CreateOrUpdate(this IJobOperations operations, string jobId, JobCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).CreateOrUpdateAsync(jobId, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Job with a user-provided job id, or updates an /// existing job, replacing its definition with that specified. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to create or update. /// </param> /// <param name='parameters'> /// Required. Parameters specifying the job definition for a /// CreateOrUpdate Job operation. /// </param> /// <returns> /// The CreateOrUpdate Job operation response. /// </returns> public static Task<JobCreateOrUpdateResponse> CreateOrUpdateAsync(this IJobOperations operations, string jobId, JobCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(jobId, parameters, CancellationToken.None); } /// <summary> /// Deletes a job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IJobOperations operations, string jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).DeleteAsync(jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IJobOperations operations, string jobId) { return operations.DeleteAsync(jobId, CancellationToken.None); } /// <summary> /// Get the definition and status of a job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to get. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static JobGetResponse Get(this IJobOperations operations, string jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetAsync(jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the definition and status of a job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to get. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static Task<JobGetResponse> GetAsync(this IJobOperations operations, string jobId) { return operations.GetAsync(jobId, CancellationToken.None); } /// <summary> /// Get the execution history of a Job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to get the history of. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Get Job History operation. /// </param> /// <returns> /// The Get Job History operation response. /// </returns> public static JobGetHistoryResponse GetHistory(this IJobOperations operations, string jobId, JobGetHistoryParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetHistoryAsync(jobId, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the execution history of a Job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to get the history of. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Get Job History operation. /// </param> /// <returns> /// The Get Job History operation response. /// </returns> public static Task<JobGetHistoryResponse> GetHistoryAsync(this IJobOperations operations, string jobId, JobGetHistoryParameters parameters) { return operations.GetHistoryAsync(jobId, parameters, CancellationToken.None); } /// <summary> /// Get the execution history of a Job with a filter on the job Status. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to get the history of. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Get Job History With Filter /// operation. /// </param> /// <returns> /// The Get Job History operation response. /// </returns> public static JobGetHistoryResponse GetHistoryWithFilter(this IJobOperations operations, string jobId, JobGetHistoryWithFilterParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetHistoryWithFilterAsync(jobId, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the execution history of a Job with a filter on the job Status. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to get the history of. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Get Job History With Filter /// operation. /// </param> /// <returns> /// The Get Job History operation response. /// </returns> public static Task<JobGetHistoryResponse> GetHistoryWithFilterAsync(this IJobOperations operations, string jobId, JobGetHistoryWithFilterParameters parameters) { return operations.GetHistoryWithFilterAsync(jobId, parameters, CancellationToken.None); } /// <summary> /// Get the list of all jobs in a job collection. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the List Jobs operation. /// </param> /// <returns> /// The List Jobs operation response. /// </returns> public static JobListResponse List(this IJobOperations operations, JobListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all jobs in a job collection. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the List Jobs operation. /// </param> /// <returns> /// The List Jobs operation response. /// </returns> public static Task<JobListResponse> ListAsync(this IJobOperations operations, JobListParameters parameters) { return operations.ListAsync(parameters, CancellationToken.None); } /// <summary> /// Get the list of jobs in a job collection matching a filter on job /// state. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the List Jobs with filter /// operation. /// </param> /// <returns> /// The List Jobs operation response. /// </returns> public static JobListResponse ListWithFilter(this IJobOperations operations, JobListWithFilterParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListWithFilterAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of jobs in a job collection matching a filter on job /// state. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the List Jobs with filter /// operation. /// </param> /// <returns> /// The List Jobs operation response. /// </returns> public static Task<JobListResponse> ListWithFilterAsync(this IJobOperations operations, JobListWithFilterParameters parameters) { return operations.ListWithFilterAsync(parameters, CancellationToken.None); } /// <summary> /// Update the state of all jobs in a job collections. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Jobs State operation. /// </param> /// <returns> /// The Update Jobs State operation response. /// </returns> public static JobCollectionJobsUpdateStateResponse UpdateJobCollectionState(this IJobOperations operations, JobCollectionJobsUpdateStateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).UpdateJobCollectionStateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update the state of all jobs in a job collections. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Jobs State operation. /// </param> /// <returns> /// The Update Jobs State operation response. /// </returns> public static Task<JobCollectionJobsUpdateStateResponse> UpdateJobCollectionStateAsync(this IJobOperations operations, JobCollectionJobsUpdateStateParameters parameters) { return operations.UpdateJobCollectionStateAsync(parameters, CancellationToken.None); } /// <summary> /// Update the state of a job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to update. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Job State operation. /// </param> /// <returns> /// The Update Job State operation response. /// </returns> public static JobUpdateStateResponse UpdateState(this IJobOperations operations, string jobId, JobUpdateStateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).UpdateStateAsync(jobId, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update the state of a job. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.WindowsAzure.Scheduler.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Id of the job to update. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Job State operation. /// </param> /// <returns> /// The Update Job State operation response. /// </returns> public static Task<JobUpdateStateResponse> UpdateStateAsync(this IJobOperations operations, string jobId, JobUpdateStateParameters parameters) { return operations.UpdateStateAsync(jobId, parameters, CancellationToken.None); } } }
//----------------------------------------------------------------------------- // // <copyright file="RightsManagementFailureCode.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Error Code used by Rights Management RightsManagement exceptions // // History: // 09/27/2005: IgorBel : Initial Implementation // //----------------------------------------------------------------------------- using System; namespace System.Security.RightsManagement { /// <summary> /// This error code is used to communicate reasons for failure from the UseLicense.Bind call /// </summary> public enum RightsManagementFailureCode : int { //--------------------------------- // Success ////////////// //--------------------------------- /// <summary> /// Success /// </summary> Success = 0, //--------------------------------- // licenses ////////////// //--------------------------------- /// <summary> /// InvalidLicense /// </summary> InvalidLicense = unchecked((int)0x8004CF00), /// <summary> /// InfoNotInLicense /// </summary> InfoNotInLicense = unchecked((int)0x8004CF01), /// <summary> /// InvalidLicenseSignature /// </summary> InvalidLicenseSignature = unchecked((int)0x8004CF02), /// <summary> /// EncryptionNotPermitted /// </summary> EncryptionNotPermitted = unchecked((int)0x8004CF04), /// <summary> /// RightNotGranted /// </summary> RightNotGranted = unchecked((int)0x8004CF05), /// <summary> /// InvalidVersion /// </summary> InvalidVersion = unchecked((int)0x8004CF06), /// <summary> /// InvalidEncodingType /// </summary> InvalidEncodingType = unchecked((int)0x8004CF07), /// <summary> /// InvalidNumericalValue /// </summary> InvalidNumericalValue = unchecked((int)0x8004CF08), /// <summary> /// InvalidAlgorithmType /// </summary> InvalidAlgorithmType = unchecked((int)0x8004CF09), //--------------------------------- // environments ///////// //--------------------------------- /// <summary> /// EnvironmentNotLoaded /// </summary> EnvironmentNotLoaded = unchecked((int)0x8004CF0A), /// <summary> /// EnvironmentCannotLoad /// </summary> EnvironmentCannotLoad = unchecked((int)0x8004CF0B), /// <summary> /// TooManyLoadedEnvironments /// </summary> TooManyLoadedEnvironments = unchecked((int)0x8004CF0C), /// <summary> /// IncompatibleObjects /// </summary> IncompatibleObjects = unchecked((int)0x8004CF0E), //--------------------------------- // libraries ////////////// //--------------------------------- /// <summary> /// LibraryFail /// </summary> LibraryFail = unchecked((int)0x8004CF0F), //--------------------------------- // miscellany //////////// //--------------------------------- /// <summary> /// EnablingPrincipalFailure /// </summary> EnablingPrincipalFailure = unchecked((int)0x8004CF10), /// <summary> /// InfoNotPresent /// </summary> InfoNotPresent = unchecked((int)0x8004CF11), /// <summary> /// BadGetInfoQuery /// </summary> BadGetInfoQuery = unchecked((int)0x8004CF12), /// <summary> /// KeyTypeUnsupported /// </summary> KeyTypeUnsupported = unchecked((int)0x8004CF13), /// <summary> /// CryptoOperationUnsupported /// </summary> CryptoOperationUnsupported = unchecked((int)0x8004CF14), /// <summary> /// ClockRollbackDetected /// </summary> ClockRollbackDetected = unchecked((int)0x8004CF15), /// <summary> /// QueryReportsNoResults /// </summary> QueryReportsNoResults = unchecked((int)0x8004CF16), /// <summary> /// UnexpectedException /// </summary> UnexpectedException = unchecked((int)0x8004CF17), //--------------------------------- // binding errors ///////// //--------------------------------- /// <summary> /// BindValidityTimeViolated /// </summary> BindValidityTimeViolated = unchecked((int)0x8004CF18), /// <summary> /// BrokenCertChain /// </summary> BrokenCertChain = unchecked((int)0x8004CF19), /// <summary> /// BindPolicyViolation /// </summary> BindPolicyViolation = unchecked((int)0x8004CF1B), /// <summary> /// ManifestPolicyViolation /// </summary> ManifestPolicyViolation = unchecked((int)0x8004930C), /// <summary> /// BindRevokedLicense /// </summary> BindRevokedLicense = unchecked((int)0x8004CF1C), /// <summary> /// BindRevokedIssuer /// </summary> BindRevokedIssuer = unchecked((int)0x8004CF1D), /// <summary> /// BindRevokedPrincipal /// </summary> BindRevokedPrincipal = unchecked((int)0x8004CF1E), /// <summary> /// BindRevokedResource /// </summary> BindRevokedResource = unchecked((int)0x8004CF1F), /// <summary> /// BindRevokedModule /// </summary> BindRevokedModule = unchecked((int)0x8004CF20), /// <summary> /// BindContentNotInEndUseLicense /// </summary> BindContentNotInEndUseLicense = unchecked((int)0x8004CF21), /// <summary> /// BindAccessPrincipalNotEnabling /// </summary> BindAccessPrincipalNotEnabling = unchecked((int)0x8004CF22), /// <summary> /// BindAccessUnsatisfied /// </summary> BindAccessUnsatisfied = unchecked((int)0x8004CF23), /// <summary> /// BindIndicatedPrincipalMissing /// </summary> BindIndicatedPrincipalMissing = unchecked((int)0x8004CF24), /// <summary> /// BindMachineNotFoundInGroupIdentity /// </summary> BindMachineNotFoundInGroupIdentity = unchecked((int)0x8004CF25), /// <summary> /// LibraryUnsupportedPlugIn /// </summary> LibraryUnsupportedPlugIn = unchecked((int)0x8004CF26), /// <summary> /// BindRevocationListStale /// </summary> BindRevocationListStale = unchecked((int)0x8004CF27), /// <summary> /// BindNoApplicableRevocationList /// </summary> BindNoApplicableRevocationList = unchecked((int)0x8004CF28), /// <summary> /// InvalidHandle /// </summary> InvalidHandle = unchecked((int)0x8004CF2C), /// <summary> /// BindIntervalTimeViolated /// </summary> BindIntervalTimeViolated = unchecked((int)0x8004CF2F), /// <summary> /// BindNoSatisfiedRightsGroup /// </summary> BindNoSatisfiedRightsGroup = unchecked((int)0x8004CF30), /// <summary> /// BindSpecifiedWorkMissing /// </summary> BindSpecifiedWorkMissing = unchecked((int)0x8004CF31), //--------------------------------- // client SDK error codes //--------------------------------- /// <summary> /// NoMoreData /// </summary> NoMoreData = unchecked((int)0x8004CF33), /// <summary> /// LicenseAcquisitionFailed /// </summary> LicenseAcquisitionFailed = unchecked((int)0x8004CF34), /// <summary> /// IdMismatch /// </summary> IdMismatch = unchecked((int)0x8004CF35), /// <summary> /// TooManyCertificates /// </summary> TooManyCertificates = unchecked((int)0x8004CF36), /// <summary> /// NoDistributionPointUrlFound /// </summary> NoDistributionPointUrlFound = unchecked((int)0x8004CF37), /// <summary> /// AlreadyInProgress /// </summary> AlreadyInProgress = unchecked((int)0x8004CF38), /// <summary> /// GroupIdentityNotSet /// </summary> GroupIdentityNotSet = unchecked((int)0x8004CF39), /// <summary> /// RecordNotFound /// </summary> RecordNotFound = unchecked((int)0x8004CF3A), /// <summary> /// NoConnect /// </summary> NoConnect = unchecked((int)0x8004CF3B), /// <summary> /// NoLicense /// </summary> NoLicense = unchecked((int)0x8004CF3C), /// <summary> /// NeedsMachineActivation /// </summary> NeedsMachineActivation = unchecked((int)0x8004CF3D), /// <summary> /// NeedsGroupIdentityActivation /// </summary> NeedsGroupIdentityActivation = unchecked((int)0x8004CF3E), /// <summary> /// ActivationFailed /// </summary> ActivationFailed = unchecked((int)0x8004CF40), /// <summary> /// Aborted /// </summary> Aborted = unchecked((int)0x8004CF41), /// <summary> /// OutOfQuota /// </summary> OutOfQuota = unchecked((int)0x8004CF42), /// <summary> /// AuthenticationFailed /// </summary> AuthenticationFailed = unchecked((int)0x8004CF43), /// <summary> /// ServerError /// </summary> ServerError = unchecked((int)0x8004CF44), /// <summary> /// InstallationFailed /// </summary> InstallationFailed = unchecked((int)0x8004CF45), /// <summary> /// HidCorrupted /// </summary> HidCorrupted = unchecked((int)0x8004CF46), /// <summary> /// InvalidServerResponse /// </summary> InvalidServerResponse = unchecked((int)0x8004CF47), /// <summary> /// ServiceNotFound /// </summary> ServiceNotFound = unchecked((int)0x8004CF48), /// <summary> /// UseDefault /// </summary> UseDefault = unchecked((int)0x8004CF49), /// <summary> /// ServerNotFound /// </summary> ServerNotFound = unchecked((int)0x8004CF4A), /// <summary> /// InvalidEmail /// </summary> InvalidEmail = unchecked((int)0x8004CF4B), /// <summary> /// ValidityTimeViolation /// </summary> ValidityTimeViolation = unchecked((int)0x8004CF4C), /// <summary> /// OutdatedModule /// </summary> OutdatedModule = unchecked((int)0x8004CF4D), /// <summary> /// ServiceMoved /// </summary> ServiceMoved = unchecked((int)0x8004CF5B), /// <summary> /// ServiceGone /// </summary> ServiceGone = unchecked((int)0x8004CF5C), /// <summary> /// AdEntryNotFound /// </summary> AdEntryNotFound = unchecked((int)0x8004CF5D), /// <summary> /// NotAChain /// </summary> NotAChain = unchecked((int)0x8004CF5E), /// <summary> /// RequestDenied /// </summary> RequestDenied = unchecked((int)0x8004CF5F), //--------------------------------- // Publishing SDK Error Codes //--------------------------------- /// <summary> /// NotSet /// </summary> NotSet = unchecked((int)0x8004CF4E), /// <summary> /// MetadataNotSet /// </summary> MetadataNotSet = unchecked((int)0x8004CF4F), /// <summary> /// RevocationInfoNotSet /// </summary> RevocationInfoNotSet = unchecked((int)0x8004CF50), /// <summary> /// InvalidTimeInfo /// </summary> InvalidTimeInfo = unchecked((int)0x8004CF51), /// <summary> /// RightNotSet /// </summary> RightNotSet = unchecked((int)0x8004CF52), //--------------------------------- // NTLM Credential checking //--------------------------------- /// <summary> /// LicenseBindingToWindowsIdentityFailed /// </summary> LicenseBindingToWindowsIdentityFailed = unchecked((int)0x8004CF53), /// <summary> /// InvalidIssuanceLicenseTemplate /// </summary> InvalidIssuanceLicenseTemplate = unchecked((int)0x8004CF54), /// <summary> /// InvalidKeyLength /// </summary> InvalidKeyLength = unchecked((int)0x8004CF55), /// <summary> /// ExpiredOfficialIssuanceLicenseTemplate /// </summary> ExpiredOfficialIssuanceLicenseTemplate = unchecked((int)0x8004CF57), /// <summary> /// InvalidClientLicensorCertificate /// </summary> InvalidClientLicensorCertificate = unchecked((int)0x8004CF58), /// <summary> /// HidInvalid /// </summary> HidInvalid = unchecked((int)0x8004CF59), /// <summary> /// EmailNotVerified /// </summary> EmailNotVerified = unchecked((int)0x8004CF5A), /// <summary> /// DebuggerDetected /// </summary> DebuggerDetected = unchecked((int)0x8004CF60), /// <summary> /// InvalidLockboxType /// </summary> InvalidLockboxType = unchecked((int)0x8004CF70), /// <summary> /// InvalidLockboxPath /// </summary> InvalidLockboxPath = unchecked((int)0x8004CF71), /// <summary> /// InvalidRegistryPath /// </summary> InvalidRegistryPath = unchecked((int)0x8004CF72), /// <summary> /// NoAesProvider /// </summary> NoAesCryptoProvider = unchecked((int)0x8004CF73), /// <summary> /// GlobalOptionAlreadySet /// </summary> GlobalOptionAlreadySet = unchecked((int)0x8004CF74), /// <summary> /// OwnerLicenseNotFound /// </summary> OwnerLicenseNotFound = unchecked((int)0x8004CF75), } }
// // Tuples.cs // // Authors: // Zoltan Varga ([email protected]) // Marek Safar ([email protected]) // // Copyright (C) 2009 Novell // // 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; namespace System { public static class Tuple { public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8> ( T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8)); } public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7> ( T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); } public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6> ( T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5> ( T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4> ( T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); } public static Tuple<T1, T2, T3> Create<T1, T2, T3> ( T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } public static Tuple<T1, T2> Create<T1, T2> ( T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1> Create<T1> ( T1 item1) { return new Tuple<T1>(item1); } } public partial class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; this.item6 = item6; this.item7 = item7; this.rest = rest; bool ok = true; if (!typeof(TRest).IsGenericType) ok = false; if (ok) { Type t = typeof(TRest).GetGenericTypeDefinition(); if (!(t == typeof(Tuple<>) || t == typeof(Tuple<,>) || t == typeof(Tuple<,,>) || t == typeof(Tuple<,,,>) || t == typeof(Tuple<,,,,>) || t == typeof(Tuple<,,,,,>) || t == typeof(Tuple<,,,,,,>) || t == typeof(Tuple<,,,,,,,>))) ok = false; } if (!ok) throw new ArgumentException("rest", "The last element of an eight element tuple must be a Tuple."); } } [Serializable] public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; public Tuple(T1 item1) { this.item1 = item1; } public T1 Item1 { get { return item1; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } return comparer.Compare(item1, t.item1); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1>; if (t == null) return false; return comparer.Equals(item1, t.item1); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(item1); } public override string ToString() { return String.Format("({0})", item1); } } [Serializable] public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; public Tuple(T1 item1, T2 item2) { this.item1 = item1; this.item2 = item2; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; return comparer.Compare(item2, t.item2); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); return h; } public override string ToString() { return String.Format("({0}, {1})", item1, item2); } } [Serializable] public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; public Tuple(T1 item1, T2 item2, T3 item3) { this.item1 = item1; this.item2 = item2; this.item3 = item3; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; res = comparer.Compare(item2, t.item2); if (res != 0) return res; return comparer.Compare(item3, t.item3); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2) && comparer.Equals(item3, t.item3); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); h = (h << 5) - h + comparer.GetHashCode(item3); return h; } public override string ToString() { return String.Format("({0}, {1}, {2})", item1, item2, item3); } } [Serializable] public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; res = comparer.Compare(item2, t.item2); if (res != 0) return res; res = comparer.Compare(item3, t.item3); if (res != 0) return res; return comparer.Compare(item4, t.item4); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2) && comparer.Equals(item3, t.item3) && comparer.Equals(item4, t.item4); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); h = (h << 5) - h + comparer.GetHashCode(item3); h = (h << 5) - h + comparer.GetHashCode(item4); return h; } public override string ToString() { return String.Format("({0}, {1}, {2}, {3})", item1, item2, item3, item4); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; res = comparer.Compare(item2, t.item2); if (res != 0) return res; res = comparer.Compare(item3, t.item3); if (res != 0) return res; res = comparer.Compare(item4, t.item4); if (res != 0) return res; return comparer.Compare(item5, t.item5); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2) && comparer.Equals(item3, t.item3) && comparer.Equals(item4, t.item4) && comparer.Equals(item5, t.item5); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); h = (h << 5) - h + comparer.GetHashCode(item3); h = (h << 5) - h + comparer.GetHashCode(item4); h = (h << 5) - h + comparer.GetHashCode(item5); return h; } public override string ToString() { return String.Format("({0}, {1}, {2}, {3}, {4})", item1, item2, item3, item4, item5); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; T6 item6; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; this.item6 = item6; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } public T6 Item6 { get { return item6; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; res = comparer.Compare(item2, t.item2); if (res != 0) return res; res = comparer.Compare(item3, t.item3); if (res != 0) return res; res = comparer.Compare(item4, t.item4); if (res != 0) return res; res = comparer.Compare(item5, t.item5); if (res != 0) return res; return comparer.Compare(item6, t.item6); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2) && comparer.Equals(item3, t.item3) && comparer.Equals(item4, t.item4) && comparer.Equals(item5, t.item5) && comparer.Equals(item6, t.item6); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); h = (h << 5) - h + comparer.GetHashCode(item3); h = (h << 5) - h + comparer.GetHashCode(item4); h = (h << 5) - h + comparer.GetHashCode(item5); h = (h << 5) - h + comparer.GetHashCode(item6); return h; } public override string ToString() { return String.Format("({0}, {1}, {2}, {3}, {4}, {5})", item1, item2, item3, item4, item5, item6); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; T6 item6; T7 item7; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; this.item6 = item6; this.item7 = item7; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } public T6 Item6 { get { return item6; } } public T7 Item7 { get { return item7; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; res = comparer.Compare(item2, t.item2); if (res != 0) return res; res = comparer.Compare(item3, t.item3); if (res != 0) return res; res = comparer.Compare(item4, t.item4); if (res != 0) return res; res = comparer.Compare(item5, t.item5); if (res != 0) return res; res = comparer.Compare(item6, t.item6); if (res != 0) return res; return comparer.Compare(item7, t.item7); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2) && comparer.Equals(item3, t.item3) && comparer.Equals(item4, t.item4) && comparer.Equals(item5, t.item5) && comparer.Equals(item6, t.item6) && comparer.Equals(item7, t.item7); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); h = (h << 5) - h + comparer.GetHashCode(item3); h = (h << 5) - h + comparer.GetHashCode(item4); h = (h << 5) - h + comparer.GetHashCode(item5); h = (h << 5) - h + comparer.GetHashCode(item6); h = (h << 5) - h + comparer.GetHashCode(item7); return h; } public override string ToString() { return String.Format("({0}, {1}, {2}, {3}, {4}, {5}, {6})", item1, item2, item3, item4, item5, item6, item7); } } [Serializable] public partial class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; T6 item6; T7 item7; TRest rest; public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } public T6 Item6 { get { return item6; } } public T7 Item7 { get { return item7; } } public TRest Rest { get { return rest; } } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (t == null) { if (other == null) return 1; throw new ArgumentException("other"); } int res = comparer.Compare(item1, t.item1); if (res != 0) return res; res = comparer.Compare(item2, t.item2); if (res != 0) return res; res = comparer.Compare(item3, t.item3); if (res != 0) return res; res = comparer.Compare(item4, t.item4); if (res != 0) return res; res = comparer.Compare(item5, t.item5); if (res != 0) return res; res = comparer.Compare(item6, t.item6); if (res != 0) return res; res = comparer.Compare(item7, t.item7); if (res != 0) return res; return comparer.Compare(rest, t.rest); } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (t == null) return false; return comparer.Equals(item1, t.item1) && comparer.Equals(item2, t.item2) && comparer.Equals(item3, t.item3) && comparer.Equals(item4, t.item4) && comparer.Equals(item5, t.item5) && comparer.Equals(item6, t.item6) && comparer.Equals(item7, t.item7) && comparer.Equals(rest, t.rest); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { int h = comparer.GetHashCode(item1); h = (h << 5) - h + comparer.GetHashCode(item2); h = (h << 5) - h + comparer.GetHashCode(item3); h = (h << 5) - h + comparer.GetHashCode(item4); h = (h << 5) - h + comparer.GetHashCode(item5); h = (h << 5) - h + comparer.GetHashCode(item6); h = (h << 5) - h + comparer.GetHashCode(item7); h = (h << 5) - h + comparer.GetHashCode(rest); return h; } public override string ToString() { return String.Format("({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})", item1, item2, item3, item4, item5, item6, item7, rest); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using Xunit; public class LogLevelTests : NLogTestBase { [Fact] [Trait("Component", "Core")] public void OrdinalTest() { Assert.True(LogLevel.Trace < LogLevel.Debug); Assert.True(LogLevel.Debug < LogLevel.Info); Assert.True(LogLevel.Info < LogLevel.Warn); Assert.True(LogLevel.Warn < LogLevel.Error); Assert.True(LogLevel.Error < LogLevel.Fatal); Assert.True(LogLevel.Fatal < LogLevel.Off); Assert.False(LogLevel.Trace > LogLevel.Debug); Assert.False(LogLevel.Debug > LogLevel.Info); Assert.False(LogLevel.Info > LogLevel.Warn); Assert.False(LogLevel.Warn > LogLevel.Error); Assert.False(LogLevel.Error > LogLevel.Fatal); Assert.False(LogLevel.Fatal > LogLevel.Off); Assert.True(LogLevel.Trace <= LogLevel.Debug); Assert.True(LogLevel.Debug <= LogLevel.Info); Assert.True(LogLevel.Info <= LogLevel.Warn); Assert.True(LogLevel.Warn <= LogLevel.Error); Assert.True(LogLevel.Error <= LogLevel.Fatal); Assert.True(LogLevel.Fatal <= LogLevel.Off); Assert.False(LogLevel.Trace >= LogLevel.Debug); Assert.False(LogLevel.Debug >= LogLevel.Info); Assert.False(LogLevel.Info >= LogLevel.Warn); Assert.False(LogLevel.Warn >= LogLevel.Error); Assert.False(LogLevel.Error >= LogLevel.Fatal); Assert.False(LogLevel.Fatal >= LogLevel.Off); } [Fact] [Trait("Component", "Core")] public void LogLevelEqualityTest() { LogLevel levelTrace = LogLevel.Trace; LogLevel levelInfo = LogLevel.Info; Assert.True(LogLevel.Trace == levelTrace); Assert.True(LogLevel.Info == levelInfo); Assert.False(LogLevel.Trace == levelInfo); Assert.False(LogLevel.Trace != levelTrace); Assert.False(LogLevel.Info != levelInfo); Assert.True(LogLevel.Trace != levelInfo); } [Fact] [Trait("Component", "Core")] public void LogLevelFromOrdinal_InputInRange_ExpectValidLevel() { Assert.Same(LogLevel.FromOrdinal(0), LogLevel.Trace); Assert.Same(LogLevel.FromOrdinal(1), LogLevel.Debug); Assert.Same(LogLevel.FromOrdinal(2), LogLevel.Info); Assert.Same(LogLevel.FromOrdinal(3), LogLevel.Warn); Assert.Same(LogLevel.FromOrdinal(4), LogLevel.Error); Assert.Same(LogLevel.FromOrdinal(5), LogLevel.Fatal); Assert.Same(LogLevel.FromOrdinal(6), LogLevel.Off); } [Fact] [Trait("Component", "Core")] public void LogLevelFromOrdinal_InputOutOfRange_ExpectException() { Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(100)); // Boundary conditions. Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(-1)); Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(7)); } [Fact] [Trait("Component", "Core")] public void FromStringTest() { Assert.Same(LogLevel.FromString("trace"), LogLevel.Trace); Assert.Same(LogLevel.FromString("debug"), LogLevel.Debug); Assert.Same(LogLevel.FromString("info"), LogLevel.Info); Assert.Same(LogLevel.FromString("warn"), LogLevel.Warn); Assert.Same(LogLevel.FromString("error"), LogLevel.Error); Assert.Same(LogLevel.FromString("fatal"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("off"), LogLevel.Off); Assert.Same(LogLevel.FromString("Trace"), LogLevel.Trace); Assert.Same(LogLevel.FromString("Debug"), LogLevel.Debug); Assert.Same(LogLevel.FromString("Info"), LogLevel.Info); Assert.Same(LogLevel.FromString("Warn"), LogLevel.Warn); Assert.Same(LogLevel.FromString("Error"), LogLevel.Error); Assert.Same(LogLevel.FromString("Fatal"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("Off"), LogLevel.Off); Assert.Same(LogLevel.FromString("TracE"), LogLevel.Trace); Assert.Same(LogLevel.FromString("DebuG"), LogLevel.Debug); Assert.Same(LogLevel.FromString("InfO"), LogLevel.Info); Assert.Same(LogLevel.FromString("WarN"), LogLevel.Warn); Assert.Same(LogLevel.FromString("ErroR"), LogLevel.Error); Assert.Same(LogLevel.FromString("FataL"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("TRACE"), LogLevel.Trace); Assert.Same(LogLevel.FromString("DEBUG"), LogLevel.Debug); Assert.Same(LogLevel.FromString("INFO"), LogLevel.Info); Assert.Same(LogLevel.FromString("WARN"), LogLevel.Warn); Assert.Same(LogLevel.FromString("ERROR"), LogLevel.Error); Assert.Same(LogLevel.FromString("FATAL"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("NoNe"), LogLevel.Off); Assert.Same(LogLevel.FromString("iNformaTION"), LogLevel.Info); Assert.Same(LogLevel.FromString("WarNING"), LogLevel.Warn); } [Fact] [Trait("Component", "Core")] public void FromStringFailingTest() { Assert.Throws<ArgumentException>(() => LogLevel.FromString("zzz")); Assert.Throws<ArgumentException>(() => LogLevel.FromString(string.Empty)); Assert.Throws<ArgumentNullException>(() => LogLevel.FromString(null)); } [Fact] [Trait("Component", "Core")] public void LogLevelNullComparison() { LogLevel level = LogLevel.Info; Assert.False(level == null); Assert.True(level != null); Assert.False(null == level); Assert.True(null != level); level = null; Assert.True(level == null); Assert.False(level != null); Assert.True(null == level); Assert.False(null != level); } [Fact] [Trait("Component", "Core")] public void ToStringTest() { Assert.Equal("Trace", LogLevel.Trace.ToString()); Assert.Equal("Debug", LogLevel.Debug.ToString()); Assert.Equal("Info", LogLevel.Info.ToString()); Assert.Equal("Warn", LogLevel.Warn.ToString()); Assert.Equal("Error", LogLevel.Error.ToString()); Assert.Equal("Fatal", LogLevel.Fatal.ToString()); } [Fact] [Trait("Component", "Core")] public void LogLevelCompareTo_ValidLevels_ExpectIntValues() { LogLevel levelTrace = LogLevel.Trace; LogLevel levelDebug = LogLevel.Debug; LogLevel levelInfo = LogLevel.Info; LogLevel levelWarn = LogLevel.Warn; LogLevel levelError = LogLevel.Error; LogLevel levelFatal = LogLevel.Fatal; LogLevel levelOff = LogLevel.Off; LogLevel levelMin = LogLevel.MinLevel; LogLevel levelMax = LogLevel.MaxLevel; Assert.Equal(LogLevel.Trace.CompareTo(levelDebug), -1); Assert.Equal(LogLevel.Debug.CompareTo(levelInfo), -1); Assert.Equal(LogLevel.Info.CompareTo(levelWarn), -1); Assert.Equal(LogLevel.Warn.CompareTo(levelError), -1); Assert.Equal(LogLevel.Error.CompareTo(levelFatal), -1); Assert.Equal(LogLevel.Fatal.CompareTo(levelOff), -1); Assert.Equal(1, LogLevel.Debug.CompareTo(levelTrace)); Assert.Equal(1, LogLevel.Info.CompareTo(levelDebug)); Assert.Equal(1, LogLevel.Warn.CompareTo(levelInfo)); Assert.Equal(1, LogLevel.Error.CompareTo(levelWarn)); Assert.Equal(1, LogLevel.Fatal.CompareTo(levelError)); Assert.Equal(1, LogLevel.Off.CompareTo(levelFatal)); Assert.Equal(0, LogLevel.Debug.CompareTo(levelDebug)); Assert.Equal(0, LogLevel.Info.CompareTo(levelInfo)); Assert.Equal(0, LogLevel.Warn.CompareTo(levelWarn)); Assert.Equal(0, LogLevel.Error.CompareTo(levelError)); Assert.Equal(0, LogLevel.Fatal.CompareTo(levelFatal)); Assert.Equal(0, LogLevel.Off.CompareTo(levelOff)); Assert.Equal(0, LogLevel.Trace.CompareTo(levelMin)); Assert.Equal(1, LogLevel.Debug.CompareTo(levelMin)); Assert.Equal(2, LogLevel.Info.CompareTo(levelMin)); Assert.Equal(3, LogLevel.Warn.CompareTo(levelMin)); Assert.Equal(4, LogLevel.Error.CompareTo(levelMin)); Assert.Equal(5, LogLevel.Fatal.CompareTo(levelMin)); Assert.Equal(6, LogLevel.Off.CompareTo(levelMin)); Assert.Equal(LogLevel.Trace.CompareTo(levelMax), -5); Assert.Equal(LogLevel.Debug.CompareTo(levelMax), -4); Assert.Equal(LogLevel.Info.CompareTo(levelMax), -3); Assert.Equal(LogLevel.Warn.CompareTo(levelMax), -2); Assert.Equal(LogLevel.Error.CompareTo(levelMax), -1); Assert.Equal(0, LogLevel.Fatal.CompareTo(levelMax)); Assert.Equal(1, LogLevel.Off.CompareTo(levelMax)); } [Fact] [Trait("Component", "Core")] public void LogLevelCompareTo_Null_ExpectException() { Assert.Throws<ArgumentNullException>(() => LogLevel.MinLevel.CompareTo(null)); Assert.Throws<ArgumentNullException>(() => LogLevel.MaxLevel.CompareTo(null)); Assert.Throws<ArgumentNullException>(() => LogLevel.Debug.CompareTo(null)); } [Fact] [Trait("Component", "Core")] public void LogLevel_MinMaxLevels_ExpectConstantValues() { Assert.Same(LogLevel.Trace, LogLevel.MinLevel); Assert.Same(LogLevel.Fatal, LogLevel.MaxLevel); } [Fact] [Trait("Component", "Core")] public void LogLevelGetHashCode() { Assert.Equal(0, LogLevel.Trace.GetHashCode()); Assert.Equal(1, LogLevel.Debug.GetHashCode()); Assert.Equal(2, LogLevel.Info.GetHashCode()); Assert.Equal(3, LogLevel.Warn.GetHashCode()); Assert.Equal(4, LogLevel.Error.GetHashCode()); Assert.Equal(5, LogLevel.Fatal.GetHashCode()); Assert.Equal(6, LogLevel.Off.GetHashCode()); } [Fact] [Trait("Component", "Core")] public void LogLevelEquals_Null_ExpectFalse() { Assert.False(LogLevel.Debug.Equals(null)); LogLevel logLevel = null; Assert.False(LogLevel.Debug.Equals(logLevel)); Object obj = logLevel; Assert.False(LogLevel.Debug.Equals(obj)); } [Fact] public void LogLevelEqual_TypeOfObject() { // Objects of any other type should always return false. Assert.False(LogLevel.Debug.Equals((int) 1)); Assert.False(LogLevel.Debug.Equals((string)"Debug")); // Valid LogLevel objects boxed as Object type. Object levelTrace = LogLevel.Trace; Object levelDebug = LogLevel.Debug; Object levelInfo = LogLevel.Info; Object levelWarn = LogLevel.Warn; Object levelError = LogLevel.Error; Object levelFatal = LogLevel.Fatal; Object levelOff = LogLevel.Off; Assert.False(LogLevel.Warn.Equals(levelTrace)); Assert.False(LogLevel.Warn.Equals(levelDebug)); Assert.False(LogLevel.Warn.Equals(levelInfo)); Assert.True(LogLevel.Warn.Equals(levelWarn)); Assert.False(LogLevel.Warn.Equals(levelError)); Assert.False(LogLevel.Warn.Equals(levelFatal)); Assert.False(LogLevel.Warn.Equals(levelOff)); } [Fact] public void LogLevelEqual_TypeOfLogLevel() { Assert.False(LogLevel.Warn.Equals(LogLevel.Trace)); Assert.False(LogLevel.Warn.Equals(LogLevel.Debug)); Assert.False(LogLevel.Warn.Equals(LogLevel.Info)); Assert.True(LogLevel.Warn.Equals(LogLevel.Warn)); Assert.False(LogLevel.Warn.Equals(LogLevel.Error)); Assert.False(LogLevel.Warn.Equals(LogLevel.Fatal)); Assert.False(LogLevel.Warn.Equals(LogLevel.Off)); } [Fact] public void LogLevel_GetAllLevels() { Assert.Equal( new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal, LogLevel.Off }, LogLevel.AllLevels); } [Fact] public void LogLevel_SetAllLevels() { Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>) LogLevel.AllLevels).Add(LogLevel.Fatal)); } [Fact] public void LogLevel_GetAllLoggingLevels() { Assert.Equal( new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }, LogLevel.AllLoggingLevels); } [Fact] public void LogLevel_SetAllLoggingLevels() { Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>)LogLevel.AllLoggingLevels).Add(LogLevel.Fatal)); } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Framework.Profiler; using Microsoft.Build.Internal; using Microsoft.Build.Shared; namespace Microsoft.Build.Logging { /// <summary> /// Serializes BuildEventArgs-derived objects into a provided BinaryWriter /// </summary> internal class BuildEventArgsWriter { private readonly Stream originalStream; /// <summary> /// When writing the current record, first write it to a memory stream, /// then flush to the originalStream. This is needed so that if we discover /// that we need to write a string record in the middle of writing the /// current record, we will write the string record to the original stream /// and the current record will end up after the string record. /// </summary> private readonly MemoryStream currentRecordStream; /// <summary> /// The binary writer around the originalStream. /// </summary> private readonly BinaryWriter originalBinaryWriter; /// <summary> /// The binary writer around the currentRecordStream. /// </summary> private readonly BinaryWriter currentRecordWriter; /// <summary> /// The binary writer we're currently using. Is pointing at the currentRecordWriter usually, /// but sometimes we repoint it to the originalBinaryWriter temporarily, when writing string /// and name-value records. /// </summary> private BinaryWriter binaryWriter; /// <summary> /// Hashtable used for deduplicating strings. When we need to write a string, /// we check in this hashtable first, and if we've seen the string before, /// just write out its index. Otherwise write out a string record, and then /// write the string index. A string record is guaranteed to precede its first /// usage. /// The reader will read the string records first and then be able to retrieve /// a string by its index. This allows us to keep the format streaming instead /// of writing one giant string table at the end. If a binlog is interrupted /// we'll be able to use all the information we've discovered thus far. /// </summary> private readonly Dictionary<HashKey, int> stringHashes = new Dictionary<HashKey, int>(); /// <summary> /// Hashtable used for deduplicating name-value lists. Same as strings. /// </summary> private readonly Dictionary<HashKey, int> nameValueListHashes = new Dictionary<HashKey, int>(); /// <summary> /// Index 0 is null, Index 1 is the empty string. /// Reserve indices 2-9 for future use. Start indexing actual strings at 10. /// </summary> internal const int StringStartIndex = 10; /// <summary> /// Let's reserve a few indices for future use. /// </summary> internal const int NameValueRecordStartIndex = 10; /// <summary> /// 0 is null, 1 is empty string /// 2-9 are reserved for future use. /// Start indexing at 10. /// </summary> private int stringRecordId = StringStartIndex; /// <summary> /// The index of the next record to be written. /// </summary> private int nameValueRecordId = NameValueRecordStartIndex; /// <summary> /// A temporary buffer we use when writing a NameValueList record. Avoids allocating a list each time. /// </summary> private readonly List<KeyValuePair<string, string>> nameValueListBuffer = new List<KeyValuePair<string, string>>(1024); /// <summary> /// A temporary buffer we use when hashing a NameValueList record. Stores the indices of hashed strings /// instead of the actual names and values. /// </summary> private readonly List<KeyValuePair<int, int>> nameValueIndexListBuffer = new List<KeyValuePair<int, int>>(1024); /// <summary> /// Raised when an item is encountered with a hint to embed a file into the binlog. /// </summary> public event Action<string> EmbedFile; /// <summary> /// Initializes a new instance of BuildEventArgsWriter with a BinaryWriter /// </summary> /// <param name="binaryWriter">A BinaryWriter to write the BuildEventArgs instances to</param> public BuildEventArgsWriter(BinaryWriter binaryWriter) { this.originalStream = binaryWriter.BaseStream; // this doesn't exceed 30K for smaller binlogs so seems like a reasonable // starting point to avoid reallocations in the common case this.currentRecordStream = new MemoryStream(65536); this.originalBinaryWriter = binaryWriter; this.currentRecordWriter = new BinaryWriter(currentRecordStream); this.binaryWriter = currentRecordWriter; } /// <summary> /// Write a provided instance of BuildEventArgs to the BinaryWriter /// </summary> public void Write(BuildEventArgs e) { WriteCore(e); // flush the current record and clear the MemoryStream to prepare for next use currentRecordStream.WriteTo(originalStream); currentRecordStream.SetLength(0); } /* Base types and inheritance ("EventArgs" suffix omitted): Build Telemetry LazyFormattedBuild BuildMessage CriticalBuildMessage EnvironmentVariableRead MetaprojectGenerated ProjectImported PropertyInitialValueSet PropertyReassignment TargetSkipped TaskCommandLine TaskParameter UninitializedPropertyRead BuildStatus TaskStarted TaskFinished TargetStarted TargetFinished ProjectStarted ProjectFinished BuildStarted BuildFinished ProjectEvaluationStarted ProjectEvaluationFinished BuildError BuildWarning CustomBuild ExternalProjectStarted ExternalProjectFinished */ private void WriteCore(BuildEventArgs e) { switch (e) { case BuildMessageEventArgs buildMessage: Write(buildMessage); break; case TaskStartedEventArgs taskStarted: Write(taskStarted); break; case TaskFinishedEventArgs taskFinished: Write(taskFinished); break; case TargetStartedEventArgs targetStarted: Write(targetStarted); break; case TargetFinishedEventArgs targetFinished: Write(targetFinished); break; case BuildErrorEventArgs buildError: Write(buildError); break; case BuildWarningEventArgs buildWarning: Write(buildWarning); break; case ProjectStartedEventArgs projectStarted: Write(projectStarted); break; case ProjectFinishedEventArgs projectFinished: Write(projectFinished); break; case BuildStartedEventArgs buildStarted: Write(buildStarted); break; case BuildFinishedEventArgs buildFinished: Write(buildFinished); break; case ProjectEvaluationStartedEventArgs projectEvaluationStarted: Write(projectEvaluationStarted); break; case ProjectEvaluationFinishedEventArgs projectEvaluationFinished: Write(projectEvaluationFinished); break; default: // convert all unrecognized objects to message // and just preserve the message var buildMessageEventArgs = new BuildMessageEventArgs( e.Message, e.HelpKeyword, e.SenderName, MessageImportance.Normal, e.Timestamp); buildMessageEventArgs.BuildEventContext = e.BuildEventContext ?? BuildEventContext.Invalid; Write(buildMessageEventArgs); break; } } public void WriteBlob(BinaryLogRecordKind kind, byte[] bytes) { // write the blob directly to the underlying writer, // bypassing the memory stream using var redirection = RedirectWritesToOriginalWriter(); Write(kind); Write(bytes.Length); Write(bytes); } /// <summary> /// Switches the binaryWriter used by the Write* methods to the direct underlying stream writer /// until the disposable is disposed. Useful to bypass the currentRecordWriter to write a string, /// blob or NameValueRecord that should precede the record being currently written. /// </summary> private IDisposable RedirectWritesToOriginalWriter() { binaryWriter = originalBinaryWriter; return new RedirectionScope(this); } private struct RedirectionScope : IDisposable { private readonly BuildEventArgsWriter _writer; public RedirectionScope(BuildEventArgsWriter buildEventArgsWriter) { _writer = buildEventArgsWriter; } public void Dispose() { _writer.binaryWriter = _writer.currentRecordWriter; } } private void Write(BuildStartedEventArgs e) { Write(BinaryLogRecordKind.BuildStarted); WriteBuildEventArgsFields(e); Write(e.BuildEnvironment); } private void Write(BuildFinishedEventArgs e) { Write(BinaryLogRecordKind.BuildFinished); WriteBuildEventArgsFields(e); Write(e.Succeeded); } private void Write(ProjectEvaluationStartedEventArgs e) { Write(BinaryLogRecordKind.ProjectEvaluationStarted); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.ProjectFile); } private void Write(ProjectEvaluationFinishedEventArgs e) { Write(BinaryLogRecordKind.ProjectEvaluationFinished); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.ProjectFile); if (e.GlobalProperties == null) { Write(false); } else { Write(true); WriteProperties(e.GlobalProperties); } WriteProperties(e.Properties); WriteProjectItems(e.Items); var result = e.ProfilerResult; Write(result.HasValue); if (result.HasValue) { Write(result.Value.ProfiledLocations.Count); foreach (var item in result.Value.ProfiledLocations) { Write(item.Key); Write(item.Value); } } } private void Write(ProjectStartedEventArgs e) { Write(BinaryLogRecordKind.ProjectStarted); WriteBuildEventArgsFields(e, writeMessage: false); if (e.ParentProjectBuildEventContext == null) { Write(false); } else { Write(true); Write(e.ParentProjectBuildEventContext); } WriteDeduplicatedString(e.ProjectFile); Write(e.ProjectId); WriteDeduplicatedString(e.TargetNames); WriteDeduplicatedString(e.ToolsVersion); if (e.GlobalProperties == null) { Write(false); } else { Write(true); Write(e.GlobalProperties); } WriteProperties(e.Properties); WriteProjectItems(e.Items); } private void Write(ProjectFinishedEventArgs e) { Write(BinaryLogRecordKind.ProjectFinished); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.ProjectFile); Write(e.Succeeded); } private void Write(TargetStartedEventArgs e) { Write(BinaryLogRecordKind.TargetStarted); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.TargetName); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TargetFile); WriteDeduplicatedString(e.ParentTarget); Write((int)e.BuildReason); } private void Write(TargetFinishedEventArgs e) { Write(BinaryLogRecordKind.TargetFinished); WriteBuildEventArgsFields(e, writeMessage: false); Write(e.Succeeded); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TargetFile); WriteDeduplicatedString(e.TargetName); WriteTaskItemList(e.TargetOutputs); } private void Write(TaskStartedEventArgs e) { Write(BinaryLogRecordKind.TaskStarted); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.TaskName); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TaskFile); } private void Write(TaskFinishedEventArgs e) { Write(BinaryLogRecordKind.TaskFinished); WriteBuildEventArgsFields(e, writeMessage: false); Write(e.Succeeded); WriteDeduplicatedString(e.TaskName); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TaskFile); } private void Write(BuildErrorEventArgs e) { Write(BinaryLogRecordKind.Error); WriteBuildEventArgsFields(e); WriteDeduplicatedString(e.Subcategory); WriteDeduplicatedString(e.Code); WriteDeduplicatedString(e.File); WriteDeduplicatedString(e.ProjectFile); Write(e.LineNumber); Write(e.ColumnNumber); Write(e.EndLineNumber); Write(e.EndColumnNumber); } private void Write(BuildWarningEventArgs e) { Write(BinaryLogRecordKind.Warning); WriteBuildEventArgsFields(e); WriteDeduplicatedString(e.Subcategory); WriteDeduplicatedString(e.Code); WriteDeduplicatedString(e.File); WriteDeduplicatedString(e.ProjectFile); Write(e.LineNumber); Write(e.ColumnNumber); Write(e.EndLineNumber); Write(e.EndColumnNumber); } private void Write(BuildMessageEventArgs e) { switch (e) { case TaskParameterEventArgs taskParameter: Write(taskParameter); break; case ProjectImportedEventArgs projectImported: Write(projectImported); break; case TargetSkippedEventArgs targetSkipped: Write(targetSkipped); break; case PropertyReassignmentEventArgs propertyReassignment: Write(propertyReassignment); break; case TaskCommandLineEventArgs taskCommandLine: Write(taskCommandLine); break; case UninitializedPropertyReadEventArgs uninitializedPropertyRead: Write(uninitializedPropertyRead); break; case EnvironmentVariableReadEventArgs environmentVariableRead: Write(environmentVariableRead); break; case PropertyInitialValueSetEventArgs propertyInitialValueSet: Write(propertyInitialValueSet); break; case CriticalBuildMessageEventArgs criticalBuildMessage: Write(criticalBuildMessage); break; default: // actual BuildMessageEventArgs Write(BinaryLogRecordKind.Message); WriteMessageFields(e, writeImportance: true); break; } } private void Write(ProjectImportedEventArgs e) { Write(BinaryLogRecordKind.ProjectImported); WriteMessageFields(e); Write(e.ImportIgnored); WriteDeduplicatedString(e.ImportedProjectFile); WriteDeduplicatedString(e.UnexpandedProject); } private void Write(TargetSkippedEventArgs e) { Write(BinaryLogRecordKind.TargetSkipped); WriteMessageFields(e, writeMessage: false); WriteDeduplicatedString(e.TargetFile); WriteDeduplicatedString(e.TargetName); WriteDeduplicatedString(e.ParentTarget); WriteDeduplicatedString(e.Condition); WriteDeduplicatedString(e.EvaluatedCondition); Write(e.OriginallySucceeded); Write((int)e.BuildReason); } private void Write(CriticalBuildMessageEventArgs e) { Write(BinaryLogRecordKind.CriticalBuildMessage); WriteMessageFields(e); } private void Write(PropertyReassignmentEventArgs e) { Write(BinaryLogRecordKind.PropertyReassignment); WriteMessageFields(e, writeMessage: false, writeImportance: true); WriteDeduplicatedString(e.PropertyName); WriteDeduplicatedString(e.PreviousValue); WriteDeduplicatedString(e.NewValue); WriteDeduplicatedString(e.Location); } private void Write(UninitializedPropertyReadEventArgs e) { Write(BinaryLogRecordKind.UninitializedPropertyRead); WriteMessageFields(e, writeImportance: true); WriteDeduplicatedString(e.PropertyName); } private void Write(PropertyInitialValueSetEventArgs e) { Write(BinaryLogRecordKind.PropertyInitialValueSet); WriteMessageFields(e, writeImportance: true); WriteDeduplicatedString(e.PropertyName); WriteDeduplicatedString(e.PropertyValue); WriteDeduplicatedString(e.PropertySource); } private void Write(EnvironmentVariableReadEventArgs e) { Write(BinaryLogRecordKind.EnvironmentVariableRead); WriteMessageFields(e, writeImportance: true); WriteDeduplicatedString(e.EnvironmentVariableName); } private void Write(TaskCommandLineEventArgs e) { Write(BinaryLogRecordKind.TaskCommandLine); WriteMessageFields(e, writeMessage: false, writeImportance: true); WriteDeduplicatedString(e.CommandLine); WriteDeduplicatedString(e.TaskName); } private void Write(TaskParameterEventArgs e) { Write(BinaryLogRecordKind.TaskParameter); WriteMessageFields(e, writeMessage: false); Write((int)e.Kind); WriteDeduplicatedString(e.ItemType); WriteTaskItemList(e.Items, e.LogItemMetadata); } private void WriteBuildEventArgsFields(BuildEventArgs e, bool writeMessage = true) { var flags = GetBuildEventArgsFieldFlags(e, writeMessage); Write((int)flags); WriteBaseFields(e, flags); } private void WriteBaseFields(BuildEventArgs e, BuildEventArgsFieldFlags flags) { if ((flags & BuildEventArgsFieldFlags.Message) != 0) { WriteDeduplicatedString(e.RawMessage); } if ((flags & BuildEventArgsFieldFlags.BuildEventContext) != 0) { Write(e.BuildEventContext); } if ((flags & BuildEventArgsFieldFlags.ThreadId) != 0) { Write(e.ThreadId); } if ((flags & BuildEventArgsFieldFlags.HelpKeyword) != 0) { WriteDeduplicatedString(e.HelpKeyword); } if ((flags & BuildEventArgsFieldFlags.SenderName) != 0) { WriteDeduplicatedString(e.SenderName); } if ((flags & BuildEventArgsFieldFlags.Timestamp) != 0) { Write(e.Timestamp); } } private void WriteMessageFields(BuildMessageEventArgs e, bool writeMessage = true, bool writeImportance = false) { var flags = GetBuildEventArgsFieldFlags(e, writeMessage); flags = GetMessageFlags(e, flags, writeMessage, writeImportance); Write((int)flags); WriteBaseFields(e, flags); if ((flags & BuildEventArgsFieldFlags.Subcategory) != 0) { WriteDeduplicatedString(e.Subcategory); } if ((flags & BuildEventArgsFieldFlags.Code) != 0) { WriteDeduplicatedString(e.Code); } if ((flags & BuildEventArgsFieldFlags.File) != 0) { WriteDeduplicatedString(e.File); } if ((flags & BuildEventArgsFieldFlags.ProjectFile) != 0) { WriteDeduplicatedString(e.ProjectFile); } if ((flags & BuildEventArgsFieldFlags.LineNumber) != 0) { Write(e.LineNumber); } if ((flags & BuildEventArgsFieldFlags.ColumnNumber) != 0) { Write(e.ColumnNumber); } if ((flags & BuildEventArgsFieldFlags.EndLineNumber) != 0) { Write(e.EndLineNumber); } if ((flags & BuildEventArgsFieldFlags.EndColumnNumber) != 0) { Write(e.EndColumnNumber); } if ((flags & BuildEventArgsFieldFlags.Arguments) != 0) { Write(e.RawArguments.Length); for (int i = 0; i < e.RawArguments.Length; i++) { string argument = Convert.ToString(e.RawArguments[i], CultureInfo.CurrentCulture); WriteDeduplicatedString(argument); } } if ((flags & BuildEventArgsFieldFlags.Importance) != 0) { Write((int)e.Importance); } } private static BuildEventArgsFieldFlags GetMessageFlags(BuildMessageEventArgs e, BuildEventArgsFieldFlags flags, bool writeMessage = true, bool writeImportance = false) { if (e.Subcategory != null) { flags |= BuildEventArgsFieldFlags.Subcategory; } if (e.Code != null) { flags |= BuildEventArgsFieldFlags.Code; } if (e.File != null) { flags |= BuildEventArgsFieldFlags.File; } if (e.ProjectFile != null) { flags |= BuildEventArgsFieldFlags.ProjectFile; } if (e.LineNumber != 0) { flags |= BuildEventArgsFieldFlags.LineNumber; } if (e.ColumnNumber != 0) { flags |= BuildEventArgsFieldFlags.ColumnNumber; } if (e.EndLineNumber != 0) { flags |= BuildEventArgsFieldFlags.EndLineNumber; } if (e.EndColumnNumber != 0) { flags |= BuildEventArgsFieldFlags.EndColumnNumber; } if (writeMessage && e.RawArguments != null && e.RawArguments.Length > 0) { flags |= BuildEventArgsFieldFlags.Arguments; } if (writeImportance && e.Importance != MessageImportance.Low) { flags |= BuildEventArgsFieldFlags.Importance; } return flags; } private static BuildEventArgsFieldFlags GetBuildEventArgsFieldFlags(BuildEventArgs e, bool writeMessage = true) { var flags = BuildEventArgsFieldFlags.None; if (e.BuildEventContext != null) { flags |= BuildEventArgsFieldFlags.BuildEventContext; } if (e.HelpKeyword != null) { flags |= BuildEventArgsFieldFlags.HelpKeyword; } if (writeMessage) { flags |= BuildEventArgsFieldFlags.Message; } // no need to waste space for the default sender name if (e.SenderName != null && e.SenderName != "MSBuild") { flags |= BuildEventArgsFieldFlags.SenderName; } // ThreadId never seems to be used or useful for anything. //if (e.ThreadId > 0) //{ // flags |= BuildEventArgsFieldFlags.ThreadId; //} if (e.Timestamp != default(DateTime)) { flags |= BuildEventArgsFieldFlags.Timestamp; } return flags; } // Both of these are used simultaneously so can't just have a single list private readonly List<object> reusableItemsList = new List<object>(); private readonly List<object> reusableProjectItemList = new List<object>(); private void WriteTaskItemList(IEnumerable items, bool writeMetadata = true) { if (items == null) { Write(false); return; } // For target outputs bypass copying of all items to save on performance. // The proxy creates a deep clone of each item to protect against writes, // but since we're not writing we don't need the deep cloning. // Additionally, it is safe to access the underlying List<ITaskItem> as it's allocated // in a single location and noboby else mutates it after that: // https://github.com/dotnet/msbuild/blob/f0eebf2872d76ab0cd43fdc4153ba636232b222f/src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs#L564 if (items is TargetLoggingContext.TargetOutputItemsInstanceEnumeratorProxy proxy) { items = proxy.BackingItems; } int count; if (items is ICollection arrayList) { count = arrayList.Count; } else if (items is ICollection<ITaskItem> genericList) { count = genericList.Count; } else { // enumerate only once foreach (var item in items) { if (item != null) { reusableItemsList.Add(item); } } items = reusableItemsList; count = reusableItemsList.Count; } Write(count); foreach (var item in items) { if (item is ITaskItem taskItem) { Write(taskItem, writeMetadata); } else { WriteDeduplicatedString(item?.ToString() ?? ""); // itemspec Write(0); // no metadata } } reusableItemsList.Clear(); } private void WriteProjectItems(IEnumerable items) { if (items == null) { Write(0); return; } if (items is ItemDictionary<ProjectItemInstance> itemInstanceDictionary) { // If we have access to the live data from evaluation, it exposes a special method // to iterate the data structure under a lock and return results grouped by item type. // There's no need to allocate or call GroupBy this way. itemInstanceDictionary.EnumerateItemsPerType((itemType, itemList) => { WriteDeduplicatedString(itemType); WriteTaskItemList(itemList); CheckForFilesToEmbed(itemType, itemList); }); // signal the end Write(0); } // not sure when this can get hit, but best to be safe and support this else if (items is ItemDictionary<ProjectItem> itemDictionary) { itemDictionary.EnumerateItemsPerType((itemType, itemList) => { WriteDeduplicatedString(itemType); WriteTaskItemList(itemList); CheckForFilesToEmbed(itemType, itemList); }); // signal the end Write(0); } else { string currentItemType = null; // Write out a sequence of items for each item type while avoiding GroupBy // and associated allocations. We rely on the fact that items of each type // are contiguous. For each item type, write the item type name and the list // of items. Write 0 at the end (which would correspond to item type null). // This is how the reader will know how to stop. We can't write out the // count of item types at the beginning because we don't know how many there // will be (we'd have to enumerate twice to calculate that). This scheme // allows us to stream in a single pass with no allocations for intermediate // results. Internal.Utilities.EnumerateItems(items, dictionaryEntry => { string key = (string)dictionaryEntry.Key; // boundary between item types if (currentItemType != null && currentItemType != key) { WriteDeduplicatedString(currentItemType); WriteTaskItemList(reusableProjectItemList); CheckForFilesToEmbed(currentItemType, reusableProjectItemList); reusableProjectItemList.Clear(); } reusableProjectItemList.Add(dictionaryEntry.Value); currentItemType = key; }); // write out the last item type if (reusableProjectItemList.Count > 0) { WriteDeduplicatedString(currentItemType); WriteTaskItemList(reusableProjectItemList); CheckForFilesToEmbed(currentItemType, reusableProjectItemList); reusableProjectItemList.Clear(); } // signal the end Write(0); } } private void CheckForFilesToEmbed(string itemType, object itemList) { if (EmbedFile == null || !string.Equals(itemType, ItemTypeNames.EmbedInBinlog, StringComparison.OrdinalIgnoreCase) || itemList is not IEnumerable list) { return; } foreach (var item in list) { if (item is ITaskItem taskItem && !string.IsNullOrEmpty(taskItem.ItemSpec)) { EmbedFile.Invoke(taskItem.ItemSpec); } else if (item is string itemSpec && !string.IsNullOrEmpty(itemSpec)) { EmbedFile.Invoke(itemSpec); } } } private void Write(ITaskItem item, bool writeMetadata = true) { WriteDeduplicatedString(item.ItemSpec); if (!writeMetadata) { Write((byte)0); return; } // WARNING: Can't use AddRange here because CopyOnWriteDictionary in Microsoft.Build.Utilities.v4.0.dll // is broken. Microsoft.Build.Utilities.v4.0.dll loads from the GAC by XAML markup tooling and it's // implementation doesn't work with AddRange because AddRange special-cases ICollection<T> and // CopyOnWriteDictionary doesn't implement it properly. foreach (var kvp in item.EnumerateMetadata()) { nameValueListBuffer.Add(kvp); } // Don't sort metadata because we want the binary log to be fully roundtrippable // and we need to preserve the original order. //if (nameValueListBuffer.Count > 1) //{ // nameValueListBuffer.Sort((l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.Key, r.Key)); //} WriteNameValueList(); nameValueListBuffer.Clear(); } private void WriteProperties(IEnumerable properties) { if (properties == null) { Write(0); return; } Internal.Utilities.EnumerateProperties(properties, kvp => nameValueListBuffer.Add(kvp)); WriteNameValueList(); nameValueListBuffer.Clear(); } private void Write(BuildEventContext buildEventContext) { Write(buildEventContext.NodeId); Write(buildEventContext.ProjectContextId); Write(buildEventContext.TargetId); Write(buildEventContext.TaskId); Write(buildEventContext.SubmissionId); Write(buildEventContext.ProjectInstanceId); Write(buildEventContext.EvaluationId); } private void Write(IEnumerable<KeyValuePair<string, string>> keyValuePairs) { if (keyValuePairs != null) { foreach (var kvp in keyValuePairs) { nameValueListBuffer.Add(kvp); } } WriteNameValueList(); nameValueListBuffer.Clear(); } private void WriteNameValueList() { if (nameValueListBuffer.Count == 0) { Write((byte)0); return; } HashKey hash = HashAllStrings(nameValueListBuffer); if (!nameValueListHashes.TryGetValue(hash, out var recordId)) { recordId = nameValueRecordId; nameValueListHashes[hash] = nameValueRecordId; WriteNameValueListRecord(); nameValueRecordId += 1; } Write(recordId); } /// <summary> /// In the middle of writing the current record we may discover that we want to write another record /// preceding the current one, specifically the list of names and values we want to reuse in the /// future. As we are writing the current record to a MemoryStream first, it's OK to temporarily /// switch to the direct underlying stream and write the NameValueList record first. /// When the current record is done writing, the MemoryStream will flush to the underlying stream /// and the current record will end up after the NameValueList record, as desired. /// </summary> private void WriteNameValueListRecord() { // Switch the binaryWriter used by the Write* methods to the direct underlying stream writer. // We want this record to precede the record we're currently writing to currentRecordWriter // which is backed by a MemoryStream buffer using var redirectionScope = RedirectWritesToOriginalWriter(); Write(BinaryLogRecordKind.NameValueList); Write(nameValueIndexListBuffer.Count); for (int i = 0; i < nameValueListBuffer.Count; i++) { var kvp = nameValueIndexListBuffer[i]; Write(kvp.Key); Write(kvp.Value); } } /// <summary> /// Compute the total hash of all items in the nameValueList /// while simultaneously filling the nameValueIndexListBuffer with the individual /// hashes of the strings, mirroring the strings in the original nameValueList. /// This helps us avoid hashing strings twice (once to hash the string individually /// and the second time when hashing it as part of the nameValueList) /// </summary> private HashKey HashAllStrings(List<KeyValuePair<string, string>> nameValueList) { HashKey hash = new HashKey(); nameValueIndexListBuffer.Clear(); for (int i = 0; i < nameValueList.Count; i++) { var kvp = nameValueList[i]; var (keyIndex, keyHash) = HashString(kvp.Key); var (valueIndex, valueHash) = HashString(kvp.Value); hash = hash.Add(keyHash); hash = hash.Add(valueHash); nameValueIndexListBuffer.Add(new KeyValuePair<int, int>(keyIndex, valueIndex)); } return hash; } private void Write(BinaryLogRecordKind kind) { Write((int)kind); } private void Write(int value) { BinaryWriterExtensions.Write7BitEncodedInt(binaryWriter, value); } private void Write(long value) { binaryWriter.Write(value); } private void Write(byte[] bytes) { binaryWriter.Write(bytes); } private void Write(byte b) { binaryWriter.Write(b); } private void Write(bool boolean) { binaryWriter.Write(boolean); } private void WriteDeduplicatedString(string text) { var (recordId, _) = HashString(text); Write(recordId); } /// <summary> /// Hash the string and write a String record if not already hashed. /// </summary> /// <returns>Returns the string record index as well as the hash.</returns> private (int index, HashKey hash) HashString(string text) { if (text == null) { return (0, default); } else if (text.Length == 0) { return (1, default); } var hash = new HashKey(text); if (!stringHashes.TryGetValue(hash, out var recordId)) { recordId = stringRecordId; stringHashes[hash] = stringRecordId; WriteStringRecord(text); stringRecordId += 1; } return (recordId, hash); } private void WriteStringRecord(string text) { using var redirectionScope = RedirectWritesToOriginalWriter(); Write(BinaryLogRecordKind.String); binaryWriter.Write(text); } private void Write(DateTime timestamp) { binaryWriter.Write(timestamp.Ticks); Write((int)timestamp.Kind); } private void Write(TimeSpan timeSpan) { binaryWriter.Write(timeSpan.Ticks); } private void Write(EvaluationLocation item) { WriteDeduplicatedString(item.ElementName); WriteDeduplicatedString(item.ElementDescription); WriteDeduplicatedString(item.EvaluationPassDescription); WriteDeduplicatedString(item.File); Write((int)item.Kind); Write((int)item.EvaluationPass); Write(item.Line.HasValue); if (item.Line.HasValue) { Write(item.Line.Value); } Write(item.Id); Write(item.ParentId.HasValue); if (item.ParentId.HasValue) { Write(item.ParentId.Value); } } private void Write(ProfiledLocation e) { Write(e.NumberOfHits); Write(e.ExclusiveTime); Write(e.InclusiveTime); } internal readonly struct HashKey : IEquatable<HashKey> { private readonly ulong value; private HashKey(ulong i) { value = i; } public HashKey(string text) { if (text == null) { value = 0; } else { value = FnvHash64.GetHashCode(text); } } public static HashKey Combine(HashKey left, HashKey right) { return new HashKey(FnvHash64.Combine(left.value, right.value)); } public HashKey Add(HashKey other) => Combine(this, other); public bool Equals(HashKey other) { return value == other.value; } public override bool Equals(object obj) { if (obj is HashKey other) { return Equals(other); } return false; } public override int GetHashCode() { return unchecked((int)value); } public override string ToString() { return value.ToString(); } } internal static class FnvHash64 { public const ulong Offset = 14695981039346656037; public const ulong Prime = 1099511628211; public static ulong GetHashCode(string text) { ulong hash = Offset; unchecked { for (int i = 0; i < text.Length; i++) { char ch = text[i]; hash = (hash ^ ch) * Prime; } } return hash; } public static ulong Combine(ulong left, ulong right) { unchecked { return (left ^ right) * Prime; } } } } }
// 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.Text; using System.Globalization; using TestLibrary; public class StringCompare { public static string[] InterestingStrings = new string[] { null, "", "a", "1", "-", "A", "!", "abc", "aBc", "a\u0400Bc", "I", "i", "\u0130", "\u0131", "A", "\uFF21", "\uFE57"}; public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Compare interesting strings ordinally"); try { foreach (string s in InterestingStrings) { foreach (string r in InterestingStrings) { retVal &= TestStrings(s, r); } } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Compare many characters"); try { for (int i = 0; i < 40; i++) // Ok, 40 isn't that many... but this takes way too long { char c = Generator.GetChar(-55); if (string.Compare(new string(new char[] { c }), new string(new char[] { c }), StringComparison.Ordinal) != 0) { TestLibrary.TestFramework.LogError("002.1", "Character " + i.ToString() + " is not equal to itself ordinally!"); retVal = false; } for (int j = 0; j < (int)c; j++) { int compareResult = string.Compare(new string(new char[] { c }), new string(new char[] { (char)j }), StringComparison.Ordinal); if (compareResult != 0) compareResult = compareResult / Math.Abs(compareResult); if (compareResult != 1) { TestLibrary.TestFramework.LogError("002.2", "Character " + ((int)c).ToString() + " is not greater than character " + j.ToString() + ", Compare result: " + compareResult.ToString()); retVal = false; } } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.4", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Compare many strings"); try { for (int i = 0; i < 1000; i++) { string str1 = Generator.GetString(-55, false, 5, 20); string str2 = Generator.GetString(-55, false, 5, 20); if (string.Compare(str1, str1, StringComparison.Ordinal) != 0) { TestLibrary.TestFramework.LogError("003.1", "Comparison not as expected! Actual result: " + string.Compare(str1, str1, StringComparison.Ordinal).ToString() + ", Expected result: 0"); TestLibrary.TestFramework.LogInformation("String 1: <" + str1 + "> : " + BytesFromString(str1) + "\nString 2: <" + str1 + "> : " + BytesFromString(str1)); retVal = false; } if (string.Compare(str2, str2, StringComparison.Ordinal) != 0) { TestLibrary.TestFramework.LogError("003.2", "Comparison not as expected! Actual result: " + string.Compare(str2, str2, StringComparison.Ordinal).ToString() + ", Expected result: 0"); TestLibrary.TestFramework.LogInformation("String 1: <" + str2 + "> : " + BytesFromString(str2) + "\nString 2: <" + str2 + "> : " + BytesFromString(str2)); retVal = false; } TestStrings(str1, str2); } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.4", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Specific regression cases"); try { CultureInfo oldCi = TestLibrary.Utilities.CurrentCulture; TestLibrary.Utilities.CurrentCulture = new CultureInfo("hu-HU"); retVal &= TestStrings("dzsdzs", "ddzs"); TestLibrary.Utilities.CurrentCulture = oldCi; retVal &= TestStrings("\u00C0nimal", "A\u0300nimal"); } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public static int Main() { StringCompare test = new StringCompare(); TestLibrary.TestFramework.BeginTestCase("StringCompare"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private bool TestStrings(string str1, string str2) { bool retVal = true; int expectValue = PredictValue(str1, str2); int actualValue = String.Compare(str1, str2, StringComparison.Ordinal); if (expectValue != 0) expectValue = expectValue / Math.Abs(expectValue); if (actualValue != 0) actualValue = actualValue / Math.Abs(actualValue); if (actualValue != expectValue) { TestLibrary.TestFramework.LogError("001.1", "Comparison not as expected! Actual result: " + actualValue + ", Expected result: " + expectValue); TestLibrary.TestFramework.LogInformation("String 1: <" + str1 + "> : " + BytesFromString(str1) + "\nString 2: <" + str2 + "> : " + BytesFromString(str2)); retVal = false; } return retVal; } int PredictValue(string str1, string str2) { if (str1 == null) { if (str2 == null) return 0; else return -1; } if (str2 == null) return 1; for (int i = 0; i < str1.Length; i++) { if (i >= str2.Length) return 1; if ((int)str1[i] > (int)str2[i]) return 1; if ((int)str1[i] < (int)str2[i]) return -1; } if (str2.Length > str1.Length) return -1; return 0; } private static string BytesFromString(string str) { if (str == null) return string.Empty; StringBuilder output = new StringBuilder(); for (int i = 0; i < str.Length; i++) { output.Append(TestLibrary.Utilities.ByteArrayToString(BitConverter.GetBytes(str[i]))); if (i != (str.Length - 1)) output.Append(", "); } return output.ToString(); } }
namespace SqlStreamStore { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MySqlConnector; using SqlStreamStore.MySqlScripts; using SqlStreamStore.Streams; partial class MySqlStreamStore { protected override async Task<AppendResult> AppendToStreamInternal( string streamId, int expectedVersion, NewStreamMessage[] messages, CancellationToken cancellationToken) { var streamIdInfo = new StreamIdInfo(streamId); if(_settings.AppendDeadlockRetryAttempts == 0) { try { return messages.Length == 0 ? await CreateEmptyStream(streamIdInfo, expectedVersion, cancellationToken) : await AppendMessagesToStream(streamIdInfo, expectedVersion, messages, cancellationToken); } catch(MySqlException ex) when(ex.IsWrongExpectedVersion()) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion( streamIdInfo.MySqlStreamId.IdOriginal, expectedVersion), streamIdInfo.MySqlStreamId.IdOriginal, expectedVersion, ex); } } var retryableExceptions = new List<Exception>(); while(retryableExceptions.Count <= _settings.AppendDeadlockRetryAttempts) { try { return messages.Length == 0 ? await CreateEmptyStream(streamIdInfo, expectedVersion, cancellationToken) : await AppendMessagesToStream(streamIdInfo, expectedVersion, messages, cancellationToken); } catch(MySqlException ex) when(ex.IsDeadlock()) { retryableExceptions.Add(ex); } catch(MySqlException ex) when(ex.IsWrongExpectedVersion()) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion( streamIdInfo.MySqlStreamId.IdOriginal, expectedVersion), streamIdInfo.MySqlStreamId.IdOriginal, expectedVersion, ex); } } throw new WrongExpectedVersionException( MySqlErrorMessages.AppendFailedDeadlock( streamIdInfo.MySqlStreamId.IdOriginal, expectedVersion, _settings.AppendDeadlockRetryAttempts), streamIdInfo.MySqlStreamId.IdOriginal, expectedVersion, new AggregateException(retryableExceptions)); } private async Task<AppendResult> AppendMessagesToStream( StreamIdInfo streamId, int expectedVersion, NewStreamMessage[] messages, CancellationToken cancellationToken) { var appendResult = new AppendResult(StreamVersion.End, Position.End); var nextExpectedVersion = expectedVersion; using(var connection = await OpenConnection(cancellationToken)) using(var transaction = await connection .BeginTransactionAsync(cancellationToken) .ConfigureAwait(false)) { var throwIfAdditionalMessages = false; for(var i = 0; i < messages.Length; i++) { bool messageExists; (nextExpectedVersion, appendResult, messageExists) = await AppendMessageToStream( streamId, nextExpectedVersion, messages[i], transaction, cancellationToken); if(i == 0) { throwIfAdditionalMessages = messageExists; } else { if(throwIfAdditionalMessages && !messageExists) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion( streamId.MySqlStreamId.IdOriginal, expectedVersion), streamId.MySqlStreamId.IdOriginal, expectedVersion); } } } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); } await TryScavenge(streamId, cancellationToken).ConfigureAwait(false); return appendResult; } private Task<(int nextExpectedVersion, AppendResult appendResult, bool messageExists)> AppendMessageToStream( StreamIdInfo streamId, int expectedVersion, NewStreamMessage message, MySqlTransaction transaction, CancellationToken cancellationToken) { switch(expectedVersion) { case ExpectedVersion.Any: return AppendToStreamExpectedVersionAny(streamId, message, transaction, cancellationToken); case ExpectedVersion.NoStream: return AppendToStreamExpectedVersionNoStream(streamId, message, transaction, cancellationToken); case ExpectedVersion.EmptyStream: return AppendToStreamExpectedVersionEmptyStream(streamId, message, transaction, cancellationToken); default: return AppendToStreamExpectedVersion( streamId, expectedVersion, message, transaction, cancellationToken); } } private async Task<(int nextExpectedVersion, AppendResult appendResult, bool messageExists)> AppendToStreamExpectedVersionAny( StreamIdInfo streamId, NewStreamMessage message, MySqlTransaction transaction, CancellationToken cancellationToken) { var currentVersion = Parameters.CurrentVersion(); var currentPosition = Parameters.CurrentPosition(); var messageExists = Parameters.MessageExists(); using(var command = BuildStoredProcedureCall( _schema.AppendToStreamExpectedVersionAny, transaction, Parameters.StreamId(streamId.MySqlStreamId), Parameters.StreamIdOriginal(streamId.MySqlStreamId), Parameters.MetadataStreamId(streamId.MetadataMySqlStreamId), Parameters.CreatedUtc(_settings.GetUtcNow?.Invoke()), Parameters.MessageId(message.MessageId), Parameters.Type(message.Type), Parameters.JsonData(message.JsonData), Parameters.JsonMetadata(message.JsonMetadata), currentVersion, currentPosition, messageExists)) { var nextExpectedVersion = Convert.ToInt32( await command .ExecuteScalarAsync(cancellationToken) .ConfigureAwait(false)); return ( nextExpectedVersion, new AppendResult( (int) currentVersion.Value, (long) currentPosition.Value), (bool) messageExists.Value); } } private async Task<(int nextExpectedVersion, AppendResult appendResult, bool messageExists)> AppendToStreamExpectedVersionNoStream( StreamIdInfo streamId, NewStreamMessage message, MySqlTransaction transaction, CancellationToken cancellationToken) { var currentVersion = Parameters.CurrentVersion(); var currentPosition = Parameters.CurrentPosition(); var messageExists = Parameters.MessageExists(); using(var command = BuildStoredProcedureCall( _schema.AppendToStreamExpectedVersionNoStream, transaction, Parameters.StreamId(streamId.MySqlStreamId), Parameters.StreamIdOriginal(streamId.MySqlStreamId), Parameters.MetadataStreamId(streamId.MetadataMySqlStreamId), Parameters.CreatedUtc(_settings.GetUtcNow?.Invoke()), Parameters.MessageId(message.MessageId), Parameters.Type(message.Type), Parameters.JsonData(message.JsonData), Parameters.JsonMetadata(message.JsonMetadata), currentVersion, currentPosition, messageExists)) { var nextExpectedVersion = Convert.ToInt32( await command .ExecuteScalarAsync(cancellationToken) .ConfigureAwait(false)); return ( nextExpectedVersion, new AppendResult( (int) currentVersion.Value, (long) currentPosition.Value), (bool) messageExists.Value); } } private async Task<(int nextExpectedVersion, AppendResult appendResult, bool messageExists)> AppendToStreamExpectedVersionEmptyStream( StreamIdInfo streamId, NewStreamMessage message, MySqlTransaction transaction, CancellationToken cancellationToken) { var currentVersion = Parameters.CurrentVersion(); var currentPosition = Parameters.CurrentPosition(); var messageExists = Parameters.MessageExists(); using(var command = BuildStoredProcedureCall( _schema.AppendToStreamExpectedVersionEmptyStream, transaction, Parameters.StreamId(streamId.MySqlStreamId), Parameters.StreamIdOriginal(streamId.MySqlStreamId), Parameters.MetadataStreamId(streamId.MetadataMySqlStreamId), Parameters.CreatedUtc(_settings.GetUtcNow?.Invoke()), Parameters.MessageId(message.MessageId), Parameters.Type(message.Type), Parameters.JsonData(message.JsonData), Parameters.JsonMetadata(message.JsonMetadata), currentVersion, currentPosition, messageExists)) { var nextExpectedVersion = Convert.ToInt32( await command .ExecuteScalarAsync(cancellationToken) .ConfigureAwait(false)); return ( nextExpectedVersion, new AppendResult( (int) currentVersion.Value, (long) currentPosition.Value), (bool) messageExists.Value); } } private async Task<(int nextExpectedVersion, AppendResult appendResult, bool messageExists)> AppendToStreamExpectedVersion( StreamIdInfo streamId, int expectedVersion, NewStreamMessage message, MySqlTransaction transaction, CancellationToken cancellationToken) { var currentVersion = Parameters.CurrentVersion(); var currentPosition = Parameters.CurrentPosition(); var messageExists = Parameters.MessageExists(); using(var command = BuildStoredProcedureCall( _schema.AppendToStreamExpectedVersion, transaction, Parameters.StreamId(streamId.MySqlStreamId), Parameters.ExpectedVersion(expectedVersion), Parameters.CreatedUtc(_settings.GetUtcNow?.Invoke()), Parameters.MessageId(message.MessageId), Parameters.Type(message.Type), Parameters.JsonData(message.JsonData), Parameters.JsonMetadata(message.JsonMetadata), messageExists, currentVersion, currentPosition)) { var nextExpectedVersion = Convert.ToInt32( await command .ExecuteScalarAsync(cancellationToken) .ConfigureAwait(false)); return ( nextExpectedVersion, new AppendResult( (int) currentVersion.Value, (long) currentPosition.Value), (bool) messageExists.Value); } } private async Task<AppendResult> CreateEmptyStream( StreamIdInfo streamId, int expectedVersion, CancellationToken cancellationToken) { var appendResult = new AppendResult(StreamVersion.End, Position.End); using(var connection = await OpenConnection(cancellationToken)) using(var transaction = await connection .BeginTransactionAsync(cancellationToken) .ConfigureAwait(false)) using(var command = BuildStoredProcedureCall( _schema.CreateEmptyStream, transaction, Parameters.StreamId(streamId.MySqlStreamId), Parameters.StreamIdOriginal(streamId.MySqlStreamId), Parameters.MetadataStreamId(streamId.MetadataMySqlStreamId), Parameters.ExpectedVersion(expectedVersion))) using(var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false)) { await reader.ReadAsync(cancellationToken).ConfigureAwait(false); appendResult = new AppendResult(reader.GetInt32(0), reader.GetInt64(1)); reader.Close(); await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); } return appendResult; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.HttpListenerResponse // // Author: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (c) 2005 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 System.Globalization; using System.IO; using System.Text; using System.Threading.Tasks; namespace System.Net { public sealed partial class HttpListenerResponse : IDisposable { private bool _disposed; private Encoding _contentEncoding; private long _contentLength; private bool _clSet; private string _contentType; private bool _keepAlive = true; private HttpResponseStream _outputStream; private Version _version = HttpVersion.Version11; private string _location; private int _statusCode = 200; private string _statusDescription = "OK"; private bool _chunked; private HttpListenerContext _context; internal bool _headersSent; internal object _headersLock = new object(); private bool _forceCloseChunked; internal HttpListenerResponse(HttpListenerContext context) { _context = context; } internal bool ForceCloseChunked { get { return _forceCloseChunked; } } public Encoding ContentEncoding { get { if (_contentEncoding == null) { _contentEncoding = Encoding.Default; } return _contentEncoding; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); _contentEncoding = value; } } public long ContentLength64 { get { return _contentLength; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall); _clSet = true; _contentLength = value; } } public string ContentType { get { return _contentType; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); _contentType = value; } } public bool KeepAlive { get { return _keepAlive; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); _keepAlive = value; } } public Stream OutputStream { get { if (_outputStream == null) _outputStream = _context.Connection.GetResponseStream(); return _outputStream; } } public Version ProtocolVersion { get { return _version; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); if (value == null) throw new ArgumentNullException(nameof(value)); if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1)) throw new ArgumentException(SR.net_wrongversion, nameof(value)); _version = value; } } public string RedirectLocation { get { return _location; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); _location = value; } } public bool SendChunked { get { return _chunked; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); _chunked = value; } } public int StatusCode { get { return _statusCode; } set { if (_disposed) throw new ObjectDisposedException(GetType().ToString()); if (_headersSent) throw new InvalidOperationException(SR.net_cannot_change_after_headers); if (value < 100 || value > 999) throw new ProtocolViolationException(SR.net_invalidstatus); _statusCode = value; } } public string StatusDescription { get { return _statusDescription; } set { _statusDescription = value; } } private void Dispose() { Close(true); } public void Close() { if (_disposed) return; Close(false); } public void Abort() { if (_disposed) return; Close(true); } private void Close(bool force) { _disposed = true; _context.Connection.Close(force); } public void Close(byte[] responseEntity, bool willBlock) { if (_disposed) return; if (responseEntity == null) throw new ArgumentNullException(nameof(responseEntity)); ContentLength64 = responseEntity.Length; OutputStream.Write(responseEntity, 0, (int)_contentLength); Close(false); } public void CopyFrom(HttpListenerResponse templateResponse) { _webHeaders.Clear(); _webHeaders.Add(templateResponse._webHeaders); _contentLength = templateResponse._contentLength; _statusCode = templateResponse._statusCode; _statusDescription = templateResponse._statusDescription; _keepAlive = templateResponse._keepAlive; _version = templateResponse._version; } public void Redirect(string url) { StatusCode = 302; // Found _location = url; } private bool FindCookie(Cookie cookie) { string name = cookie.Name; string domain = cookie.Domain; string path = cookie.Path; foreach (Cookie c in _cookies) { if (name != c.Name) continue; if (domain != c.Domain) continue; if (path == c.Path) return true; } return false; } internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false) { Encoding encoding = _contentEncoding; if (encoding == null) encoding = Encoding.Default; if (!isWebSocketHandshake) { if (_contentType != null) { if (_contentEncoding != null && _contentType.IndexOf(HttpHeaderStrings.Charset, StringComparison.Ordinal) == -1) { string enc_name = _contentEncoding.WebName; _webHeaders.Set(HttpKnownHeaderNames.ContentType, _contentType + "; " + HttpHeaderStrings.Charset + enc_name); } else { _webHeaders.Set(HttpKnownHeaderNames.ContentType, _contentType); } } if (_webHeaders[HttpKnownHeaderNames.Server] == null) _webHeaders.Set(HttpKnownHeaderNames.Server, HttpHeaderStrings.NetCoreServerName); CultureInfo inv = CultureInfo.InvariantCulture; if (_webHeaders[HttpKnownHeaderNames.Date] == null) _webHeaders.Set(HttpKnownHeaderNames.Date, DateTime.UtcNow.ToString("r", inv)); if (!_chunked) { if (!_clSet && closing) { _clSet = true; _contentLength = 0; } if (_clSet) _webHeaders.Set(HttpKnownHeaderNames.ContentLength, _contentLength.ToString(inv)); } Version v = _context.Request.ProtocolVersion; if (!_clSet && !_chunked && v >= HttpVersion.Version11) _chunked = true; /* Apache forces closing the connection for these status codes: * HttpStatusCode.BadRequest 400 * HttpStatusCode.RequestTimeout 408 * HttpStatusCode.LengthRequired 411 * HttpStatusCode.RequestEntityTooLarge 413 * HttpStatusCode.RequestUriTooLong 414 * HttpStatusCode.InternalServerError 500 * HttpStatusCode.ServiceUnavailable 503 */ bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout || _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge || _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError || _statusCode == (int)HttpStatusCode.ServiceUnavailable); if (conn_close == false) conn_close = !_context.Request.KeepAlive; // They sent both KeepAlive: true and Connection: close if (!_keepAlive || conn_close) { _webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close); conn_close = true; } if (_chunked) _webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked); int reuses = _context.Connection.Reuses; if (reuses >= 100) { _forceCloseChunked = true; if (!conn_close) { _webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close); conn_close = true; } } if (!conn_close) { _webHeaders.Set(HttpKnownHeaderNames.KeepAlive, String.Format("timeout=15,max={0}", 100 - reuses)); if (_context.Request.ProtocolVersion <= HttpVersion.Version10) _webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.KeepAlive); } if (_location != null) _webHeaders.Set(HttpKnownHeaderNames.Location, _location); if (_cookies != null) { foreach (Cookie cookie in _cookies) _webHeaders.Set(HttpKnownHeaderNames.SetCookie, CookieToClientString(cookie)); } } StreamWriter writer = new StreamWriter(ms, encoding, 256); writer.Write("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription); string headers_str = FormatHeaders(_webHeaders); writer.Write(headers_str); writer.Flush(); int preamble = encoding.GetPreamble().Length; if (_outputStream == null) _outputStream = _context.Connection.GetResponseStream(); /* Assumes that the ms was at position 0 */ ms.Position = preamble; _headersSent = !isWebSocketHandshake; } private static string FormatHeaders(WebHeaderCollection headers) { var sb = new StringBuilder(); for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); string[] values = headers.GetValues(i); for (int j = 0; j < values.Length; j++) { sb.Append(key).Append(": ").Append(values[j]).Append("\r\n"); } } return sb.Append("\r\n").ToString(); } private static string CookieToClientString(Cookie cookie) { if (cookie.Name.Length == 0) return String.Empty; StringBuilder result = new StringBuilder(64); if (cookie.Version > 0) result.Append("Version=").Append(cookie.Version).Append(";"); result.Append(cookie.Name).Append("=").Append(cookie.Value); if (cookie.Path != null && cookie.Path.Length != 0) result.Append(";Path=").Append(QuotedString(cookie, cookie.Path)); if (cookie.Domain != null && cookie.Domain.Length != 0) result.Append(";Domain=").Append(QuotedString(cookie, cookie.Domain)); if (cookie.Port != null && cookie.Port.Length != 0) result.Append(";Port=").Append(cookie.Port); return result.ToString(); } private static string QuotedString(Cookie cookie, string value) { if (cookie.Version == 0 || IsToken(value)) return value; else return "\"" + value.Replace("\"", "\\\"") + "\""; } private static string s_tspecials = "()<>@,;:\\\"/[]?={} \t"; // from RFC 2965, 2068 private static bool IsToken(string value) { int len = value.Length; for (int i = 0; i < len; i++) { char c = value[i]; if (c < 0x20 || c >= 0x7f || s_tspecials.IndexOf(c) != -1) return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; namespace System.Data.ProviderBase { internal abstract class DbReferenceCollection { private struct CollectionEntry { private int _tag; // information about the reference private WeakReference _weak; // the reference itself. public void NewTarget(int tag, object target) { Debug.Assert(!HasTarget, "Entry already has a valid target"); Debug.Assert(tag != 0, "Bad tag"); Debug.Assert(target != null, "Invalid target"); if (_weak == null) { _weak = new WeakReference(target, false); } else { _weak.Target = target; } _tag = tag; } public void RemoveTarget() { _tag = 0; } public bool HasTarget { get { return ((_tag != 0) && (_weak.IsAlive)); } } public int Tag { get { return _tag; } } public object Target { get { return (_tag == 0 ? null : _weak.Target); } } } private const int LockPollTime = 100; // Time to wait (in ms) between attempting to get the _itemLock private const int DefaultCollectionSize = 20; // Default size for the collection, and the amount to grow everytime the collection is full private CollectionEntry[] _items; // The collection of items we are keeping track of private readonly object _itemLock; // Used to synchronize access to the _items collection private int _optimisticCount; // (#ItemsAdded - #ItemsRemoved) - This estimates the number of items that we *should* have (but doesn't take into account item targets being GC'd) private int _lastItemIndex; // Location of the last item in _items private volatile bool _isNotifying; // Indicates that the collection is currently being notified (and, therefore, about to be cleared) protected DbReferenceCollection() { _items = new CollectionEntry[DefaultCollectionSize]; _itemLock = new object(); _optimisticCount = 0; _lastItemIndex = 0; } public abstract void Add(object value, int tag); protected void AddItem(object value, int tag) { Debug.Assert(null != value && 0 != tag, "AddItem with null value or 0 tag"); bool itemAdded = false; lock (_itemLock) { // Try to find a free spot for (int i = 0; i <= _lastItemIndex; ++i) { if (_items[i].Tag == 0) { _items[i].NewTarget(tag, value); Debug.Assert(_items[i].HasTarget, "missing expected target"); itemAdded = true; break; } } // No free spots, can we just add on to the end? if ((!itemAdded) && (_lastItemIndex + 1 < _items.Length)) { _lastItemIndex++; _items[_lastItemIndex].NewTarget(tag, value); itemAdded = true; } // If no free spots and no space at the end, try to find a dead item if (!itemAdded) { for (int i = 0; i <= _lastItemIndex; ++i) { if (!_items[i].HasTarget) { _items[i].NewTarget(tag, value); Debug.Assert(_items[i].HasTarget, "missing expected target"); itemAdded = true; break; } } } // If nothing was free, then resize and add to the end if (!itemAdded) { Array.Resize<CollectionEntry>(ref _items, _items.Length * 2); _lastItemIndex++; _items[_lastItemIndex].NewTarget(tag, value); } _optimisticCount++; } } internal T FindItem<T>(int tag, Func<T, bool> filterMethod) where T : class { bool lockObtained = false; try { TryEnterItemLock(ref lockObtained); if (lockObtained) { if (_optimisticCount > 0) { // Loop through the items for (int counter = 0; counter <= _lastItemIndex; counter++) { // Check tag (should be easiest and quickest) if (_items[counter].Tag == tag) { // NOTE: Check if the returned value is null twice may seem wasteful, but this if for performance // Since checking for null twice is cheaper than calling both HasTarget and Target OR always attempting to typecast object value = _items[counter].Target; if (value != null) { // Make sure the item has the correct type and passes the filtering T tempItem = value as T; if ((tempItem != null) && (filterMethod(tempItem))) { return tempItem; } } } } } } } finally { ExitItemLockIfNeeded(lockObtained); } // If we got to here, then no item was found, so return null return null; } public void Notify(int message) { bool lockObtained = false; try { TryEnterItemLock(ref lockObtained); if (lockObtained) { try { _isNotifying = true; // Loop through each live item and notify it if (_optimisticCount > 0) { for (int index = 0; index <= _lastItemIndex; ++index) { object value = _items[index].Target; // checks tag & gets target if (null != value) { NotifyItem(message, _items[index].Tag, value); _items[index].RemoveTarget(); } Debug.Assert(!_items[index].HasTarget, "Unexpected target after notifying"); } _optimisticCount = 0; } // Shrink collection (if needed) if (_items.Length > 100) { _lastItemIndex = 0; _items = new CollectionEntry[DefaultCollectionSize]; } } finally { _isNotifying = false; } } } finally { ExitItemLockIfNeeded(lockObtained); } } protected abstract void NotifyItem(int message, int tag, object value); public abstract void Remove(object value); protected void RemoveItem(object value) { Debug.Assert(null != value, "RemoveItem with null"); bool lockObtained = false; try { TryEnterItemLock(ref lockObtained); if (lockObtained) { // Find the value, and then remove the target from our collection if (_optimisticCount > 0) { for (int index = 0; index <= _lastItemIndex; ++index) { if (value == _items[index].Target) { // checks tag & gets target _items[index].RemoveTarget(); _optimisticCount--; break; } } } } } finally { ExitItemLockIfNeeded(lockObtained); } } // This is polling lock that will abandon getting the lock if _isNotifying is set to true private void TryEnterItemLock(ref bool lockObtained) { // Assume that we couldn't take the lock lockObtained = false; // Keep trying to take the lock until either we've taken it, or the collection is being notified while ((!_isNotifying) && (!lockObtained)) { Monitor.TryEnter(_itemLock, LockPollTime, ref lockObtained); } } private void ExitItemLockIfNeeded(bool lockObtained) { if (lockObtained) { Monitor.Exit(_itemLock); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Dictionary operations. /// </summary> public partial class Dictionary : IServiceOperations<AutoRestComplexTestService>, IDictionary { /// <summary> /// Initializes a new instance of the Dictionary class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Dictionary(AutoRestComplexTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types with dictionary property /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DictionaryWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with dictionary property /// </summary> /// <param name='defaultProgram'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { DictionaryWrapper complexBody = new DictionaryWrapper(); if (defaultProgram != null) { complexBody.DefaultProgram = defaultProgram; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with dictionary property which is empty /// </summary> /// <param name='defaultProgram'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { DictionaryWrapper complexBody = new DictionaryWrapper(); if (defaultProgram != null) { complexBody.DefaultProgram = defaultProgram; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property which is null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/null").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property while server doesn't provide a /// response payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/notprovided").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeX509ChainHandle : System.Runtime.InteropServices.SafeHandle { internal SafeX509ChainHandle() : base(default(System.IntPtr), default(bool)) { } protected override bool ReleaseHandle() { return default(bool); } } } namespace System.Security.Cryptography.X509Certificates { [System.FlagsAttribute] public enum OpenFlags { IncludeArchived = 8, MaxAllowed = 2, OpenExistingOnly = 4, ReadOnly = 0, ReadWrite = 1, } public sealed partial class PublicKey { public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { } public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { return default(System.Security.Cryptography.AsnEncodedData); } } public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { return default(System.Security.Cryptography.AsnEncodedData); } } public System.Security.Cryptography.Oid Oid { get { return default(System.Security.Cryptography.Oid); } } } public static partial class RSACertificateExtensions { public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.RSA); } public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.RSA); } } public enum StoreLocation { CurrentUser = 1, LocalMachine = 2, } public enum StoreName { AddressBook = 1, AuthRoot = 2, CertificateAuthority = 3, Disallowed = 4, My = 5, Root = 6, TrustedPeople = 7, TrustedPublisher = 8, } public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { } public X500DistinguishedName(string distinguishedName) { } public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { } public string Name { get { return default(string); } } public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { return default(string); } public override string Format(bool multiLine) { return default(string); } } [System.FlagsAttribute] public enum X500DistinguishedNameFlags { DoNotUsePlusSign = 32, DoNotUseQuotes = 64, ForceUTF8Encoding = 16384, None = 0, Reversed = 1, UseCommas = 128, UseNewLines = 256, UseSemicolons = 16, UseT61Encoding = 8192, UseUTF8Encoding = 4096, } public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509BasicConstraintsExtension() { } public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { } public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { } public bool CertificateAuthority { get { return default(bool); } } public bool HasPathLengthConstraint { get { return default(bool); } } public int PathLengthConstraint { get { return default(int); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Certificate : System.IDisposable { public X509Certificate() { } public X509Certificate(byte[] data) { } public X509Certificate(byte[] rawData, string password) { } public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } [System.Security.SecurityCriticalAttribute] public X509Certificate(System.IntPtr handle) { } public X509Certificate(string fileName) { } public X509Certificate(string fileName, string password) { } public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public System.IntPtr Handle {[System.Security.SecurityCriticalAttribute]get { return default(System.IntPtr); } } public string Issuer { get { return default(string); } } public string Subject { get { return default(string); } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override bool Equals(object obj) { return default(bool); } public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { return default(bool); } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { return default(byte[]); } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { return default(byte[]); } public virtual byte[] GetCertHash() { return default(byte[]); } public virtual string GetFormat() { return default(string); } public override int GetHashCode() { return default(int); } public virtual string GetKeyAlgorithm() { return default(string); } public virtual byte[] GetKeyAlgorithmParameters() { return default(byte[]); } public virtual string GetKeyAlgorithmParametersString() { return default(string); } public virtual byte[] GetPublicKey() { return default(byte[]); } public virtual byte[] GetSerialNumber() { return default(byte[]); } public override string ToString() { return default(string); } public virtual string ToString(bool fVerbose) { return default(string); } } public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate { public X509Certificate2() { } public X509Certificate2(byte[] rawData) { } public X509Certificate2(byte[] rawData, string password) { } public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(System.IntPtr handle) { } public X509Certificate2(string fileName) { } public X509Certificate2(string fileName, string password) { } public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public bool Archived { get { return default(bool); } set { } } public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { return default(System.Security.Cryptography.X509Certificates.X509ExtensionCollection); } } public string FriendlyName { get { return default(string); } set { } } public bool HasPrivateKey { get { return default(bool); } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { return default(System.Security.Cryptography.X509Certificates.X500DistinguishedName); } } public System.DateTime NotAfter { get { return default(System.DateTime); } } public System.DateTime NotBefore { get { return default(System.DateTime); } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { return default(System.Security.Cryptography.X509Certificates.PublicKey); } } public byte[] RawData { get { return default(byte[]); } } public string SerialNumber { get { return default(string); } } public System.Security.Cryptography.Oid SignatureAlgorithm { get { return default(System.Security.Cryptography.Oid); } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { return default(System.Security.Cryptography.X509Certificates.X500DistinguishedName); } } public string Thumbprint { get { return default(string); } } public int Version { get { return default(int); } } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { return default(System.Security.Cryptography.X509Certificates.X509ContentType); } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { return default(System.Security.Cryptography.X509Certificates.X509ContentType); } public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { return default(string); } public override string ToString() { return default(string); } public override string ToString(bool verbose) { return default(string); } } public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(int); } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(bool); } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { return default(byte[]); } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { return default(byte[]); } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator); } public void Import(byte[] rawData) { } public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Import(string fileName) { } public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator { internal X509Certificate2Enumerator() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } public partial class X509CertificateCollection { public X509CertificateCollection() { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(int); } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(bool); } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator); } public override int GetHashCode() { return default(int); } public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(int); } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { } public partial class X509CertificateEnumerator : System.Collections.IEnumerator { public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { } public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public partial class X509Chain : System.IDisposable { public X509Chain() { } public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElementCollection); } } public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { return default(System.Security.Cryptography.X509Certificates.X509ChainPolicy); } set { } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatus[]); } } public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { return default(Microsoft.Win32.SafeHandles.SafeX509ChainHandle); } } public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(bool); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public partial class X509ChainElement { internal X509ChainElement() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatus[]); } } public string Information { get { return default(string); } } } public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal X509ChainElementCollection() { } public int Count { get { return default(int); } } public bool IsSynchronized { get { return default(bool); } } public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElement); } } public object SyncRoot { get { return default(object); } } public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator { internal X509ChainElementEnumerator() { } public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElement); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } } public sealed partial class X509ChainPolicy { public X509ChainPolicy() { } public System.Security.Cryptography.OidCollection ApplicationPolicy { get { return default(System.Security.Cryptography.OidCollection); } } public System.Security.Cryptography.OidCollection CertificatePolicy { get { return default(System.Security.Cryptography.OidCollection); } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } } public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { return default(System.Security.Cryptography.X509Certificates.X509RevocationFlag); } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { return default(System.Security.Cryptography.X509Certificates.X509RevocationMode); } set { } } public System.TimeSpan UrlRetrievalTimeout { get { return default(System.TimeSpan); } set { } } public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { return default(System.Security.Cryptography.X509Certificates.X509VerificationFlags); } set { } } public System.DateTime VerificationTime { get { return default(System.DateTime); } set { } } public void Reset() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509ChainStatus { public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatusFlags); } set { } } public string StatusInformation { get { return default(string); } set { } } } [System.FlagsAttribute] public enum X509ChainStatusFlags { CtlNotSignatureValid = 262144, CtlNotTimeValid = 131072, CtlNotValidForUsage = 524288, Cyclic = 128, HasExcludedNameConstraint = 32768, HasNotDefinedNameConstraint = 8192, HasNotPermittedNameConstraint = 16384, HasNotSupportedNameConstraint = 4096, InvalidBasicConstraints = 1024, InvalidExtension = 256, InvalidNameConstraints = 2048, InvalidPolicyConstraints = 512, NoError = 0, NoIssuanceChainPolicy = 33554432, NotSignatureValid = 8, NotTimeNested = 2, NotTimeValid = 1, NotValidForUsage = 16, OfflineRevocation = 16777216, PartialChain = 65536, RevocationStatusUnknown = 64, Revoked = 4, UntrustedRoot = 32, } public enum X509ContentType { Authenticode = 6, Cert = 1, Pfx = 3, Pkcs12 = 3, Pkcs7 = 5, SerializedCert = 2, SerializedStore = 4, Unknown = 0, } public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509EnhancedKeyUsageExtension() { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { } public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { return default(System.Security.Cryptography.OidCollection); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Extension : System.Security.Cryptography.AsnEncodedData { protected X509Extension() { } public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { } public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { } public X509Extension(string oid, byte[] rawData, bool critical) { } public bool Critical { get { return default(bool); } set { } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable { public X509ExtensionCollection() { } public int Count { get { return default(int); } } public bool IsSynchronized { get { return default(bool); } } public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } } public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } } public object SyncRoot { get { return default(object); } } public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { return default(int); } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator { internal X509ExtensionEnumerator() { } public System.Security.Cryptography.X509Certificates.X509Extension Current { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } } public enum X509FindType { FindByApplicationPolicy = 10, FindByCertificatePolicy = 11, FindByExtension = 12, FindByIssuerDistinguishedName = 4, FindByIssuerName = 3, FindByKeyUsage = 13, FindBySerialNumber = 5, FindBySubjectDistinguishedName = 2, FindBySubjectKeyIdentifier = 14, FindBySubjectName = 1, FindByTemplateName = 9, FindByThumbprint = 0, FindByTimeExpired = 8, FindByTimeNotYetValid = 7, FindByTimeValid = 6, } [System.FlagsAttribute] public enum X509KeyStorageFlags { DefaultKeySet = 0, Exportable = 4, MachineKeySet = 2, PersistKeySet = 16, UserKeySet = 1, UserProtected = 8, } public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509KeyUsageExtension() { } public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { } public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { } public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { return default(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } [System.FlagsAttribute] public enum X509KeyUsageFlags { CrlSign = 2, DataEncipherment = 16, DecipherOnly = 32768, DigitalSignature = 128, EncipherOnly = 1, KeyAgreement = 8, KeyCertSign = 4, KeyEncipherment = 32, None = 0, NonRepudiation = 64, } public enum X509NameType { DnsFromAlternativeName = 4, DnsName = 3, EmailName = 1, SimpleName = 0, UpnName = 2, UrlName = 5, } public enum X509RevocationFlag { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } public enum X509RevocationMode { NoCheck = 0, Offline = 2, Online = 1, } public sealed partial class X509Store : System.IDisposable { public X509Store() { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } } public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { return default(System.Security.Cryptography.X509Certificates.StoreLocation); } } public string Name { get { return default(string); } } public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Dispose() { } public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } } public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509SubjectKeyIdentifierExtension() { } public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { } public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { } public string SubjectKeyIdentifier { get { return default(string); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public enum X509SubjectKeyIdentifierHashAlgorithm { CapiSha1 = 2, Sha1 = 0, ShortSha1 = 1, } [System.FlagsAttribute] public enum X509VerificationFlags { AllFlags = 4095, AllowUnknownCertificateAuthority = 16, IgnoreCertificateAuthorityRevocationUnknown = 1024, IgnoreCtlNotTimeValid = 2, IgnoreCtlSignerRevocationUnknown = 512, IgnoreEndRevocationUnknown = 256, IgnoreInvalidBasicConstraints = 8, IgnoreInvalidName = 64, IgnoreInvalidPolicy = 128, IgnoreNotTimeNested = 4, IgnoreNotTimeValid = 1, IgnoreRootRevocationUnknown = 2048, IgnoreWrongUsage = 32, NoFlag = 0, } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Services.InventoryService { /// <summary> /// The Inventory service reference implementation /// </summary> public class InventoryService : InventoryServiceBase, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public InventoryService(IConfigSource config) : base(config) { m_log.Debug("[INVENTORY SERVICE]: Initialized."); } #region IInventoryServices methods public string Host { get { return "default"; } } public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { m_log.DebugFormat("[INVENTORY SERVICE]: Getting inventory skeleton for {0}", userId); InventoryFolderBase rootFolder = GetRootFolder(userId); // Agent has no inventory structure yet. if (null == rootFolder) { return null; } List<InventoryFolderBase> userFolders = new List<InventoryFolderBase>(); userFolders.Add(rootFolder); IList<InventoryFolderBase> folders = m_Database.getFolderHierarchy(rootFolder.ID); userFolders.AddRange(folders); // m_log.DebugFormat("[INVENTORY SERVICE]: Got folder {0} {1}", folder.name, folder.folderID); return userFolders; } public virtual bool HasInventoryForUser(UUID userID) { return false; } // See IInventoryServices public virtual InventoryFolderBase GetRootFolder(UUID userID) { //m_log.DebugFormat("[INVENTORY SERVICE]: Getting root folder for {0}", userID); // Retrieve the first root folder we get from the DB. InventoryFolderBase rootFolder = m_Database.getUserRootFolder(userID); if (rootFolder != null) return rootFolder; // Return nothing if the plugin was unable to supply a root folder return null; } // See IInventoryServices public bool CreateUserInventory(UUID user) { InventoryFolderBase existingRootFolder; try { existingRootFolder = GetRootFolder(user); } catch (Exception e) { // Munch the exception, it has already been reported // return false; } if (null != existingRootFolder) { m_log.WarnFormat( "[INVENTORY SERVICE]: Did not create a new inventory for user {0} since they already have " + "a root inventory folder with id {1}", user, existingRootFolder.ID); } else { UsersInventory inven = new UsersInventory(); inven.CreateNewInventorySet(user); AddNewInventorySet(inven); return true; } return false; } // See IInventoryServices /// <summary> /// Return a user's entire inventory synchronously /// </summary> /// <param name="rawUserID"></param> /// <returns>The user's inventory. If an inventory cannot be found then an empty collection is returned.</returns> public InventoryCollection GetUserInventory(UUID userID) { m_log.InfoFormat("[INVENTORY SERVICE]: Processing request for inventory of {0}", userID); // Uncomment me to simulate a slow responding inventory server //Thread.Sleep(16000); InventoryCollection invCollection = new InventoryCollection(); List<InventoryFolderBase> allFolders = GetInventorySkeleton(userID); if (null == allFolders) { m_log.WarnFormat("[INVENTORY SERVICE]: No inventory found for user {0}", userID); return invCollection; } List<InventoryItemBase> allItems = new List<InventoryItemBase>(); foreach (InventoryFolderBase folder in allFolders) { List<InventoryItemBase> items = GetFolderItems(userID, folder.ID); if (items != null) { allItems.InsertRange(0, items); } } invCollection.UserID = userID; invCollection.Folders = allFolders; invCollection.Items = allItems; // foreach (InventoryFolderBase folder in invCollection.Folders) // { // m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back folder {0} {1}", folder.Name, folder.ID); // } // // foreach (InventoryItemBase item in invCollection.Items) // { // m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back item {0} {1}, folder {2}", item.Name, item.ID, item.Folder); // } m_log.InfoFormat( "[INVENTORY SERVICE]: Sending back inventory response to user {0} containing {1} folders and {2} items", invCollection.UserID, invCollection.Folders.Count, invCollection.Items.Count); return invCollection; } /// <summary> /// Asynchronous inventory fetch. /// </summary> /// <param name="userID"></param> /// <param name="callback"></param> public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { m_log.InfoFormat("[INVENTORY SERVICE]: Requesting inventory for user {0}", userID); List<InventoryFolderImpl> folders = new List<InventoryFolderImpl>(); List<InventoryItemBase> items = new List<InventoryItemBase>(); List<InventoryFolderBase> skeletonFolders = GetInventorySkeleton(userID); if (skeletonFolders != null) { InventoryFolderImpl rootFolder = null; // Need to retrieve the root folder on the first pass foreach (InventoryFolderBase folder in skeletonFolders) { if (folder.ParentID == UUID.Zero) { rootFolder = new InventoryFolderImpl(folder); folders.Add(rootFolder); items.AddRange(GetFolderItems(userID, rootFolder.ID)); break; // Only 1 root folder per user } } if (rootFolder != null) { foreach (InventoryFolderBase folder in skeletonFolders) { if (folder.ID != rootFolder.ID) { folders.Add(new InventoryFolderImpl(folder)); items.AddRange(GetFolderItems(userID, folder.ID)); } } } m_log.InfoFormat( "[INVENTORY SERVICE]: Received inventory response for user {0} containing {1} folders and {2} items", userID, folders.Count, items.Count); } else { m_log.WarnFormat("[INVENTORY SERVICE]: User {0} inventory not available", userID); } Util.FireAndForget(delegate { callback(folders, items); }); } public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { // Uncomment me to simulate a slow responding inventory server //Thread.Sleep(16000); InventoryCollection invCollection = new InventoryCollection(); List<InventoryItemBase> items = GetFolderItems(userID, folderID); List<InventoryFolderBase> folders = RequestSubFolders(folderID); invCollection.UserID = userID; invCollection.Folders = folders; invCollection.Items = items; m_log.DebugFormat("[INVENTORY SERVICE]: Found {0} items and {1} folders in folder {2}", items.Count, folders.Count, folderID); return invCollection; } public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { InventoryFolderBase root = m_Database.getUserRootFolder(userID); if (root != null) { List<InventoryFolderBase> folders = RequestSubFolders(root.ID); foreach (InventoryFolderBase folder in folders) { if (folder.Type == (short)type) return folder; } } // we didn't find any folder of that type. Return the root folder // hopefully the root folder is not null. If it is, too bad return root; } public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID) { InventoryFolderBase root = GetRootFolder(userID); if (root != null) { InventoryCollection content = GetFolderContent(userID, root.ID); if (content != null) { Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>(); foreach (InventoryFolderBase folder in content.Folders) { if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown)) folders[(AssetType)folder.Type] = folder; } return folders; } } m_log.WarnFormat("[INVENTORY SERVICE]: System folders for {0} not found", userID); return new Dictionary<AssetType, InventoryFolderBase>(); } public List<InventoryItemBase> GetActiveGestures(UUID userId) { List<InventoryItemBase> activeGestures = new List<InventoryItemBase>(); activeGestures.AddRange(m_Database.fetchActiveGestures(userId)); return activeGestures; } #endregion #region Methods used by GridInventoryService public List<InventoryFolderBase> RequestSubFolders(UUID parentFolderID) { List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>(); inventoryList.AddRange(m_Database.getInventoryFolders(parentFolderID)); return inventoryList; } public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { List<InventoryItemBase> itemsList = new List<InventoryItemBase>(); itemsList.AddRange(m_Database.getInventoryInFolder(folderID)); return itemsList; } #endregion // See IInventoryServices public virtual bool AddFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Adding folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); m_Database.addInventoryFolder(folder); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool UpdateFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Updating folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); m_Database.updateInventoryFolder(folder); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool MoveFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Moving folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); m_Database.moveInventoryFolder(folder); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool AddItem(InventoryItemBase item) { m_log.DebugFormat( "[INVENTORY SERVICE]: Adding item {0} {1} to folder {2}", item.Name, item.ID, item.Folder); m_Database.addInventoryItem(item); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool UpdateItem(InventoryItemBase item) { m_log.InfoFormat( "[INVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder); m_Database.updateInventoryItem(item); // FIXME: Should return false on failure return true; } public virtual bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { m_log.InfoFormat( "[INVENTORY SERVICE]: Moving {0} items from user {1}", items.Count, ownerID); InventoryItemBase itm = null; foreach (InventoryItemBase item in items) { itm = GetInventoryItem(item.ID); itm.Folder = item.Folder; if ((item.Name != null) && !item.Name.Equals(string.Empty)) itm.Name = item.Name; m_Database.updateInventoryItem(itm); } return true; } // See IInventoryServices public virtual bool DeleteItems(UUID owner, List<UUID> itemIDs) { m_log.InfoFormat( "[INVENTORY SERVICE]: Deleting {0} items from user {1}", itemIDs.Count, owner); // uhh..... foreach (UUID uuid in itemIDs) m_Database.deleteInventoryItem(uuid); // FIXME: Should return false on failure return true; } public virtual InventoryItemBase GetItem(InventoryItemBase item) { InventoryItemBase result = m_Database.getInventoryItem(item.ID); if (result != null) return result; m_log.DebugFormat("[INVENTORY SERVICE]: GetItem failed to find item {0}", item.ID); return null; } public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder) { InventoryFolderBase result = m_Database.getInventoryFolder(folder.ID); if (result != null) return result; m_log.DebugFormat("[INVENTORY SERVICE]: GetFolder failed to find folder {0}", folder.ID); return null; } public virtual bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) { m_log.InfoFormat("[INVENTORY SERVICE]: Deleting {0} folders from user {1}", folderIDs.Count, ownerID); foreach (UUID id in folderIDs) { InventoryFolderBase folder = new InventoryFolderBase(id, ownerID); PurgeFolder(folder); m_Database.deleteInventoryFolder(id); } return true; } /// <summary> /// Purge a folder of all items items and subfolders. /// /// FIXME: Really nasty in a sense, because we have to query the database to get information we may /// already know... Needs heavy refactoring. /// </summary> /// <param name="folder"></param> public virtual bool PurgeFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Purging folder {0} {1} of its contents", folder.Name, folder.ID); List<InventoryFolderBase> subFolders = RequestSubFolders(folder.ID); foreach (InventoryFolderBase subFolder in subFolders) { // m_log.DebugFormat("[INVENTORY SERVICE]: Deleting folder {0} {1}", subFolder.Name, subFolder.ID); m_Database.deleteInventoryFolder(subFolder.ID); } List<InventoryItemBase> items = GetFolderItems(folder.Owner, folder.ID); List<UUID> uuids = new List<UUID>(); foreach (InventoryItemBase item in items) { uuids.Add(item.ID); } DeleteItems(folder.Owner, uuids); // FIXME: Should return false on failure return true; } private void AddNewInventorySet(UsersInventory inventory) { foreach (InventoryFolderBase folder in inventory.Folders.Values) { AddFolder(folder); } } public InventoryItemBase GetInventoryItem(UUID itemID) { InventoryItemBase item = m_Database.getInventoryItem(itemID); if (item != null) return item; return null; } public int GetAssetPermissions(UUID userID, UUID assetID) { InventoryFolderBase parent = GetRootFolder(userID); return FindAssetPerms(parent, assetID); } private int FindAssetPerms(InventoryFolderBase folder, UUID assetID) { InventoryCollection contents = GetFolderContent(folder.Owner, folder.ID); int perms = 0; foreach (InventoryItemBase item in contents.Items) { if (item.AssetID == assetID) perms = (int)item.CurrentPermissions | perms; } foreach (InventoryFolderBase subfolder in contents.Folders) perms = perms | FindAssetPerms(subfolder, assetID); return perms; } /// <summary> /// Used to create a new user inventory. /// </summary> private class UsersInventory { public Dictionary<UUID, InventoryFolderBase> Folders = new Dictionary<UUID, InventoryFolderBase>(); public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>(); public virtual void CreateNewInventorySet(UUID user) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ParentID = UUID.Zero; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "My Inventory"; folder.Type = (short)AssetType.Folder; folder.Version = 1; Folders.Add(folder.ID, folder); UUID rootFolder = folder.ID; folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Animations"; folder.Type = (short)AssetType.Animation; folder.Version = 1; Folders.Add(folder.ID, folder); // realXtend avatar to webdav folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Avatar"; folder.Type = (short)AssetType.Bodypart; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Body Parts"; folder.Type = (short)AssetType.Bodypart; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Calling Cards"; folder.Type = (short)AssetType.CallingCard; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Clothing"; folder.Type = (short)AssetType.Clothing; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Gestures"; folder.Type = (short)AssetType.Gesture; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Landmarks"; folder.Type = (short)AssetType.Landmark; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Lost And Found"; folder.Type = (short)AssetType.LostAndFoundFolder; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Notecards"; folder.Type = (short)AssetType.Notecard; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Objects"; folder.Type = (short)AssetType.Object; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Photo Album"; folder.Type = (short)AssetType.SnapshotFolder; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Scripts"; folder.Type = (short)AssetType.LSLText; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Sounds"; folder.Type = (short)AssetType.Sound; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Textures"; folder.Type = (short)AssetType.Texture; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Trash"; folder.Type = (short)AssetType.TrashFolder; folder.Version = 1; Folders.Add(folder.ID, folder); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/hold_adjustment.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Supply { /// <summary>Holder for reflection information generated from supply/hold_adjustment.proto</summary> public static partial class HoldAdjustmentReflection { #region Descriptor /// <summary>File descriptor for supply/hold_adjustment.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static HoldAdjustmentReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChxzdXBwbHkvaG9sZF9hZGp1c3RtZW50LnByb3RvEhJob2xtcy50eXBlcy5z", "dXBwbHkaK3N1cHBseS9yb29tX3R5cGVzL3Jvb21fdHlwZV9pbmRpY2F0b3Iu", "cHJvdG8aHXByaW1pdGl2ZS9wYl9sb2NhbF9kYXRlLnByb3RvIqIBCg5Ib2xk", "QWRqdXN0bWVudBJDCglyb29tX3R5cGUYASABKAsyMC5ob2xtcy50eXBlcy5z", "dXBwbHkucm9vbV90eXBlcy5Sb29tVHlwZUluZGljYXRvchIwCgRkYXRlGAIg", "ASgLMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlBiTG9jYWxEYXRlEhkKEWFk", "anVzdG1lbnRfYW1vdW50GAMgASgFQh1aBnN1cHBseaoCEkhPTE1TLlR5cGVz", "LlN1cHBseWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.HoldAdjustment), global::HOLMS.Types.Supply.HoldAdjustment.Parser, new[]{ "RoomType", "Date", "AdjustmentAmount" }, null, null, null) })); } #endregion } #region Messages public sealed partial class HoldAdjustment : pb::IMessage<HoldAdjustment> { private static readonly pb::MessageParser<HoldAdjustment> _parser = new pb::MessageParser<HoldAdjustment>(() => new HoldAdjustment()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HoldAdjustment> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.HoldAdjustmentReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HoldAdjustment() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HoldAdjustment(HoldAdjustment other) : this() { RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; Date = other.date_ != null ? other.Date.Clone() : null; adjustmentAmount_ = other.adjustmentAmount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HoldAdjustment Clone() { return new HoldAdjustment(this); } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 1; private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomType_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomType { get { return roomType_; } set { roomType_ = value; } } /// <summary>Field number for the "date" field.</summary> public const int DateFieldNumber = 2; private global::HOLMS.Types.Primitive.PbLocalDate date_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Date { get { return date_; } set { date_ = value; } } /// <summary>Field number for the "adjustment_amount" field.</summary> public const int AdjustmentAmountFieldNumber = 3; private int adjustmentAmount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int AdjustmentAmount { get { return adjustmentAmount_; } set { adjustmentAmount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HoldAdjustment); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HoldAdjustment other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(RoomType, other.RoomType)) return false; if (!object.Equals(Date, other.Date)) return false; if (AdjustmentAmount != other.AdjustmentAmount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (roomType_ != null) hash ^= RoomType.GetHashCode(); if (date_ != null) hash ^= Date.GetHashCode(); if (AdjustmentAmount != 0) hash ^= AdjustmentAmount.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (roomType_ != null) { output.WriteRawTag(10); output.WriteMessage(RoomType); } if (date_ != null) { output.WriteRawTag(18); output.WriteMessage(Date); } if (AdjustmentAmount != 0) { output.WriteRawTag(24); output.WriteInt32(AdjustmentAmount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (roomType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType); } if (date_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date); } if (AdjustmentAmount != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(AdjustmentAmount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HoldAdjustment other) { if (other == null) { return; } if (other.roomType_ != null) { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } RoomType.MergeFrom(other.RoomType); } if (other.date_ != null) { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Date.MergeFrom(other.Date); } if (other.AdjustmentAmount != 0) { AdjustmentAmount = other.AdjustmentAmount; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } input.ReadMessage(roomType_); break; } case 18: { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(date_); break; } case 24: { AdjustmentAmount = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmGRVPromotion : System.Windows.Forms.Form { private ADODB.Recordset withEventsField_adoPrimaryRS; public ADODB.Recordset adoPrimaryRS { get { return withEventsField_adoPrimaryRS; } set { if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord; } withEventsField_adoPrimaryRS = value; if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord; } } } bool mbChangedByCode; int mvBookMark; bool mbEditFlag; bool mbAddNewFlag; bool mbDataChanged; int gID; int p_Prom; bool p_Prom1; bool mbAddNewFlagID; List<TextBox> txtFields = new List<TextBox>(); List<DateTimePicker> DTFields = new List<DateTimePicker>(); List<CheckBox> chkFields = new List<CheckBox>(); private void loadLanguage() { //frmPromotion = No Code [Edit Promotion Details] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmPromotion.Caption = rsLang("LanguageLayoutLnk_Description"): frmPromotion.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074; //Undo|Checked if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085; //Print|Checked if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010; //General|Checked if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1139 'Promotion Name|Checked //If rsLang.RecordCount Then lblLabels(38).Caption = rsLang("LanguageLayoutLnk_Description"): lblLabels(38).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1140; //Start Date|Checked if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1141; //End Date|Checked if (modRecordSet.rsLang.RecordCount){_lblLabels_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1142; //From Time|Checked if (modRecordSet.rsLang.RecordCount){Label1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1143; //To Time|Checked if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2463; //Disabled|Checked if (modRecordSet.rsLang.RecordCount){_chkFields_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1145; //Apply only to POS channel|Checked if (modRecordSet.rsLang.RecordCount){_chkFields_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1146; //Only for Specific Time|Checked if (modRecordSet.rsLang.RecordCount){_chkFields_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1147; //Add|Checked if (modRecordSet.rsLang.RecordCount){cmdAdd.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdAdd.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1148; //Delete|Checked if (modRecordSet.rsLang.RecordCount){cmdDelete.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdDelete.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmGRVPromotion.HelpContextID was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void buildDataControls() { // doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name" } private void doDataControl(ref System.Windows.Forms.Control dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField) { //Dim rs As ADODB.Recordset //rs = getRS(sql) //'UPGRADE_WARNING: Couldn't resolve default property of object dataControl.RowSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.RowSource = rs //'UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //dataControl.DataSource = adoPrimaryRS //UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //dataControl.DataField = DataField //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.boundColumn = boundColumn //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.listField = listField } public void loadItem(ref int id) { System.Windows.Forms.TextBox oText = null; DateTimePicker oDate = null; System.Windows.Forms.CheckBox oCheck = null; mbAddNewFlagID = false; // ERROR: Not supported in C#: OnErrorStatement if (id) { p_Prom = id; adoPrimaryRS = modRecordSet.getRS(ref "select GRVPromotion.* from GRVPromotion WHERE PromotionID = " + id); } else { adoPrimaryRS = modRecordSet.getRS(ref "select * from GRVPromotion"); adoPrimaryRS.AddNew(); this.Text = this.Text + " [New record]"; mbAddNewFlag = true; mbAddNewFlagID = true; } setup(); foreach (TextBox oText_loopVariable in txtFields) { oText = oText_loopVariable; oText.DataBindings.Add(adoPrimaryRS); oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize; } foreach (DateTimePicker oDate_loopVariable in DTFields) { oDate = oDate_loopVariable; oDate.DataBindings.Add(adoPrimaryRS); } //adoPrimaryRS("Promotion_SpeTime") //Bind the check boxes to the data provider foreach (CheckBox oCheck_loopVariable in chkFields) { oCheck = oCheck_loopVariable; oCheck.DataBindings.Add(adoPrimaryRS); } buildDataControls(); mbDataChanged = false; loadItems(); loadLanguage(); ShowDialog(); } private void setup() { } private void cmdAdd_Click(System.Object eventSender, System.EventArgs eventArgs) { int lID = 0; ADODB.Recordset rs = default(ADODB.Recordset); if (mbAddNewFlagID == true) { if (string.IsNullOrEmpty(txtFields[0].Text)) { Interaction.MsgBox("Deal name is invalid."); txtFields[0].Focus(); return; } System.Windows.Forms.Application.DoEvents(); if (update_Renamed()) { p_Prom = adoPrimaryRS.Fields("PromotionID").Value; if (chkFields[1].CheckState == 0) { modRecordSet.cnnDB.Execute("UPDATE GRVPromotion SET Promotion_StartDate = #" + DTFields[0].Value + "#, Promotion_EndDate = #" + DTFields[1].Value + "#, Promotion_StartTime = #" + DTFields[2].Value + "# ,Promotion_EndTime =#" + DTFields[3].Value + "# WHERE PromotionID = " + p_Prom + ";"); } } else { return; } } lID = My.MyProject.Forms.frmStockList.getItem(); string[,] DateArr = null; System.DateTime xDate = default(System.DateTime); System.DateTime yDate = default(System.DateTime); short xInt = 0; if (lID != 0) { // ERROR: Not supported in C#: OnErrorStatement xInt = (DateAndTime.DateDiff(Microsoft.VisualBasic.DateInterval.Day, _DTFields_0.Value, _DTFields_1.Value) == 0 ? 1 : DateAndTime.DateDiff(Microsoft.VisualBasic.DateInterval.Day, _DTFields_0.Value, _DTFields_1.Value)); DateArr = new string[xInt + 1, 2]; xInt = 0; //For xDate = _DTFields_0.Value.Date To _DTFields_1.Value.Date while (_DTFields_0.Value.Date < _DTFields_1.Value.Date) { if (xDate == _DTFields_0.Value) { DateArr[xInt, 0] = Convert.ToString(xDate); DateArr[xInt, 1] = "S"; } else if (xDate == _DTFields_1.Value) { DateArr[xInt, 0] = Convert.ToString(xDate); DateArr[xInt, 1] = "E"; } else { DateArr[xInt, 0] = Convert.ToString(xDate); DateArr[xInt, 1] = "A"; } xInt = xInt + 1; } //Next rs = modRecordSet.getRS(ref "SELECT GRVPromotion.Promotion_Name, GRVPromotionItem.PromotionItem_StockItemID, GRVPromotionItem.PromotionItem_Price, GRVPromotion.Promotion_StartDate, GRVPromotion.Promotion_EndDate FROM GRVPromotion INNER JOIN GRVPromotionItem ON GRVPromotion.PromotionID = GRVPromotionItem.PromotionItem_PromotionID WHERE (((GRVPromotionItem.PromotionItem_StockItemID)=" + lID + "));"); if (rs.RecordCount > 0) { while (!rs.EOF) { xInt = 0; for (xInt = 0; xInt <= Information.UBound(DateArr); xInt++) { if (DateArr[xInt, 0] == rs.Fields("Promotion_StartDate").Value) { if (DateArr[xInt, 1] == "E") { } else { Interaction.MsgBox("Selected Item already part of '" + rs.Fields("Promotion_Name").Value + "' deal. Please use different date or exclude it from the other deals."); rs.MoveLast(); rs.MoveNext(); return; } } else if (DateArr[xInt, 0] == rs.Fields("Promotion_EndDate").Value) { if (DateArr[xInt, 1] == "S") { } else { Interaction.MsgBox("Selected Item already part of '" + rs.Fields("Promotion_Name").Value + "' deal. Please use different date or exclude it from the other deals."); rs.MoveLast(); rs.MoveNext(); return; } } } rs.MoveNext(); } } rs = modRecordSet.getRS(ref "SELECT GRVPromotion.Promotion_Name, GRVPromotionItem.PromotionItem_StockItemID, GRVPromotionItem.PromotionItem_Price, GRVPromotion.Promotion_StartDate, GRVPromotion.Promotion_EndDate FROM GRVPromotion INNER JOIN GRVPromotionItem ON GRVPromotion.PromotionID = GRVPromotionItem.PromotionItem_PromotionID WHERE (((GRVPromotionItem.PromotionItem_StockItemID)=" + lID + ") AND ((GRVPromotion.Promotion_StartDate)<=#" + Strings.Format(_DTFields_0.Value, "yyyy/MM/dd") + "#) AND ((GRVPromotion.Promotion_EndDate)>=#" + Strings.Format(_DTFields_1.Value, "yyyy/MM/dd") + "#));"); if (rs.RecordCount > 0) { Interaction.MsgBox("Selected Item already part of '" + rs.Fields("Promotion_Name").Value + "' deal. Please use different date or exclude it from the other deals."); } else { //cnnDB.Execute "INSERT INTO PromotionItem ( PromotionItem_PromotionID, PromotionItem_StockItemID, PromotionItem_Quantity, PromotionItem_Price ) SELECT " & adoPrimaryRS("PromotionID") & " AS [Set], CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, 1,CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk WHERE (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID)=" & lID & ") AND ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity)=1) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));" My.MyProject.Forms.frmGRVPromotionItem.loadItem(adoPrimaryRS.Fields("PromotionID").Value, lID); loadItems(lID); } } } private void cmdDelete_Click(System.Object eventSender, System.EventArgs eventArgs) { int lID = 0; if (lvPromotion.FocusedItem == null) { } else { if (Interaction.MsgBox("Are you sure you wish to remove " + lvPromotion.FocusedItem.Text + " from this Deal?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "DELETE") == MsgBoxResult.Yes) { lID = Convert.ToInt32(Strings.Split(lvPromotion.FocusedItem.Name, "_")[0]); modRecordSet.cnnDB.Execute("DELETE GRVPromotionItem.* From GRVPromotionItem WHERE GRVPromotionItem.PromotionItem_PromotionID=" + adoPrimaryRS.Fields("PromotionID").Value + " AND GRVPromotionItem.PromotionItem_StockItemID=" + lID + " AND GRVPromotionItem.PromotionItem_Quantity=" + Strings.Split(lvPromotion.FocusedItem.Name, "_")[1] + ";"); loadItems(); } } } private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs) { update_Renamed(); modApplication.report_PromotionGRV(); } private void frmGRVPromotion_Load(System.Object eventSender, System.EventArgs eventArgs) { txtFields.AddRange(new TextBox[] { _txtFields_0 }); DTFields.AddRange(new DateTimePicker[] { _DTFields_0, _DTFields_1, _DTFields_2, _DTFields_3 }); chkFields.AddRange(new CheckBox[] { _chkFields_0, _chkFields_1, _chkFields_2 }); TextBox tb = new TextBox(); CheckBox cb = new CheckBox(); DateTimePicker dt = new DateTimePicker(); foreach (TextBox tb_loopVariable in txtFields) { tb = tb_loopVariable; tb.Enter += txtFields_Enter; } lvPromotion.Columns.Clear(); lvPromotion.Columns.Add("", "Stock Item", Convert.ToInt32(sizeConvertors.twipsToPixels(4550, true))); lvPromotion.Columns.Add("QTY", Convert.ToInt32(sizeConvertors.twipsToPixels(1, true)), System.Windows.Forms.HorizontalAlignment.Right); lvPromotion.Columns.Add("Price", Convert.ToInt32(sizeConvertors.twipsToPixels(1740, true)), System.Windows.Forms.HorizontalAlignment.Right); } private void loadItems(ref int lID = 0, ref short quantity = 0) { System.Windows.Forms.ListViewItem listItem = null; ADODB.Recordset rs = default(ADODB.Recordset); lvPromotion.Items.Clear(); rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, GRVPromotionItem.* FROM GRVPromotionItem INNER JOIN StockItem ON GRVPromotionItem.PromotionItem_StockItemID = StockItem.StockItemID Where (((GRVPromotionItem.PromotionItem_PromotionID) = " + adoPrimaryRS.Fields("PromotionID").Value + ")) ORDER BY StockItem.StockItem_Name, GRVPromotionItem.PromotionItem_Quantity;"); while (!(rs.EOF)) { listItem = lvPromotion.Items.Add(rs.Fields("PromotionItem_StockItemID").Value + "_" + rs.Fields("PromotionItem_Quantity").Value, rs.Fields("Stockitem_Name").Value, ""); //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 1) { listItem.SubItems[1].Text = rs.Fields("PromotionItem_Quantity").Value; } else { listItem.SubItems.Insert(1, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("PromotionItem_Quantity").Value)); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 2) { listItem.SubItems[2].Text = Strings.FormatNumber(rs.Fields("PromotionItem_Price").Value, 2); } else { listItem.SubItems.Insert(2, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, Strings.FormatNumber(rs.Fields("PromotionItem_Price").Value, 2))); } if (rs.Fields("PromotionItem_StockItemID").Value == lID & rs.Fields("PromotionItem_Quantity").Value == quantity) listItem.Selected = true; rs.moveNext(); } } //UPGRADE_WARNING: Event frmGRVPromotion.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' private void frmGRVPromotion_Resize(System.Object eventSender, System.EventArgs eventArgs) { Button cmdLast = new Button(); Button cmdNext = new Button(); Label lblStatus = new Label(); // ERROR: Not supported in C#: OnErrorStatement lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500; cmdNext.Left = lblStatus.Width + 700; cmdLast.Left = cmdNext.Left + 340; } private void frmGRVPromotion_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (mbEditFlag | mbAddNewFlag) goto EventExitSub; switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; adoPrimaryRS.Move(0); cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); cmdClose_Click(cmdClose, new System.EventArgs()); break; } EventExitSub: eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmGRVPromotion_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs) { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This will display the current record position for this recordset } private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This is where you put validation code //This event gets called when the following actions occur bool bCancel = false; switch (adReason) { case ADODB.EventReasonEnum.adRsnAddNew: break; case ADODB.EventReasonEnum.adRsnClose: break; case ADODB.EventReasonEnum.adRsnDelete: break; case ADODB.EventReasonEnum.adRsnFirstChange: break; case ADODB.EventReasonEnum.adRsnMove: break; case ADODB.EventReasonEnum.adRsnRequery: break; case ADODB.EventReasonEnum.adRsnResynch: break; case ADODB.EventReasonEnum.adRsnUndoAddNew: break; case ADODB.EventReasonEnum.adRsnUndoDelete: break; case ADODB.EventReasonEnum.adRsnUndoUpdate: break; case ADODB.EventReasonEnum.adRsnUpdate: break; } if (bCancel) adStatus = ADODB.EventStatusEnum.adStatusCancel; } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement if (mbAddNewFlag) { this.Close(); } else { mbEditFlag = false; mbAddNewFlag = false; adoPrimaryRS.CancelUpdate(); if (mvBookMark > 0) { adoPrimaryRS.Bookmark = mvBookMark; } else { adoPrimaryRS.MoveFirst(); } mbDataChanged = false; } } //UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' private bool update_Renamed() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement functionReturnValue = true; adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll); if (mbAddNewFlag) { adoPrimaryRS.MoveLast(); //move to the new record } mbEditFlag = false; mbAddNewFlag = false; mbDataChanged = false; return functionReturnValue; UpdateErr: Interaction.MsgBox(Err().Description); functionReturnValue = false; return functionReturnValue; } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); if (update_Renamed()) { if (chkFields[1].CheckState == 0) { modRecordSet.cnnDB.Execute("UPDATE GRVPromotion SET Promotion_StartDate = #" + DTFields[0].Value + "#, Promotion_EndDate = #" + DTFields[1].Value + "#, Promotion_StartTime = #" + DTFields[2].Value + "# ,Promotion_EndTime =#" + DTFields[3].Value + "# WHERE PromotionID = " + p_Prom + ";"); } this.Close(); } } private void lvPromotion_DoubleClick(System.Object eventSender, System.EventArgs eventArgs) { int lID = 0; short lQty = 0; if (lvPromotion.FocusedItem == null) { } else { lID = Convert.ToInt32(Strings.Split(lvPromotion.FocusedItem.Name, "_")[0]); lQty = Convert.ToInt16(Strings.Split(lvPromotion.FocusedItem.Name, "_")[1]); My.MyProject.Forms.frmGRVPromotionItem.loadItem(ref adoPrimaryRS.Fields("PromotionID").Value, ref lID, ref Convert.ToInt16(lQty)); loadItems(ref lID, ref lQty); } } private void lvPromotion_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 13) { lvPromotion_DoubleClick(lvPromotion, new System.EventArgs()); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs) { TextBox txtBox = new TextBox(); txtBox = (TextBox)eventSender; int Index = GetIndex.GetIndexer(ref txtBox, ref txtFields); modUtilities.MyGotFocus(ref txtFields[Index]); } private void txtInteger_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtInteger(Index) } private void txtInteger_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtInteger_MyLostFocus(ref short Index) { // LostFocus txtInteger(Index), 0 } private void txtFloat_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index) } private void txtFloat_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtFloat_MyLostFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index), 2 } private void txtFloatNegative_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloatNegative(Index) } private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii) { // KeyPressNegative txtFloatNegative(Index), KeyAscii } private void txtFloatNegative_MyLostFocus(ref short Index) { // LostFocus txtFloatNegative(Index), 2 } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; using System.Text; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Logging; using Microsoft.Rest.Generator.Properties; using Microsoft.Rest.Generator.Utilities; namespace Microsoft.Rest.Generator { public abstract class CodeNamer { private static readonly IDictionary<char, string> basicLaticCharacters; protected CodeNamer() { ReservedWords = new HashSet<string>(); } /// <summary> /// Gets collection of reserved words. /// </summary> public HashSet<string> ReservedWords { get; private set; } /// <summary> /// Formats segments of a string split by underscores or hyphens into "Camel" case strings. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public static string CamelCase(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } if (name[0] == '_') // Preserve leading underscores. return '_' + CamelCase(name.Substring(1)); return name.Split('_', '-', ' ') .Where(s => !string.IsNullOrEmpty(s)) .Select((s, i) => FormatCase(s, i == 0)) // Pass true/toLower for just the first element. .DefaultIfEmpty("") .Aggregate(string.Concat); } /// <summary> /// Formats segments of a string split by underscores or hyphens into "Pascal" case. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public static string PascalCase(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } if (name[0] == '_') // Preserve leading underscores and treat them like // uppercase characters by calling 'CamelCase()' on the rest. return '_' + CamelCase(name.Substring(1)); return name.Split('_', '-', ' ') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => FormatCase(s, false)) .DefaultIfEmpty("") .Aggregate(string.Concat); } /// <summary> /// Wraps value in quotes and escapes quotes inside. /// </summary> /// <param name="value">String to quote</param> /// <param name="quoteChar">Quote character</param> /// <param name="escapeChar">Escape character</param> /// <exception cref="System.ArgumentNullException">Throw when either quoteChar or escapeChar are null.</exception> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public static string QuoteValue(string value, string quoteChar = "\"", string escapeChar = "\\") { if (quoteChar == null) { throw new ArgumentNullException("quoteChar"); } if (escapeChar == null) { throw new ArgumentNullException("escapeChar"); } if (value == null) { value = string.Empty; } return quoteChar + value.Replace(quoteChar, escapeChar + quoteChar) + quoteChar; } /// <summary> /// Recursively normalizes names in the client model /// </summary> /// <param name="client"></param> public virtual void NormalizeClientModel(ServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } client.Name = GetTypeName(client.Name); client.Namespace = GetNamespaceName(client.Namespace); NormalizeClientProperties(client); var normalizedModels = new List<CompositeType>(); foreach (var modelType in client.ModelTypes) { normalizedModels.Add(NormalizeTypeDeclaration(modelType) as CompositeType); modelType.Properties.ForEach(p => QuoteParameter(p)); } client.ModelTypes.Clear(); normalizedModels.ForEach((item) => client.ModelTypes.Add(item)); var normalizedErrors = new List<CompositeType>(); foreach (var modelType in client.ErrorTypes) { normalizedErrors.Add(NormalizeTypeDeclaration(modelType) as CompositeType); } client.ErrorTypes.Clear(); normalizedErrors.ForEach((item) => client.ErrorTypes.Add(item)); var normalizedHeaders = new List<CompositeType>(); foreach (var modelType in client.HeaderTypes) { normalizedHeaders.Add(NormalizeTypeDeclaration(modelType) as CompositeType); } client.HeaderTypes.Clear(); normalizedHeaders.ForEach((item) => client.HeaderTypes.Add(item)); var normalizedEnums = new List<EnumType>(); foreach (var enumType in client.EnumTypes) { var normalizedType = NormalizeTypeDeclaration(enumType) as EnumType; if (normalizedType != null) { normalizedEnums.Add(NormalizeTypeDeclaration(enumType) as EnumType); } } client.EnumTypes.Clear(); normalizedEnums.ForEach((item) => client.EnumTypes.Add(item)); foreach (var method in client.Methods) { NormalizeMethod(method); } } /// <summary> /// Normalizes the client properties names of a client model /// </summary> /// <param name="client">A client model</param> protected virtual void NormalizeClientProperties(ServiceClient client) { if (client != null) { foreach (var property in client.Properties) { property.Name = GetPropertyName(property.Name); property.Type = NormalizeTypeReference(property.Type); QuoteParameter(property); } } } /// <summary> /// Normalizes names in the method /// </summary> /// <param name="method"></param> public virtual void NormalizeMethod(Method method) { if (method == null) { throw new ArgumentNullException("method"); } method.Name = GetMethodName(method.Name); method.Group = GetMethodGroupName(method.Group); method.ReturnType = NormalizeTypeReference(method.ReturnType); method.DefaultResponse = NormalizeTypeReference(method.DefaultResponse); var normalizedResponses = new Dictionary<HttpStatusCode, Response>(); foreach (var statusCode in method.Responses.Keys) { normalizedResponses[statusCode] = NormalizeTypeReference(method.Responses[statusCode]); } method.Responses.Clear(); foreach (var statusCode in normalizedResponses.Keys) { method.Responses[statusCode] = normalizedResponses[statusCode]; } NormalizeParameters(method); } /// <summary> /// Normalizes the parameter names of a method /// </summary> /// <param name="method">A method model</param> protected virtual void NormalizeParameters(Method method) { if (method != null) { foreach (var parameter in method.Parameters) { parameter.Name = method.Scope.GetUniqueName(GetParameterName(parameter.Name)); parameter.Type = NormalizeTypeReference(parameter.Type); QuoteParameter(parameter); } foreach (var parameterTransformation in method.InputParameterTransformation) { parameterTransformation.OutputParameter.Name = method.Scope.GetUniqueName(GetParameterName(parameterTransformation.OutputParameter.Name)); parameterTransformation.OutputParameter.Type = NormalizeTypeReference(parameterTransformation.OutputParameter.Type); QuoteParameter(parameterTransformation.OutputParameter); foreach (var parameterMapping in parameterTransformation.ParameterMappings) { if (parameterMapping.InputParameterProperty != null) { parameterMapping.InputParameterProperty = GetPropertyName(parameterMapping.InputParameterProperty); } if (parameterMapping.OutputParameterProperty != null) { parameterMapping.OutputParameterProperty = GetPropertyName(parameterMapping.OutputParameterProperty); } } } } } /// <summary> /// Quotes default value of the parameter. /// </summary> /// <param name="parameter"></param> protected void QuoteParameter(IParameter parameter) { if (parameter != null) { parameter.DefaultValue = EscapeDefaultValue(parameter.DefaultValue, parameter.Type); } } /// <summary> /// Returns a quoted string for the given language if applicable. /// </summary> /// <param name="defaultValue">Value to quote.</param> /// <param name="type">Data type.</param> public abstract string EscapeDefaultValue(string defaultValue, IType type); /// <summary> /// Formats a string for naming members of an enum using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetEnumMemberName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(name)); } /// <summary> /// Formats a string for naming fields using a prefix '_' and VariableName Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetFieldName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return '_' + GetVariableName(name); } /// <summary> /// Formats a string for naming interfaces using a prefix 'I' and Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetInterfaceName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return "I" + PascalCase(RemoveInvalidCharacters(name)); } /// <summary> /// Formats a string for naming a method using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetMethodName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation"))); } /// <summary> /// Formats a string for identifying a namespace using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetNamespaceName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharactersNamespace(name)); } /// <summary> /// Formats a string for naming method parameters using GetVariableName Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetParameterName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return GetVariableName(GetEscapedReservedName(name, "Parameter")); } /// <summary> /// Formats a string for naming properties using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetPropertyName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property"))); } /// <summary> /// Formats a string for naming a Type or Object using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetTypeName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model"))); } /// <summary> /// Formats a string for naming a Method Group using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetMethodGroupName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model"))); } /// <summary> /// Formats a string for naming a local variable using Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetVariableName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable"))); } /// <summary> /// Returns language specific type reference name. /// </summary> /// <param name="typePair"></param> /// <returns></returns> public virtual Response NormalizeTypeReference(Response typePair) { return new Response(NormalizeTypeReference(typePair.Body), NormalizeTypeReference(typePair.Headers)); } /// <summary> /// Returns language specific type reference name. /// </summary> /// <param name="type"></param> /// <returns></returns> public abstract IType NormalizeTypeReference(IType type); /// <summary> /// Returns language specific type declaration name. /// </summary> /// <param name="type"></param> /// <returns></returns> public abstract IType NormalizeTypeDeclaration(IType type); /// <summary> /// Formats a string as upper or lower case. Two-letter inputs that are all upper case are both lowered. /// Example: ID = > id, Ex => ex /// </summary> /// <param name="name"></param> /// <param name="toLower"></param> /// <returns>The formatted string.</returns> private static string FormatCase(string name, bool toLower) { if (!string.IsNullOrEmpty(name)) { if (name.Length < 2 || (name.Length == 2 && char.IsUpper(name[0]) && char.IsUpper(name[1]))) { name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant(); } else { name = (toLower ? char.ToLowerInvariant(name[0]) : char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1); } } return name; } /// <summary> /// Removes invalid characters from the name. Everything but alpha-numeral, underscore, /// and dash. /// </summary> /// <param name="name">String to parse.</param> /// <returns>Name with invalid characters removed.</returns> public static string RemoveInvalidCharacters(string name) { return GetValidName(name, '_', '-'); } /// <summary> /// Removes invalid characters from the namespace. Everything but alpha-numeral, underscore, /// period, and dash. /// </summary> /// <param name="name">String to parse.</param> /// <returns>Namespace with invalid characters removed.</returns> protected virtual string RemoveInvalidCharactersNamespace(string name) { return GetValidName(name, '_', '-', '.'); } /// <summary> /// Gets valid name for the identifier. /// </summary> /// <param name="name">String to parse.</param> /// <param name="allowedCharacters">Allowed characters.</param> /// <returns>Name with invalid characters removed.</returns> protected static string GetValidName(string name, params char[] allowedCharacters) { var correctName = RemoveInvalidCharacters(name, allowedCharacters); // here we have only letters and digits or an empty string if (string.IsNullOrEmpty(correctName) || basicLaticCharacters.ContainsKey(correctName[0])) { var sb = new StringBuilder(); foreach (char symbol in name) { if (basicLaticCharacters.ContainsKey(symbol)) { sb.Append(basicLaticCharacters[symbol]); } else { sb.Append(symbol); } } correctName = RemoveInvalidCharacters(sb.ToString(), allowedCharacters); } // if it is still empty string, throw if (correctName.IsNullOrEmpty()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName, name)); } return correctName; } /// <summary> /// Removes invalid characters from the name. /// </summary> /// <param name="name">String to parse.</param> /// <param name="allowerCharacters">Allowed characters.</param> /// <returns>Name with invalid characters removed.</returns> private static string RemoveInvalidCharacters(string name, params char[] allowerCharacters) { return new string(name.Replace("[]", "Sequence") .Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c)) .ToArray()); } /// <summary> /// If the provided name is a reserved word in a programming language then the method converts the /// name by appending the provided appendValue /// </summary> /// <param name="name">Name.</param> /// <param name="appendValue">String to append.</param> /// <returns>The transformed reserved name</returns> protected virtual string GetEscapedReservedName(string name, string appendValue) { if (name == null) { throw new ArgumentNullException("name"); } if (appendValue == null) { throw new ArgumentNullException("appendValue"); } if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase)) { name += appendValue; } return name; } /// <summary> /// Resolves name collisions in the client model by iterating over namespaces (if provided, /// model names, client name, and client method groups. /// </summary> /// <param name="serviceClient">Service client to process.</param> /// <param name="clientNamespace">Client namespace or null.</param> /// <param name="modelNamespace">Client model namespace or null.</param> public virtual void ResolveNameCollisions(ServiceClient serviceClient, string clientNamespace, string modelNamespace) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } // take all namespaces of Models var exclusionListQuery = SplitNamespaceAndIgnoreLast(modelNamespace) .Union(SplitNamespaceAndIgnoreLast(clientNamespace)); var exclusionDictionary = new Dictionary<string, string>(exclusionListQuery .Where(s => !string.IsNullOrWhiteSpace(s)) .ToDictionary(s => s, v => "namespace"), StringComparer.OrdinalIgnoreCase); var models = new List<CompositeType>(serviceClient.ModelTypes); serviceClient.ModelTypes.Clear(); foreach (var model in models) { model.Name = ResolveNameConflict( exclusionDictionary, model.Name, "Schema definition", "Model"); serviceClient.ModelTypes.Add(model); } models = new List<CompositeType>(serviceClient.HeaderTypes); serviceClient.HeaderTypes.Clear(); foreach (var model in models) { model.Name = ResolveNameConflict( exclusionDictionary, model.Name, "Schema definition", "Model"); serviceClient.HeaderTypes.Add(model); } foreach (var model in serviceClient.ModelTypes .Concat(serviceClient.HeaderTypes) .Concat(serviceClient.ErrorTypes)) { foreach (var property in model.Properties) { if (property.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase)) { property.Name += "Property"; } } } var enumTypes = new List<EnumType>(serviceClient.EnumTypes); serviceClient.EnumTypes.Clear(); foreach (var enumType in enumTypes) { enumType.Name = ResolveNameConflict( exclusionDictionary, enumType.Name, "Enum name", "Enum"); serviceClient.EnumTypes.Add(enumType); } serviceClient.Name = ResolveNameConflict( exclusionDictionary, serviceClient.Name, "Client", "Client"); ResolveMethodGroupNameCollision(serviceClient, exclusionDictionary); } /// <summary> /// Resolves name collisions in the client model for method groups (operations). /// </summary> /// <param name="serviceClient"></param> /// <param name="exclusionDictionary"></param> protected virtual void ResolveMethodGroupNameCollision(ServiceClient serviceClient, Dictionary<string, string> exclusionDictionary) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (exclusionDictionary == null) { throw new ArgumentNullException("exclusionDictionary"); } var methodGroups = serviceClient.MethodGroups.ToList(); foreach (var methodGroup in methodGroups) { var resolvedName = ResolveNameConflict( exclusionDictionary, methodGroup, "Client operation", "Operations"); foreach (var method in serviceClient.Methods) { if (method.Group == methodGroup) { method.Group = resolvedName; } } } } private static string ResolveNameConflict( Dictionary<string, string> exclusionDictionary, string typeName, string type, string suffix) { string resolvedName = typeName; var sb = new StringBuilder(); sb.AppendLine(); while (exclusionDictionary.ContainsKey(resolvedName)) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, Resources.NamespaceConflictReasonMessage, resolvedName, exclusionDictionary[resolvedName])); resolvedName += suffix; } if (!string.Equals(resolvedName, typeName, StringComparison.OrdinalIgnoreCase)) { sb.AppendLine(Resources.NamingConflictsSuggestion); Logger.LogWarning( string.Format( CultureInfo.InvariantCulture, Resources.EntityConflictTitleMessage, type, typeName, resolvedName, sb)); } exclusionDictionary.Add(resolvedName, type); return resolvedName; } private static IEnumerable<string> SplitNamespaceAndIgnoreLast(string nameSpace) { if (string.IsNullOrEmpty(nameSpace)) { return Enumerable.Empty<string>(); } var namespaceWords = nameSpace.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); if (namespaceWords.Length < 1) { return Enumerable.Empty<string>(); } // else we do not need the last part of the namespace return namespaceWords.Take(namespaceWords.Length - 1); } [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static CodeNamer() { basicLaticCharacters = new Dictionary<char, string>(); basicLaticCharacters[(char)32] = "Space"; basicLaticCharacters[(char)33] = "ExclamationMark"; basicLaticCharacters[(char)34] = "QuotationMark"; basicLaticCharacters[(char)35] = "NumberSign"; basicLaticCharacters[(char)36] = "DollarSign"; basicLaticCharacters[(char)37] = "PercentSign"; basicLaticCharacters[(char)38] = "Ampersand"; basicLaticCharacters[(char)39] = "Apostrophe"; basicLaticCharacters[(char)40] = "LeftParenthesis"; basicLaticCharacters[(char)41] = "RightParenthesis"; basicLaticCharacters[(char)42] = "Asterisk"; basicLaticCharacters[(char)43] = "PlusSign"; basicLaticCharacters[(char)44] = "Comma"; basicLaticCharacters[(char)45] = "HyphenMinus"; basicLaticCharacters[(char)46] = "FullStop"; basicLaticCharacters[(char)47] = "Slash"; basicLaticCharacters[(char)48] = "Zero"; basicLaticCharacters[(char)49] = "One"; basicLaticCharacters[(char)50] = "Two"; basicLaticCharacters[(char)51] = "Three"; basicLaticCharacters[(char)52] = "Four"; basicLaticCharacters[(char)53] = "Five"; basicLaticCharacters[(char)54] = "Six"; basicLaticCharacters[(char)55] = "Seven"; basicLaticCharacters[(char)56] = "Eight"; basicLaticCharacters[(char)57] = "Nine"; basicLaticCharacters[(char)58] = "Colon"; basicLaticCharacters[(char)59] = "Semicolon"; basicLaticCharacters[(char)60] = "LessThanSign"; basicLaticCharacters[(char)61] = "EqualSign"; basicLaticCharacters[(char)62] = "GreaterThanSign"; basicLaticCharacters[(char)63] = "QuestionMark"; basicLaticCharacters[(char)64] = "AtSign"; basicLaticCharacters[(char)91] = "LeftSquareBracket"; basicLaticCharacters[(char)92] = "Backslash"; basicLaticCharacters[(char)93] = "RightSquareBracket"; basicLaticCharacters[(char)94] = "CircumflexAccent"; basicLaticCharacters[(char)96] = "GraveAccent"; basicLaticCharacters[(char)123] = "LeftCurlyBracket"; basicLaticCharacters[(char)124] = "VerticalBar"; basicLaticCharacters[(char)125] = "RightCurlyBracket"; basicLaticCharacters[(char)126] = "Tilde"; } } }
// *********************************************************************** // Copyright (c) 2012 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.Diagnostics; using System.Threading; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { /// <summary> /// A WorkItem may be an individual test case, a fixture or /// a higher level grouping of tests. All WorkItems inherit /// from the abstract WorkItem class, which uses the template /// pattern to allow derived classes to perform work in /// whatever way is needed. /// /// A WorkItem is created with a particular TestExecutionContext /// and is responsible for re-establishing that context in the /// current thread before it begins or resumes execution. /// </summary> public abstract class WorkItem { static Logger log = InternalTrace.GetLogger("WorkItem"); #region Static Factory Method /// <summary> /// Creates a work item. /// </summary> /// <param name="test">The test for which this WorkItem is being created.</param> /// <param name="filter">The filter to be used in selecting any child Tests.</param> /// <returns></returns> static public WorkItem CreateWorkItem(ITest test, ITestFilter filter) { TestSuite suite = test as TestSuite; if (suite != null) return new CompositeWorkItem(suite, filter); else return new SimpleWorkItem((TestMethod)test, filter); } #endregion #region Construction and Initialization /// <summary> /// Construct a WorkItem for a particular test. /// </summary> /// <param name="test">The test that the WorkItem will run</param> public WorkItem(Test test) { Test = test; Result = test.MakeTestResult(); State = WorkItemState.Ready; Actions = new List<ITestAction>(); #if !PORTABLE && !SILVERLIGHT && !NETCF TargetApartment = Test.Properties.ContainsKey(PropertyNames.ApartmentState) ? (ApartmentState)Test.Properties.Get(PropertyNames.ApartmentState) : ApartmentState.Unknown; #endif } /// <summary> /// Initialize the TestExecutionContext. This must be done /// before executing the WorkItem. /// </summary> /// <remarks> /// Originally, the context was provided in the constructor /// but delaying initialization of the context until the item /// is about to be dispatched allows changes in the parent /// context during OneTimeSetUp to be reflected in the child. /// </remarks> /// <param name="context">The TestExecutionContext to use</param> public void InitializeContext(TestExecutionContext context) { Guard.OperationValid(Context == null, "The context has already been initialized"); Context = context; if (Test is TestAssembly) Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(((TestAssembly)Test).Assembly)); else if (Test is ParameterizedMethodSuite) Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(Test.Method.MethodInfo)); else if (Test.TypeInfo != null) Actions.AddRange(ActionsHelper.GetActionsFromTypesAttributes(Test.TypeInfo.Type)); } #endregion #region Properties and Events /// <summary> /// Event triggered when the item is complete /// </summary> public event EventHandler Completed; /// <summary> /// Gets the current state of the WorkItem /// </summary> public WorkItemState State { get; private set; } /// <summary> /// The test being executed by the work item /// </summary> public Test Test { get; private set; } /// <summary> /// The execution context /// </summary> public TestExecutionContext Context { get; private set; } /// <summary> /// The unique id of the worker executing this item. /// </summary> public string WorkerId {get; internal set;} /// <summary> /// The test actions to be performed before and after this test /// </summary> public List<ITestAction> Actions { get; private set; } #if PARALLEL /// <summary> /// Indicates whether this WorkItem may be run in parallel /// </summary> public bool IsParallelizable { get { ParallelScope scope = ParallelScope.None; if (Test.Properties.ContainsKey(PropertyNames.ParallelScope)) { scope = (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope); if ((scope & ParallelScope.Self) != 0) return true; } else { scope = Context.ParallelScope; if ((scope & ParallelScope.Children) != 0) return true; } if (Test is TestFixture && (scope & ParallelScope.Fixtures) != 0) return true; // Special handling for the top level TestAssembly. // If it has any scope specified other than None, // we will use the parallel queue. This heuristic // is intended to minimize creation of unneeded // queues and workers, since the assembly and // namespace level tests can easily run in any queue. if (Test is TestAssembly && scope != ParallelScope.None) return true; return false; } } #endif /// <summary> /// The test result /// </summary> public TestResult Result { get; protected set; } #if !SILVERLIGHT && !NETCF && !PORTABLE internal ApartmentState TargetApartment { get; set; } private ApartmentState CurrentApartment { get; set; } #endif #endregion #region OwnThreadReason Enumeration [Flags] private enum OwnThreadReason { NotNeeded = 0, RequiresThread = 1, Timeout = 2, DifferentApartment = 4 } #endregion #region Public Methods /// <summary> /// Execute the current work item, including any /// child work items. /// </summary> public virtual void Execute() { // Timeout set at a higher level int timeout = Context.TestCaseTimeout; // Timeout set on this test if (Test.Properties.ContainsKey(PropertyNames.Timeout)) timeout = (int)Test.Properties.Get(PropertyNames.Timeout); // Unless the context is single threaded, a supplementary thread // is created on the various platforms... // 1. If the test used the RequiresThreadAttribute. // 2. If a test method has a timeout. // 3. If the test needs to run in a different apartment. // // NOTE: We want to eliminate or significantly reduce // cases 2 and 3 in the future. // // Case 2 requires the ability to stop and start test workers // dynamically. We would cancel the worker thread, dispose of // the worker and start a new worker on a new thread. // // Case 3 occurs when using either dispatcher whenever a // child test calls for a different apartment from the one // used by it's parent. It routinely occurs under the simple // dispatcher (--workers=0 option). Under the parallel dispatcher // it is needed when test cases are not enabled for parallel // execution. Currently, test cases are always run sequentially, // so this continues to apply fairly generally. var ownThreadReason = OwnThreadReason.NotNeeded; #if !PORTABLE if (Test.RequiresThread) ownThreadReason |= OwnThreadReason.RequiresThread; if (timeout > 0 && Test is TestMethod) ownThreadReason |= OwnThreadReason.Timeout; #if !SILVERLIGHT && !NETCF CurrentApartment = Thread.CurrentThread.GetApartmentState(); if (CurrentApartment != TargetApartment && TargetApartment != ApartmentState.Unknown) ownThreadReason |= OwnThreadReason.DifferentApartment; #endif #endif if (ownThreadReason == OwnThreadReason.NotNeeded) RunTest(); else if (Context.IsSingleThreaded) { var msg = "Test is not runnable in single-threaded context. " + ownThreadReason; log.Error(msg); Result.SetResult(ResultState.NotRunnable, msg); WorkItemComplete(); } else { log.Debug("Running test on own thread. " + ownThreadReason); #if SILVERLIGHT || NETCF RunTestOnOwnThread(timeout); #elif !PORTABLE var apartment = (ownThreadReason | OwnThreadReason.DifferentApartment) != 0 ? TargetApartment : CurrentApartment; RunTestOnOwnThread(timeout, apartment); #endif } } #if SILVERLIGHT || NETCF private Thread thread; private void RunTestOnOwnThread(int timeout) { thread = new Thread(RunTest); RunThread(timeout); } #endif #if !SILVERLIGHT && !NETCF && !PORTABLE private Thread thread; private void RunTestOnOwnThread(int timeout, ApartmentState apartment) { thread = new Thread(new ThreadStart(RunTest)); thread.SetApartmentState(apartment); RunThread(timeout); } #endif #if !PORTABLE private void RunThread(int timeout) { #if !NETCF thread.CurrentCulture = Context.CurrentCulture; thread.CurrentUICulture = Context.CurrentUICulture; #endif thread.Start(); if (!Test.IsAsynchronous || timeout > 0) { if (timeout <= 0) timeout = Timeout.Infinite; if (!thread.Join(timeout)) { Thread tThread; lock (threadLock) { if (thread == null) return; tThread = thread; thread = null; } if (Context.ExecutionStatus == TestExecutionStatus.AbortRequested) return; log.Debug("Killing thread {0}, which exceeded timeout", tThread.ManagedThreadId); ThreadUtility.Kill(tThread); // NOTE: Without the use of Join, there is a race condition here. // The thread sets the result to Cancelled and our code below sets // it to Failure. In order for the result to be shown as a failure, // we need to ensure that the following code executes after the // thread has terminated. There is a risk here: the test code might // refuse to terminate. However, it's more important to deal with // the normal rather than a pathological case. tThread.Join(); log.Debug("Changing result from {0} to Timeout Failure", Result.ResultState); Result.SetResult(ResultState.Failure, string.Format("Test exceeded Timeout value of {0}ms", timeout)); WorkItemComplete(); } } } #endif private void RunTest() { Context.CurrentTest = this.Test; Context.CurrentResult = this.Result; Context.Listener.TestStarted(this.Test); Context.StartTime = DateTime.UtcNow; Context.StartTicks = Stopwatch.GetTimestamp(); Context.WorkerId = this.WorkerId; Context.EstablishExecutionEnvironment(); State = WorkItemState.Running; PerformWork(); } private object threadLock = new object(); /// <summary> /// Cancel (abort or stop) a WorkItem /// </summary> /// <param name="force">true if the WorkItem should be aborted, false if it should run to completion</param> public virtual void Cancel(bool force) { if (Context != null) Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; if (!force) return; #if !PORTABLE Thread tThread; lock (threadLock) { if (thread == null) return; tThread = thread; thread = null; } if (!tThread.Join(0)) { log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId); ThreadUtility.Kill(tThread); tThread.Join(); log.Debug("Changing result from {0} to Cancelled", Result.ResultState); Result.SetResult(ResultState.Cancelled, "Cancelled by user"); WorkItemComplete(); } #endif } #endregion #region Protected Methods /// <summary> /// Method that performs actually performs the work. It should /// set the State to WorkItemState.Complete when done. /// </summary> protected abstract void PerformWork(); /// <summary> /// Method called by the derived class when all work is complete /// </summary> protected void WorkItemComplete() { State = WorkItemState.Complete; Result.StartTime = Context.StartTime; Result.EndTime = DateTime.UtcNow; long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks; double seconds = (double)tickCount / Stopwatch.Frequency; Result.Duration = seconds; // We add in the assert count from the context. If // this item is for a test case, we are adding the // test assert count to zero. If it's a fixture, we // are adding in any asserts that were run in the // fixture setup or teardown. Each context only // counts the asserts taking place in that context. // Each result accumulates the count from child // results along with it's own asserts. Result.AssertCount += Context.AssertCount; Context.Listener.TestFinished(Result); if (Completed != null) Completed(this, EventArgs.Empty); //Clear references to test objects to reduce memory usage Context.TestObject = null; Test.Fixture = null; } #endregion } }
// Copyright 2016, 2015, 2014 Matthias Koch // // 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 JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.ReSharper.Psi.Tree; // ReSharper disable All namespace TestFx.ReSharper.Model.Tree.Wrapper { public abstract partial class FileBase : TreeNodeBase, ICSharpFile { private readonly ICSharpFile _file; protected FileBase (ICSharpFile file) : base(file) { _file = file; } public IFile ReParse (TreeTextRange modifiedRange, string text) { return _file.ReParse(modifiedRange, text); } public PsiFileModificationInfo GetReParseResult (TreeTextRange modifiedRange, string text) { return _file.GetReParseResult(modifiedRange, text); } public bool IsInjected () { return _file.IsInjected(); } public CachingLexer CachingLexer { get { return _file.CachingLexer; } } public int ModificationCounter { get { return _file.ModificationCounter; } } public bool CanContainCaseInsensitiveReferences { get { return _file.CanContainCaseInsensitiveReferences; } } public TreeNodeEnumerable<ICSharpNamespaceDeclaration> NamespaceDeclarationsEnumerable { get { return _file.NamespaceDeclarationsEnumerable; } } TreeNodeCollection<ICSharpTypeDeclaration> ICSharpTypeAndNamespaceHolderDeclaration.TypeDeclarations { get { return _file.TypeDeclarations; } } public TreeNodeEnumerable<ICSharpTypeDeclaration> TypeDeclarationsEnumerable { get { return _file.TypeDeclarationsEnumerable; } } IList<ITypeDeclaration> ITypeDeclarationHolder.TypeDeclarations { get { return ((ITypeDeclarationHolder) _file).TypeDeclarations; } } public IUsingList ImportsList { get { return _file.ImportsList; } } TreeNodeCollection<ICSharpNamespaceDeclaration> ICSharpTypeAndNamespaceHolderDeclaration.NamespaceDeclarations { get { return _file.NamespaceDeclarations; } } IList<INamespaceDeclaration> INamespaceDeclarationHolder.NamespaceDeclarations { get { return ((INamespaceDeclarationHolder) _file).NamespaceDeclarations; } } public IDeclarationsRange GetAllDeclarationsRange () { return _file.GetAllDeclarationsRange(); } public IDeclarationsRange GetDeclarationsRange (TreeTextRange range) { return _file.GetDeclarationsRange(range); } public IDeclarationsRange GetDeclarationsRange (IDeclaration first, IDeclaration last) { return _file.GetDeclarationsRange(first, last); } public void RemoveDeclarationsRange (IDeclarationsRange range) { _file.RemoveDeclarationsRange(range); } public IDeclarationsRange AddDeclarationsRangeAfter (IDeclarationsRange range, ITreeNode anchor) { return _file.AddDeclarationsRangeAfter(range, anchor); } public IDeclarationsRange AddDeclarationsRangeBefore (IDeclarationsRange range, ITreeNode anchor) { return _file.AddDeclarationsRangeBefore(range, anchor); } public IUsingDirective AddImportAfter (IUsingDirective param, IUsingDirective anchor) { return _file.AddImportAfter(param, anchor); } public IUsingDirective AddImportBefore (IUsingDirective param, IUsingDirective anchor) { return _file.AddImportBefore(param, anchor); } public IUsingDirective AddImport (IUsingDirective param, bool saveUsingListPosition = false) { return _file.AddImport(param, saveUsingListPosition); } public void RemoveImport (IUsingDirective param) { _file.RemoveImport(param); } public ICSharpTypeDeclaration AddTypeDeclarationBefore (ICSharpTypeDeclaration param, ICSharpTypeDeclaration anchor) { return _file.AddTypeDeclarationBefore(param, anchor); } public ICSharpTypeDeclaration AddTypeDeclarationAfter (ICSharpTypeDeclaration param, ICSharpTypeDeclaration anchor) { return _file.AddTypeDeclarationAfter(param, anchor); } public void RemoveTypeDeclaration (ICSharpTypeDeclaration param) { _file.RemoveTypeDeclaration(param); } public ICSharpNamespaceDeclaration AddNamespaceDeclarationBefore (ICSharpNamespaceDeclaration param, ICSharpNamespaceDeclaration anchor) { return _file.AddNamespaceDeclarationBefore(param, anchor); } public ICSharpNamespaceDeclaration AddNamespaceDeclarationAfter (ICSharpNamespaceDeclaration param, ICSharpNamespaceDeclaration anchor) { return _file.AddNamespaceDeclarationAfter(param, anchor); } public void RemoveNamespaceDeclaration (ICSharpNamespaceDeclaration param) { _file.RemoveNamespaceDeclaration(param); } public IUsingList SetImportsList (IUsingList param) { return _file.SetImportsList(param); } public ICSharpTypeAndNamespaceHolderDeclaration ContainingTypeAndNamespaceHolder { get { return _file.ContainingTypeAndNamespaceHolder; } } public TreeNodeCollection<IExternAliasDirective> ExternAliases { get { return _file.ExternAliases; } } public TreeNodeEnumerable<IExternAliasDirective> ExternAliasesEnumerable { get { return _file.ExternAliasesEnumerable; } } public TreeNodeCollection<IUsingDirective> Imports { get { return _file.Imports; } } public TreeNodeEnumerable<IUsingDirective> ImportsEnumerable { get { return _file.ImportsEnumerable; } } ITypeAndNamespaceHolderDeclaration ITypeAndNamespaceHolderDeclaration.ContainingTypeAndNamespaceHolder { get { return _file.ContainingTypeAndNamespaceHolder; } } public PreProcessingDirectivesInFile GetPreprocessorConditionals () { return _file.GetPreprocessorConditionals(); } public void RemoveAttribute (IAttribute attribute) { _file.RemoveAttribute(attribute); } public void AddAttribueBefore (IAttribute attribute, IAttribute tag) { _file.AddAttribueBefore(attribute, tag); } public TreeNodeCollection<ICSharpNamespaceDeclaration> NamespaceDeclarationNodes { get { return _file.NamespaceDeclarationNodes; } } public TreeNodeEnumerable<ICSharpNamespaceDeclaration> NamespaceDeclarationNodesEnumerable { get { return _file.NamespaceDeclarationNodesEnumerable; } } public TreeNodeCollection<IAttributeSection> Sections { get { return _file.Sections; } } public TreeNodeEnumerable<IAttributeSection> SectionsEnumerable { get { return _file.SectionsEnumerable; } } public TreeNodeCollection<IAttribute> Attributes { get { return _file.Attributes; } } public TreeNodeEnumerable<IAttribute> AttributesEnumerable { get { return _file.AttributesEnumerable; } } public IExternAliasDirective AddExternAliasAfter (IExternAliasDirective externAlias, IExternAliasDirective anchor) { return _file.AddExternAliasAfter(externAlias, anchor); } public IExternAliasDirective AddExternAliasBefore (IExternAliasDirective externAlias, IExternAliasDirective anchor) { return _file.AddExternAliasBefore(externAlias, anchor); } public void RemoveExternAlias (IExternAliasDirective externAlias) { _file.RemoveExternAlias(externAlias); } } }
// Authors: // Rafael Mizrahi <[email protected]> // Erez Lotan <[email protected]> // Oren Gurfinkel <[email protected]> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // 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; using GHTUtils; using GHTUtils.Base; namespace tests.system_data_dll.System_Data { [TestFixture] public class DataRelation_ctor_SDclmDclm : GHTBase { [Test] public void Main() { DataRelation_ctor_SDclmDclm tc = new DataRelation_ctor_SDclmDclm(); Exception exp = null; try { tc.BeginTest("DataRelation_ctor_SDclmDclm"); tc.run(); } catch(Exception ex) { exp = ex; } finally { tc.EndTest(exp); } } //Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataSet ds = new DataSet(); DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable(); DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); ds.Tables.Add(dtChild); DataRelation dRel; dRel = new DataRelation("MyRelation",dtParent.Columns[0],dtChild.Columns[0]); ds.Relations.Add(dRel); try { BeginCase("DataRelation - CTor"); Compare(dRel == null ,false ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - parent Constraints"); Compare(dtParent.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - child Constraints"); Compare(dtChild.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - child relations"); Compare(dtParent.ChildRelations[0] ,dRel); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - parent relations"); Compare(dtChild.ParentRelations[0],dRel ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - name"); Compare(dRel.RelationName ,"MyRelation" ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - parent UniqueConstraint"); Compare(dtParent.Constraints[0].GetType() ,typeof(UniqueConstraint)); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - Child ForeignKeyConstraint"); Compare(dtChild.Constraints[0].GetType() ,typeof(ForeignKeyConstraint)); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} ds.Relations.Clear(); try { BeginCase("Remove DataRelation - Parent Constraints"); Compare(dtParent.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Remove DataRelation - Child Constraints"); Compare(dtChild.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Remove DataRelation - child relations"); Compare(dtParent.ChildRelations.Count ,0); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Remove DataRelation - parent relations"); Compare(dtChild.ParentRelations.Count ,0); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //add relation which will create invalid constraint dtChild.Constraints.Clear(); dtParent.Constraints.Clear(); //add duplicated row dtParent.Rows.Add(dtParent.Rows[0].ItemArray); dRel = new DataRelation("MyRelation",dtParent.Columns[0],dtChild.Columns[0]); try { BeginCase("Add relation which will create invalid constraint"); exp = new Exception(); try { ds.Relations.Add(dRel); } catch (ArgumentException ex) {exp=ex;} Compare(exp.GetType().FullName ,typeof(ArgumentException).FullName ); exp=null; } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Drawing; namespace fyiReporting.RDL { ///<summary> /// Line chart definition and processing. ///</summary> [Serializable] internal class ChartBubble: ChartBase { internal ChartBubble(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat) : base(r, row, c, m,showTooltips,showTooltipsX,_ToolTipYFormat, _ToolTipXFormat) { } override internal void Draw(Report rpt) { CreateSizedBitmap(); using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using(Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.PageUnit = GraphicsUnit.Pixel; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; // 20022008 AJM GJL - Added new required info double ymax=0,ymin=0; // Get the max and min values for the y axis GetValueMaxMin(rpt, ref ymax, ref ymin, 1,1); double xmax = 0, xmin = 0; // Get the max and min values for the x axis GetValueMaxMin(rpt, ref xmax, ref xmin, 0,1); double bmax = 0, bmin = 0; // Get the max and min values for the bubble size if (ChartDefn.Type == ChartTypeEnum.Bubble) // only applies to bubble (not scatter) GetValueMaxMin(rpt, ref bmax, ref bmin, 2,1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, Layout.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, ymin, ymax); Layout.LeftMargin = vaSize.Width; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt,g, false, true); // Adjust the bottom margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g, xmin, xmax); Layout.BottomMargin = caSize.Height; AdjustMargins(lRect,rpt,g); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Value Axis if (vaSize.Width > 0) // If we made room for the axis - we need to draw it DrawValueAxis(rpt, g, ymin, ymax, new System.Drawing.Rectangle(Layout.LeftMargin - vaSize.Width, Layout.TopMargin, vaSize.Width, Layout.PlotArea.Height), Layout.LeftMargin, _bm.Width - Layout.RightMargin); // Draw Category Axis if (caSize.Height > 0) DrawCategoryAxis(rpt, g, xmin, xmax, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin); // Draw Plot area data DrawPlot(rpt, g, xmin, xmax, ymin, ymax, bmin, bmax); DrawLegend(rpt, g, false, false); } } void DrawPlot(Report rpt, Graphics g, double xmin, double xmax, double ymin, double ymax, double bmin, double bmax) { // Draw Plot area data int maxPointHeight = (int)Layout.PlotArea.Height; int maxPointWidth = (int)Layout.PlotArea.Width; for (int iCol = 1; iCol <= SeriesCount; iCol++) { //handle either line scatter or line plot type GJL 020308 Point lastPoint = new Point(); Point[] Points = new Point[2]; bool isLine = GetPlotType(rpt, iCol, 1).ToUpper() == "LINE"; for (int iRow = 1; iRow <= CategoryCount; iRow++) { double xv = this.GetDataValue(rpt, iRow, iCol, 0); double yv = this.GetDataValue(rpt, iRow, iCol, 1); double bv = this.ChartDefn.Type == ChartTypeEnum.Bubble ? this.GetDataValue(rpt, iRow, iCol, 2) : 0; if (xv < xmin || yv < ymin || xv > xmax || yv > ymax) continue; int x = (int)(((Math.Min(xv, xmax) - xmin) / (xmax - xmin)) * maxPointWidth); int y = (int)(((Math.Min(yv, ymax) - ymin) / (ymax - ymin)) * maxPointHeight); if (y != int.MinValue && x != int.MinValue) { Point p = new Point(Layout.PlotArea.Left + x, Layout.PlotArea.Top + (maxPointHeight - y)); //GJL 010308 Line subtype scatter plot if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Line || (ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.SmoothLine || isLine) { if (!(lastPoint.IsEmpty)) { Points[0] = lastPoint; Points[1] = p; String LineSize = getLineSize(rpt, iCol, 1); int intLineSize = 2; switch (LineSize) { case "Small": intLineSize = 1; break; case "Regular": intLineSize = 2; break; case "Large": intLineSize = 3; break; case "Extra Large": intLineSize = 4; break; case "Super Size": intLineSize = 5; break; } DrawLineBetweenPoints(g, rpt, GetSeriesBrush(rpt, iRow, iCol), Points, intLineSize); //Add a metafilecomment to use as a tooltip GJL 26092008 if (_showToolTips || _showToolTipsX) { string display = ""; if (_showToolTipsX) display = xv.ToString(_tooltipXFormat); if (_showToolTips) { if (display.Length > 0) display += " , "; display += yv.ToString(_tooltipYFormat); } String val = "ToolTip:" + display + "|X:" + (int)(p.X - 3) + "|Y:" + (int)(p.Y - 3) + "|W:" + 6 + "|H:" + 6; g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val)); } } } else { DrawBubble(rpt, g, GetSeriesBrush(rpt, iRow, iCol), p, iRow, iCol, bmin, bmax, bv,xv,yv); } lastPoint = p; } } } return; } /* This code was copied from the Line drawing class. * 010308 GJL */ void DrawLineBetweenPoints(Graphics g, Report rpt, Brush brush, Point[] points) { DrawLineBetweenPoints(g, rpt, brush, points, 2); } void DrawLineBetweenPoints(Graphics g, Report rpt, Brush brush, Point[] points,int intLineSize) { if (points.Length <= 1) // Need at least 2 points return; Pen p = null; try { if (brush.GetType() == typeof(System.Drawing.Drawing2D.HatchBrush)) { System.Drawing.Drawing2D.HatchBrush tmpBrush = (System.Drawing.Drawing2D.HatchBrush)brush; p = new Pen(new SolidBrush(tmpBrush.ForegroundColor), intLineSize); //1.5F); // todo - use line from style ???? } else { p = new Pen(brush, intLineSize); } if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Smooth && points.Length > 2) g.DrawCurve(p, points, 0.5F); else g.DrawLines(p, points); } finally { if (p != null) p.Dispose(); } return; } void DrawBubble(Report rpt, Graphics g, Brush brush, Point p, int iRow, int iCol, double bmin, double bmax, double bv,double xv,double yv) { Pen pen=null; int diameter = BubbleSize(rpt, iRow, iCol, bmin, bmax, bv); // set diameter of bubble int radius= diameter /2; try { if (this.ChartDefn.Type == ChartTypeEnum.Scatter && brush.GetType() == typeof(System.Drawing.Drawing2D.HatchBrush)) { System.Drawing.Drawing2D.HatchBrush tmpBrush = (System.Drawing.Drawing2D.HatchBrush)brush; SolidBrush br = new SolidBrush(tmpBrush.ForegroundColor); pen = new Pen(new SolidBrush(tmpBrush.ForegroundColor)); DrawLegendMarker(g, br, pen, SeriesMarker[iCol - 1], p.X - radius, p.Y - radius, diameter); DrawDataPoint(rpt, g, new Point(p.X - 3, p.Y + 3), iRow, iCol); } else { pen = new Pen(brush); DrawLegendMarker(g, brush, pen, ChartMarkerEnum.Bubble, p.X - radius, p.Y - radius, diameter); DrawDataPoint(rpt, g, new Point(p.X - 3, p.Y + 3), iRow, iCol); } //Add a metafilecomment to use as a tooltip GJL 26092008 if (_showToolTips || _showToolTipsX) { string display = ""; if (_showToolTipsX) display = xv.ToString(_tooltipXFormat); if (_showToolTips) { if (display.Length > 0) display += " , "; display += yv.ToString(_tooltipYFormat); } String val = "ToolTip:" + display + "|X:" + (int)(p.X - 3) + "|Y:" + (int)(p.Y - 3) + "|W:" + 6 + "|H:" + 6; g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val)); } } finally { if (pen != null) pen.Dispose(); } return; } private int BubbleSize(Report rpt, int iRow, int iCol, double minB, double maxB, double bv) { int diameter = 5; if (ChartDefn.Type != ChartTypeEnum.Bubble) return diameter; int bubbleMax = 30; // maximum bubble size int bubbleMin = 4; // minimum bubble size double diff = maxB - minB; double vdiff = bv - minB; if (Math.Abs(diff) < 1e-9d) // very small difference between max and min? return diameter; // just use the smallest diameter = (int) ((vdiff / diff) * (bubbleMax - bubbleMin) + bubbleMin); return diameter; } // Calculate the size of the value axis; width is max value width + title width // height is max value height protected Size ValueAxisSize(Report rpt, Graphics g, double min, double max) { Size size = Size.Empty; if (ChartDefn.ValueAxis == null) return size; Axis a = ChartDefn.ValueAxis.Axis; if (a == null) return size; Size minSize; Size maxSize; if (!a.Visible) { minSize = maxSize = Size.Empty; } else if (a.Style != null) { minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue); maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue); } else { minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue); maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue); } // Choose the largest size.Width = Math.Max(minSize.Width, maxSize.Width); size.Height = Math.Max(minSize.Height, maxSize.Height); // Now we need to add in the width of the title (if any) Size titleSize = DrawTitleMeasure(rpt, g, a.Title); size.Width += titleSize.Width; return size; } protected void DrawValueAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotLeft, int plotRight) { if (this.ChartDefn.ValueAxis == null) return; Axis a = this.ChartDefn.ValueAxis.Axis; if (a == null) return; Style s = a.Style; int intervalCount; double incr; SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count Size tSize = DrawTitleMeasure(rpt, g, a.Title); DrawTitle(rpt, g, a.Title, new System.Drawing.Rectangle(rect.Left, rect.Top, tSize.Width, rect.Height)); double v = min; for (int i = 0; i < intervalCount + 1; i++) { int h = (int)(((Math.Min(v, max) - min) / (max - min)) * rect.Height); if (h < 0) // this is really some form of error { v += incr; continue; } if (!a.Visible) { // nothing to do } else if (s != null) { Size size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue); System.Drawing.Rectangle vRect = new System.Drawing.Rectangle(rect.Left + tSize.Width, rect.Top + rect.Height - h - size.Height / 2, rect.Width - tSize.Width, size.Height); s.DrawString(rpt, g, v, TypeCode.Double, null, vRect); } else { Size size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue); System.Drawing.Rectangle vRect = new System.Drawing.Rectangle(rect.Left + tSize.Width, rect.Top + rect.Height - h - size.Height / 2, rect.Width - tSize.Width, size.Height); Style.DrawStringDefaults(g, v, vRect); } DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(plotLeft, rect.Top + rect.Height - h), new Point(plotRight, rect.Top + rect.Height - h)); DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(plotLeft, rect.Top + rect.Height - h)); v += incr; } // Draw the end points of the major grid lines DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(plotLeft, rect.Top), new Point(plotLeft, rect.Bottom)); DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(plotLeft, rect.Top)); DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(plotRight, rect.Top), new Point(plotRight, rect.Bottom)); DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(plotRight, rect.Bottom)); return; } protected void DrawValueAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e) { if (gl == null || !gl.ShowGridLines) return; if (gl.Style != null) gl.Style.DrawStyleLine(rpt, g, null, s, e); else g.DrawLine(Pens.Black, s, e); return; } protected void DrawValueAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p) { if (tickType == AxisTickMarksEnum.None) return; int len = bMajor ? AxisTickMarkMajorLen : AxisTickMarkMinorLen; Point s, e; switch (tickType) { case AxisTickMarksEnum.Inside: s = new Point(p.X, p.Y); e = new Point(p.X + len, p.Y); break; case AxisTickMarksEnum.Cross: s = new Point(p.X - len, p.Y); e = new Point(p.X + len, p.Y); break; case AxisTickMarksEnum.Outside: default: s = new Point(p.X - len, p.Y); e = new Point(p.X, p.Y); break; } Style style = gl.Style; if (style != null) style.DrawStyleLine(rpt, g, null, s, e); else g.DrawLine(Pens.Black, s, e); return; } ///////////////////////// protected void DrawCategoryAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotTop, int plotBottom) { if (this.ChartDefn.CategoryAxis == null) return; Axis a = this.ChartDefn.CategoryAxis.Axis; if (a == null) return; Style s = a.Style; // Account for tick marks int tickSize = 0; if (a.MajorTickMarks == AxisTickMarksEnum.Cross || a.MajorTickMarks == AxisTickMarksEnum.Outside) tickSize = this.AxisTickMarkMajorLen; else if (a.MinorTickMarks == AxisTickMarksEnum.Cross || a.MinorTickMarks == AxisTickMarksEnum.Outside) tickSize += this.AxisTickMarkMinorLen; int intervalCount; double incr; SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count int maxValueHeight = 0; double v = min; Size size = Size.Empty; for (int i = 0; i < intervalCount + 1; i++) { int x = (int)(((Math.Min(v, max) - min) / (max - min)) * rect.Width); if (!a.Visible) { // nothing to do } else if (s != null) { size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue); System.Drawing.Rectangle vRect = new System.Drawing.Rectangle(rect.Left + x - size.Width / 2, rect.Top + tickSize, size.Width, size.Height); s.DrawString(rpt, g, v, TypeCode.Double, null, vRect); } else { size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue); System.Drawing.Rectangle vRect = new System.Drawing.Rectangle(rect.Left + x - size.Width / 2, rect.Top + tickSize, size.Width, size.Height); Style.DrawStringDefaults(g, v, vRect); } if (size.Height > maxValueHeight) // Need to keep track of the maximum height maxValueHeight = size.Height; // this is probably overkill since it should always be the same?? DrawCategoryAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left + x, plotTop), new Point(rect.Left + x, plotBottom)); DrawCategoryAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left + x, plotBottom)); v += incr; } // Draw the end points of the major grid lines DrawCategoryAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left, plotTop), new Point(rect.Left, plotBottom)); DrawCategoryAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left, plotBottom)); DrawCategoryAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Right, plotTop), new Point(rect.Right, plotBottom)); DrawCategoryAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Right, plotBottom)); Size tSize = DrawTitleMeasure(rpt, g, a.Title); DrawTitle(rpt, g, a.Title, new System.Drawing.Rectangle(rect.Left, rect.Top + maxValueHeight + tickSize, rect.Width, tSize.Height)); return; } protected void DrawCategoryAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e) { if (gl == null || !gl.ShowGridLines) return; if (gl.Style != null) gl.Style.DrawStyleLine(rpt, g, null, s, e); else g.DrawLine(Pens.Black, s, e); return; } protected void DrawCategoryAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p) { if (tickType == AxisTickMarksEnum.None) return; int len = bMajor ? AxisTickMarkMajorLen : AxisTickMarkMinorLen; Point s, e; switch (tickType) { case AxisTickMarksEnum.Inside: s = new Point(p.X, p.Y); e = new Point(p.X, p.Y - len); break; case AxisTickMarksEnum.Cross: s = new Point(p.X, p.Y - len); e = new Point(p.X, p.Y + len); break; case AxisTickMarksEnum.Outside: default: s = new Point(p.X, p.Y + len); e = new Point(p.X, p.Y); break; } Style style = gl.Style; if (style != null) style.DrawStyleLine(rpt, g, null, s, e); else g.DrawLine(Pens.Black, s, e); return; } // Calculate the size of the value axis; width is max value width + title width // height is max value height protected Size CategoryAxisSize(Report rpt, Graphics g, double min, double max) { Size size = Size.Empty; if (ChartDefn.CategoryAxis == null) return size; Axis a = ChartDefn.CategoryAxis.Axis;//Not ValueAxis... if (a == null) return size; Size minSize; Size maxSize; if (!a.Visible) { minSize = maxSize = Size.Empty; } else if (a.Style != null) { minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue); maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue); } else { minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue); maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue); } // Choose the largest size.Width = Math.Max(minSize.Width, maxSize.Width); size.Height = Math.Max(minSize.Height, maxSize.Height); // Now we need to add in the height of the title (if any) Size titleSize = DrawTitleMeasure(rpt, g, a.Title); size.Height += titleSize.Height; if (a.MajorTickMarks == AxisTickMarksEnum.Cross || a.MajorTickMarks == AxisTickMarksEnum.Outside) size.Height += this.AxisTickMarkMajorLen; else if (a.MinorTickMarks == AxisTickMarksEnum.Cross || a.MinorTickMarks == AxisTickMarksEnum.Outside) size.Height += this.AxisTickMarkMinorLen; return size; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using AnlabMvc.Controllers; using AnlabMvc.Models.Roles; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.CodeAnalysis.CSharp.Syntax; using Shouldly; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; namespace Test.TestsController { [Trait("Category", "ControllerTests")] public class ImpersonationControllerTests { //TODO } [Trait("Category", "Controller Reflection")] public class ImpersonationControllerReflectionTests { private readonly ITestOutputHelper output; public ImpersonationControllerReflectionTests(ITestOutputHelper output) { this.output = output; } protected readonly Type ControllerClass = typeof(ImpersonationController); #region Controller Class Tests [Fact] public void TestControllerInheritsFromApplicationController() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act controllerClass.BaseType.ShouldNotBe(null); var result = controllerClass.BaseType.Name; #endregion Act #region Assert result.ShouldBe("ApplicationController"); #endregion Assert } [Fact] public void TestControllerExpectedNumberOfAttributes() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in result) { output.WriteLine(o.ToString()); //Output shows } result.Count().ShouldBe(3); #endregion Assert } /// <summary> /// #1 /// </summary> [Fact] public void TestControllerHasControllerAttribute() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true).OfType<ControllerAttribute>(); #endregion Act #region Assert result.Count().ShouldBeGreaterThan(0, "ControllerAttribute not found."); #endregion Assert } /// <summary> /// #2 /// </summary> [Fact] public void TestControllerHasAutoValidateAntiforgeryTokenAttribute() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true).OfType<AutoValidateAntiforgeryTokenAttribute>(); #endregion Act #region Assert result.Count().ShouldBeGreaterThan(0, "AutoValidateAntiforgeryTokenAttribute not found."); #endregion Assert } /// <summary> /// #3 /// </summary> [Fact] public void TestControllerHasAuthorizeAttributeAttribute() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true).OfType<AuthorizeAttribute>(); #endregion Act #region Assert result.Count().ShouldBeGreaterThan(0, "AuthorizeAttribute not found."); result.ElementAt(0).Roles.ShouldBeNull(); #endregion Assert } #endregion Controller Class Tests #region Controller Method Tests [Fact]//(Skip = "Tests are still being written. When done, remove this line.")] public void TestControllerContainsExpectedNumberOfPublicMethods() { #region Arrange var controllerClass = ControllerClass; #endregion Arrange #region Act var result = controllerClass.GetMethods().Where(a => a.DeclaringType == controllerClass); #endregion Act #region Assert result.Count().ShouldBe(2); #endregion Assert } [Fact] public void TestControllerMethodImpersonateUserContainsExpectedAttributes1() { #region Arrange var controllerClass = ControllerClass; var controllerMethod = controllerClass.GetMethod("ImpersonateUser"); #endregion Arrange #region Act var expectedAttribute = controllerMethod.GetCustomAttributes(true).OfType<AuthorizeAttribute>(); var allAttributes = controllerMethod.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in allAttributes) { output.WriteLine(o.ToString()); //Output shows if the test fails } #if DEBUG allAttributes.Count().ShouldBe(3, "No Attributes"); #else allAttributes.Count().ShouldBe(2, "No Attributes"); #endif expectedAttribute.Count().ShouldBe(1, "AuthorizeAttribute not found"); expectedAttribute.ElementAt(0).Roles.ShouldBe(RoleCodes.Admin); #endregion Assert } [Fact] public void TestControllerMethodImpersonateUserContainsExpectedAttributes2() { #region Arrange var controllerClass = ControllerClass; var controllerMethod = controllerClass.GetMethod("ImpersonateUser"); #endregion Arrange #region Act var expectedAttribute = controllerMethod.GetCustomAttributes(true).OfType<AsyncStateMachineAttribute>(); var allAttributes = controllerMethod.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in allAttributes) { output.WriteLine(o.ToString()); //Output shows if the test fails } #if DEBUG allAttributes.Count().ShouldBe(3, "No Attributes"); #else allAttributes.Count().ShouldBe(2, "No Attributes"); #endif expectedAttribute.Count().ShouldBe(1, "AsyncStateMachineAttribute not found"); #endregion Assert } #if DEBUG [Fact] public void TestControllerMethodImpersonateUserContainsExpectedAttributes3() { #region Arrange var controllerClass = ControllerClass; var controllerMethod = controllerClass.GetMethod("ImpersonateUser"); #endregion Arrange #region Act var expectedAttribute = controllerMethod.GetCustomAttributes(true).OfType<DebuggerStepThroughAttribute>(); var allAttributes = controllerMethod.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in allAttributes) { output.WriteLine(o.ToString()); //Output shows if the test fails } allAttributes.Count().ShouldBe(3, "No Attributes"); expectedAttribute.Count().ShouldBe(1, "DebuggerStepThroughAttribute not found"); #endregion Assert } #endif #endregion Controller Method Tests } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); readonly Func<TWrite, byte[]> serializer; readonly Func<byte[], TRead> deserializer; protected readonly object myLock = new object(); protected CallSafeHandle call; protected bool disposed; protected bool started; protected bool errorOccured; protected bool cancelRequested; protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null. protected AsyncCompletionDelegate<TRead> readCompletionDelegate; // Completion of a pending send or sendclose if not null. protected bool readingDone; protected bool halfcloseRequested; protected bool halfclosed; protected bool finished; // True if close has been received from the peer. protected bool initialMetadataSent; protected long streamingWritesCounter; public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer) { this.serializer = Preconditions.CheckNotNull(serializer); this.deserializer = Preconditions.CheckNotNull(deserializer); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { Preconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> public void CancelWithStatus(Status status) { lock (myLock) { Preconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(CallSafeHandle call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartSendMessageInternal(TWrite msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent); sendCompletionDelegate = completionDelegate; initialMetadataSent = true; streamingWritesCounter++; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartReadMessageInternal(AsyncCompletionDelegate<TRead> completionDelegate) { lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckReadingAllowed(); call.StartReceiveMessage(HandleReadFinished); readCompletionDelegate = completionDelegate; } } // TODO(jtattermusch): find more fitting name for this method. /// <summary> /// Default behavior just completes the read observer, but more sofisticated behavior might be required /// by subclasses. /// </summary> protected virtual void ProcessLastRead(AsyncCompletionDelegate<TRead> completionDelegate) { FireCompletion(completionDelegate, default(TRead), null); } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { if (!disposed && call != null) { bool noMoreSendCompletions = halfclosed || (cancelRequested && sendCompletionDelegate == null); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } private void ReleaseResources() { OnReleaseResources(); if (call != null) { call.Dispose(); } disposed = true; } protected virtual void OnReleaseResources() { } protected void CheckSendingAllowed() { Preconditions.CheckState(started); Preconditions.CheckState(!errorOccured); CheckNotCancelled(); Preconditions.CheckState(!disposed); Preconditions.CheckState(!halfcloseRequested, "Already halfclosed."); Preconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time"); } protected void CheckReadingAllowed() { Preconditions.CheckState(started); Preconditions.CheckState(!disposed); Preconditions.CheckState(!errorOccured); Preconditions.CheckState(!readingDone, "Stream has already been closed."); Preconditions.CheckState(readCompletionDelegate == null, "Only one read can be pending at a time"); } protected void CheckNotCancelled() { if (cancelRequested) { throw new OperationCanceledException("Remote call has been cancelled."); } } protected byte[] UnsafeSerialize(TWrite msg) { return serializer(msg); } protected bool TrySerialize(TWrite msg, out byte[] payload) { try { payload = serializer(msg); return true; } catch (Exception e) { Logger.Error(e, "Exception occured while trying to serialize message"); payload = null; return false; } } protected bool TryDeserialize(byte[] payload, out TRead msg) { try { msg = deserializer(payload); return true; } catch (Exception e) { Logger.Error(e, "Exception occured while trying to deserialize message."); msg = default(TRead); return false; } } protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error) { try { completionDelegate(value, error); } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } /// <summary> /// Handles send completion. /// </summary> protected void HandleSendFinished(bool success, BatchContextSafeHandle ctx) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Send failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles halfclose completion. /// </summary> protected void HandleHalfclosed(bool success, BatchContextSafeHandle ctx) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { halfclosed = true; origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Halfclose failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, BatchContextSafeHandle ctx) { var payload = ctx.GetReceivedMessage(); AsyncCompletionDelegate<TRead> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = readCompletionDelegate; if (payload != null) { readCompletionDelegate = null; } else { // This was the last read. Keeping the readCompletionDelegate // to be either fired by this handler or by client-side finished // handler. readingDone = true; } ReleaseResourcesIfPossible(); } // TODO: handle the case when error occured... if (payload != null) { // TODO: handle deserialization error TRead msg; TryDeserialize(payload, out msg); FireCompletion(origCompletionDelegate, msg, null); } else { ProcessLastRead(origCompletionDelegate); } } } }
//----------------------------------------------------------------------- // This file is part of Microsoft Robotics Developer Studio Code Samples. // // Copyright (C) Microsoft Corporation. All rights reserved. // // $File: MicrosoftGps.cs $ $Revision: 1 $ //----------------------------------------------------------------------- //#define TRACEDATA using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Net; using System.Net.Mime; using System.Security.Permissions; using W3C.Soap; using Microsoft.Ccr.Core; using Microsoft.Dss.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.Core.DsspHttpUtilities; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using Microsoft.Robotics.Services.Sensors.Gps.Properties; using submgr = Microsoft.Dss.Services.SubscriptionManager; namespace Microsoft.Robotics.Services.Sensors.Gps { /// <summary> /// Microsoft Gps Service Implementation /// </summary> [Contract(Contract.Identifier)] [DisplayName("(User) Microsoft GPS-360")] [Description("Provides GPS data in NMEA 0183 output format.")] public class MicrosoftGpsService : DsspServiceBase { private bool simulateFromLogNmea = false; [EmbeddedResource("Microsoft.Robotics.Services.Sensors.Gps.MicrosoftGps.user.xslt")] private string _transformGpsData = null; [EmbeddedResource("Microsoft.Robotics.Services.Sensors.Gps.MicrosoftGpsMap.user.xslt")] private string _transformGpsMap = null; private const double _knotsToMetersPerSecond = 0.514444444; private const string _root = "/MicrosoftGps"; private const string _showTop = "/top"; private const string _showMap = "/map"; private const string _configFile = ServicePaths.Store + "/MicrosoftGps.config.xml"; const string Tag_GpGga = "GPGGA"; const string Tag_GpGsa = "GPGSA"; const string Tag_GpGll = "GPGLL"; const string Tag_GpGsv = "GPGSV"; const string Tag_GpRmc = "GPRMC"; const string Tag_GpVtg = "GPVTG"; /// <summary> /// The Microsoft Gps main port /// </summary> [ServicePort(_root, AllowMultipleInstances = true)] #if DEBUG [SuppressMessage("Microsoft.Performance", "CA1805", Justification = "ServicePort requires field initialization")] #endif private MicrosoftGpsOperations _mainPort = new MicrosoftGpsOperations(); /// <summary> /// The Microsoft Gps current state /// </summary> [InitialStatePartner(Optional = true, ServiceUri = _configFile)] private GpsState _state = new GpsState(); /// <summary> /// The subscription manager which keeps track of subscriptions to our Gps data /// </summary> [Partner("SubMgr", Contract = submgr.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.CreateAlways)] submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort(); /// <summary> /// Communicate with the Gps hardware /// </summary> private GpsConnection _gpsConnection = null; /// <summary> /// A CCR port for receiving Gps data /// </summary> private GpsDataPort _gpsDataPort = new GpsDataPort(); /// <summary> /// Http helpers /// </summary> private DsspHttpUtilitiesPort _httpUtilities = new DsspHttpUtilitiesPort(); /// <summary> /// Default Constructor /// </summary> public MicrosoftGpsService(DsspServiceCreationPort creationPort) : base(creationPort) { } /// <summary> /// Service Start /// </summary> protected override void Start() { if (_state == null) { _state = new GpsState(); _state.MicrosoftGpsConfig = new MicrosoftGpsConfig(); _state.MicrosoftGpsConfig.CommPort = 0; _state.MicrosoftGpsConfig.CaptureHistory = true; _state.MicrosoftGpsConfig.CaptureNmea = true; _state.MicrosoftGpsConfig.RetrackNmea = false; SaveState(_state); } else { // Clear old Gps readings _state.GpGga = null; _state.GpGll = null; _state.GpGsa = null; _state.GpGsv = null; _state.GpRmc = null; _state.GpVtg = null; } _httpUtilities = DsspHttpUtilitiesService.Create(Environment); if (_state.MicrosoftGpsConfig == null) _state.MicrosoftGpsConfig = new MicrosoftGpsConfig(); // Publish the service to the local Node Directory DirectoryInsert(); if (simulateFromLogNmea) { SpawnIterator(SimulateMicrosoftGps); } else { _gpsConnection = new GpsConnection(_state.MicrosoftGpsConfig, _gpsDataPort); setCaptureNmea(); SpawnIterator(ConnectToMicrosoftGps); } // Listen on the main port for requests and call the appropriate handler. Interleave mainInterleave = ActivateDsspOperationHandlers(); mainInterleave.CombineWith(new Interleave(new ExclusiveReceiverGroup( Arbiter.Receive<string[]>(true, _gpsDataPort, DataReceivedHandler) ,Arbiter.Receive<Exception>(true, _gpsDataPort, ExceptionHandler) #if TRACEDATA // see Info messages with data strings coming from GPS at http://localhost:50000/console/output ,Arbiter.Receive<string>(true, _gpsDataPort, MessageHandler) #endif ), new ConcurrentReceiverGroup())); // display HTTP service Uri LogInfo(LogGroups.Console, "Overhead view [" + FindServiceAliasFromScheme(Uri.UriSchemeHttp) + "/top]\r\n* Service uri: "); LogInfo(LogGroups.Console, "Map view [" + FindServiceAliasFromScheme(Uri.UriSchemeHttp) + "/map]\r\n* Service uri: "); LogInfo(LogGroups.Console, string.Format("Switches: CaptureHistory={0} CaptureNmea={1} RetrackNmea={2}", _state.MicrosoftGpsConfig.CaptureHistory, _state.MicrosoftGpsConfig.CaptureNmea, _state.MicrosoftGpsConfig.RetrackNmea)); Console.WriteLine(string.Format("Switches: CaptureHistory={0} CaptureNmea={1} RetrackNmea={2}", _state.MicrosoftGpsConfig.CaptureHistory, _state.MicrosoftGpsConfig.CaptureNmea, _state.MicrosoftGpsConfig.RetrackNmea)); } private void setCaptureNmea() { if (_gpsConnection != null) { _gpsConnection.captureNmea = false; //_gpsConnection.nmeaFileName = ServicePaths.Store + "/MicrosoftGps.nmea"; _gpsConnection.nmeaFileName = Path.Combine(@"C:\Microsoft Robotics Dev Studio 4\store", string.Format("MicrosoftGps_{0:yyyyMMdd_HHmmss}.nmea", DateTime.Now)); _gpsConnection.captureNmea = _state.MicrosoftGpsConfig.CaptureNmea; Console.WriteLine("FYI: setCaptureNmea(): " + _state.MicrosoftGpsConfig.CaptureNmea); } else { Console.WriteLine("Warning: _gpsConnection is null in setCaptureNmea()"); } } #region Service Handlers /// <summary> /// Handle Errors /// </summary> /// <param name="ex"></param> private void ExceptionHandler(Exception ex) { LogError(ex.Message); } /// <summary> /// Handle messages /// </summary> /// <param name="message"></param> private void MessageHandler(string message) { LogInfo(message); } /// <summary> /// Handle inbound Gps Data /// </summary> /// <param name="fields"></param> private void DataReceivedHandler(string[] fields) { //string nmeaLine = string.Join(",", fields); // no checksum //Console.WriteLine(nmeaLine); if (fields[0].Equals("$GPGGA")) GgaHandler(fields); else if (fields[0].Equals("$GPGSA")) GsaHandler(fields); else if (fields[0].Equals("$GPGLL")) GllHandler(fields); else if (fields[0].Equals("$GPGSV")) GsvHandler(fields); else if (fields[0].Equals("$GPRMC")) RmcHandler(fields); else if (fields[0].Equals("$GPVTG")) VtgHandler(fields); else { string line = string.Join(",", fields); MessageHandler(Resources.UnhandledGpsData + line); } } /// <summary> /// Handle Gps GPGGA data packet /// </summary> /// <param name="fields"></param> private void GgaHandler(string[] fields) { try { if (_state.GpGga == null) _state.GpGga = new GpGga(); _state.GpGga.IsValid = false; if (fields.Length != 15) { MessageHandler(string.Format(CultureInfo.InvariantCulture, "Invalid Number of parameters in GPGGA ({0}/{1})", fields.Length, 15)); return; } _state.GpGga.LastUpdate = DateTime.Now; _state.GpGga.UTCPosition = DateTime.Now.ToUniversalTime().Date.Add(ParseUTCTime(fields[1])); // hhmmss.sss _state.GpGga.Latitude = ParseLatitude(fields[2], fields[3]); _state.GpGga.Longitude = ParseLongitude(fields[4], fields[5]); _state.GpGga.PositionFixIndicator = (PositionFixIndicator)int.Parse(fields[6], CultureInfo.InvariantCulture); // table 3 _state.GpGga.SatellitesUsed = int.Parse(fields[7], CultureInfo.InvariantCulture); _state.GpGga.AltitudeUnits = fields[10]; // M-Meters _state.GpGga.GeoIdSeparation = fields[11]; _state.GpGga.GeoIdSeparationUnits = fields[12]; // M-Meters _state.GpGga.AgeOfDifferentialCorrection = fields[13]; // null when DGPS not used _state.GpGga.DiffRefStationId = fields[14]; if (_state.GpGga.PositionFixIndicator != PositionFixIndicator.FixNotAvailable) { _state.GpGga.HorizontalDilutionOfPrecision = double.Parse(fields[8], CultureInfo.InvariantCulture); // 50.0 is bad _state.GpGga.AltitudeMeters = double.Parse(fields[9], CultureInfo.InvariantCulture); // no geoid corrections, values are WGS84 ellipsoid heights _state.GpGga.IsValid = true; } SendNotification(_subMgrPort, new GpGgaNotification(_state.GpGga), Tag_GpGga, _state.GpGga.IsValid.ToString()); } catch (Exception ex) { Debug.WriteLine("Exception in GgaHandler(): " + ex); _gpsDataPort.Post(ex); } } /// <summary> /// Handle Gps GPGSA data packet /// </summary> /// <param name="fields"></param> private void GsaHandler(string[] fields) { try { if (_state.GpGsa == null) _state.GpGsa = new GpGsa(); _state.GpGsa.IsValid = false; if (fields.Length != 18) { MessageHandler(string.Format(CultureInfo.InvariantCulture, "Invalid Number of parameters in GPGSA ({0}/{1})", fields.Length, 18)); return; } string Mode1 = fields[1]; // M-Manual A-Automatic switch between 2D and 3d int Mode2 = int.Parse(fields[2], CultureInfo.InvariantCulture); // 1-Fix not available, 2-2D, 3-3D string Status; switch (Mode2) { case 2: Status = "2D Fix"; break; case 3: Status = "3D Fix"; break; default: Status = "Fix not available"; break; } int satelliteId; for(int i = 0; i < 12; i++) { if (int.TryParse(fields[i + 3], NumberStyles.Integer, CultureInfo.InvariantCulture, out satelliteId)) _state.GpGsa._satelliteUsed[i] = satelliteId; else _state.GpGsa._satelliteUsed[i] = 0; } double SphericalDilutionOfPrecision = -1.0d; double.TryParse(fields[15], out SphericalDilutionOfPrecision); double HorizontalDilutionOfPrecision = -1.0d; double.TryParse(fields[16], out HorizontalDilutionOfPrecision); double VerticalDilutionOfPrecision = -1.0d; double.TryParse(fields[17], out VerticalDilutionOfPrecision); _state.GpGsa.LastUpdate = DateTime.Now; _state.GpGsa.Status = Status; _state.GpGsa.AutoManual = Mode1; _state.GpGsa.Mode = (GsaMode)Mode2; _state.GpGsa.SphericalDilutionOfPrecision = SphericalDilutionOfPrecision; _state.GpGsa.HorizontalDilutionOfPrecision = HorizontalDilutionOfPrecision; _state.GpGsa.VerticalDilutionOfPrecision = VerticalDilutionOfPrecision; _state.GpGsa.IsValid = (_state.GpGsa.Mode != GsaMode.NoFix); if (_state.MicrosoftGpsConfig.CaptureHistory && _state.GpGsa != null && _state.GpGsa.IsValid // GSA: Precision data. && (_state.GpGll != null && _state.GpGll.IsValid || _state.GpRmc != null && _state.GpRmc.IsValid) && _state.GpGga != null && _state.GpGga.IsValid) // GGA: Altitude and backup position. { double Latitude, Longitude; DateTime LastUpdate; if (_state.GpGll != null && _state.GpGll.IsValid) { // GLL: Primary Position. Latitude = _state.GpGll.Latitude; Longitude = _state.GpGll.Longitude; LastUpdate = _state.GpGll.LastUpdate; } else { // RMC: Backup course, speed, and position. Latitude = _state.GpRmc.Latitude; Longitude = _state.GpRmc.Longitude; LastUpdate = _state.GpRmc.LastUpdate; } EarthCoordinates ec = new EarthCoordinates(Latitude, Longitude, _state.GpGga.AltitudeMeters, LastUpdate, _state.GpGsa.HorizontalDilutionOfPrecision, _state.GpGsa.VerticalDilutionOfPrecision); _state.History.Add(ec); if (_state.History.Count % 100 == 0) SaveState(_state); } SendNotification(_subMgrPort, new GpGsaNotification(_state.GpGsa), Tag_GpGsa, _state.GpGsa.IsValid.ToString()); } catch (Exception ex) { Debug.WriteLine("Exception in GsaHandler(): " + ex); _gpsDataPort.Post(ex); } } /// <summary> /// Handle Gps GPGLL data packet /// </summary> /// <param name="fields"></param> private void GllHandler(string[] fields) { try { if (_state.GpGll == null) _state.GpGll = new GpGll(); _state.GpGll.IsValid = false; if (fields.Length != 7) { MessageHandler(string.Format(CultureInfo.InvariantCulture, "Invalid Number of parameters in GPGLL ({0}/{1})", fields.Length, 7)); return; } _state.GpGll.LastUpdate = DateTime.Now; _state.GpGll.Latitude = ParseLatitude(fields[1], fields[2]); _state.GpGll.Longitude = ParseLongitude(fields[3], fields[4]); _state.GpGll.GllTime = DateTime.Now.ToUniversalTime().Date.Add(ParseUTCTime(fields[5])); _state.GpGll.Status = (fields[6].Length > 0) ? fields[6].Substring(0, 1) : string.Empty; _state.GpGll.IsValid = (_state.GpGll.Status == "A"); SendNotification(_subMgrPort, new GpGllNotification(_state.GpGll), Tag_GpGll, _state.GpGll.IsValid.ToString()); } catch (Exception ex) { Debug.WriteLine("Exception in GllHandler(): " + ex); _gpsDataPort.Post(ex); } } /// <summary> /// Handle Gps GPGSV data packet /// </summary> /// <param name="fields"></param> private void GsvHandler(string[] fields) { try { if (_state.GpGsv == null) _state.GpGsv = new GpGsv(); _state.GpGsv.IsValid = false; int NumberOfMessages = int.Parse(fields[1], CultureInfo.InvariantCulture); int MessageNumber = int.Parse(fields[2], CultureInfo.InvariantCulture); int satellitesInView = int.Parse(fields[3], CultureInfo.InvariantCulture); int priorMessages = (4 * (MessageNumber - 1)); int currentMessages = Math.Min(4, satellitesInView - priorMessages); int ColumnsExpected = 4 + (currentMessages * 4); if (fields.Length != ColumnsExpected) { MessageHandler(string.Format(CultureInfo.InvariantCulture, "Invalid Number of parameters in GPGSV ({0}/{1})", fields.Length, ColumnsExpected)); return; } if (_state.GpGsv._gsvSatellites == null || _state.GpGsv._gsvSatellites.Length != satellitesInView) { _state.GpGsv._gsvSatellites = new GsvSatellite[satellitesInView]; for (int i = 0; i < satellitesInView; i++) _state.GpGsv._gsvSatellites[i] = new GsvSatellite(); } int number; for (int i = 0; i < currentMessages; i++) { string satelliteId = fields[4 + (i * 4)]; if (!string.IsNullOrEmpty(satelliteId) && int.TryParse(satelliteId, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) _state.GpGsv._gsvSatellites[priorMessages + i].Id = number; string elevationDegrees = fields[5 + (i * 4)]; if (!string.IsNullOrEmpty(elevationDegrees) && int.TryParse(elevationDegrees, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) _state.GpGsv._gsvSatellites[priorMessages + i].ElevationDegrees = number; string azimuthDegrees = fields[6 + (i * 4)]; if (!string.IsNullOrEmpty(azimuthDegrees) && int.TryParse(azimuthDegrees, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) _state.GpGsv._gsvSatellites[priorMessages + i].AzimuthDegrees = number; string signalToNoiseRatio = fields[7 + (i * 4)]; if (!string.IsNullOrEmpty(signalToNoiseRatio) && int.TryParse(signalToNoiseRatio, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) _state.GpGsv._gsvSatellites[priorMessages + i].SignalToNoiseRatio = number; else _state.GpGsv._gsvSatellites[priorMessages + i].SignalToNoiseRatio = -1; } _state.GpGsv.LastUpdate = DateTime.Now; _state.GpGsv.SatellitesInView = satellitesInView; _state.GpGsv.IsValid = (satellitesInView > 1); SendNotification(_subMgrPort, new GpGsvNotification(_state.GpGsv), Tag_GpGsv, _state.GpGsv.IsValid.ToString()); } catch (Exception ex) { Debug.WriteLine("Exception in GsvHandler(): " + ex); _gpsDataPort.Post(ex); } } /// <summary> /// Handle Gps GPRMC data packet /// </summary> /// <param name="fields"></param> private void RmcHandler(string[] fields) { try { if (_state.GpRmc == null) _state.GpRmc = new GpRmc(); _state.GpRmc.IsValid = false; if (fields.Length < 11 || fields.Length > 13) { MessageHandler(string.Format(CultureInfo.InvariantCulture, "Invalid Number of parameters in GPRMC ({0}/{1})", fields.Length, 12)); return; } string UtcTime = fields[1]; string Status = fields[2]; // V string latitude = fields[3]; string northSouth = fields[4]; string longitude = fields[5]; string eastWest = fields[6]; double speedKnots = 0; if (IsNumericDouble(fields[7])) { speedKnots = double.Parse(fields[7], CultureInfo.InvariantCulture); } string courseDegrees = fields[8]; string dateDDMMYY = fields[9]; //120120 is bad data // string magneticVariationDegrees = fields[10]; _state.GpRmc.LastUpdate = DateTime.Now; _state.GpRmc.Status = Status; _state.GpRmc.Latitude = ParseLatitude(latitude, northSouth); _state.GpRmc.Longitude = ParseLongitude(longitude, eastWest); _state.GpRmc.SpeedMetersPerSecond = KnotsToMetersPerSecond(speedKnots); if (IsNumericDouble(courseDegrees)) { _state.GpRmc.CourseDegrees = double.Parse(courseDegrees, CultureInfo.InvariantCulture); } _state.GpRmc.DateTime = ParseUTCDateTime(dateDDMMYY, UtcTime); // hhmmss.sss // Validate! _state.GpRmc.IsValid = (Status != "V"); SendNotification(_subMgrPort, new GpRmcNotification(_state.GpRmc), Tag_GpRmc, _state.GpRmc.IsValid.ToString()); } catch (Exception ex) { Debug.WriteLine("Exception in RmcHandler(): " + ex); _gpsDataPort.Post(ex); } } /// <summary> /// Handle Gps GPVTG data packet /// </summary> /// <param name="fields"></param> private void VtgHandler(string[] fields) { try { if (_state.GpVtg == null) _state.GpVtg = new GpVtg(); _state.GpVtg.IsValid = false; if (fields.Length != 9 && fields.Length != 10) { MessageHandler(string.Format(CultureInfo.InvariantCulture, "Invalid Number of parameters in GPVTG ({0}/{1})", fields.Length, 9)); return; } _state.GpVtg.LastUpdate = DateTime.Now; string CourseDegrees = fields[1]; string Reference = fields[2]; // T = True string Course2 = fields[3]; string Reference2 = fields[4]; // M = Magnetic string Speed1 = fields[5]; string Units1 = fields[6]; // N = Knots string Speed2 = fields[7]; string Units2 = fields[8]; // K = Kilometer per hour if (IsNumericDouble(CourseDegrees) && (Reference == "T" || Reference2 != "T" || !IsNumericDouble(Course2))) _state.GpVtg.CourseDegrees = double.Parse(CourseDegrees, CultureInfo.InvariantCulture); else if (IsNumericDouble(Course2)) _state.GpVtg.CourseDegrees = double.Parse(Course2, CultureInfo.InvariantCulture); double speed = -1; string units = string.Empty; if (IsNumericDouble(Speed1) && (Units1 == "N" || Units1 == "K")) { speed = double.Parse(Speed1, CultureInfo.InvariantCulture); units = Units1; } else if (IsNumericDouble(Speed2) && (Units2 == "N" || Units2 == "K")) { speed = double.Parse(Speed2, CultureInfo.InvariantCulture); units = Units2; } if (speed < 0) return; if (units.Equals("N", StringComparison.OrdinalIgnoreCase)) _state.GpVtg.SpeedMetersPerSecond = KnotsToMetersPerSecond(speed); else if (units.Equals("K", StringComparison.OrdinalIgnoreCase)) _state.GpVtg.SpeedMetersPerSecond = speed * 1000.0 / 60.0 / 60.0; _state.GpVtg.IsValid = true; SendNotification(_subMgrPort, new GpVtgNotification(_state.GpVtg), Tag_GpVtg, _state.GpVtg.IsValid.ToString()); } catch (Exception ex) { Debug.WriteLine("Exception in VtgHandler(): " + ex); _gpsDataPort.Post(ex); } } #endregion #region Operation Handlers /// <summary> /// Http Get Handler /// </summary> /// <param name="httpGet"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet) { HttpListenerRequest request = httpGet.Body.Context.Request; HttpListenerResponse response = httpGet.Body.Context.Response; Stream image = null; HttpResponseType rsp = null; string path = request.Url.AbsolutePath.ToLowerInvariant(); if (path.StartsWith(_root, StringComparison.InvariantCultureIgnoreCase)) { if (path.EndsWith(_showTop, StringComparison.InvariantCultureIgnoreCase)) { image = GenerateTop(800); if (image != null) { SendJpeg(httpGet.Body.Context, image); } else { httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason( W3C.Soap.FaultCodes.Receiver, DsspFaultCodes.OperationFailed, "Unable to generate Image")); } yield break; } else if (path.EndsWith(_showMap, StringComparison.InvariantCultureIgnoreCase)) { rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsMap); httpGet.ResponsePort.Post(rsp); yield break; } } rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsData); httpGet.ResponsePort.Post(rsp); yield break; } /// <summary> /// Http Post Handler /// </summary> /// <param name="httpPost"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { // Use helper to read form data ReadFormData readForm = new ReadFormData(httpPost); _httpUtilities.Post(readForm); // Wait for result Activate(Arbiter.Choice(readForm.ResultPort, delegate(NameValueCollection parameters) { if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "MicrosoftGpsConfig" ) { if (parameters["buttonOk"] == "Search") { FindGpsConfig findConfig = new FindGpsConfig(); _mainPort.Post(findConfig); Activate( Arbiter.Choice( Arbiter.Receive<MicrosoftGpsConfig>(false, findConfig.ResponsePort, delegate(MicrosoftGpsConfig response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, findConfig.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } else if (parameters["buttonOk"] == "Connect and Update") { MicrosoftGpsConfig config = (MicrosoftGpsConfig)_state.MicrosoftGpsConfig.Clone(); int port; if (int.TryParse(parameters["CommPort"], out port) && port >= 0) { config.CommPort = port; config.PortName = "COM" + port.ToString(); } int baud; if (int.TryParse(parameters["BaudRate"], out baud) && GpsConnection.ValidBaudRate(baud)) { config.BaudRate = baud; } config.CaptureHistory = ((parameters["CaptureHistory"] ?? "off") == "on"); config.CaptureNmea = ((parameters["CaptureNmea"] ?? "off") == "on"); config.RetrackNmea = ((parameters["RetrackNmea"] ?? "off") == "on"); Console.WriteLine(string.Format("Switches: CaptureHistory={0} CaptureNmea={1} RetrackNmea={2}", config.CaptureHistory, config.CaptureNmea, config.RetrackNmea)); Configure configure = new Configure(config); _mainPort.Post(configure); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, configure.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, configure.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } } else { HttpPostFailure(httpPost, null); } }, delegate(Exception Failure) { LogError(Failure.Message); }) ); yield break; } /// <summary> /// Send Http Post Success Response /// </summary> /// <param name="httpPost"></param> private void HttpPostSuccess(HttpPost httpPost) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsData); httpPost.ResponsePort.Post(rsp); } /// <summary> /// Send Http Post Failure Response /// </summary> /// <param name="httpPost"></param> /// <param name="fault"></param> private static void HttpPostFailure(HttpPost httpPost, Fault fault) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.BadRequest, fault); httpPost.ResponsePort.Post(rsp); } /// <summary> /// Get Handler /// </summary> /// <param name="get"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public virtual IEnumerator<ITask> GetHandler(Get get) { get.ResponsePort.Post(_state); yield break; } /// <summary> /// Configure Handler /// </summary> /// <param name="update"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> ConfigureHandler(Configure update) { _state.MicrosoftGpsConfig = update.Body; bool connected = _gpsConnection.Open(_state.MicrosoftGpsConfig.CommPort, _state.MicrosoftGpsConfig.BaudRate); if (_state.MicrosoftGpsConfig.CaptureHistory) _state.History = new List<EarthCoordinates>(); else _state.History = null; SaveState(_state); setCaptureNmea(); update.ResponsePort.Post(DefaultUpdateResponseType.Instance); yield break; } /// <summary> /// Subscribe Handler /// </summary> /// <param name="subscribe"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> SubscribeHandler(Subscribe subscribe) { SubscribeRequest request = subscribe.Body; submgr.InsertSubscription insert = new submgr.InsertSubscription(request); insert.Body.FilterType = submgr.FilterType.Default; string valid = request.ValidOnly ? "True" : null; List<submgr.QueryType> query = new List<submgr.QueryType>(); if (request.MessageTypes == GpsMessageType.All || request.MessageTypes == GpsMessageType.None) { if (request.ValidOnly) { query.Add(new submgr.QueryType(null, valid)); } } else { if ((request.MessageTypes & GpsMessageType.GPGGA) != 0) { query.Add(new submgr.QueryType(Tag_GpGga, valid)); } if ((request.MessageTypes & GpsMessageType.GPGLL) != 0) { query.Add(new submgr.QueryType(Tag_GpGll, valid)); } if ((request.MessageTypes & GpsMessageType.GPGSA) != 0) { query.Add(new submgr.QueryType(Tag_GpGsa, valid)); } if ((request.MessageTypes & GpsMessageType.GPGSV) != 0) { query.Add(new submgr.QueryType(Tag_GpGsv, valid)); } if ((request.MessageTypes & GpsMessageType.GPRMC) != 0) { query.Add(new submgr.QueryType(Tag_GpRmc, valid)); } if ((request.MessageTypes & GpsMessageType.GPVTG) != 0) { query.Add(new submgr.QueryType(Tag_GpVtg, valid)); } } if (query.Count > 0) { insert.Body.QueryList = query.ToArray(); } _subMgrPort.Post(insert); yield return Arbiter.Choice( insert.ResponsePort, subscribe.ResponsePort.Post, subscribe.ResponsePort.Post ); } /// <summary> /// Find a Microsoft GPS on any serial port /// </summary> /// <param name="query"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> FindGpsConfigHandler(FindGpsConfig query) { _state.Connected = _gpsConnection.FindGps(); if (_state.Connected) { _state.MicrosoftGpsConfig = _gpsConnection.MicrosoftGpsConfig; SaveState(_state); } query.ResponsePort.Post(_state.MicrosoftGpsConfig); yield break; } /// <summary> /// SendGpsCommand Handler /// </summary> /// <param name="update"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> SendGpsCommandHandler(SendMicrosoftGpsCommand update) { update.ResponsePort.Post( Fault.FromException( new NotImplementedException("The Microsoft Gps service is a sample. Sending commands to the GPS is an exercise left to the community."))); yield break; } /// <summary> /// Shut down the GPS connection /// </summary> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Teardown)] public virtual IEnumerator<ITask> DropHandler(DsspDefaultDrop drop) { if (_state.Connected) { _gpsConnection.Close(); _state.Connected = false; } base.DefaultDropHandler(drop); yield break; } #endregion #region GPS NMEA Log Reader for simulation private IEnumerator<ITask> SimulateMicrosoftGps() { yield return TimeoutPort(20000).Receive(); // initial startup delay string nmeaFileName = @"C:\Microsoft Robotics Dev Studio 4\store\MicrosoftGps - Copy.nmea"; // Open and read the file. using (StreamReader r = File.OpenText(nmeaFileName)) { string line; while ((line = r.ReadLine()) != null) { Console.WriteLine(line); int ix = line.IndexOf('*'); if (ix > 0) { string[] fields = line.Substring(0, ix).Split(','); _gpsDataPort.Post(fields); } yield return TimeoutPort(1000).Receive(); } r.Close(); } yield break; } #endregion // GPS NMEA Log Reader for simulation #region Gps Helpers /// <summary> /// Connect to a Microsoft Gps. /// If no configuration exists, search for the connection. /// </summary> private IEnumerator<ITask> ConnectToMicrosoftGps() { try { _state.GpGga = null; _state.GpGll = null; _state.GpGsa = null; _state.GpGsv = null; _state.GpRmc = null; _state.GpVtg = null; _state.Connected = false; if (_state.MicrosoftGpsConfig.CommPort != 0 && _state.MicrosoftGpsConfig.BaudRate != 0) { _state.MicrosoftGpsConfig.ConfigurationStatus = "Opening Gps on Port " + _state.MicrosoftGpsConfig.CommPort.ToString(); Console.WriteLine(_state.MicrosoftGpsConfig.ConfigurationStatus + " Baud: " + _state.MicrosoftGpsConfig.BaudRate); _state.Connected = _gpsConnection.Open(_state.MicrosoftGpsConfig.CommPort, _state.MicrosoftGpsConfig.BaudRate); Console.WriteLine("Connected: " + _state.Connected); } else if (File.Exists(_state.MicrosoftGpsConfig.PortName)) { _state.MicrosoftGpsConfig.ConfigurationStatus = "Opening Gps on " + _state.MicrosoftGpsConfig.PortName; Console.WriteLine(_state.MicrosoftGpsConfig.ConfigurationStatus); _state.Connected = _gpsConnection.Open(_state.MicrosoftGpsConfig.PortName); Console.WriteLine("Connected: " + _state.Connected); } else { _state.MicrosoftGpsConfig.ConfigurationStatus = "Searching for the GPS Port"; Console.WriteLine(_state.MicrosoftGpsConfig.ConfigurationStatus); _state.Connected = _gpsConnection.FindGps(); Console.WriteLine("Connected: " + _state.Connected); if (_state.Connected) { _state.MicrosoftGpsConfig = _gpsConnection.MicrosoftGpsConfig; SaveState(_state); Console.WriteLine("Port:: " + _state.MicrosoftGpsConfig.CommPort + " Baud: " + _state.MicrosoftGpsConfig.BaudRate); } } } catch (UnauthorizedAccessException ex) { LogError(ex); } catch (IOException ex) { LogError(ex); } catch (ArgumentOutOfRangeException ex) { LogError(ex); } catch (ArgumentException ex) { LogError(ex); } catch (InvalidOperationException ex) { LogError(ex); } if (!_state.Connected) { _state.MicrosoftGpsConfig.ConfigurationStatus = "Not Connected"; LogInfo(LogGroups.Console, "The Microsoft GPS is not detected.\r\n* To configure the Microsoft Gps, navigate to: "); } else { _state.MicrosoftGpsConfig.ConfigurationStatus = "Connected"; } yield break; } /// <summary> /// Convert knots to meters per second /// </summary> /// <param name="knots"></param> /// <returns></returns> public static double KnotsToMetersPerSecond(double knots) { if (knots >= 0) return knots * _knotsToMetersPerSecond; return -1; } /// <summary> /// True when the specified string is a valid double /// </summary> /// <param name="numeric"></param> /// <returns></returns> public static bool IsNumericDouble(string numeric) { if (string.IsNullOrEmpty(numeric)) return false; bool decimalFound = false; numeric = numeric.Trim(); if (numeric.StartsWith("+", StringComparison.Ordinal) || numeric.StartsWith("-", StringComparison.Ordinal)) numeric = numeric.Substring(1); if (numeric.Length == 0) return false; foreach (char c in numeric) { if (c >= '0' && c <= '9') continue; if ((c == '.') && !decimalFound) { decimalFound = true; continue; } return false; } return true; } /// <summary> /// Parse Gps Latitude /// </summary> /// <param name="Latitude"></param> /// <param name="NorthSouth"></param> /// <returns></returns> private static double ParseLatitude(string Latitude, string NorthSouth) { if (string.IsNullOrEmpty(Latitude) || string.IsNullOrEmpty(NorthSouth) || Latitude.Length < 3) return 0.0d; // LATITUDE bool IsNorth = (NorthSouth != "S"); double degrees = Double.Parse(Latitude.Substring(0, 2), CultureInfo.InvariantCulture); double minutes = Double.Parse(Latitude.Substring(2), CultureInfo.InvariantCulture); double dLatitude = degrees + minutes / 60.0; if (!IsNorth) { dLatitude = -dLatitude; } return dLatitude; } /// <summary> /// Parse Gps Longitude /// </summary> /// <param name="Longitude"></param> /// <param name="EastWest"></param> /// <returns></returns> private static double ParseLongitude(string Longitude, string EastWest) { if (string.IsNullOrEmpty(Longitude) || string.IsNullOrEmpty(EastWest) || Longitude.Length < 3) return 0.0d; // LONGITUDE bool IsWest = (EastWest != "E"); double degrees = Double.Parse(Longitude.Substring(0, 3), CultureInfo.InvariantCulture); double minutes = Double.Parse(Longitude.Substring(3), CultureInfo.InvariantCulture); double dLongitude = degrees + minutes / 60.0; if (IsWest) { dLongitude = -dLongitude; } return dLongitude; } /// <summary> /// Parse UTC Date and Time /// </summary> /// <param name="DateDDMMYY"></param> /// <param name="UTCPosition"></param> /// <returns></returns> private static DateTime ParseUTCDateTime(string DateDDMMYY, string UTCPosition) { DateTime date = DateTime.Now.Date; if (DateDDMMYY.Length > 0) { string DateMMDDYY = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", DateDDMMYY.Substring(2, 2), DateDDMMYY.Substring(0, 2), DateDDMMYY.Substring(4, 2)); date = System.Convert.ToDateTime(DateMMDDYY, CultureInfo.InvariantCulture).Date; } // hhmmss.sss int hh = int.Parse(UTCPosition.Substring(0, 2), CultureInfo.InvariantCulture); int mm = int.Parse(UTCPosition.Substring(2, 2), CultureInfo.InvariantCulture); int ss = int.Parse(UTCPosition.Substring(4, 2), CultureInfo.InvariantCulture); int ms = int.Parse(UTCPosition.Substring(7), CultureInfo.InvariantCulture); DateTime Utc = new DateTime(date.Year, date.Month, date.Day, hh, mm, ss, ms); DateTime adjustedDate = Utc.ToLocalTime(); return adjustedDate; } /// <summary> /// Parse UTC Time /// </summary> /// <param name="UTCPosition"></param> /// <returns></returns> private static TimeSpan ParseUTCTime(string UTCPosition) { if (UTCPosition.Length < 8) return TimeSpan.MinValue; // hhmmss.sss int hh = int.Parse(UTCPosition.Substring(0, 2), CultureInfo.InvariantCulture); int mm = int.Parse(UTCPosition.Substring(2, 2), CultureInfo.InvariantCulture); int ss = int.Parse(UTCPosition.Substring(4, 2), CultureInfo.InvariantCulture); int ms = int.Parse(UTCPosition.Substring(7), CultureInfo.InvariantCulture); DateTime date = DateTime.Now.Date; DateTime Utc = new DateTime(date.Year, date.Month, date.Day, hh, mm, ss, ms); DateTime adjustedDate = Utc.ToLocalTime(); TimeSpan time = new TimeSpan(0, adjustedDate.Hour, adjustedDate.Minute, adjustedDate.Second, adjustedDate.Millisecond); return time; } #endregion #region Image Helpers /// <summary> /// Post an image to the Http web request /// </summary> /// <param name="context"></param> /// <param name="stream"></param> private void SendJpeg(HttpListenerContext context, Stream stream) { WriteResponseFromStream write = new WriteResponseFromStream(context, stream, MediaTypeNames.Image.Jpeg); _httpUtilities.Post(write); Activate( Arbiter.Choice( write.ResultPort, delegate(Stream res) { stream.Close(); }, delegate(Exception e) { stream.Close(); LogError(e); } ) ); } /// <summary> /// Generate a bitmap showing an overhead view of the gps waypoints /// </summary> /// <param name="width"></param> /// <returns></returns> private Stream GenerateTop(int width) { MemoryStream memory = null; int height = width * 3 / 4; using (Bitmap bmp = new Bitmap(width, height)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.LightGray); g.DrawRectangle(Pens.White, new Rectangle(-1, -1, 3, 3)); if (_state.History == null || _state.History.Count < 1) { g.DrawString("No Data - check 'Capture History' box to see the track", new Font(FontFamily.GenericSansSerif, 16, GraphicsUnit.Pixel), Brushes.Red, new Point(10, 10)); } else // plot a simple map from the Gps waypoints { double minLongitude = 9999.0, minLatitude = 9999.0, minAltitude = 9999999.0; double maxLongitude = -9999.0, maxLatitude = -9999.0, maxAltitude = -9999999.0; foreach (EarthCoordinates ec in _state.History) { minLongitude = Math.Min(minLongitude, ec.Longitude); minLatitude = Math.Min(minLatitude, ec.Latitude); minAltitude = Math.Min(minAltitude, ec.AltitudeMeters); maxLongitude = Math.Max(maxLongitude, ec.Longitude); maxLatitude = Math.Max(maxLatitude, ec.Latitude); maxAltitude = Math.Max(maxAltitude, ec.AltitudeMeters); } if (minLongitude < 0) { double hold = minLongitude; minLongitude = maxLongitude; maxLongitude = hold; } EarthCoordinates start = new EarthCoordinates(minLatitude, minLongitude, minAltitude); EarthCoordinates end = new EarthCoordinates(maxLatitude, maxLongitude, maxAltitude); Point3 box = end.OffsetFromStart(start); double scale = Math.Max(box.X / (double)width, box.Y / (double)height); Point lastPoint = Point.Empty; Point currentPoint; foreach (EarthCoordinates ec in _state.History) { box = ec.OffsetFromStart(start); currentPoint = new Point(width - (int)(box.Y / scale) - 10, height - (int)(box.X / scale) - 10); // Draw the point. int dop = (int)Math.Truncate(ec.HorizontalDilutionOfPrecision); Rectangle r = new Rectangle(currentPoint.X - dop, currentPoint.Y - dop, dop * 2, dop * 2); g.FillEllipse(Brushes.Azure, r); g.DrawEllipse(Pens.Yellow, r); if (lastPoint == Point.Empty) g.DrawString("Start", new Font(FontFamily.GenericSansSerif, 16, GraphicsUnit.Pixel), Brushes.Green, currentPoint); else { g.DrawLine(Pens.Red, lastPoint, currentPoint); } lastPoint = currentPoint; } } } memory = new MemoryStream(); bmp.Save(memory, ImageFormat.Jpeg); memory.Position = 0; } return memory; } #endregion } }
// // CairoExtensions.cs // // Author: // Jonathan Pobst <[email protected]> // // Copyright (c) 2010 Jonathan Pobst // // 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 Cairo; namespace fyiReporting.RdlGtkViewer { public static class CairoExtensions { // Most of these functions return an affected area // This can be ignored if you don't need it #region context public static Rectangle DrawRectangle (this Context g, Rectangle r, Color color, int lineWidth) { // Put it on a pixel line if (lineWidth == 1) r = new Rectangle (r.X - 0.5, r.Y - 0.5, r.Width, r.Height); g.Save (); g.MoveTo (r.X, r.Y); g.LineTo (r.X + r.Width, r.Y); g.LineTo (r.X + r.Width, r.Y + r.Height); g.LineTo (r.X, r.Y + r.Height); g.LineTo (r.X, r.Y); g.Color = color; g.LineWidth = lineWidth; g.LineCap = LineCap.Square; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Path CreateRectanglePath (this Context g, Rectangle r) { g.Save (); g.MoveTo (r.X, r.Y); g.LineTo (r.X + r.Width, r.Y); g.LineTo (r.X + r.Width, r.Y + r.Height); g.LineTo (r.X, r.Y + r.Height); g.LineTo (r.X, r.Y); Path path = g.CopyPath (); g.Restore (); return path; } public static Rectangle FillRectangle (this Context g, Rectangle r, Color color) { g.Save (); g.MoveTo (r.X, r.Y); g.LineTo (r.X + r.Width, r.Y); g.LineTo (r.X + r.Width, r.Y + r.Height); g.LineTo (r.X, r.Y + r.Height); g.LineTo (r.X, r.Y); g.Color = color; Rectangle dirty = g.StrokeExtents (); g.Fill (); g.Restore (); return dirty; } public static Rectangle FillRectangle (this Context g, Rectangle r, Pattern pattern) { g.Save (); g.MoveTo (r.X, r.Y); g.LineTo (r.X + r.Width, r.Y); g.LineTo (r.X + r.Width, r.Y + r.Height); g.LineTo (r.X, r.Y + r.Height); g.LineTo (r.X, r.Y); g.Pattern = pattern; Rectangle dirty = g.StrokeExtents (); g.Fill (); g.Restore (); return dirty; } public static Rectangle DrawPolygonal (this Context g, PointD[] points, Color color) { Random rand=new Random(); g.Save (); g.MoveTo (points [0]); foreach (var point in points) { g.LineTo (point.X - rand.NextDouble()*0, point.Y); //g.Stroke(); } g.Color = color; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Rectangle FillPolygonal (this Context g, PointD[] points, Color color) { g.Save (); g.MoveTo (points [0]); foreach (var point in points) g.LineTo (point); g.Color = color; Rectangle dirty = g.StrokeExtents (); g.Fill (); g.Restore (); return dirty; } public static Rectangle FillStrokedRectangle (this Context g, Rectangle r, Color fill, Color stroke, int lineWidth) { double x = r.X; double y = r.Y; g.Save (); // Put it on a pixel line if (lineWidth == 1) { x += 0.5; y += 0.5; } g.MoveTo (x, y); g.LineTo (x + r.Width, y); g.LineTo (x + r.Width, y + r.Height); g.LineTo (x, y + r.Height); g.LineTo (x, y); g.Color = fill; g.FillPreserve (); g.Color = stroke; g.LineWidth = lineWidth; g.LineCap = LineCap.Square; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Rectangle DrawEllipse (this Context g, Rectangle r, Color color, int lineWidth) { double rx = r.Width / 2; double ry = r.Height / 2; double cx = r.X + rx; double cy = r.Y + ry; double c1 = 0.552285; g.Save (); g.MoveTo (cx + rx, cy); g.CurveTo (cx + rx, cy - c1 * ry, cx + c1 * rx, cy - ry, cx, cy - ry); g.CurveTo (cx - c1 * rx, cy - ry, cx - rx, cy - c1 * ry, cx - rx, cy); g.CurveTo (cx - rx, cy + c1 * ry, cx - c1 * rx, cy + ry, cx, cy + ry); g.CurveTo (cx + c1 * rx, cy + ry, cx + rx, cy + c1 * ry, cx + rx, cy); g.ClosePath (); g.Color = color; g.LineWidth = lineWidth; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Rectangle FillEllipse (this Context g, Rectangle r, Color color) { double rx = r.Width / 2; double ry = r.Height / 2; double cx = r.X + rx; double cy = r.Y + ry; double c1 = 0.552285; g.Save (); g.MoveTo (cx + rx, cy); g.CurveTo (cx + rx, cy - c1 * ry, cx + c1 * rx, cy - ry, cx, cy - ry); g.CurveTo (cx - c1 * rx, cy - ry, cx - rx, cy - c1 * ry, cx - rx, cy); g.CurveTo (cx - rx, cy + c1 * ry, cx - c1 * rx, cy + ry, cx, cy + ry); g.CurveTo (cx + c1 * rx, cy + ry, cx + rx, cy + c1 * ry, cx + rx, cy); g.ClosePath (); g.Color = color; Rectangle dirty = g.StrokeExtents (); g.Fill (); g.Restore (); return dirty; } public static Path CreateEllipsePath (this Context g, Rectangle r) { double rx = r.Width / 2; double ry = r.Height / 2; double cx = r.X + rx; double cy = r.Y + ry; double c1 = 0.552285; g.Save (); g.MoveTo (cx + rx, cy); g.CurveTo (cx + rx, cy - c1 * ry, cx + c1 * rx, cy - ry, cx, cy - ry); g.CurveTo (cx - c1 * rx, cy - ry, cx - rx, cy - c1 * ry, cx - rx, cy); g.CurveTo (cx - rx, cy + c1 * ry, cx - c1 * rx, cy + ry, cx, cy + ry); g.CurveTo (cx + c1 * rx, cy + ry, cx + rx, cy + c1 * ry, cx + rx, cy); g.ClosePath (); Path path = g.CopyPath (); g.Restore (); return path; } public static Rectangle FillStrokedEllipse (this Context g, Rectangle r, Color fill, Color stroke, int lineWidth) { double rx = r.Width / 2; double ry = r.Height / 2; double cx = r.X + rx; double cy = r.Y + ry; double c1 = 0.552285; g.Save (); g.MoveTo (cx + rx, cy); g.CurveTo (cx + rx, cy - c1 * ry, cx + c1 * rx, cy - ry, cx, cy - ry); g.CurveTo (cx - c1 * rx, cy - ry, cx - rx, cy - c1 * ry, cx - rx, cy); g.CurveTo (cx - rx, cy + c1 * ry, cx - c1 * rx, cy + ry, cx, cy + ry); g.CurveTo (cx + c1 * rx, cy + ry, cx + rx, cy + c1 * ry, cx + rx, cy); g.ClosePath (); g.Color = fill; g.FillPreserve (); g.Color = stroke; g.LineWidth = lineWidth; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Rectangle FillStrokedRoundedRectangle (this Context g, Rectangle r, double radius, Color fill, Color stroke, int lineWidth) { g.Save (); if ((radius > r.Height / 2) || (radius > r.Width / 2)) radius = Math.Min (r.Height / 2, r.Width / 2); g.MoveTo (r.X, r.Y + radius); g.Arc (r.X + radius, r.Y + radius, radius, Math.PI, -Math.PI / 2); g.LineTo (r.X + r.Width - radius, r.Y); g.Arc (r.X + r.Width - radius, r.Y + radius, radius, -Math.PI / 2, 0); g.LineTo (r.X + r.Width, r.Y + r.Height - radius); g.Arc (r.X + r.Width - radius, r.Y + r.Height - radius, radius, 0, Math.PI / 2); g.LineTo (r.X + radius, r.Y + r.Height); g.Arc (r.X + radius, r.Y + r.Height - radius, radius, Math.PI / 2, Math.PI); g.ClosePath (); g.Restore (); g.Color = fill; g.FillPreserve (); g.Color = stroke; g.LineWidth = lineWidth; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Rectangle FillRoundedRectangle (this Context g, Rectangle r, double radius, Color fill) { g.Save (); if ((radius > r.Height / 2) || (radius > r.Width / 2)) radius = Math.Min (r.Height / 2, r.Width / 2); g.MoveTo (r.X, r.Y + radius); g.Arc (r.X + radius, r.Y + radius, radius, Math.PI, -Math.PI / 2); g.LineTo (r.X + r.Width - radius, r.Y); g.Arc (r.X + r.Width - radius, r.Y + radius, radius, -Math.PI / 2, 0); g.LineTo (r.X + r.Width, r.Y + r.Height - radius); g.Arc (r.X + r.Width - radius, r.Y + r.Height - radius, radius, 0, Math.PI / 2); g.LineTo (r.X + radius, r.Y + r.Height); g.Arc (r.X + radius, r.Y + r.Height - radius, radius, Math.PI / 2, Math.PI); g.ClosePath (); //g.Restore (); g.Color = fill; Rectangle dirty = g.StrokeExtents (); g.Fill (); g.Restore (); return dirty; } public static void FillRegion (this Context g, Gdk.Region region, Color color) { g.Save (); g.Color = color; foreach (Gdk.Rectangle r in region.GetRectangles()) { g.MoveTo (r.X, r.Y); g.LineTo (r.X + r.Width, r.Y); g.LineTo (r.X + r.Width, r.Y + r.Height); g.LineTo (r.X, r.Y + r.Height); g.LineTo (r.X, r.Y); g.Color = color; g.StrokeExtents (); g.Fill (); } g.Restore (); } public static Rectangle DrawRoundedRectangle (this Context g, Rectangle r, double radius, Color stroke, int lineWidth) { g.Save (); Path p = g.CreateRoundedRectanglePath (r, radius); g.AppendPath (p); g.Color = stroke; g.LineWidth = lineWidth; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); (p as IDisposable).Dispose (); return dirty; } public static Path CreateRoundedRectanglePath (this Context g, Rectangle r, double radius) { g.Save (); if ((radius > r.Height / 2) || (radius > r.Width / 2)) radius = Math.Min (r.Height / 2, r.Width / 2); g.MoveTo (r.X, r.Y + radius); g.Arc (r.X + radius, r.Y + radius, radius, Math.PI, -Math.PI / 2); g.LineTo (r.X + r.Width - radius, r.Y); g.Arc (r.X + r.Width - radius, r.Y + radius, radius, -Math.PI / 2, 0); g.LineTo (r.X + r.Width, r.Y + r.Height - radius); g.Arc (r.X + r.Width - radius, r.Y + r.Height - radius, radius, 0, Math.PI / 2); g.LineTo (r.X + radius, r.Y + r.Height); g.Arc (r.X + radius, r.Y + r.Height - radius, radius, Math.PI / 2, Math.PI); g.ClosePath (); Path p = g.CopyPath (); g.Restore (); return p; } public static Rectangle DrawLine (this Context g, PointD p1, PointD p2, Color color, int lineWidth) { // Put it on a pixel line if (lineWidth == 1) p1 = new PointD (p1.X - 0.5, p1.Y - 0.5); g.Save (); g.MoveTo (p1.X, p1.Y); g.LineTo (p2.X, p2.Y); g.Color = color; g.LineWidth = lineWidth; g.LineCap = LineCap.Square; Rectangle dirty = g.StrokeExtents (); g.Stroke (); g.Restore (); return dirty; } public static Rectangle DrawText (this Context g, PointD p, string family, FontSlant slant, FontWeight weight, double size, Color color, string text) { g.Save (); g.MoveTo (p.X, p.Y); g.SelectFontFace (family, slant, weight); g.SetFontSize (size); g.Color = color; TextExtents te = g.TextExtents(text); //TODO alignment // Center text on bottom /*// TODO cut the string in char array and for each center on bottom * TextExtents te = g.TextExtents("a"); cr.MoveTo(0.5 - te.Width / 2 - te.XBearing, 0.5 - te.Height / 2 - te.YBearing); */ //// Draw g.ShowText (text); //or //g.TextPath(text); //g.Fill(); g.Restore (); return new Rectangle(te.XBearing, te.YBearing, te.Width, te.Height); } public static void DrawPixbuf (this Context g, Gdk.Pixbuf pixbuf, Point dest) { g.DrawPixbuf (pixbuf, dest.X, dest.Y); } public static void DrawPixbuf (this Context g, Gdk.Pixbuf pixbuf, int x, int y) { g.Save (); Gdk.CairoHelper.SetSourcePixbuf (g, pixbuf, x, y); g.Paint (); g.Restore (); } public static void DrawPixbufRect (this Context g, Gdk.Pixbuf pixbuf, Rectangle r, float scale) { var wScale = (r.Width / scale) / pixbuf.Width; var hScale = (r.Height / scale) / pixbuf.Height; g.Save(); g.Scale(scale * wScale, scale * hScale); Gdk.CairoHelper.SetSourcePixbuf(g, pixbuf, (int)(r.X / scale / wScale), (int)(r.Y / scale / hScale)); g.Paint(); g.Restore(); } #endregion public static double Distance (this PointD s, PointD e) { return Magnitude (new PointD (s.X - e.X, s.Y - e.Y)); } public static double Magnitude(this PointD p) { return Math.Sqrt(p.X * p.X + p.Y * p.Y); } public static Cairo.Rectangle ToCairoRectangle (this Gdk.Rectangle r) { return new Cairo.Rectangle (r.X, r.Y, r.Width, r.Height); } public static Cairo.Point Location (this Cairo.Rectangle r) { return new Cairo.Point ((int)r.X, (int)r.Y); } public static Cairo.Rectangle Clamp (this Cairo.Rectangle r) { double x = r.X; double y = r.Y; double w = r.Width; double h = r.Height; if (x < 0) { w -= x; x = 0; } if (y < 0) { h -= y; y = 0; } return new Cairo.Rectangle (x, y, w, h); } public static Gdk.Rectangle ToGdkRectangle (this Cairo.Rectangle r) { return new Gdk.Rectangle ((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height); } public static bool ContainsPoint (this Cairo.Rectangle r, double x, double y) { if (x < r.X || x >= r.X + r.Width) return false; if (y < r.Y || y >= r.Y + r.Height) return false; return true; } public static Gdk.Size ToSize (this Cairo.Point point) { return new Gdk.Size (point.X, point.Y); } public static ImageSurface Clone (this ImageSurface surf) { ImageSurface newsurf = new ImageSurface (surf.Format, surf.Width, surf.Height); using (Context g = new Context (newsurf)) { g.SetSource (surf); g.Paint (); } return newsurf; } public static Gdk.Color ToGdkColor (this Cairo.Color color) { Gdk.Color c = new Gdk.Color (); c.Blue = (ushort)(color.B * ushort.MaxValue); c.Red = (ushort)(color.R * ushort.MaxValue); c.Green = (ushort)(color.G * ushort.MaxValue); return c; } public static ushort GdkColorAlpha (this Cairo.Color color) { return (ushort)(color.A * ushort.MaxValue); } public static double GetBottom (this Rectangle rect) { return rect.Y + rect.Height; } public static double GetRight (this Rectangle rect) { return rect.X + rect.Width; } /// <summary> /// Determines if the requested pixel coordinate is within bounds. /// </summary> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <returns>true if (x,y) is in bounds, false if it's not.</returns> public static bool IsVisible(this ImageSurface surf, int x, int y) { return x >= 0 && x < surf.Width && y >= 0 && y < surf.Height; } public static Path CreatePolygonPath (this Context g, Point[][] polygonSet) { g.Save (); Point p; for (int i =0; i < polygonSet.Length; i++) { if (polygonSet[i].Length == 0) continue; p = polygonSet[i][0]; g.MoveTo (p.X, p.Y); for (int j =1; j < polygonSet[i].Length; j++) { p = polygonSet[i][j]; g.LineTo (p.X, p.Y); } g.ClosePath (); } Path path = g.CopyPath (); g.Restore (); return path; } public static Color ToCairoColor (this System.Drawing.Color color) { return new Color (color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f); } } }
/* * 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 { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Xml; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Deployment; using Apache.Ignite.Core.Discovery; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Plugin; using Apache.Ignite.Core.Transactions; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter; /// <summary> /// Grid configuration. /// </summary> public class IgniteConfiguration { /// <summary> /// Default initial JVM memory in megabytes. /// </summary> public const int DefaultJvmInitMem = -1; /// <summary> /// Default maximum JVM memory in megabytes. /// </summary> public const int DefaultJvmMaxMem = -1; /// <summary> /// Default metrics expire time. /// </summary> public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue; /// <summary> /// Default metrics history size. /// </summary> public const int DefaultMetricsHistorySize = 10000; /// <summary> /// Default metrics log frequency. /// </summary> public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000); /// <summary> /// Default metrics update frequency. /// </summary> public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000); /// <summary> /// Default network timeout. /// </summary> public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000); /// <summary> /// Default network retry delay. /// </summary> public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000); /// <summary> /// Default failure detection timeout. /// </summary> public static readonly TimeSpan DefaultFailureDetectionTimeout = TimeSpan.FromSeconds(10); /// <summary> /// Default failure detection timeout. /// </summary> public static readonly TimeSpan DefaultClientFailureDetectionTimeout = TimeSpan.FromSeconds(30); /// <summary> /// Default thread pool size. /// </summary> public static readonly int DefaultThreadPoolSize = Math.Max(8, Environment.ProcessorCount); /// <summary> /// Default management thread pool size. /// </summary> public const int DefaultManagementThreadPoolSize = 4; /// <summary> /// Default timeout after which long query warning will be printed. /// </summary> public static readonly TimeSpan DefaultLongQueryWarningTimeout = TimeSpan.FromMilliseconds(3000); /** */ private TimeSpan? _metricsExpireTime; /** */ private int? _metricsHistorySize; /** */ private TimeSpan? _metricsLogFrequency; /** */ private TimeSpan? _metricsUpdateFrequency; /** */ private int? _networkSendRetryCount; /** */ private TimeSpan? _networkSendRetryDelay; /** */ private TimeSpan? _networkTimeout; /** */ private bool? _isDaemon; /** */ private bool? _clientMode; /** */ private TimeSpan? _failureDetectionTimeout; /** */ private TimeSpan? _clientFailureDetectionTimeout; /** */ private int? _publicThreadPoolSize; /** */ private int? _stripedThreadPoolSize; /** */ private int? _serviceThreadPoolSize; /** */ private int? _systemThreadPoolSize; /** */ private int? _asyncCallbackThreadPoolSize; /** */ private int? _managementThreadPoolSize; /** */ private int? _dataStreamerThreadPoolSize; /** */ private int? _utilityCacheThreadPoolSize; /** */ private int? _queryThreadPoolSize; /** */ private TimeSpan? _longQueryWarningTimeout; /** */ private bool? _isActiveOnStart; /// <summary> /// Default network retry count. /// </summary> public const int DefaultNetworkSendRetryCount = 3; /// <summary> /// Default late affinity assignment mode. /// </summary> public const bool DefaultIsLateAffinityAssignment = true; /// <summary> /// Default value for <see cref="IsActiveOnStart"/> property. /// </summary> public const bool DefaultIsActiveOnStart = true; /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> public IgniteConfiguration() { JvmInitialMemoryMb = DefaultJvmInitMem; JvmMaxMemoryMb = DefaultJvmMaxMem; } /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> /// <param name="configuration">The configuration to copy.</param> public IgniteConfiguration(IgniteConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var marsh = BinaryUtils.Marshaller; configuration.Write(marsh.StartMarshal(stream)); stream.SynchronizeOutput(); stream.Seek(0, SeekOrigin.Begin); ReadCore(marsh.StartUnmarshal(stream)); } CopyLocalProperties(configuration); } /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration" /> class from a reader. /// </summary> /// <param name="binaryReader">The binary reader.</param> /// <param name="baseConfig">The base configuration.</param> internal IgniteConfiguration(BinaryReader binaryReader, IgniteConfiguration baseConfig) { Debug.Assert(binaryReader != null); Debug.Assert(baseConfig != null); CopyLocalProperties(baseConfig); Read(binaryReader); } /// <summary> /// Writes this instance to a writer. /// </summary> /// <param name="writer">The writer.</param> internal void Write(BinaryWriter writer) { Debug.Assert(writer != null); // Simple properties writer.WriteBooleanNullable(_clientMode); writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray()); writer.WriteTimeSpanAsLongNullable(_metricsExpireTime); writer.WriteIntNullable(_metricsHistorySize); writer.WriteTimeSpanAsLongNullable(_metricsLogFrequency); writer.WriteTimeSpanAsLongNullable(_metricsUpdateFrequency); writer.WriteIntNullable(_networkSendRetryCount); writer.WriteTimeSpanAsLongNullable(_networkSendRetryDelay); writer.WriteTimeSpanAsLongNullable(_networkTimeout); writer.WriteString(WorkDirectory); writer.WriteString(Localhost); writer.WriteBooleanNullable(_isDaemon); writer.WriteTimeSpanAsLongNullable(_failureDetectionTimeout); writer.WriteTimeSpanAsLongNullable(_clientFailureDetectionTimeout); writer.WriteTimeSpanAsLongNullable(_longQueryWarningTimeout); writer.WriteBooleanNullable(_isActiveOnStart); // Thread pools writer.WriteIntNullable(_publicThreadPoolSize); writer.WriteIntNullable(_stripedThreadPoolSize); writer.WriteIntNullable(_serviceThreadPoolSize); writer.WriteIntNullable(_systemThreadPoolSize); writer.WriteIntNullable(_asyncCallbackThreadPoolSize); writer.WriteIntNullable(_managementThreadPoolSize); writer.WriteIntNullable(_dataStreamerThreadPoolSize); writer.WriteIntNullable(_utilityCacheThreadPoolSize); writer.WriteIntNullable(_queryThreadPoolSize); // Cache config var caches = CacheConfiguration; if (caches == null) writer.WriteInt(0); else { writer.WriteInt(caches.Count); foreach (var cache in caches) cache.Write(writer); } // Discovery config var disco = DiscoverySpi; if (disco != null) { writer.WriteBoolean(true); var tcpDisco = disco as TcpDiscoverySpi; if (tcpDisco == null) throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType()); tcpDisco.Write(writer); } else writer.WriteBoolean(false); // Communication config var comm = CommunicationSpi; if (comm != null) { writer.WriteBoolean(true); var tcpComm = comm as TcpCommunicationSpi; if (tcpComm == null) throw new InvalidOperationException("Unsupported communication SPI: " + comm.GetType()); tcpComm.Write(writer); } else writer.WriteBoolean(false); // Binary config if (BinaryConfiguration != null) { writer.WriteBoolean(true); if (BinaryConfiguration.CompactFooterInternal != null) { writer.WriteBoolean(true); writer.WriteBoolean(BinaryConfiguration.CompactFooter); } else { writer.WriteBoolean(false); } // Name mapper. var mapper = BinaryConfiguration.NameMapper as BinaryBasicNameMapper; writer.WriteBoolean(mapper != null && mapper.IsSimpleName); } else { writer.WriteBoolean(false); } // User attributes var attrs = UserAttributes; if (attrs == null) writer.WriteInt(0); else { writer.WriteInt(attrs.Count); foreach (var pair in attrs) { writer.WriteString(pair.Key); writer.Write(pair.Value); } } // Atomic if (AtomicConfiguration != null) { writer.WriteBoolean(true); writer.WriteInt(AtomicConfiguration.AtomicSequenceReserveSize); writer.WriteInt(AtomicConfiguration.Backups); writer.WriteInt((int) AtomicConfiguration.CacheMode); } else writer.WriteBoolean(false); // Tx if (TransactionConfiguration != null) { writer.WriteBoolean(true); writer.WriteInt(TransactionConfiguration.PessimisticTransactionLogSize); writer.WriteInt((int) TransactionConfiguration.DefaultTransactionConcurrency); writer.WriteInt((int) TransactionConfiguration.DefaultTransactionIsolation); writer.WriteLong((long) TransactionConfiguration.DefaultTimeout.TotalMilliseconds); writer.WriteInt((int) TransactionConfiguration.PessimisticTransactionLogLinger.TotalMilliseconds); } else writer.WriteBoolean(false); // Event storage if (EventStorageSpi == null) { writer.WriteByte(0); } else if (EventStorageSpi is NoopEventStorageSpi) { writer.WriteByte(1); } else { var memEventStorage = EventStorageSpi as MemoryEventStorageSpi; if (memEventStorage == null) { throw new IgniteException(string.Format( "Unsupported IgniteConfiguration.EventStorageSpi: '{0}'. " + "Supported implementations: '{1}', '{2}'.", EventStorageSpi.GetType(), typeof(NoopEventStorageSpi), typeof(MemoryEventStorageSpi))); } writer.WriteByte(2); memEventStorage.Write(writer); } if (MemoryConfiguration != null) { writer.WriteBoolean(true); MemoryConfiguration.Write(writer); } else { writer.WriteBoolean(false); } // SQL if (SqlConnectorConfiguration != null) { writer.WriteBoolean(true); SqlConnectorConfiguration.Write(writer); } else { writer.WriteBoolean(false); } // Persistence. if (PersistentStoreConfiguration != null) { writer.WriteBoolean(true); PersistentStoreConfiguration.Write(writer); } else { writer.WriteBoolean(false); } // Plugins (should be last) if (PluginConfigurations != null) { var pos = writer.Stream.Position; writer.WriteInt(0); // reserve count var cnt = 0; foreach (var cfg in PluginConfigurations) { if (cfg.PluginConfigurationClosureFactoryId != null) { writer.WriteInt(cfg.PluginConfigurationClosureFactoryId.Value); cfg.WriteBinary(writer); cnt++; } } writer.Stream.WriteInt(pos, cnt); } else { writer.WriteInt(0); } } /// <summary> /// Validates this instance and outputs information to the log, if necessary. /// </summary> internal void Validate(ILogger log) { Debug.Assert(log != null); var ccfg = CacheConfiguration; if (ccfg != null) { foreach (var cfg in ccfg) cfg.Validate(log); } } /// <summary> /// Reads data from specified reader into current instance. /// </summary> /// <param name="r">The binary reader.</param> private void ReadCore(BinaryReader r) { // Simple properties _clientMode = r.ReadBooleanNullable(); IncludedEventTypes = r.ReadIntArray(); _metricsExpireTime = r.ReadTimeSpanNullable(); _metricsHistorySize = r.ReadIntNullable(); _metricsLogFrequency = r.ReadTimeSpanNullable(); _metricsUpdateFrequency = r.ReadTimeSpanNullable(); _networkSendRetryCount = r.ReadIntNullable(); _networkSendRetryDelay = r.ReadTimeSpanNullable(); _networkTimeout = r.ReadTimeSpanNullable(); WorkDirectory = r.ReadString(); Localhost = r.ReadString(); _isDaemon = r.ReadBooleanNullable(); _failureDetectionTimeout = r.ReadTimeSpanNullable(); _clientFailureDetectionTimeout = r.ReadTimeSpanNullable(); _longQueryWarningTimeout = r.ReadTimeSpanNullable(); _isActiveOnStart = r.ReadBooleanNullable(); // Thread pools _publicThreadPoolSize = r.ReadIntNullable(); _stripedThreadPoolSize = r.ReadIntNullable(); _serviceThreadPoolSize = r.ReadIntNullable(); _systemThreadPoolSize = r.ReadIntNullable(); _asyncCallbackThreadPoolSize = r.ReadIntNullable(); _managementThreadPoolSize = r.ReadIntNullable(); _dataStreamerThreadPoolSize = r.ReadIntNullable(); _utilityCacheThreadPoolSize = r.ReadIntNullable(); _queryThreadPoolSize = r.ReadIntNullable(); // Cache config var cacheCfgCount = r.ReadInt(); CacheConfiguration = new List<CacheConfiguration>(cacheCfgCount); for (int i = 0; i < cacheCfgCount; i++) CacheConfiguration.Add(new CacheConfiguration(r)); // Discovery config DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null; // Communication config CommunicationSpi = r.ReadBoolean() ? new TcpCommunicationSpi(r) : null; // Binary config if (r.ReadBoolean()) { BinaryConfiguration = BinaryConfiguration ?? new BinaryConfiguration(); if (r.ReadBoolean()) { BinaryConfiguration.CompactFooter = r.ReadBoolean(); } if (r.ReadBoolean()) { BinaryConfiguration.NameMapper = BinaryBasicNameMapper.SimpleNameInstance; } } // User attributes UserAttributes = Enumerable.Range(0, r.ReadInt()) .ToDictionary(x => r.ReadString(), x => r.ReadObject<object>()); // Atomic if (r.ReadBoolean()) { AtomicConfiguration = new AtomicConfiguration { AtomicSequenceReserveSize = r.ReadInt(), Backups = r.ReadInt(), CacheMode = (CacheMode) r.ReadInt() }; } // Tx if (r.ReadBoolean()) { TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = r.ReadInt(), DefaultTransactionConcurrency = (TransactionConcurrency) r.ReadInt(), DefaultTransactionIsolation = (TransactionIsolation) r.ReadInt(), DefaultTimeout = TimeSpan.FromMilliseconds(r.ReadLong()), PessimisticTransactionLogLinger = TimeSpan.FromMilliseconds(r.ReadInt()) }; } // Event storage switch (r.ReadByte()) { case 1: EventStorageSpi = new NoopEventStorageSpi(); break; case 2: EventStorageSpi = MemoryEventStorageSpi.Read(r); break; } if (r.ReadBoolean()) { MemoryConfiguration = new MemoryConfiguration(r); } // SQL if (r.ReadBoolean()) { SqlConnectorConfiguration = new SqlConnectorConfiguration(r); } // Persistence. if (r.ReadBoolean()) { PersistentStoreConfiguration = new PersistentStoreConfiguration(r); } } /// <summary> /// Reads data from specified reader into current instance. /// </summary> /// <param name="binaryReader">The binary reader.</param> private void Read(BinaryReader binaryReader) { ReadCore(binaryReader); // Misc IgniteHome = binaryReader.ReadString(); JvmInitialMemoryMb = (int) (binaryReader.ReadLong()/1024/2014); JvmMaxMemoryMb = (int) (binaryReader.ReadLong()/1024/2014); // Local data (not from reader) JvmDllPath = Process.GetCurrentProcess().Modules.OfType<ProcessModule>() .Single(x => string.Equals(x.ModuleName, IgniteUtils.FileJvmDll, StringComparison.OrdinalIgnoreCase)) .FileName; } /// <summary> /// Copies the local properties (properties that are not written in Write method). /// </summary> private void CopyLocalProperties(IgniteConfiguration cfg) { IgniteInstanceName = cfg.IgniteInstanceName; if (BinaryConfiguration != null && cfg.BinaryConfiguration != null) { BinaryConfiguration.MergeTypes(cfg.BinaryConfiguration); } else if (cfg.BinaryConfiguration != null) { BinaryConfiguration = new BinaryConfiguration(cfg.BinaryConfiguration); } JvmClasspath = cfg.JvmClasspath; JvmOptions = cfg.JvmOptions; Assemblies = cfg.Assemblies; SuppressWarnings = cfg.SuppressWarnings; LifecycleHandlers = cfg.LifecycleHandlers; Logger = cfg.Logger; JvmInitialMemoryMb = cfg.JvmInitialMemoryMb; JvmMaxMemoryMb = cfg.JvmMaxMemoryMb; PluginConfigurations = cfg.PluginConfigurations; AutoGenerateIgniteInstanceName = cfg.AutoGenerateIgniteInstanceName; } /// <summary> /// Gets or sets optional local instance name. /// <para /> /// This name only works locally and has no effect on topology. /// <para /> /// This property is used to when there are multiple Ignite nodes in one process to distinguish them. /// </summary> public string IgniteInstanceName { get; set; } /// <summary> /// Gets or sets a value indicating whether unique <see cref="IgniteInstanceName"/> should be generated. /// <para /> /// Set this to true in scenarios where new node should be started regardless of other nodes present within /// current process. In particular, this setting is useful is ASP.NET and IIS environments, where AppDomains /// are loaded and unloaded within a single process during application restarts. Ignite stops all nodes /// on <see cref="AppDomain"/> unload, however, IIS does not wait for previous AppDomain to unload before /// starting up a new one, which may cause "Ignite instance with this name has already been started" errors. /// This setting solves the issue. /// </summary> public bool AutoGenerateIgniteInstanceName { get; set; } /// <summary> /// Gets or sets optional local instance name. /// <para /> /// This name only works locally and has no effect on topology. /// <para /> /// This property is used to when there are multiple Ignite nodes in one process to distinguish them. /// </summary> [Obsolete("Use IgniteInstanceName instead.")] public string GridName { get { return IgniteInstanceName; } set { IgniteInstanceName = value; } } /// <summary> /// Gets or sets the binary configuration. /// </summary> /// <value> /// The binary configuration. /// </value> public BinaryConfiguration BinaryConfiguration { get; set; } /// <summary> /// Gets or sets the cache configuration. /// </summary> /// <value> /// The cache configuration. /// </value> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<CacheConfiguration> CacheConfiguration { get; set; } /// <summary> /// URL to Spring configuration file. /// <para /> /// Spring configuration is loaded first, then <see cref="IgniteConfiguration"/> properties are applied. /// Null property values do not override Spring values. /// Value-typed properties are tracked internally: if setter was not called, Spring value won't be overwritten. /// <para /> /// This merging happens on the top level only; e. g. if there are cache configurations defined in Spring /// and in .NET, .NET caches will overwrite Spring caches. /// </summary> [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string SpringConfigUrl { get; set; } /// <summary> /// Path jvm.dll file. If not set, it's location will be determined /// using JAVA_HOME environment variable. /// If path is neither set nor determined automatically, an exception /// will be thrown. /// </summary> public string JvmDllPath { get; set; } /// <summary> /// Path to Ignite home. If not set environment variable IGNITE_HOME will be used. /// </summary> public string IgniteHome { get; set; } /// <summary> /// Classpath used by JVM on Ignite start. /// </summary> public string JvmClasspath { get; set; } /// <summary> /// Collection of options passed to JVM on Ignite start. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<string> JvmOptions { get; set; } /// <summary> /// List of additional .Net assemblies to load on Ignite start. Each item can be either /// fully qualified assembly name, path to assembly to DLL or path to a directory when /// assemblies reside. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<string> Assemblies { get; set; } /// <summary> /// Whether to suppress warnings. /// </summary> public bool SuppressWarnings { get; set; } /// <summary> /// Lifecycle handlers. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<ILifecycleHandler> LifecycleHandlers { get; set; } /// <summary> /// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option. /// <code>-1</code> maps to JVM defaults. /// Defaults to <see cref="DefaultJvmInitMem"/>. /// </summary> [DefaultValue(DefaultJvmInitMem)] public int JvmInitialMemoryMb { get; set; } /// <summary> /// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option. /// <code>-1</code> maps to JVM defaults. /// Defaults to <see cref="DefaultJvmMaxMem"/>. /// </summary> [DefaultValue(DefaultJvmMaxMem)] public int JvmMaxMemoryMb { get; set; } /// <summary> /// Gets or sets the discovery service provider. /// Null for default discovery. /// </summary> public IDiscoverySpi DiscoverySpi { get; set; } /// <summary> /// Gets or sets the communication service provider. /// Null for default communication. /// </summary> public ICommunicationSpi CommunicationSpi { get; set; } /// <summary> /// Gets or sets a value indicating whether node should start in client mode. /// Client node cannot hold data in the caches. /// </summary> public bool ClientMode { get { return _clientMode ?? default(bool); } set { _clientMode = value; } } /// <summary> /// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<int> IncludedEventTypes { get; set; } /// <summary> /// Gets or sets the time after which a certain metric value is considered expired. /// </summary> [DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")] public TimeSpan MetricsExpireTime { get { return _metricsExpireTime ?? DefaultMetricsExpireTime; } set { _metricsExpireTime = value; } } /// <summary> /// Gets or sets the number of metrics kept in history to compute totals and averages. /// </summary> [DefaultValue(DefaultMetricsHistorySize)] public int MetricsHistorySize { get { return _metricsHistorySize ?? DefaultMetricsHistorySize; } set { _metricsHistorySize = value; } } /// <summary> /// Gets or sets the frequency of metrics log print out. /// <see cref="TimeSpan.Zero"/> to disable metrics print out. /// </summary> [DefaultValue(typeof(TimeSpan), "00:01:00")] public TimeSpan MetricsLogFrequency { get { return _metricsLogFrequency ?? DefaultMetricsLogFrequency; } set { _metricsLogFrequency = value; } } /// <summary> /// Gets or sets the job metrics update frequency. /// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish. /// Negative value to never update metrics. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:02")] public TimeSpan MetricsUpdateFrequency { get { return _metricsUpdateFrequency ?? DefaultMetricsUpdateFrequency; } set { _metricsUpdateFrequency = value; } } /// <summary> /// Gets or sets the network send retry count. /// </summary> [DefaultValue(DefaultNetworkSendRetryCount)] public int NetworkSendRetryCount { get { return _networkSendRetryCount ?? DefaultNetworkSendRetryCount; } set { _networkSendRetryCount = value; } } /// <summary> /// Gets or sets the network send retry delay. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:01")] public TimeSpan NetworkSendRetryDelay { get { return _networkSendRetryDelay ?? DefaultNetworkSendRetryDelay; } set { _networkSendRetryDelay = value; } } /// <summary> /// Gets or sets the network timeout. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:05")] public TimeSpan NetworkTimeout { get { return _networkTimeout ?? DefaultNetworkTimeout; } set { _networkTimeout = value; } } /// <summary> /// Gets or sets the work directory. /// If not provided, a folder under <see cref="IgniteHome"/> will be used. /// </summary> public string WorkDirectory { get; set; } /// <summary> /// Gets or sets system-wide local address or host for all Ignite components to bind to. /// If provided it will override all default local bind settings within Ignite. /// <para /> /// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services /// will be available on all network interfaces of the host machine. /// <para /> /// It is strongly recommended to set this parameter for all production environments. /// </summary> public string Localhost { get; set; } /// <summary> /// Gets or sets a value indicating whether this node should be a daemon node. /// <para /> /// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs, /// i.e. they are not part of any cluster groups. /// <para /> /// Daemon nodes are used primarily for management and monitoring functionality that is built on Ignite /// and needs to participate in the topology, but also needs to be excluded from the "normal" topology, /// so that it won't participate in the task execution or in-memory data grid storage. /// </summary> public bool IsDaemon { get { return _isDaemon ?? default(bool); } set { _isDaemon = value; } } /// <summary> /// Gets or sets the user attributes for this node. /// <para /> /// These attributes can be retrieved later via <see cref="IClusterNode.GetAttributes"/>. /// Environment variables are added to node attributes automatically. /// NOTE: attribute names starting with "org.apache.ignite" are reserved for internal use. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary<string, object> UserAttributes { get; set; } /// <summary> /// Gets or sets the atomic data structures configuration. /// </summary> public AtomicConfiguration AtomicConfiguration { get; set; } /// <summary> /// Gets or sets the transaction configuration. /// </summary> public TransactionConfiguration TransactionConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating whether late affinity assignment mode should be used. /// <para /> /// On each topology change, for each started cache, partition-to-node mapping is /// calculated using AffinityFunction for cache. When late /// affinity assignment mode is disabled then new affinity mapping is applied immediately. /// <para /> /// With late affinity assignment mode, if primary node was changed for some partition, but data for this /// partition is not rebalanced yet on this node, then current primary is not changed and new primary /// is temporary assigned as backup. This nodes becomes primary only when rebalancing for all assigned primary /// partitions is finished. This mode can show better performance for cache operations, since when cache /// primary node executes some operation and data is not rebalanced yet, then it sends additional message /// to force rebalancing from other nodes. /// <para /> /// Note, that <see cref="ICacheAffinity"/> interface provides assignment information taking late assignment /// into account, so while rebalancing for new primary nodes is not finished it can return assignment /// which differs from assignment calculated by AffinityFunction. /// <para /> /// This property should have the same value for all nodes in cluster. /// <para /> /// If not provided, default value is <see cref="DefaultIsLateAffinityAssignment"/>. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] [DefaultValue(DefaultIsLateAffinityAssignment)] [Obsolete("No longer supported, always true.")] public bool IsLateAffinityAssignment { get { return DefaultIsLateAffinityAssignment; } // ReSharper disable once ValueParameterNotUsed set { /* No-op. */ } } /// <summary> /// Serializes this instance to the specified XML writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="rootElementName">Name of the root element.</param> public void ToXml(XmlWriter writer, string rootElementName) { IgniteArgumentCheck.NotNull(writer, "writer"); IgniteArgumentCheck.NotNullOrEmpty(rootElementName, "rootElementName"); IgniteConfigurationXmlSerializer.Serialize(this, writer, rootElementName); } /// <summary> /// Serializes this instance to an XML string. /// </summary> public string ToXml() { var sb = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(sb, settings)) { ToXml(xmlWriter, "igniteConfiguration"); } return sb.ToString(); } /// <summary> /// Deserializes IgniteConfiguration from the XML reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Deserialized instance.</returns> public static IgniteConfiguration FromXml(XmlReader reader) { IgniteArgumentCheck.NotNull(reader, "reader"); return IgniteConfigurationXmlSerializer.Deserialize(reader); } /// <summary> /// Deserializes IgniteConfiguration from the XML string. /// </summary> /// <param name="xml">Xml string.</param> /// <returns>Deserialized instance.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SuppressMessage("Microsoft.Usage", "CA2202: Do not call Dispose more than one time on an object")] public static IgniteConfiguration FromXml(string xml) { IgniteArgumentCheck.NotNullOrEmpty(xml, "xml"); using (var stringReader = new StringReader(xml)) using (var xmlReader = XmlReader.Create(stringReader)) { // Skip XML header. xmlReader.MoveToContent(); return FromXml(xmlReader); } } /// <summary> /// Gets or sets the logger. /// <para /> /// If no logger is set, logging is delegated to Java, which uses the logger defined in Spring XML (if present) /// or logs to console otherwise. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/> /// and <see cref="TcpCommunicationSpi"/>. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:10")] public TimeSpan FailureDetectionTimeout { get { return _failureDetectionTimeout ?? DefaultFailureDetectionTimeout; } set { _failureDetectionTimeout = value; } } /// <summary> /// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/> /// and <see cref="TcpCommunicationSpi"/> for client nodes. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:30")] public TimeSpan ClientFailureDetectionTimeout { get { return _clientFailureDetectionTimeout ?? DefaultClientFailureDetectionTimeout; } set { _clientFailureDetectionTimeout = value; } } /// <summary> /// Gets or sets the configurations for plugins to be started. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<IPluginConfiguration> PluginConfigurations { get; set; } /// <summary> /// Gets or sets the event storage interface. /// <para /> /// Only predefined implementations are supported: /// <see cref="NoopEventStorageSpi"/>, <see cref="MemoryEventStorageSpi"/>. /// </summary> public IEventStorageSpi EventStorageSpi { get; set; } /// <summary> /// Gets or sets the page memory configuration. /// <see cref="MemoryConfiguration"/> for more details. /// </summary> public MemoryConfiguration MemoryConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating how user assemblies should be loaded on remote nodes. /// <para /> /// For example, when executing <see cref="ICompute.Call{TRes}(IComputeFunc{TRes})"/>, /// the assembly with corresponding <see cref="IComputeFunc{TRes}"/> should be loaded on remote nodes. /// With this option enabled, Ignite will attempt to send the assembly to remote nodes /// and load it there automatically. /// <para /> /// Default is <see cref="Apache.Ignite.Core.Deployment.PeerAssemblyLoadingMode.Disabled"/>. /// <para /> /// Peer loading is enabled for <see cref="ICompute"/> functionality. /// </summary> public PeerAssemblyLoadingMode PeerAssemblyLoadingMode { get; set; } /// <summary> /// Gets or sets the size of the public thread pool, which processes compute jobs and user messages. /// </summary> public int PublicThreadPoolSize { get { return _publicThreadPoolSize ?? DefaultThreadPoolSize; } set { _publicThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the striped thread pool, which processes cache requests. /// </summary> public int StripedThreadPoolSize { get { return _stripedThreadPoolSize ?? DefaultThreadPoolSize; } set { _stripedThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the service thread pool, which processes Ignite services. /// </summary> public int ServiceThreadPoolSize { get { return _serviceThreadPoolSize ?? DefaultThreadPoolSize; } set { _serviceThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the system thread pool, which processes internal system messages. /// </summary> public int SystemThreadPoolSize { get { return _systemThreadPoolSize ?? DefaultThreadPoolSize; } set { _systemThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the asynchronous callback thread pool. /// </summary> public int AsyncCallbackThreadPoolSize { get { return _asyncCallbackThreadPoolSize ?? DefaultThreadPoolSize; } set { _asyncCallbackThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the management thread pool, which processes internal Ignite jobs. /// </summary> [DefaultValue(DefaultManagementThreadPoolSize)] public int ManagementThreadPoolSize { get { return _managementThreadPoolSize ?? DefaultManagementThreadPoolSize; } set { _managementThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the data streamer thread pool. /// </summary> public int DataStreamerThreadPoolSize { get { return _dataStreamerThreadPoolSize ?? DefaultThreadPoolSize; } set { _dataStreamerThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the utility cache thread pool. /// </summary> public int UtilityCacheThreadPoolSize { get { return _utilityCacheThreadPoolSize ?? DefaultThreadPoolSize; } set { _utilityCacheThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the query thread pool. /// </summary> public int QueryThreadPoolSize { get { return _queryThreadPoolSize ?? DefaultThreadPoolSize; } set { _queryThreadPoolSize = value; } } /// <summary> /// Gets or sets the SQL connector configuration (for JDBC and ODBC). /// </summary> public SqlConnectorConfiguration SqlConnectorConfiguration { get; set; } /// <summary> /// Gets or sets the timeout after which long query warning will be printed. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:03")] public TimeSpan LongQueryWarningTimeout { get { return _longQueryWarningTimeout ?? DefaultLongQueryWarningTimeout; } set { _longQueryWarningTimeout = value; } } /// <summary> /// Gets or sets the persistent store configuration. /// </summary> public PersistentStoreConfiguration PersistentStoreConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating whether grid should be active on start. /// See also <see cref="IIgnite.IsActive"/> and <see cref="IIgnite.SetActive"/>. /// </summary> [DefaultValue(DefaultIsActiveOnStart)] public bool IsActiveOnStart { get { return _isActiveOnStart ?? DefaultIsActiveOnStart; } set { _isActiveOnStart = value; } } } }
using System.Buffers; using System.Diagnostics; using System.Globalization; using System.Runtime.ExceptionServices; using MySqlConnector.Protocol; using MySqlConnector.Protocol.Payloads; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySqlConnector.Core; internal sealed class ResultSet { public ResultSet(MySqlDataReader dataReader) { DataReader = dataReader; } public void Reset() { // ResultSet can be re-used, so initialize everything BufferState = ResultSetState.None; ColumnDefinitions = null; ColumnTypes = null; WarningCount = 0; State = ResultSetState.None; ContainsCommandParameters = false; m_columnDefinitionPayloadUsedBytes = 0; m_readBuffer?.Clear(); m_row = null; m_hasRows = false; ReadResultSetHeaderException = null; } public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior) { Reset(); try { while (true) { var payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); var firstByte = payload.HeaderByte; if (firstByte == OkPayload.Signature) { var ok = OkPayload.Create(payload.Span, Session.SupportsDeprecateEof, Session.SupportsSessionTrack); // if we've read a result set header then this is a SELECT statement, so we shouldn't overwrite RecordsAffected // (which should be -1 for SELECT) unless the server reports a non-zero count if (State != ResultSetState.ReadResultSetHeader || ok.AffectedRowCount != 0) DataReader.RealRecordsAffected = (DataReader.RealRecordsAffected ?? 0) + ok.AffectedRowCount; if (ok.LastInsertId != 0) Command?.SetLastInsertedId((long) ok.LastInsertId); WarningCount = ok.WarningCount; if (ok.NewSchema is not null) Connection.Session.DatabaseOverride = ok.NewSchema; ColumnDefinitions = null; ColumnTypes = null; State = (ok.ServerStatus & ServerStatus.MoreResultsExist) == 0 ? ResultSetState.NoMoreData : ResultSetState.HasMoreData; if (State == ResultSetState.NoMoreData) break; } else if (firstByte == LocalInfilePayload.Signature) { try { if (!Connection.AllowLoadLocalInfile) throw new NotSupportedException("To use LOAD DATA LOCAL INFILE, set AllowLoadLocalInfile=true in the connection string. See https://fl.vu/mysql-load-data"); var localInfile = LocalInfilePayload.Create(payload.Span); var hasSourcePrefix = localInfile.FileName.StartsWith(MySqlBulkLoader.SourcePrefix, StringComparison.Ordinal); if (!IsHostVerified(Connection) && !hasSourcePrefix) throw new NotSupportedException("Use SourceStream or SslMode >= VerifyCA for LOAD DATA LOCAL INFILE. See https://fl.vu/mysql-load-data"); var source = hasSourcePrefix ? MySqlBulkLoader.GetAndRemoveSource(localInfile.FileName) : File.OpenRead(localInfile.FileName); switch (source) { case Stream stream: var buffer = ArrayPool<byte>.Shared.Rent(1048576); try { int byteCount; while ((byteCount = await stream.ReadAsync(buffer, 0, buffer.Length, CancellationToken.None).ConfigureAwait(false)) > 0) { payload = new(new ArraySegment<byte>(buffer, 0, byteCount)); await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false); } } finally { ArrayPool<byte>.Shared.Return(buffer); stream.Dispose(); } break; case MySqlBulkCopy bulkCopy: await bulkCopy.SendDataReaderAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); break; default: throw new InvalidOperationException("Unsupported Source type: {0}".FormatInvariant(source.GetType().Name)); } } catch (Exception ex) { // store the exception, to be thrown after reading the response packet from the server ReadResultSetHeaderException = ExceptionDispatchInfo.Capture(new MySqlException("Error during LOAD DATA LOCAL INFILE", ex)); } await Session.SendReplyAsync(EmptyPayload.Instance, ioBehavior, CancellationToken.None).ConfigureAwait(false); } else { static int ReadColumnCount(ReadOnlySpan<byte> span) { var reader = new ByteArrayReader(span); var columnCount_ = (int) reader.ReadLengthEncodedInteger(); if (reader.BytesRemaining != 0) throw new MySqlException("Unexpected data at end of column_count packet; see https://github.com/mysql-net/MySqlConnector/issues/324"); return columnCount_; } var columnCount = ReadColumnCount(payload.Span); // reserve adequate space to hold a copy of all column definitions (but note that this can be resized below if we guess too small) Utility.Resize(ref m_columnDefinitionPayloads, columnCount * 96); ColumnDefinitions = new ColumnDefinitionPayload[columnCount]; ColumnTypes = new MySqlDbType[columnCount]; for (var column = 0; column < ColumnDefinitions.Length; column++) { payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); var payloadLength = payload.Span.Length; // 'Session.ReceiveReplyAsync' reuses a shared buffer; make a copy so that the column definitions can always be safely read at any future point if (m_columnDefinitionPayloadUsedBytes + payloadLength > m_columnDefinitionPayloads.Count) Utility.Resize(ref m_columnDefinitionPayloads, m_columnDefinitionPayloadUsedBytes + payloadLength); payload.Span.CopyTo(m_columnDefinitionPayloads.Array.AsSpan().Slice(m_columnDefinitionPayloadUsedBytes)); var columnDefinition = ColumnDefinitionPayload.Create(new ResizableArraySegment<byte>(m_columnDefinitionPayloads, m_columnDefinitionPayloadUsedBytes, payloadLength)); ColumnDefinitions[column] = columnDefinition; ColumnTypes[column] = TypeMapper.ConvertToMySqlDbType(columnDefinition, treatTinyAsBoolean: Connection.TreatTinyAsBoolean, guidFormat: Connection.GuidFormat); m_columnDefinitionPayloadUsedBytes += payloadLength; } if (!Session.SupportsDeprecateEof) { payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); EofPayload.Create(payload.Span); } if (ColumnDefinitions.Length == (Command?.OutParameters?.Count + 1) && ColumnDefinitions[0].Name == SingleCommandPayloadCreator.OutParameterSentinelColumnName) ContainsCommandParameters = true; WarningCount = 0; State = ResultSetState.ReadResultSetHeader; if (DataReader.Activity is { IsAllDataRequested: true }) DataReader.Activity.AddEvent(new ActivityEvent("read-result-set-header")); break; } } } catch (Exception ex) { ReadResultSetHeaderException = ExceptionDispatchInfo.Capture(ex); } finally { BufferState = State; } } private static bool IsHostVerified(MySqlConnection connection) { return connection.SslMode == MySqlSslMode.VerifyCA || connection.SslMode == MySqlSslMode.VerifyFull; } public async Task ReadEntireAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { while (State is ResultSetState.ReadingRows or ResultSetState.ReadResultSetHeader) await ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } public bool Read() { return ReadAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); } public Task<bool> ReadAsync(CancellationToken cancellationToken) => ReadAsync(Connection.AsyncIOBehavior, cancellationToken); public async Task<bool> ReadAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { m_row = m_readBuffer?.Count > 0 ? m_readBuffer.Dequeue() : await ScanRowAsync(ioBehavior, m_row, cancellationToken).ConfigureAwait(false); if (Command.ReturnParameter is not null && m_row is not null) { Command.ReturnParameter.Value = m_row.GetValue(0); Command.ReturnParameter = null; } if (m_row is null) { State = BufferState; return false; } State = ResultSetState.ReadingRows; return true; } public async Task<Row?> BufferReadAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { var row = await ScanRowAsync(ioBehavior, null, cancellationToken).ConfigureAwait(false); if (row is null) return null; m_readBuffer ??= new(); m_readBuffer.Enqueue(row); return row; } private ValueTask<Row?> ScanRowAsync(IOBehavior ioBehavior, Row? row, CancellationToken cancellationToken) { // if we've already read past the end of this resultset, Read returns false if (BufferState is ResultSetState.HasMoreData or ResultSetState.NoMoreData or ResultSetState.None) return new ValueTask<Row?>(default(Row?)); using var registration = Command.CancellableCommand.RegisterCancel(cancellationToken); var payloadValueTask = Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None); return payloadValueTask.IsCompletedSuccessfully ? new ValueTask<Row?>(ScanRowAsyncRemainder(this, payloadValueTask.Result, row)) : new ValueTask<Row?>(ScanRowAsyncAwaited(this, payloadValueTask.AsTask(), row, cancellationToken)); static async Task<Row?> ScanRowAsyncAwaited(ResultSet resultSet, Task<PayloadData> payloadTask, Row? row, CancellationToken token) { PayloadData payloadData; try { payloadData = await payloadTask.ConfigureAwait(false); } catch (MySqlException ex) { resultSet.BufferState = resultSet.State = ResultSetState.NoMoreData; if (ex.ErrorCode == MySqlErrorCode.QueryInterrupted && token.IsCancellationRequested) throw new OperationCanceledException(ex.Message, ex, token); if (ex.ErrorCode == MySqlErrorCode.QueryInterrupted && resultSet.Command.CancellableCommand.IsTimedOut) throw MySqlException.CreateForTimeout(ex); throw; } return ScanRowAsyncRemainder(resultSet, payloadData, row); } static Row? ScanRowAsyncRemainder(ResultSet resultSet, PayloadData payload, Row? row) { if (payload.HeaderByte == EofPayload.Signature) { var span = payload.Span; if (resultSet.Session.SupportsDeprecateEof && OkPayload.IsOk(span, resultSet.Session.SupportsDeprecateEof)) { var ok = OkPayload.Create(span, resultSet.Session.SupportsDeprecateEof, resultSet.Session.SupportsSessionTrack); resultSet.BufferState = (ok.ServerStatus & ServerStatus.MoreResultsExist) == 0 ? ResultSetState.NoMoreData : ResultSetState.HasMoreData; return null; } if (!resultSet.Session.SupportsDeprecateEof && EofPayload.IsEof(payload)) { var eof = EofPayload.Create(span); resultSet.BufferState = (eof.ServerStatus & ServerStatus.MoreResultsExist) == 0 ? ResultSetState.NoMoreData : ResultSetState.HasMoreData; return null; } } row ??= resultSet.Command.TryGetPreparedStatements() is null ? new TextRow(resultSet) : new BinaryRow(resultSet); row.SetData(payload.Memory); resultSet.m_hasRows = true; resultSet.BufferState = ResultSetState.ReadingRows; return row; } } #pragma warning disable CA1822 // Mark members as static public int Depth => 0; #pragma warning restore CA1822 // Mark members as static #pragma warning disable CA2201 // Do not raise reserved exception types (IndexOutOfRangeException) public string GetName(int ordinal) { if (ColumnDefinitions is null) throw new InvalidOperationException("There is no current result set."); if (ordinal < 0 || ordinal >= ColumnDefinitions.Length) throw new IndexOutOfRangeException("value must be between 0 and {0}".FormatInvariant(ColumnDefinitions.Length - 1)); return ColumnDefinitions[ordinal].Name; } public string GetDataTypeName(int ordinal) { if (ColumnDefinitions is null) throw new InvalidOperationException("There is no current result set."); if (ordinal < 0 || ordinal >= ColumnDefinitions.Length) throw new IndexOutOfRangeException("value must be between 0 and {0}.".FormatInvariant(ColumnDefinitions.Length)); var mySqlDbType = ColumnTypes![ordinal]; if (mySqlDbType == MySqlDbType.String) return string.Format(CultureInfo.InvariantCulture, "CHAR({0})", ColumnDefinitions[ordinal].ColumnLength / ProtocolUtility.GetBytesPerCharacter(ColumnDefinitions[ordinal].CharacterSet)); return TypeMapper.Instance.GetColumnTypeMetadata(mySqlDbType).SimpleDataTypeName; } public Type GetFieldType(int ordinal) { if (ColumnDefinitions is null) throw new InvalidOperationException("There is no current result set."); if (ordinal < 0 || ordinal >= ColumnDefinitions.Length) throw new IndexOutOfRangeException("value must be between 0 and {0}.".FormatInvariant(ColumnDefinitions.Length)); var type = TypeMapper.Instance.GetColumnTypeMetadata(ColumnTypes![ordinal]).DbTypeMapping.ClrType; if (Connection.AllowZeroDateTime && type == typeof(DateTime)) type = typeof(MySqlDateTime); return type; } public int FieldCount => ColumnDefinitions?.Length ?? 0; public bool HasRows { get { if (BufferState == ResultSetState.ReadResultSetHeader) return BufferReadAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult() is not null; return m_hasRows; } } public int GetOrdinal(string name) { if (name is null) throw new ArgumentNullException(nameof(name)); if (ColumnDefinitions is null) throw new InvalidOperationException("There is no current result set."); for (var column = 0; column < ColumnDefinitions.Length; column++) { if (name.Equals(ColumnDefinitions[column].Name, StringComparison.OrdinalIgnoreCase)) return column; } throw new IndexOutOfRangeException("The column name '{0}' does not exist in the result set.".FormatInvariant(name)); } public Row GetCurrentRow() { if (State != ResultSetState.ReadingRows) throw new InvalidOperationException("Read must be called first."); return m_row ?? throw new InvalidOperationException("There is no current row."); } public MySqlDataReader DataReader { get; } public ExceptionDispatchInfo? ReadResultSetHeaderException { get; private set; } public IMySqlCommand Command => DataReader.Command!; public MySqlConnection Connection => DataReader.Connection!; public ServerSession Session => DataReader.Session!; public ResultSetState BufferState { get; private set; } public ColumnDefinitionPayload[]? ColumnDefinitions { get; private set; } public MySqlDbType[]? ColumnTypes { get; private set; } public int WarningCount { get; private set; } public ResultSetState State { get; private set; } public bool ContainsCommandParameters { get; private set; } private ResizableArray<byte>? m_columnDefinitionPayloads; private int m_columnDefinitionPayloadUsedBytes; private Queue<Row>? m_readBuffer; private Row? m_row; private bool m_hasRows; }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using FeedbackSystem.Web.Areas.HelpPage.ModelDescriptions; using FeedbackSystem.Web.Areas.HelpPage.Models; namespace FeedbackSystem.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region License /* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Configuration; using System.Reflection; using System.Xml; using Common.Logging; using Spring.Core; using Spring.Core.TypeResolution; using Spring.Objects; using Spring.Reflection.Dynamic; using Spring.Util; #endregion namespace Spring.Context.Support { /// <summary> /// Creates an <see cref="Spring.Context.IApplicationContext"/> instance /// using context definitions supplied in a custom configuration and /// configures the <see cref="ContextRegistry"/> with that instance. /// </summary> /// <remarks> /// Implementations of the <see cref="Spring.Context.IApplicationContext"/> /// interface <b>must</b> provide the following two constructors: /// <list type="number"> /// <item> /// <description> /// A constructor that takes a string array of resource locations. /// </description> /// </item> /// <item> /// <description> /// A constructor that takes a reference to a parent application context /// and a string array of resource locations (and in that order). /// </description> /// </item> /// </list> /// <p> /// Note that if the <c>type</c> attribute is not present in the declaration /// of a particular context, then a default /// <see cref="Spring.Context.IApplicationContext"/> <see cref="System.Type"/> /// is assumed. This default /// <see cref="Spring.Context.IApplicationContext"/> <see cref="System.Type"/> /// is currently the <see cref="Spring.Context.Support.XmlApplicationContext"/> /// <see cref="System.Type"/>; please note the exact <see cref="System.Type"/> /// of this default <see cref="Spring.Context.IApplicationContext"/> is an /// implementation detail, that, while unlikely, may do so in the future. /// to /// </p> /// </remarks> /// <example> /// <p> /// This is an example of specifying a context that reads its resources from /// an embedded Spring.NET XML object configuration file... /// </p> /// <code escaped="true"> /// <configuration> /// <configSections> /// <sectionGroup name="spring"> /// <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> /// </sectionGroup> /// </configSections> /// <spring> /// <context> /// <resource uri="assembly://MyAssemblyName/MyResourceNamespace/MyObjects.xml"/> /// </context> /// </spring> /// </configuration> /// </code> /// <p> /// This is an example of specifying a context that reads its resources from /// a custom configuration section within the same application / web /// configuration file and uses case insensitive object lookups. /// </p> /// <p> /// Please note that you <b>must</b> adhere to the naming /// of the various sections (i.e. '&lt;sectionGroup name="spring"&gt;' and /// '&lt;section name="context"&gt;'. /// </p> /// <code escaped="true"> /// <configuration> /// <configSections> /// <sectionGroup name="spring"> /// <section name="context" /// type="Spring.Context.Support.ContextHandler, Spring.Core"/> /// <section name="objects" /// type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> /// </sectionGroup> /// </configSections> /// <spring> /// <context /// caseSensitive="false" /// type="Spring.Context.Support.XmlApplicationContext, Spring.Core"> /// <resource uri="config://spring/objects"/> /// </context> /// <objects xmlns="http://www.springframework.net"> /// <!-- object definitions... --> /// </objects> /// </spring> /// </configuration> /// </code> /// <p> /// And this is an example of specifying a hierarchy of contexts. The /// hierarchy in this case is only a simple parent->child hierarchy, but /// hopefully it illustrates the nesting of context configurations. This /// nesting of contexts can be arbitrarily deep, and is one way... child /// contexts know about their parent contexts, but parent contexts do not /// know how many child contexts they have (if any), or have references /// to any such child contexts. /// </p> /// <code escaped="true"> /// <configuration> /// <configSections> /// <sectionGroup name='spring'> /// <section name='context' type='Spring.Context.Support.ContextHandler, Spring.Core'/> /// <section name='objects' type='Spring.Context.Support.DefaultSectionHandler, Spring.Core' /> /// <sectionGroup name="child"> /// <section name='objects' type='Spring.Context.Support.DefaultSectionHandler, Spring.Core' /> /// </sectionGroup> /// </sectionGroup> /// </configSections> /// /// <spring> /// <context name='Parent'> /// <resource uri='config://spring/objects'/> /// <context name='Child'> /// <resource uri='config://spring/childObjects'/> /// </context> /// </context> /// <!-- parent context's objects --> /// <objects xmlns='http://www.springframework.net'> /// <object id='Parent' type='Spring.Objects.TestObject,Spring.Core.Tests'> /// <property name='name' value='Parent'/> /// </object> /// </objects> /// <!-- child context's objects --> /// <child> /// <objects xmlns='http://www.springframework.net'> /// <object id='Child' type='Spring.Objects.TestObject,Spring.Core.Tests'> /// <property name='name' value='Child'/> /// </object> /// </objects> /// </child> /// </spring> /// </configuration> /// </code> /// </example> /// <author>Mark Pollack</author> /// <author>Aleksandar Seovic</author> /// <author>Rick Evans</author> /// <seealso cref="ContextRegistry"/> public class ContextHandler : IConfigurationSectionHandler { private readonly ILog Log = LogManager.GetLogger(typeof(ContextHandler)); /// <summary> /// The <see cref="System.Type"/> of <see cref="Spring.Context.IApplicationContext"/> /// created if no <c>type</c> attribute is specified on a <c>context</c> element. /// </summary> /// <seealso cref="GetContextType"/> protected virtual Type DefaultApplicationContextType { get { return typeof (XmlApplicationContext); } } /// <summary> /// Get the context's case-sensitivity to use if none is specified /// </summary> /// <remarks> /// <p> /// Derived handlers may override this property to change their default case-sensitivity. /// </p> /// <p> /// Defaults to 'true'. /// </p> /// </remarks> protected virtual bool DefaultCaseSensitivity { get { return true; } } /// <summary> /// Specifies, whether the instantiated context will be automatically registered in the /// global <see cref="ContextRegistry"/>. /// </summary> protected virtual bool AutoRegisterWithContextRegistry { get { return true; } } /// <summary> /// Creates an <see cref="Spring.Context.IApplicationContext"/> instance /// using the context definitions supplied in a custom /// configuration section. /// </summary> /// <remarks> /// <p> /// This <see cref="Spring.Context.IApplicationContext"/> instance is /// also used to configure the <see cref="ContextRegistry"/>. /// </p> /// </remarks> /// <param name="parent"> /// The configuration settings in a corresponding parent /// configuration section. /// </param> /// <param name="configContext"> /// The configuration context when called from the ASP.NET /// configuration system. Otherwise, this parameter is reserved and /// is <see langword="null"/>. /// </param> /// <param name="section"> /// The <see cref="System.Xml.XmlNode"/> for the section. /// </param> /// <returns> /// An <see cref="Spring.Context.IApplicationContext"/> instance /// populated with the object definitions supplied in the configuration /// section. /// </returns> public object Create(object parent, object configContext, XmlNode section) { XmlElement contextElement = section as XmlElement; #region Sanity Checks if (contextElement == null) { throw ConfigurationUtils.CreateConfigurationException( "Context configuration section must be an XmlElement."); } // sanity check on parent if ( (parent != null) && !(parent is IApplicationContext) ) { throw ConfigurationUtils.CreateConfigurationException( String.Format("Parent context must be of type IApplicationContext, but was '{0}'", parent.GetType().FullName)); } #endregion // determine name of context to be created string contextName = GetContextName(configContext, contextElement); if (!StringUtils.HasLength(contextName)) { contextName = AbstractApplicationContext.DefaultRootContextName; } #region Instrumentation if (Log.IsDebugEnabled) Log.Debug(string.Format("creating context '{0}'", contextName ) ); #endregion IApplicationContext context = null; try { IApplicationContext parentContext = parent as IApplicationContext; // determine context type Type contextType = GetContextType(contextElement, parentContext); // determine case-sensitivity bool caseSensitive = GetCaseSensitivity(contextElement); // get resource-list string[] resources = GetResources(contextElement); // finally create the context instance context = InstantiateContext(parentContext, configContext, contextName, contextType, caseSensitive, resources); // and register with global context registry if (AutoRegisterWithContextRegistry) { ContextRegistry.RegisterContext(context); } // get and create child context definitions XmlNode[] childContexts = GetChildContexts(contextElement); CreateChildContexts(context, configContext, childContexts); if (Log.IsDebugEnabled) Log.Debug( string.Format("context '{0}' created for name '{1}'", context, contextName) ); } catch (Exception ex) { if (!ConfigurationUtils.IsConfigurationException(ex)) { throw ConfigurationUtils.CreateConfigurationException( String.Format("Error creating context '{0}': {1}", contextName, ReflectionUtils.GetExplicitBaseException(ex).Message), ex); } throw; } return context; } /// <summary> /// Create all child-contexts in the given <see cref="XmlNodeList"/> for the given context. /// </summary> /// <param name="parentContext">The parent context to use</param> /// <param name="configContext">The current configContext <see cref="IConfigurationSectionHandler.Create"/></param> /// <param name="childContexts">The list of child context elements</param> protected virtual void CreateChildContexts(IApplicationContext parentContext, object configContext, XmlNode[] childContexts) { // create child contexts for 'the most recently created context'... foreach (XmlNode childContext in childContexts) { this.Create(parentContext, configContext, childContext); } } /// <summary> /// Instantiates a new context. /// </summary> protected virtual IApplicationContext InstantiateContext(IApplicationContext parentContext, object configContext, string contextName, Type contextType, bool caseSensitive, string[] resources) { IApplicationContext context; ContextInstantiator instantiator; if (parentContext == null) { instantiator = new RootContextInstantiator(contextType, contextName, caseSensitive, resources); } else { instantiator = new DescendantContextInstantiator(parentContext, contextType, contextName, caseSensitive, resources); } if (IsLazy) { // TODO } context = instantiator.InstantiateContext(); return context; } /// <summary> /// Gets the context's name specified in the name attribute of the context element. /// </summary> /// <param name="configContext">The current configContext <see cref="IConfigurationSectionHandler.Create"/></param> /// <param name="contextElement">The context element</param> protected virtual string GetContextName(object configContext, XmlElement contextElement) { string contextName; contextName = contextElement.GetAttribute(ContextSchema.NameAttribute); return contextName; } /// <summary> /// Extracts the context-type from the context element. /// If none is specified, returns the parent's type. /// </summary> private Type GetContextType(XmlElement contextElement, IApplicationContext parentContext) { Type contextType; if (parentContext != null) { // set default context type to parent's type (allows for type inheritance) contextType = GetConfiguredContextType(contextElement, parentContext.GetType()); } else { contextType = GetConfiguredContextType(contextElement, this.DefaultApplicationContextType); } return contextType; } /// <summary> /// Extracts the case-sensitivity attribute from the context element /// </summary> private bool GetCaseSensitivity(XmlElement contextElement) { bool caseSensitive = DefaultCaseSensitivity; string caseSensitiveAttr = contextElement.GetAttribute(ContextSchema.CaseSensitiveAttribute); if (StringUtils.HasText(caseSensitiveAttr)) { caseSensitive = Boolean.Parse(caseSensitiveAttr); } return caseSensitive; } /// <summary> /// Gets the context <see cref="System.Type"/> specified in the type /// attribute of the context element. /// </summary> /// <remarks> /// <p> /// If this attribute is not defined it defaults to the /// <see cref="Spring.Context.Support.XmlApplicationContext"/> type. /// </p> /// </remarks> /// <exception cref="TypeMismatchException"> /// If the context type does not implement the /// <see cref="Spring.Context.IApplicationContext"/> interface. /// </exception> private Type GetConfiguredContextType(XmlElement contextElement, Type defaultContextType) { string typeName = contextElement.GetAttribute(ContextSchema.TypeAttribute); if (StringUtils.IsNullOrEmpty(typeName)) { return defaultContextType; } else { Type type = TypeResolutionUtils.ResolveType(typeName); if (typeof(IApplicationContext).IsAssignableFrom(type)) { return type; } else { throw new TypeMismatchException( type.Name + " does not implement IApplicationContext."); } } } /// <summary> /// Returns <see langword="true"/> if the context should be lazily /// initialized. /// </summary> private bool IsLazy { get { return false; } } /// <summary> /// Returns the array of resources containing object definitions for /// this context. /// </summary> private string[] GetResources( XmlElement contextElement ) { ArrayList resourceNodes = new ArrayList(contextElement.ChildNodes.Count); foreach (XmlNode possibleResourceNode in contextElement.ChildNodes) { XmlElement possibleResourceElement = possibleResourceNode as XmlElement; if(possibleResourceElement != null && possibleResourceElement.LocalName == ContextSchema.ResourceElement) { string resourceName = possibleResourceElement.GetAttribute(ContextSchema.URIAttribute); if(StringUtils.HasText(resourceName)) { resourceNodes.Add(resourceName); } } } return (string[]) resourceNodes.ToArray(typeof(string)); } /// <summary> /// Returns the array of child contexts for this context. /// </summary> private XmlNode[] GetChildContexts(XmlElement contextElement) { ArrayList contextNodes = new ArrayList(contextElement.ChildNodes.Count); foreach (XmlNode possibleContextNode in contextElement.ChildNodes) { XmlElement possibleContextElement = possibleContextNode as XmlElement; if (possibleContextElement != null && possibleContextElement.LocalName == ContextSchema.ContextElement) { contextNodes.Add(possibleContextElement); } } return (XmlNode[])contextNodes.ToArray(typeof(XmlNode)); } #region Inner Class : ContextInstantiator private abstract class ContextInstantiator { protected ContextInstantiator( Type contextType, string contextName, bool caseSensitive, string[] resources) { _contextType = contextType; _contextName = contextName; _caseSensitive = caseSensitive; _resources = resources; } public IApplicationContext InstantiateContext() { ConstructorInfo ctor = GetContextConstructor(); if (ctor == null) { string errorMessage = "No constructor with string[] argument found for context type [" + ContextType.Name + "]"; throw ConfigurationUtils.CreateConfigurationException(errorMessage); } IApplicationContext context = InvokeContextConstructor(ctor); return context; } protected abstract ConstructorInfo GetContextConstructor(); protected abstract IApplicationContext InvokeContextConstructor( ConstructorInfo ctor); protected Type ContextType { get { return _contextType; } } protected string ContextName { get { return _contextName; } } protected bool CaseSensitive { get { return _caseSensitive; } } protected string[] Resources { get { return _resources; } } private Type _contextType; private string _contextName; private bool _caseSensitive; private string[] _resources; } #endregion #region Inner Class : RootContextInstantiator private sealed class RootContextInstantiator : ContextInstantiator { public RootContextInstantiator( Type contextType, string contextName, bool caseSensitive, string[] resources) : base(contextType, contextName, caseSensitive, resources) { } protected override ConstructorInfo GetContextConstructor() { return ContextType.GetConstructor(new Type[] {typeof(string), typeof(bool), typeof(string[])}); } protected override IApplicationContext InvokeContextConstructor( ConstructorInfo ctor) { return (IApplicationContext)(new SafeConstructor(ctor).Invoke(new object[] {ContextName, CaseSensitive, Resources})); } } #endregion #region Inner Class : DescendantContextInstantiator private sealed class DescendantContextInstantiator : ContextInstantiator { public DescendantContextInstantiator( IApplicationContext parentContext, Type contextType, string contextName, bool caseSensitive, string[] resources) : base(contextType, contextName, caseSensitive, resources) { this.parentContext = parentContext; } protected override ConstructorInfo GetContextConstructor() { return ContextType.GetConstructor( new Type[] {typeof(string), typeof(bool), typeof(IApplicationContext), typeof(string[])}); } protected override IApplicationContext InvokeContextConstructor( ConstructorInfo ctor) { return (IApplicationContext)(new SafeConstructor(ctor).Invoke(new object[] {ContextName, CaseSensitive, this.parentContext, Resources})); } private IApplicationContext parentContext; } #endregion #region Context Schema Constants /// <summary> /// Constants defining the structure and values associated with the /// schema for laying out Spring.NET contexts in XML. /// </summary> private sealed class ContextSchema { /// <summary> /// Defines a single /// <see cref="Spring.Context.IApplicationContext"/>. /// </summary> public const string ContextElement = "context"; /// <summary> /// Specifies a context name. /// </summary> public const string NameAttribute = "name"; /// <summary> /// Specifies if context should be case sensitive or not. Default is <c>true</c>. /// </summary> public const string CaseSensitiveAttribute = "caseSensitive"; /// <summary> /// Specifies a <see cref="System.Type"/>. /// </summary> /// <remarks> /// <p> /// Does not have to be fully assembly qualified, but its generally regarded /// as better form if the <see cref="System.Type"/> names of one's objects /// are specified explicitly. /// </p> /// </remarks> public const string TypeAttribute = "type"; /// <summary> /// Specifies whether context should be lazy initialized. /// </summary> public const string LazyAttribute = "lazy"; /// <summary> /// Defines an <see cref="Spring.Core.IO.IResource"/> /// </summary> public const string ResourceElement = "resource"; /// <summary> /// Specifies the URI for an /// <see cref="Spring.Core.IO.IResource"/>. /// </summary> public const string URIAttribute = "uri"; } #endregion } }
/* Copyright (c) 2016, Ncortiz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NIC16-Assembler nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace NIC16_Assembler { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.compileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.compileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.textBox_sourceCode = new ScintillaNET.Scintilla(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // openFileDialog // this.openFileDialog.Filter = "NIC16 Assembly Files (*.nic16_asm)|*.nic16_asm|All Files (*.*)|*.*"; // // saveFileDialog // this.saveFileDialog.Filter = "NIC16 Assembly Files (*.nic16_asm)|*.nic16_asm|All Files (*.*)|*.*"; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.compileToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(624, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.openToolStripMenuItem, this.saveToolStripMenuItem, this.toolStripSeparator1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image"))); this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.openToolStripMenuItem.Text = "Open..."; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image"))); this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.saveToolStripMenuItem.Text = "Save..."; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(149, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("exitToolStripMenuItem.Image"))); this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // compileToolStripMenuItem // this.compileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.compileToolStripMenuItem1}); this.compileToolStripMenuItem.Name = "compileToolStripMenuItem"; this.compileToolStripMenuItem.Size = new System.Drawing.Size(64, 20); this.compileToolStripMenuItem.Text = "Compile"; // // compileToolStripMenuItem1 // this.compileToolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("compileToolStripMenuItem1.Image"))); this.compileToolStripMenuItem1.Name = "compileToolStripMenuItem1"; this.compileToolStripMenuItem1.Size = new System.Drawing.Size(152, 22); this.compileToolStripMenuItem1.Text = "Compile"; this.compileToolStripMenuItem1.Click += new System.EventHandler(this.compileToolStripMenuItem1_Click); // // textBox_sourceCode // this.textBox_sourceCode.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox_sourceCode.Location = new System.Drawing.Point(0, 24); this.textBox_sourceCode.Name = "textBox_sourceCode"; this.textBox_sourceCode.Size = new System.Drawing.Size(624, 397); this.textBox_sourceCode.TabIndex = 3; this.textBox_sourceCode.UseTabs = false; this.textBox_sourceCode.StyleNeeded += new System.EventHandler<ScintillaNET.StyleNeededEventArgs>(this.textBox_sourceCode_StyleNeeded); this.textBox_sourceCode.TextChanged += new System.EventHandler(this.textBox_sourceCode_TextChanged); // // newToolStripMenuItem // this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image"))); this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.newToolStripMenuItem.Text = "New"; this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(624, 421); this.Controls.Add(this.textBox_sourceCode); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "Form1"; this.Text = "NIC16 Assembler"; this.Load += new System.EventHandler(this.Form1_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem compileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem compileToolStripMenuItem1; private ScintillaNET.Scintilla textBox_sourceCode; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; } }
/* * 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.Examples.Datagrid { using System; using System.Linq; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.ExamplesDll.Binary; using Apache.Ignite.Linq; /// <summary> /// This example populates cache with sample data and runs several LINQ queries over this data. /// <para /> /// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build). /// Apache.Ignite.ExamplesDll.dll must appear in %IGNITE_HOME%/platforms/dotnet/examples/Apache.Ignite.ExamplesDll/bin/${Platform]/${Configuration} folder. /// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties -> /// Application -> Startup object); /// 3) Start example (F5 or Ctrl+F5). /// <para /> /// This example can be run with standalone Apache Ignite.NET node: /// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe: /// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config -assembly=[path_to_Apache.Ignite.ExamplesDll.dll] /// 2) Start example. /// </summary> public class LinqExample { /// <summary>Organization cache name.</summary> private const string OrganizationCacheName = "dotnet_cache_query_organization"; /// <summary>Employee cache name.</summary> private const string EmployeeCacheName = "dotnet_cache_query_employee"; /// <summary>Colocated employee cache name.</summary> private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated"; [STAThread] public static void Main() { using (var ignite = Ignition.StartFromApplicationConfiguration()) { Console.WriteLine(); Console.WriteLine(">>> Cache LINQ example started."); var employeeCache = ignite.GetOrCreateCache<int, Employee>( new CacheConfiguration(EmployeeCacheName, typeof(Employee))); var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>( new CacheConfiguration(EmployeeCacheNameColocated, typeof(Employee))); var organizationCache = ignite.GetOrCreateCache<int, Organization>( new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization)))); // Populate cache with sample data entries. PopulateCache(employeeCache); PopulateCache(employeeCacheColocated); PopulateCache(organizationCache); // Run SQL query example. QueryExample(employeeCache); // Run compiled SQL query example. CompiledQueryExample(employeeCache); // Run SQL query with join example. JoinQueryExample(employeeCacheColocated, organizationCache); // Run SQL query with distributed join example. DistributedJoinQueryExample(employeeCache, organizationCache); // Run SQL fields query example. FieldsQueryExample(employeeCache); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(">>> Example finished, press any key to exit ..."); Console.ReadKey(); } /// <summary> /// Queries employees that have provided ZIP code in address. /// </summary> /// <param name="cache">Cache.</param> private static void QueryExample(ICache<int, Employee> cache) { const int zip = 94109; IQueryable<ICacheEntry<int, Employee>> qry = cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == zip); Console.WriteLine(); Console.WriteLine(">>> Employees with zipcode " + zip + ":"); foreach (ICacheEntry<int, Employee> entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that have provided ZIP code in address with a compiled query. /// </summary> /// <param name="cache">Cache.</param> private static void CompiledQueryExample(ICache<int, Employee> cache) { const int zip = 94109; // Compile cache query to eliminate LINQ overhead on multiple runs. Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry = CompiledQuery.Compile((int z) => cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == z)); Console.WriteLine(); Console.WriteLine(">>> Employees with zipcode using compiled query " + zip + ":"); foreach (ICacheEntry<int, Employee> entry in qry(zip)) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that work for organization with provided name. /// </summary> /// <param name="employeeCache">Employee cache.</param> /// <param name="organizationCache">Organization cache.</param> private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache, ICache<int, Organization> organizationCache) { const string orgName = "Apache"; IQueryable<ICacheEntry<AffinityKey, Employee>> employees = employeeCache.AsCacheQueryable(); IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(); IQueryable<ICacheEntry<AffinityKey, Employee>> qry = from employee in employees from organization in organizations where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName select employee; Console.WriteLine(); Console.WriteLine(">>> Employees working for " + orgName + ":"); foreach (ICacheEntry<AffinityKey, Employee> entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that work for organization with provided name. /// </summary> /// <param name="employeeCache">Employee cache.</param> /// <param name="organizationCache">Organization cache.</param> private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache, ICache<int, Organization> organizationCache) { const string orgName = "Apache"; var queryOptions = new QueryOptions {EnableDistributedJoins = true}; IQueryable<ICacheEntry<int, Employee>> employees = employeeCache.AsCacheQueryable(queryOptions); IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(queryOptions); IQueryable<ICacheEntry<int, Employee>> qry = from employee in employees from organization in organizations where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName select employee; Console.WriteLine(); Console.WriteLine(">>> Employees working for " + orgName + ":"); foreach (ICacheEntry<int, Employee> entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries names and salaries for all employees. /// </summary> /// <param name="cache">Cache.</param> private static void FieldsQueryExample(ICache<int, Employee> cache) { var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary}); Console.WriteLine(); Console.WriteLine(">>> Employee names and their salaries:"); foreach (var row in qry) Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']'); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, Organization> cache) { cache.Put(1, new Organization( "Apache", new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404), OrganizationType.Private, DateTime.Now)); cache.Put(2, new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now)); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<AffinityKey, Employee> cache) { cache.Put(new AffinityKey(1, 1), new Employee( "James Wilson", 12500, new Address("1096 Eddy Street, San Francisco, CA", 94109), new[] {"Human Resources", "Customer Service"}, 1)); cache.Put(new AffinityKey(2, 1), new Employee( "Daniel Adams", 11000, new Address("184 Fidler Drive, San Antonio, TX", 78130), new[] {"Development", "QA"}, 1)); cache.Put(new AffinityKey(3, 1), new Employee( "Cristian Moss", 12500, new Address("667 Jerry Dove Drive, Florence, SC", 29501), new[] {"Logistics"}, 1)); cache.Put(new AffinityKey(4, 2), new Employee( "Allison Mathis", 25300, new Address("2702 Freedom Lane, San Francisco, CA", 94109), new[] {"Development"}, 2)); cache.Put(new AffinityKey(5, 2), new Employee( "Breana Robbin", 6500, new Address("3960 Sundown Lane, Austin, TX", 78130), new[] {"Sales"}, 2)); cache.Put(new AffinityKey(6, 2), new Employee( "Philip Horsley", 19800, new Address("2803 Elsie Drive, Sioux Falls, SD", 57104), new[] {"Sales"}, 2)); cache.Put(new AffinityKey(7, 2), new Employee( "Brian Peters", 10600, new Address("1407 Pearlman Avenue, Boston, MA", 12110), new[] {"Development", "QA"}, 2)); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, Employee> cache) { cache.Put(1, new Employee( "James Wilson", 12500, new Address("1096 Eddy Street, San Francisco, CA", 94109), new[] {"Human Resources", "Customer Service"}, 1)); cache.Put(2, new Employee( "Daniel Adams", 11000, new Address("184 Fidler Drive, San Antonio, TX", 78130), new[] {"Development", "QA"}, 1)); cache.Put(3, new Employee( "Cristian Moss", 12500, new Address("667 Jerry Dove Drive, Florence, SC", 29501), new[] {"Logistics"}, 1)); cache.Put(4, new Employee( "Allison Mathis", 25300, new Address("2702 Freedom Lane, San Francisco, CA", 94109), new[] {"Development"}, 2)); cache.Put(5, new Employee( "Breana Robbin", 6500, new Address("3960 Sundown Lane, Austin, TX", 78130), new[] {"Sales"}, 2)); cache.Put(6, new Employee( "Philip Horsley", 19800, new Address("2803 Elsie Drive, Sioux Falls, SD", 57104), new[] {"Sales"}, 2)); cache.Put(7, new Employee( "Brian Peters", 10600, new Address("1407 Pearlman Avenue, Boston, MA", 12110), new[] {"Development", "QA"}, 2)); } } }
// 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.Text; using Gallio.Framework; using Gallio.Common.Text; using Gallio.Common.Markup; using Gallio.Common.Markup.Tags; using MbUnit.Framework; namespace Gallio.Tests.Common.Text { [TestsOn(typeof(DiffSet))] public class DiffSetTest { [Test] public void ContainsDocumentAndDiffs() { DiffSet diffSet = new DiffSet(new[] { new Diff(DiffKind.Change, new Range(0, 3), new Range(0, 3)) }, "abc", "def"); Assert.AreEqual("abc", diffSet.LeftDocument); Assert.AreEqual("def", diffSet.RightDocument); Assert.AreElementsEqual(new[] { new Diff(DiffKind.Change, new Range(0, 3), new Range(0, 3)) }, diffSet.Diffs); } [Test, ExpectedArgumentNullException] public void LeftDocumentCannotBeNull() { new DiffSet(new Diff[] { }, null, ""); } [Test, ExpectedArgumentNullException] public void RightDocumentCannotBeNull() { new DiffSet(new Diff[] { }, "", null); } [Test, ExpectedArgumentNullException] public void DiffListCannotBeNull() { new DiffSet(null, "", ""); } [Test, ExpectedArgumentException] public void DiffListCannotBeEmptyWhenDocumentsAreNot() { new DiffSet(new Diff[] { }, "abc", "def"); } [Test] [Row(0, 3, 0, 2, ExpectedException=typeof(ArgumentException))] [Row(0, 2, 0, 4, ExpectedException=typeof(ArgumentException))] [Row(1, 2, 0, 4, ExpectedException=typeof(ArgumentException))] [Row(0, 3, 1, 3, ExpectedException=typeof(ArgumentException))] [Row(1, 3, 0, 4, ExpectedException=typeof(ArgumentException))] [Row(0, 3, 1, 4, ExpectedException=typeof(ArgumentException))] [Row(0, 3, 0, 4)] public void DiffListMustCoverBothDocuments(int x, int y, int u, int v) { new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(x, y), new Range(u, v)) }, "abc", "defg"); } [Test, ExpectedArgumentException] public void DiffListMustNotContainGaps() { new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), new Diff(DiffKind.Change, new Range(2, 1), new Range(2, 2)) }, "abc", "dbfg"); } [Test, ExpectedArgumentException] public void DiffListMustNotContainOverlappingSegments() { new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), new Diff(DiffKind.Change, new Range(0, 3), new Range(2, 2)) }, "abc", "dbfg"); } [Test] public void DiffCanConsistOfMultipleContiguousSegments() { new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), new Diff(DiffKind.NoChange, new Range(1, 1), new Range(1, 1)), new Diff(DiffKind.Change, new Range(2, 1), new Range(2, 2)) }, "abc", "dbfg"); } [Test, ExpectedArgumentNullException] public void GetDiffSetThrowsWhenLeftDocumentIsNull() { DiffSet.GetDiffSet(null, ""); } [Test, ExpectedArgumentNullException] public void GetDiffSetThrowsWhenRightDocumentIsNull() { DiffSet.GetDiffSet("", null); } [Test] public void WriteToThrowsWhenWriterIsNull() { DiffSet diffSet = new DiffSet(new Diff[] { }, "", ""); Assert.Throws<ArgumentNullException>(() => diffSet.WriteTo(null)); } [Test] public void WriteToThrowsWhenMaxContextLengthIsNegative() { DiffSet diffSet = new DiffSet(new Diff[] { }, "", ""); StructuredTextWriter writer = new StructuredTextWriter(); Assert.Throws<ArgumentOutOfRangeException>(() => diffSet.WriteTo(writer, DiffStyle.Interleaved, -1)); } [Test] public void WriteTo_InterleavedStyle() { DiffSet diffSet = new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), // change new Diff(DiffKind.NoChange, new Range(1, 1), new Range(1, 1)), // same new Diff(DiffKind.Change, new Range(2, 1), new Range(2, 0)), // deletion new Diff(DiffKind.NoChange, new Range(3, 1), new Range(2, 1)), // same new Diff(DiffKind.Change, new Range(4, 0), new Range(3, 1)), // addition }, "acde", "bcef"); StructuredTextWriter writer = new StructuredTextWriter(); diffSet.WriteTo(writer); TestLog.WriteLine(writer); Assert.AreEqual(new StructuredText(new BodyTag() { Contents = { new MarkerTag(Marker.DiffDeletion) { Contents = { new TextTag("a") } }, new MarkerTag(Marker.DiffAddition) { Contents = { new TextTag("b") } }, new TextTag("c"), new MarkerTag(Marker.DiffDeletion) { Contents = { new TextTag("d") } }, new TextTag("e"), new MarkerTag(Marker.DiffAddition) { Contents = { new TextTag("f") } } } }), writer.ToStructuredText()); } [Test] public void WriteTo_LeftOnlyStyle() { DiffSet diffSet = new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), // change new Diff(DiffKind.NoChange, new Range(1, 1), new Range(1, 1)), // same new Diff(DiffKind.Change, new Range(2, 1), new Range(2, 0)), // deletion new Diff(DiffKind.NoChange, new Range(3, 1), new Range(2, 1)), // same new Diff(DiffKind.Change, new Range(4, 0), new Range(3, 1)), // addition }, "acde", "bcef"); StructuredTextWriter writer = new StructuredTextWriter(); diffSet.WriteTo(writer, DiffStyle.LeftOnly); TestLog.WriteLine(writer); Assert.AreEqual(new StructuredText(new BodyTag() { Contents = { new MarkerTag(Marker.DiffChange) { Contents = { new TextTag("a") } }, new TextTag("c"), new MarkerTag(Marker.DiffDeletion) { Contents = { new TextTag("d") } }, new TextTag("e") } }), writer.ToStructuredText()); } [Test] public void WriteTo_RightOnlyStyle() { DiffSet diffSet = new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), // change new Diff(DiffKind.NoChange, new Range(1, 1), new Range(1, 1)), // same new Diff(DiffKind.Change, new Range(2, 1), new Range(2, 0)), // deletion new Diff(DiffKind.NoChange, new Range(3, 1), new Range(2, 1)), // same new Diff(DiffKind.Change, new Range(4, 0), new Range(3, 1)), // addition }, "acde", "bcef"); StructuredTextWriter writer = new StructuredTextWriter(); diffSet.WriteTo(writer, DiffStyle.RightOnly); TestLog.WriteLine(writer); Assert.AreEqual(new StructuredText(new BodyTag() { Contents = { new MarkerTag(Marker.DiffChange) { Contents = { new TextTag("b") } }, new TextTag("ce"), new MarkerTag(Marker.DiffDeletion) { Contents = { new TextTag("f") } } } }), writer.ToStructuredText()); } [Test] public void WriteTo_LeftOnlyWithLimitedContext() { DiffSet diffSet = new DiffSet(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)), // change new Diff(DiffKind.NoChange, new Range(1, 20), new Range(1, 20)), // same new Diff(DiffKind.Change, new Range(21, 1), new Range(21, 0)), // deletion new Diff(DiffKind.NoChange, new Range(22, 20), new Range(21, 20)), // same new Diff(DiffKind.Change, new Range(42, 0), new Range(41, 1)), // addition }, "accccccccccccccccccccdeeeeeeeeeeeeeeeeeeee", "bcccccccccccccccccccceeeeeeeeeeeeeeeeeeeef"); StructuredTextWriter writer = new StructuredTextWriter(); diffSet.WriteTo(writer, DiffStyle.LeftOnly, 7); Assert.AreEqual(new StructuredText(new BodyTag() { Contents = { new MarkerTag(Marker.DiffChange) { Contents = { new TextTag("a") } }, new TextTag("ccc"), new MarkerTag(Marker.Ellipsis) { Contents = { new TextTag("...") } }, new TextTag("ccc"), new MarkerTag(Marker.DiffDeletion) { Contents = { new TextTag("d") } }, new TextTag("eee"), new MarkerTag(Marker.Ellipsis) { Contents = { new TextTag("...") } }, new TextTag("eee") } }), writer.ToStructuredText()); } public class WhenDocumentsAreEmpty { [Test] public void ComputedDiffIsEmpty() { DiffSet diffSet = DiffSet.GetDiffSet("", ""); Assert.IsTrue(diffSet.IsEmpty); Assert.IsFalse(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { }, diffSet.Diffs); } } public class WhenDocumentsAreEqualy { [Test] public void NoChangeSpansBothDocuments() { DiffSet diffSet = DiffSet.GetDiffSet("this is a test", "this is a test"); Assert.IsFalse(diffSet.IsEmpty); Assert.IsFalse(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.NoChange, new Range(0, 14), new Range(0, 14)) }, diffSet.Diffs); } } public class WhenExactlyOneDocumentIsEmpty { [Test] public void IfLeftDocumentIsEmptyChangeSpansRightDocument() { DiffSet diffSet = DiffSet.GetDiffSet("", "abcde"); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 0), new Range(0, 5)) }, diffSet.Diffs); } [Test] public void IfRightDocumentIsEmptyChangeSpansLeftDocument() { DiffSet diffSet = DiffSet.GetDiffSet("abcde", ""); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 5), new Range(0, 0)) }, diffSet.Diffs); } } public class WhenCommonPrefixOrSuffixIsFound { [Test] public void ProblemSizeIsReducedButDiffOffsetsAreStillCorrect() { DiffSet diffSet = DiffSet.GetDiffSet("123abcZZdef45", "123uvZZxy45"); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.NoChange, new Range(0, 3), new Range(0, 3)), new Diff(DiffKind.Change, new Range(3, 3), new Range(3, 2)), new Diff(DiffKind.NoChange, new Range(6, 2), new Range(5, 2)), new Diff(DiffKind.Change, new Range(8, 3), new Range(7, 2)), new Diff(DiffKind.NoChange, new Range(11, 2), new Range(9, 2)) }, diffSet.Diffs); } } public class WhenOptimizationUsedShouldYieldSameResultsAsWhenOptimizationIsUsed { [Test] public void SingleCharEdit([Column(false, true)] bool optimize) { DiffSet diffSet = DiffSet.GetDiffSet("1", "2", optimize, true); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 1)) }, diffSet.Diffs); } [Test] public void SingleCharInsert([Column(false, true)] bool optimize) { DiffSet diffSet = DiffSet.GetDiffSet("", "1", optimize, true); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 0), new Range(0, 1)) }, diffSet.Diffs); } [Test] public void SingleCharDelete([Column(false, true)] bool optimize) { DiffSet diffSet = DiffSet.GetDiffSet("1", "", optimize, true); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 0)) }, diffSet.Diffs); } [Test] public void InsertAtHeadAndDeleteAtTail([Column(false, true)] bool optimize) { DiffSet diffSet = DiffSet.GetDiffSet("234", "123", optimize, true); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 0), new Range(0, 1)), new Diff(DiffKind.NoChange, new Range(0, 2), new Range(1, 2)), new Diff(DiffKind.Change, new Range(2, 1), new Range(3, 0)) }, diffSet.Diffs); } [Test] public void DeleteAtHeadAndInsertAtTail([Column(false, true)] bool optimize) { DiffSet diffSet = DiffSet.GetDiffSet("123", "234", optimize, true); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 1), new Range(0, 0)), new Diff(DiffKind.NoChange, new Range(1, 2), new Range(0, 2)), new Diff(DiffKind.Change, new Range(3, 0), new Range(2, 1)) }, diffSet.Diffs); } [Test] public void MultipleAdjacentChanges([Column(false, true)] bool optimize) { DiffSet diffSet = DiffSet.GetDiffSet("123abcdef", "abc456def", optimize, true); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new Diff[] { new Diff(DiffKind.Change, new Range(0, 3), new Range(0, 0)), new Diff(DiffKind.NoChange, new Range(3, 3), new Range(0, 3)), new Diff(DiffKind.Change, new Range(6, 0), new Range(3, 3)), new Diff(DiffKind.NoChange, new Range(6, 3), new Range(6, 3)) }, diffSet.Diffs); } } public class WhenDocumentsAreVeryLargeAndContainManyDifferences { [Test, Explicit("This test is timing dependent and occasionally fails on the build server under heavy load.")] public void RunTimeIsBoundedForPathologicalCaseWithNoCommonalities() { const int problemSize = 3000; long boundedMillis = RunWorstCaseDiff(problemSize, true); long unboundedMillis = RunWorstCaseDiff(problemSize, false); Assert.LessThan(boundedMillis, unboundedMillis, "The bounded approximated algorithm should be faster than the unbounded precise algorithm."); } private static long RunWorstCaseDiff(int problemSize, bool bounded) { StringBuilder left = new StringBuilder(); for (int i = 0; i < problemSize; i++) left.Append((char)i); StringBuilder right = new StringBuilder(); for (int i = problemSize; i < problemSize * 2; i++) right.Append((char)i); Stopwatch timer = Stopwatch.StartNew(); DiffSet diffSet = DiffSet.GetDiffSet(left.ToString(), right.ToString(), false, bounded); Assert.IsFalse(diffSet.IsEmpty); Assert.IsTrue(diffSet.ContainsChanges); Assert.AreElementsEqual(new[] { new Diff(DiffKind.Change, new Range(0, problemSize), new Range(0, problemSize)) }, diffSet.Diffs); return timer.ElapsedMilliseconds; } } public class WhenDiffSetIsBeingPresentedToHumans { // Some examples courtesy of Neil Fraser [Test] [Row("I am the very model of a modern major general.", "`Twas brillig, and the slithy toves did gyre and gimble in the wabe.", 2)] [Row("It was a dark and stormy night.", "The black can in the cupboard.", 2)] //[Row("Slow fool", "Quick fire", 1)] //[Row("Hovering", "My government", 1)] [Row("The black kettle and the teacup.", "The salt and the pepper.", 5)] [Row("Whistling windows.", "Wrestling wrestlers.", 5)] public void Simplify(string leftDocument, string rightDocument, int expectedNumberOfDiffs) { DiffSet originalDiffSet = DiffSet.GetDiffSet(leftDocument, rightDocument); DiffSet simplifiedDiffSet = originalDiffSet.Simplify(); using (TestLog.BeginSection("Original DiffSet")) originalDiffSet.WriteTo(TestLog.Default); using (TestLog.BeginSection("Simplified DiffSet")) simplifiedDiffSet.WriteTo(TestLog.Default); VerifyDiffSetIsValid(simplifiedDiffSet); Assert.LessThanOrEqualTo(simplifiedDiffSet.Diffs.Count, originalDiffSet.Diffs.Count); Assert.AreEqual(expectedNumberOfDiffs, simplifiedDiffSet.Diffs.Count); } } public class RegressionTests { [Test, Repeat(10)] public void ComputesValidDiffsForRandomInputs() { Random random = new Random(); StringBuilder a = new StringBuilder(); for (int i = random.Next(100); i > 0; i--) a.Append((char)(random.Next(6) + 'a')); StringBuilder b = new StringBuilder(); for (int i = random.Next(100); i > 0; i--) b.Append((char)(random.Next(6) + 'a')); Check(a.ToString(), b.ToString()); } /// <summary> /// There was a bug where we would return an invalid diff basically consisting /// of just the common prefix because the diff algorithm was terminating prematurely /// on empty input in one document without recording the diffs. /// </summary> [Test] public void TrailingAddition() { Check("o", "ogkndudaftrwhmgwdppjhplcc"); } /// <summary> /// In this case, the fast path optimization was causing problems because the /// length of the common prefix plus the length of the common suffix exceeded /// the length of the shorter string. That's because one character was part /// of both the common prefix and suffix. /// The fix was to be sure to exclude the common prefix from the range when /// computing the common suffix. /// </summary> [Test] public void OverlappingCommonPrefixAndSuffix() { Check("[\"1\", \"2\"]", "[\"1\", \"2\", \"3\"]"); } } internal static void Check(string a, string b) { TestLog.WriteLine("A: " + a); TestLog.WriteLine("B: " + b); // Standard diff. DiffSet diffSet = DiffSet.GetDiffSet(a, b); TestLog.Write("Diff: "); TestLog.WriteLine(diffSet); VerifyDiffSetIsValid(diffSet); // Also check simplified form. DiffSet simplifiedDiffSet = diffSet.Simplify(); TestLog.Write("Simplified Diff: "); TestLog.WriteLine(simplifiedDiffSet); VerifyDiffSetIsValid(simplifiedDiffSet); Assert.LessThanOrEqualTo(simplifiedDiffSet.Diffs.Count, diffSet.Diffs.Count); } internal static void VerifyDiffSetIsValid(DiffSet diffSet) { foreach (Diff diff in diffSet.Diffs) { if (diff.Kind == DiffKind.NoChange) Assert.AreEqual( diff.LeftRange.SubstringOf(diffSet.LeftDocument), diff.RightRange.SubstringOf(diffSet.RightDocument)); else Assert.AreNotEqual( diff.LeftRange.SubstringOf(diffSet.LeftDocument), diff.RightRange.SubstringOf(diffSet.RightDocument)); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Relay { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<RelayManagementClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(RelayManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RelayManagementClient /// </summary> public RelayManagementClient Client { get; private set; } /// <summary> /// Lists all of the available Relay REST API operations. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Relay/operations").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Operation>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the available Relay REST API operations. /// </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="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Operation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Operation>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.IO; namespace DereTore.Exchange.Audio.HCA { partial class HcaDecoder { private void Initialize() { ParseHeaders(); InitializeDecodeComponents(); } private void InitializeDecodeComponents() { var hcaInfo = HcaInfo; if (!_ath.Initialize(hcaInfo.AthType, hcaInfo.SamplingRate)) { throw new HcaException(ErrorMessages.GetAthInitializationFailed(), ActionResult.AthInitFailed); } var decodeParams = _decodeParams; var cipherType = decodeParams.CipherTypeOverrideEnabled ? decodeParams.OverriddenCipherType : hcaInfo.CipherType; if (!_cipher.Initialize(cipherType, decodeParams.Key1, decodeParams.Key2, decodeParams.KeyModifier)) { throw new HcaException(ErrorMessages.GetCiphInitializationFailed(), ActionResult.CiphInitFailed); } var channels = _channels = new ChannelArray(0x10); var r = new byte[10]; uint b = hcaInfo.ChannelCount / hcaInfo.CompR03; if (hcaInfo.CompR07 != 0 && b > 1) { uint rIndex = 0; for (uint i = 0; i < hcaInfo.CompR03; ++i, rIndex += b) { switch (b) { case 2: case 3: r[rIndex] = 1; r[rIndex + 1] = 2; break; case 4: r[rIndex] = 1; r[rIndex + 1] = 2; if (hcaInfo.CompR04 == 0) { r[rIndex + 2] = 1; r[rIndex + 3] = 2; } break; case 5: r[rIndex] = 1; r[rIndex + 1] = 2; if (hcaInfo.CompR04 <= 2) { r[rIndex + 3] = 1; r[rIndex + 4] = 2; } break; case 6: case 7: r[rIndex] = 1; r[rIndex + 1] = 2; r[rIndex + 4] = 1; r[rIndex + 5] = 2; break; case 8: r[rIndex] = 1; r[rIndex + 1] = 2; r[rIndex + 4] = 1; r[rIndex + 5] = 2; r[rIndex + 6] = 1; r[rIndex + 7] = 2; break; default: throw new ArgumentOutOfRangeException("b"); } } } unsafe { for (var i = 0; i < hcaInfo.ChannelCount; ++i) { var pType = channels.GetPtrOfType(i); var pValue = channels.GetPtrOfValue(i); var ppValue3 = channels.GetPtrOfValue3(i); var pCount = channels.GetPtrOfCount(i); *pType = r[i]; *ppValue3 = &pValue[hcaInfo.CompR06 + hcaInfo.CompR07]; *pCount = (uint)(hcaInfo.CompR06 + (r[i] != 2 ? hcaInfo.CompR07 : 0)); } } } private int DecodeToWaveR32(byte[] blockData, int blockIndex) { var hcaInfo = HcaInfo; if (blockData == null) { throw new ArgumentNullException(nameof(blockData)); } if (blockData.Length < hcaInfo.BlockSize) { throw new HcaException(ErrorMessages.GetInvalidParameter(nameof(blockData) + "." + nameof(blockData.Length)), ActionResult.InvalidParameter); } var checksum = HcaHelper.Checksum(blockData, 0); if (checksum != 0) { throw new HcaException(ErrorMessages.GetChecksumNotMatch(0, checksum), ActionResult.ChecksumNotMatch); } _cipher.Decrypt(blockData); var d = new DataBits(blockData, hcaInfo.BlockSize); var magic = d.GetBit(16); if (magic != 0xffff) { throw new HcaException(ErrorMessages.GetMagicNotMatch(0xffff, magic), ActionResult.MagicNotMatch); } var a = (d.GetBit(9) << 8) - d.GetBit(7); var channels = _channels; var ath = _ath; string site = null; try { int i; for (i = 0; i < hcaInfo.ChannelCount; ++i) { site = $"Decode1({i.ToString()})"; channels.Decode1(i, d, hcaInfo.CompR09, a, ath.Table); } for (i = 0; i < 8; ++i) { for (var j = 0; j < hcaInfo.ChannelCount; ++j) { site = $"Decode2({i.ToString()}/{j.ToString()})"; channels.Decode2(j, d); } for (var j = 0; j < hcaInfo.ChannelCount; ++j) { site = $"Decode3({i.ToString()}/{j.ToString()})"; channels.Decode3(j, hcaInfo.CompR09, hcaInfo.CompR08, (uint)(hcaInfo.CompR07 + hcaInfo.CompR06), hcaInfo.CompR05); } for (var j = 0; j < hcaInfo.ChannelCount - 1; ++j) { site = $"Decode4({i.ToString()}/{j.ToString()})"; channels.Decode4(j, j + 1, i, (uint)(hcaInfo.CompR05 - hcaInfo.CompR06), hcaInfo.CompR06, hcaInfo.CompR07); } for (var j = 0; j < hcaInfo.ChannelCount; ++j) { site = $"Decode5({i.ToString()}/{j.ToString()})"; channels.Decode5(j, i); } } return blockData.Length; } catch (IndexOutOfRangeException ex) { const string message = "Index access exception detected. It is probably because you are using an incorrect HCA key pair while decoding a type 56 HCA file."; var siteInfo = $"Site: {site} @ block {blockIndex.ToString()}"; var err = message + Environment.NewLine + siteInfo; throw new HcaException(err, ActionResult.DecodeFailed, ex); } } private void TransformWaveDataBlocks(Stream source, byte[] destination, uint startBlockIndex, uint blockCount, IWaveWriter waveWriter) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (waveWriter == null) { throw new ArgumentNullException(nameof(waveWriter)); } var hcaInfo = HcaInfo; var startOffset = hcaInfo.DataOffset + startBlockIndex * hcaInfo.BlockSize; source.Seek(startOffset, SeekOrigin.Begin); var channels = _channels; var decodeParams = _decodeParams; var hcaBlockBuffer = GetHcaBlockBuffer(); var channelCount = hcaInfo.ChannelCount; var rvaVolume = hcaInfo.RvaVolume; var bytesPerSample = waveWriter.BytesPerSample; var volume = decodeParams.Volume; for (var l = 0; l < (int)blockCount; ++l) { source.Read(hcaBlockBuffer, 0, hcaBlockBuffer.Length); DecodeToWaveR32(hcaBlockBuffer, l + (int)startBlockIndex); for (var i = 0; i < 8; ++i) { for (var j = 0; j < 0x80; ++j) { for (var k = 0; k < channelCount; ++k) { float f; unsafe { var pWave = channels.GetPtrOfWave(k); f = pWave[i * 0x80 + j]; f = f * volume * rvaVolume; } HcaHelper.Clamp(ref f, -1f, 1f); var offset = (((l * 8 + i) * 0x80 + j) * channelCount + k) * bytesPerSample; waveWriter.DecodeToBuffer(f, destination, (uint)offset); } } } } } private byte[] GetHcaBlockBuffer() { return _hcaBlockBuffer ?? (_hcaBlockBuffer = new byte[HcaInfo.BlockSize]); } private int GetSampleBitsFromParams() { var mode = _decodeParams.Mode; switch (mode) { case SamplingMode.R32: return 32; case SamplingMode.S16: return 16; case SamplingMode.S24: return 24; case SamplingMode.S32: return 32; case SamplingMode.U8: return 8; default: throw new ArgumentOutOfRangeException(nameof(mode)); } } private IWaveWriter GetProperWaveWriter() { var mode = _decodeParams.Mode; switch (mode) { case SamplingMode.S16: return WaveHelper.S16; case SamplingMode.R32: return WaveHelper.R32; case SamplingMode.S32: return WaveHelper.S32; case SamplingMode.U8: return WaveHelper.U8; case SamplingMode.S24: throw new NotImplementedException(); default: throw new ArgumentOutOfRangeException(nameof(mode)); } } private byte[] _hcaBlockBuffer; private readonly Ath _ath; private readonly Cipher _cipher; private ChannelArray _channels; private readonly DecodeParams _decodeParams; private int? _minWaveHeaderBufferSize; private int? _minWaveDataBufferSize; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using Microsoft.CodeAnalysis.Editor.Extensibility.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Moq; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { public class NavigateToTests { private readonly Mock<IGlyphService> _glyphServiceMock = new Mock<IGlyphService>(MockBehavior.Strict); private INavigateToItemProvider _provider; private NavigateToTestAggregator _aggregator; private static ExportProvider s_exportProvider = MinimalTestExportProvider.CreateExportProvider( TestExportProvider.CreateAssemblyCatalogWithCSharpAndVisualBasic().WithPart( typeof(Dev14NavigateToOptionsService))); private async Task<TestWorkspace> SetupWorkspaceAsync(string content) { var workspace = await TestWorkspace.CreateCSharpAsync(content, exportProvider: s_exportProvider); var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener(); _provider = new NavigateToItemProvider( workspace, _glyphServiceMock.Object, aggregateListener, workspace.ExportProvider.GetExportedValues<Lazy<INavigateToOptionsService, VisualStudioVersionMetadata>>()); _aggregator = new NavigateToTestAggregator(_provider); return workspace; } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NoItemsForEmptyFile() { using (var workspace = await SetupWorkspaceAsync("")) { Assert.Empty(_aggregator.GetItems("Hello")); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClass() { using (var workspace = await SetupWorkspaceAsync("class Foo { }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimClass() { using (var workspace = await SetupWorkspaceAsync("class @static { }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("static").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Class, displayName: "@static"); // Check searching for @static too item = _aggregator.GetItems("@static").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Class, displayName: "@static"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindNestedClass() { using (var workspace = await SetupWorkspaceAsync("class Foo { class Bar { internal class DogBed { } } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("DogBed").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", MatchKind.Exact, NavigateToItemKind.Class); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMemberInANestedClass() { using (var workspace = await SetupWorkspaceAsync("class Foo { class Bar { class DogBed { public void Method() { } } } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("Method").Single(); VerifyNavigateToResultItem(item, "Method", MatchKind.Exact, NavigateToItemKind.Method, "Method()", $"{EditorFeaturesResources.type}Foo.Bar.DogBed"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericClassWithConstraints() { using (var workspace = await SetupWorkspaceAsync("using System.Collections; class Foo<T> where T : IEnumerable { }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class, displayName: "Foo<T>"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericMethodWithConstraints() { using (var workspace = await SetupWorkspaceAsync("using System; class Foo<U> { public void Bar<T>(T item) where T:IComparable<T> {} }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("Bar").Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar<T>(T)", $"{EditorFeaturesResources.type}Foo<U>"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialClass() { using (var workspace = await SetupWorkspaceAsync("public partial class Foo { int a; } partial class Foo { int b; }")) { var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = _aggregator.GetItems("Foo"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindTypesInMetadata() { using (var workspace = await SetupWorkspaceAsync("using System; Class Program {FileStyleUriParser f;}")) { var items = _aggregator.GetItems("FileStyleUriParser"); Assert.Equal(items.Count(), 0); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassInNamespace() { using (var workspace = await SetupWorkspaceAsync("namespace Bar { class Foo { } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStruct() { using (var workspace = await SetupWorkspaceAsync("struct Bar { }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("B").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Structure); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnum() { using (var workspace = await SetupWorkspaceAsync("enum Colors {Red, Green, Blue}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("Colors").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", MatchKind.Exact, NavigateToItemKind.Enum); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnumMember() { using (var workspace = await SetupWorkspaceAsync("enum Colors {Red, Green, Blue}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("R").Single(); VerifyNavigateToResultItem(item, "Red", MatchKind.Prefix, NavigateToItemKind.EnumItem); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField1() { using (var workspace = await SetupWorkspaceAsync("class Foo { int bar;}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("b").Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField2() { using (var workspace = await SetupWorkspaceAsync("class Foo { int bar;}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("ba").Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField3() { using (var workspace = await SetupWorkspaceAsync("class Foo { int bar;}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); Assert.Empty(_aggregator.GetItems("ar")); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimField() { using (var workspace = await SetupWorkspaceAsync("class Foo { int @string;}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("string").Single(); VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{EditorFeaturesResources.type}Foo"); // Check searching for@string too item = _aggregator.GetItems("@string").Single(); VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPtrField1() { using (var workspace = await SetupWorkspaceAsync("class Foo { int* bar; }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); Assert.Empty(_aggregator.GetItems("ar")); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPtrField2() { using (var workspace = await SetupWorkspaceAsync("class Foo { int* bar; }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("b").Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstField() { using (var workspace = await SetupWorkspaceAsync("class Foo { const int bar = 7;}")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("ba").Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Constant); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindIndexer() { var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; using (var workspace = await SetupWorkspaceAsync(program)) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("this").Single(); VerifyNavigateToResultItem(item, "this[]", MatchKind.Exact, NavigateToItemKind.Property, displayName: "this[int]", additionalInfo: $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEvent() { var program = "class Foo { public event EventHandler ChangedEventHandler; }"; using (var workspace = await SetupWorkspaceAsync(program)) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("CEH").Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindAutoProperty() { using (var workspace = await SetupWorkspaceAsync("class Foo { int Bar { get; set; } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("B").Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethod() { using (var workspace = await SetupWorkspaceAsync("class Foo { void DoSomething(); }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("DS").Single(); VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething()", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimMethod() { using (var workspace = await SetupWorkspaceAsync("class Foo { void @static(); }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("static").Single(); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Method, "@static()", $"{EditorFeaturesResources.type}Foo"); // Verify if we search for @static too item = _aggregator.GetItems("@static").Single(); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Method, "@static()", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedMethod() { using (var workspace = await SetupWorkspaceAsync("class Foo { void DoSomething(int a, string b) {} }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("DS").Single(); VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething(int, string)", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstructor() { using (var workspace = await SetupWorkspaceAsync("class Foo { public Foo(){} }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo()", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedConstructor() { using (var workspace = await SetupWorkspaceAsync("class Foo { public Foo(int i){} }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo(int)", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStaticConstructor() { using (var workspace = await SetupWorkspaceAsync("class Foo { static Foo(){} }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "static Foo()", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethods() { using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }")) { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = _aggregator.GetItems("Bar"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodDefinitionOnly() { using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar(); }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("Bar").Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodImplementationOnly() { using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar() { } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("Bar").Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindOverriddenMembers() { var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }"; using (var workspace = await SetupWorkspaceAsync(program)) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = _aggregator.GetItems("Name"); VerifyNavigateToResultItems(expecteditems, items); var item = items.ElementAt(0); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{EditorFeaturesResources.type}DogBed", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); item = items.ElementAt(1); itemDisplay = item.DisplayFactory.CreateItemDisplay(item); unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{EditorFeaturesResources.type}Foo", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindInterface() { using (var workspace = await SetupWorkspaceAsync("public interface IFoo { }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("IF").Single(); VerifyNavigateToResultItem(item, "IFoo", MatchKind.Prefix, NavigateToItemKind.Interface); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindDelegateInNamespace() { using (var workspace = await SetupWorkspaceAsync("namespace Foo { delegate void DoStuff(); }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend); var item = _aggregator.GetItems("DoStuff").Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", MatchKind.Exact, NavigateToItemKind.Delegate); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindLambdaExpression() { using (var workspace = await SetupWorkspaceAsync("using System; class Foo { Func<int, int> sqr = x => x*x; }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("sqr").Single(); VerifyNavigateToResultItem(item, "sqr", MatchKind.Exact, NavigateToItemKind.Field, "sqr", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindArray() { using (var workspace = await SetupWorkspaceAsync("class Foo { object[] itemArray; }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("itemArray").Single(); VerifyNavigateToResultItem(item, "itemArray", MatchKind.Exact, NavigateToItemKind.Field, "itemArray", $"{EditorFeaturesResources.type}Foo"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassAndMethodWithSameName() { using (var workspace = await SetupWorkspaceAsync("class Foo { } class Test { void Foo() { } }")) { var expectedItems = new List<NavigateToItem> { new NavigateToItem("Foo", NavigateToItemKind.Method, "csharp", "Foo", null, MatchKind.Exact, true, null), new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", "Foo", null, MatchKind.Exact, true, null) }; var items = _aggregator.GetItems("Foo"); VerifyNavigateToResultItems(expectedItems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethodNestedInGenericTypes() { using (var workspace = await SetupWorkspaceAsync("class A<T> { class B { struct C<U> { void M() { } } } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("M").Single(); VerifyNavigateToResultItem(item, "M", MatchKind.Exact, NavigateToItemKind.Method, displayName: "M()", additionalInfo: $"{EditorFeaturesResources.type}A<T>.B.C<U>"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task OrderingOfConstructorsAndTypes() { using (var workspace = await SetupWorkspaceAsync(@" class C1 { C1(int i) {} } class C2 { C2(float f) {} static C2() {} }")) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), }; var items = _aggregator.GetItems("C").ToList(); items.Sort(CompareNavigateToItems); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NavigateToMethodWithNullableParameter() { using (var workspace = await SetupWorkspaceAsync("class C { void M(object? o) {} }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("M").Single(); VerifyNavigateToResultItem(item, "M", MatchKind.Exact, NavigateToItemKind.Method, "M(object?)"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task StartStopSanity() { // Verify that multiple calls to start/stop and dispose don't blow up using (var workspace = await SetupWorkspaceAsync("public class Foo { }")) { // Do one set of queries Assert.Single(_aggregator.GetItems("Foo").Where(x => x.Kind != "Method")); _provider.StopSearch(); // Do the same query again, make sure nothing was left over Assert.Single(_aggregator.GetItems("Foo").Where(x => x.Kind != "Method")); _provider.StopSearch(); // Dispose the provider _provider.Dispose(); } } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DescriptionItems() { using (var workspace = await SetupWorkspaceAsync("public\r\nclass\r\nFoo\r\n{ }")) { var item = _aggregator.GetItems("F").Single(x => x.Kind != "Method"); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var descriptionItems = itemDisplay.DescriptionItems; Action<string, string> assertDescription = (label, value) => { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); }; assertDescription("File:", workspace.Documents.Single().Name); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest1() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 }; var items = _aggregator.GetItems("GK"); Assert.Equal(expecteditems.Count(), items.Count()); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest2() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = _aggregator.GetItems("GKW"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest3() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = _aggregator.GetItems("K W"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest4() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { var items = _aggregator.GetItems("WKG"); Assert.Empty(items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest5() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = _aggregator.GetItems("G_K_W").Single(); VerifyNavigateToResultItem(item, "get_key_word", MatchKind.Regular, NavigateToItemKind.Field); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest6() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, true, null), new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, null) }; var items = _aggregator.GetItems("get word"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest7() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; using (var workspace = await SetupWorkspaceAsync(source)) { var items = _aggregator.GetItems("GTW"); Assert.Empty(items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermIndexer1() { var source = @"class C { public int this[int y] { get { } } } class D { void Foo() { var q = new C(); var b = q[4]; } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("this[]", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null), }; var items = _aggregator.GetItems("this"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern1() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = _aggregator.GetItems("B.Q"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern2() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { }; var items = _aggregator.GetItems("C.Q"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern3() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = _aggregator.GetItems("B.B.Q"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern4() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null) }; var items = _aggregator.GetItems("Baz.Quux"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern5() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null) }; var items = _aggregator.GetItems("F.B.B.Quux"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern6() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { }; var items = _aggregator.GetItems("F.F.B.B.Quux"); VerifyNavigateToResultItems(expecteditems, items); } } [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] [WorkItem(7855, "https://github.com/dotnet/Roslyn/issues/7855")] public async Task DottedPattern7() { var source = "namespace Foo { namespace Bar { class Baz<X,Y,Z> { void Quux() { } } } }"; using (var workspace = await SetupWorkspaceAsync(source)) { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = _aggregator.GetItems("Baz.Q"); VerifyNavigateToResultItems(expecteditems, items); } } [WorkItem(1174255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174255")] [WorkItem(8009, "https://github.com/dotnet/roslyn/issues/8009")] [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NavigateToGeneratedFiles() { using (var workspace = await TestWorkspace.CreateAsync(@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath=""File1.cs""> namespace N { public partial class C { public void VisibleMethod() { } } } </Document> <Document FilePath=""File1.g.cs""> namespace N { public partial class C { public void VisibleMethod_Generated() { } } } </Document> </Project> </Workspace> ", exportProvider: s_exportProvider)) { var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener(); _provider = new NavigateToItemProvider( workspace, _glyphServiceMock.Object, aggregateListener, workspace.ExportProvider.GetExportedValues<Lazy<INavigateToOptionsService, VisualStudioVersionMetadata>>()); _aggregator = new NavigateToTestAggregator(_provider); var items = _aggregator.GetItems("VisibleMethod"); var expectedItems = new List<NavigateToItem>() { new NavigateToItem("VisibleMethod", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null), new NavigateToItem("VisibleMethod_Generated", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; // The pattern matcher should match 'VisibleMethod' to both 'VisibleMethod' and 'VisibleMethod_Not', except that // the _Not method is declared in a generated file. VerifyNavigateToResultItems(expectedItems, items); } } [WorkItem(11474, "https://github.com/dotnet/roslyn/pull/11474")] [Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindFuzzy1() { using (var workspace = await SetupWorkspaceAsync("class C { public void ToError() { } }")) { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = _aggregator.GetItems("ToEror").Single(); VerifyNavigateToResultItem(item, "ToError", MatchKind.Regular, NavigateToItemKind.Method, displayName: "ToError()"); } } private void VerifyNavigateToResultItems(List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items) { expecteditems = expecteditems.OrderBy(i => i.Name).ToList(); items = items.OrderBy(i => i.Name).ToList(); Assert.Equal(expecteditems.Count(), items.Count()); for (int i = 0; i < expecteditems.Count; i++) { var expectedItem = expecteditems[i]; var actualItem = items.ElementAt(i); Assert.Equal(expectedItem.Name, actualItem.Name); Assert.Equal(expectedItem.MatchKind, actualItem.MatchKind); Assert.Equal(expectedItem.Language, actualItem.Language); Assert.Equal(expectedItem.Kind, actualItem.Kind); Assert.Equal(expectedItem.IsCaseSensitive, actualItem.IsCaseSensitive); if (!string.IsNullOrEmpty(expectedItem.SecondarySort)) { Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal); } } } private void VerifyNavigateToResultItem(NavigateToItem result, string name, MatchKind matchKind, string navigateToItemKind, string displayName = null, string additionalInfo = null) { // Verify symbol information Assert.Equal(name, result.Name); Assert.Equal(matchKind, result.MatchKind); Assert.Equal("csharp", result.Language); Assert.Equal(navigateToItemKind, result.Kind); // Verify display var itemDisplay = result.DisplayFactory.CreateItemDisplay(result); Assert.Equal(displayName ?? name, itemDisplay.Name); if (additionalInfo != null) { Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation); } // Make sure to fetch the glyph var unused = itemDisplay.Glyph; _glyphServiceMock.Verify(); } private void SetupVerifiableGlyph(StandardGlyphGroup standardGlyphGroup, StandardGlyphItem standardGlyphItem) { _glyphServiceMock.Setup(service => service.GetGlyph(standardGlyphGroup, standardGlyphItem)) .Returns(CreateIconBitmapSource()) .Verifiable(); } private BitmapSource CreateIconBitmapSource() { int stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16; return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride); } // For ordering of NavigateToItems, see // http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx private static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b) { int result = ((int)a.MatchKind) - ((int)b.MatchKind); if (result != 0) { return result; } result = a.Name.CompareTo(b.Name); if (result != 0) { return result; } result = a.Kind.CompareTo(b.Kind); if (result != 0) { return result; } result = a.SecondarySort.CompareTo(b.SecondarySort); return result; } } }
// Copyright (c) 2014-2016 Eberhard Beilharz // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.IO; using System.Linq; using System.Threading.Tasks; using BuildDependency.Artifacts; using BuildDependency.Tasks.Tools; using BuildDependency.Tools; using Microsoft.Build.Framework; namespace BuildDependency.Tasks { public class Dependencies: Microsoft.Build.Utilities.Task { #region LogHelper class private class LogHelper: ILog { private readonly object _syncObj = new object(); private readonly LogMessageImportance _importance; public LogHelper(LogMessageImportance importance = LogMessageImportance.High) { _importance = importance; } public void LogError(string message, params object[] messageArgs) { lock (_syncObj) { Console.Write("ERROR: "); Console.WriteLine(message, messageArgs); } } public void LogMessage(string message, params object[] messageArgs) { lock (_syncObj) { Console.WriteLine(message, messageArgs); } } public void LogMessage(LogMessageImportance importance, string message, params object[] messageArgs) { if ((int)importance <= (int)_importance) LogMessage(message, messageArgs); } } #endregion public Dependencies() { ExceptionLogging.Initialize("4bae82b8c647df7fea786dbaecb4b351"); WorkingDir = string.Empty; RunAsync = true; UseCache = true; WorkOffline = false; } /// <summary> /// File name and path of the dependency file (*.dep) /// </summary> public string DependencyFile { get; set; } /// <summary> /// File name and path of the jobs file (*.files) /// </summary> public string JobsFile { get; set; } /// <summary> /// <c>true</c> to use the dependency file, <c>false</c> to rely on the jobs file. /// </summary> [Required] public bool UseDependencyFile { get; set; } /// <summary> /// Base directory. All paths for target files are relative to this directory. /// </summary> public string WorkingDir { get; set; } /// <summary> /// <c>true</c> to download files asynchronously, otherwise <c>false</c>. Default: <c>true</c> /// </summary> public bool RunAsync { get; set; } /// <summary> /// Only relevant when <see cref="UseDependencyFile"/> is <c>true</c>. /// If <c>true</c> don't delete the generated JobsFile after finishing (and re-use /// on the next run); otherwise delete the generated JobsFile at the end of the task /// (and re-generate on the next build). /// </summary> /// <value><c>true</c> if keep jobs file; otherwise, <c>false</c>.</value> public bool KeepJobsFile { get; set; } /// <summary> /// <c>true</c> to cache the downloaded files, otherwise <c>false</c>. Default: <c>true</c> /// </summary> public bool UseCache { get; set; } /// <summary> /// <c>true</c> to work offline, <c>false</c> to try to download files over the network /// if the files on the server are newer than the local files. Default: <c>false</c>. /// </summary> public bool WorkOffline { get; set; } /// <summary> /// The platform to download files for. Can be <c>x86</c>, <c>x64</c>, or <c>AnyCPU</c>. /// <c>AnyCPU</c> here means to download files for either <c>x86</c> or <c>x64</c>. /// If not set, the bitness of the current process determines the platform. /// Default: not set /// </summary> public string Platform { get; set; } public override bool Execute() { ILog logHelper; if (Log != null) logHelper = new LogWrapper(Log); else logHelper = new LogHelper(); var version = Utils.GetVersion("BuildDependency.Tasks"); logHelper.LogMessage("Dependencies task version {0} ({1}):", version.Item1, version.Item2); if (!Network.IsInternetAvailable()) logHelper.LogMessage(LogMessageImportance.High, "No network connection available. Working in offline mode."); else if (WorkOffline) logHelper.LogMessage("Working in offline mode."); FileCache.Enabled = UseCache; Network.WorkOffline = WorkOffline; ConditionHelper.PlatformString = Platform; if (UseDependencyFile && string.IsNullOrEmpty(DependencyFile)) { logHelper.LogError("DependencyFile is not specified, but I was told to use it."); return false; } if (UseDependencyFile && !File.Exists(DependencyFile)) { logHelper.LogError("Can't find DependencyFile {0}", DependencyFile); return false; } if (!UseDependencyFile && string.IsNullOrEmpty(JobsFile)) { logHelper.LogError("JobsFile is not specified, but I was told to use it."); return false; } if (!UseDependencyFile && !File.Exists(JobsFile)) { logHelper.LogError("Can't find JobsFile {0}", JobsFile); return false; } if (string.IsNullOrEmpty(JobsFile)) JobsFile = Path.ChangeExtension(DependencyFile, ".files"); var replaceJobsFile = UseDependencyFile && !(KeepJobsFile && File.Exists(JobsFile)) || !File.Exists(JobsFile); if (UseDependencyFile && DependencyFile != null && JobsFile != null && File.Exists(JobsFile)) { var depFile = new FileInfo(DependencyFile); var jobsFile = new FileInfo(JobsFile); if (depFile.LastWriteTimeUtc > jobsFile.LastWriteTimeUtc) replaceJobsFile = true; } var retVal = true; if (RunAsync) { retVal = ExecuteAsync(replaceJobsFile, logHelper).Result; } else { if (replaceJobsFile) { var artifactTemplates = BuildDependency.DependencyFile.LoadFile(DependencyFile, logHelper); BuildDependency.JobsFile.WriteJobsFile(JobsFile, artifactTemplates); } var jobs = BuildDependency.JobsFile.ReadJobsFile(JobsFile); foreach (var job in jobs.OfType<DownloadFileJob>()) { retVal &= job.Execute(logHelper, WorkingDir).WaitAndUnwrapException(); } foreach (var job in jobs.OfType<UnzipFilesJob>()) { retVal &= job.Execute(logHelper, WorkingDir).WaitAndUnwrapException(); } } if (UseDependencyFile && !KeepJobsFile && JobsFile != null) File.Delete(JobsFile); return retVal; } private async Task<bool> ExecuteAsync(bool replaceJobsFile, ILog logHelper) { var retVal = true; if (replaceJobsFile) { if (Network.IsOnline) { var artifactTemplates = BuildDependency.DependencyFile.LoadFile(DependencyFile, logHelper); await BuildDependency.JobsFile.WriteJobsFileAsync(JobsFile, artifactTemplates); if (FileCache.Enabled) FileCache.CacheFile(JobsFile, JobsFile); } else if (FileCache.Enabled) { var cachedJobsFile = FileCache.GetCachedFile(JobsFile); if (File.Exists(cachedJobsFile)) File.Copy(cachedJobsFile, JobsFile, true); } } var jobs = BuildDependency.JobsFile.ReadJobsFile(JobsFile); var tasks = jobs.OfType<DownloadFileJob>().Select(job => job.Execute(logHelper, WorkingDir)).ToArray(); foreach (var task in tasks) { retVal &= await task; } tasks = jobs.OfType<UnzipFilesJob>().Select(job => job.Execute(logHelper, WorkingDir)).ToArray(); foreach (var task in tasks) { retVal &= await task; } return retVal; } } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDictionary { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Dictionary operations. /// </summary> public partial interface IDictionary { /// <summary> /// Get null dictionary value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary value {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullValueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null key /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with key as empty string /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetEmptyStringKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid Dictionary value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanTfftWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBooleanTfftWithHttpMessagesAsync(IDictionary<string, bool?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": null, "2": false } /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value '{"0": true, "1": "boolean", "2": /// false}' /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntegerValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutIntegerValidWithHttpMessagesAsync(IDictionary<string, int?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutLongValidWithHttpMessagesAsync(IDictionary<string, long?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutFloatValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutStringValidWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": null, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": 123, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": "2000-12-01", "1": /// "1980-01-02", "2": "1492-10-12"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": /// "1492-10-12"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2012-01-01", "1": null, "2": /// "1776-07-04"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2011-03-22", "1": "date"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": null} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "date-time"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time-rfc1123 dictionary value {"0": "Fri, 01 Dec 2000 /// 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, /// 12 Oct 1492 10:15:01 GMT"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeRfc1123ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", /// "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 /// 10:15:01 GMT"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeRfc1123ValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get duration dictionary value {"0": "P123DT22H14M12.011S", "1": /// "P5DT1H0M0S"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, TimeSpan?>>> GetDurationValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "P123DT22H14M12.011S", "1": /// "P5DT1H0M0S"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDurationValidWithHttpMessagesAsync(IDictionary<string, TimeSpan?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each item encoded in base64 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each elementencoded in base 64 /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutByteValidWithHttpMessagesAsync(IDictionary<string, byte[]> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": null} with /// the first item base64 encoded /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary of complex type {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with null item {"0": {"integer": 1, /// "string": "2"}, "1": null, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with empty item {"0": {"integer": /// 1, "string": "2"}, "1:" {}, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with {"0": {"integer": 1, "string": /// "2"}, "1": {"integer": 3, "string": "4"}, "2": {"integer": 5, /// "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put an dictionary of complex type with values {"0": {"integer": 1, /// "string": "2"}, "1": {"integer": 3, "string": "4"}, "2": /// {"integer": 5, "string": "6"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutComplexValidWithHttpMessagesAsync(IDictionary<string, Widget> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a null array /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an empty dictionary {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionary of array of strings {"0": ["1", "2", "3"], "1": /// null, "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [{"0": ["1", "2", "3"], "1": [], /// "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutArrayValidWithHttpMessagesAsync(IDictionary<string, IList<string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries with value null /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// null, "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": {}, /// "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryValidWithHttpMessagesAsync(IDictionary<string, IDictionary<string, string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using log4net; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins { public class SensorRepeat { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Used by one-off and repeated sensors /// </summary> public class SensorInfo { public uint localID; public UUID itemID; public double interval; public DateTime next; public string name; public UUID keyID; public int type; public double range; public double arc; public SceneObjectPart host; public SensorInfo Clone() { return (SensorInfo)this.MemberwiseClone(); } } public AsyncCommandManager m_CmdManager; /// <summary> /// Number of sensors active. /// </summary> public int SensorsCount { get { return SenseRepeaters.Count; } } public SensorRepeat(AsyncCommandManager CmdManager) { m_CmdManager = CmdManager; maximumRange = CmdManager.m_ScriptEngine.Config.GetDouble("SensorMaxRange", 96.0d); maximumToReturn = CmdManager.m_ScriptEngine.Config.GetInt("SensorMaxResults", 16); m_npcModule = m_CmdManager.m_ScriptEngine.World.RequestModuleInterface<INPCModule>(); } private INPCModule m_npcModule; private Object SenseLock = new Object(); private const int AGENT = 1; private const int AGENT_BY_USERNAME = 0x10; private const int NPC = 0x20; private const int ACTIVE = 2; private const int PASSIVE = 4; private const int SCRIPTED = 8; private double maximumRange = 96.0; private int maximumToReturn = 16; // // Sensed entity // private class SensedEntity : IComparable { public SensedEntity(double detectedDistance, UUID detectedID) { distance = detectedDistance; itemID = detectedID; } public int CompareTo(object obj) { if (!(obj is SensedEntity)) throw new InvalidOperationException(); SensedEntity ent = (SensedEntity)obj; if (ent == null || ent.distance < distance) return 1; if (ent.distance > distance) return -1; return 0; } public UUID itemID; public double distance; } /// <summary> /// Sensors to process. /// </summary> /// <remarks> /// Do not add or remove sensors from this list directly. Instead, copy the list and substitute the updated /// copy. This is to avoid locking the list for the duration of the sensor sweep, which increases the danger /// of deadlocks with future code updates. /// /// Always lock SenseRepeatListLock when updating this list. /// </remarks> private List<SensorInfo> SenseRepeaters = new List<SensorInfo>(); private object SenseRepeatListLock = new object(); public void SetSenseRepeatEvent(uint m_localID, UUID m_itemID, string name, UUID keyID, int type, double range, double arc, double sec, SceneObjectPart host) { // Always remove first, in case this is a re-set UnSetSenseRepeaterEvents(m_localID, m_itemID); if (sec == 0) // Disabling timer return; // Add to timer SensorInfo ts = new SensorInfo(); ts.localID = m_localID; ts.itemID = m_itemID; ts.interval = sec; ts.name = name; ts.keyID = keyID; ts.type = type; if (range > maximumRange) ts.range = maximumRange; else ts.range = range; ts.arc = arc; ts.host = host; ts.next = DateTime.UtcNow.AddSeconds(ts.interval); AddSenseRepeater(ts); } private void AddSenseRepeater(SensorInfo senseRepeater) { lock (SenseRepeatListLock) { List<SensorInfo> newSenseRepeaters = new List<SensorInfo>(SenseRepeaters); newSenseRepeaters.Add(senseRepeater); SenseRepeaters = newSenseRepeaters; } } public void UnSetSenseRepeaterEvents(uint m_localID, UUID m_itemID) { // Remove from timer lock (SenseRepeatListLock) { List<SensorInfo> newSenseRepeaters = new List<SensorInfo>(); foreach (SensorInfo ts in SenseRepeaters) { if (ts.localID != m_localID || ts.itemID != m_itemID) { newSenseRepeaters.Add(ts); } } SenseRepeaters = newSenseRepeaters; } } public void CheckSenseRepeaterEvents() { // Go through all timers List<SensorInfo> curSensors; lock(SenseRepeatListLock) curSensors = SenseRepeaters; DateTime now = DateTime.UtcNow; foreach (SensorInfo ts in curSensors) { // Time has passed? if (ts.next < now) { SensorSweep(ts); // set next interval ts.next = now.AddSeconds(ts.interval); } } } public void SenseOnce(uint m_localID, UUID m_itemID, string name, UUID keyID, int type, double range, double arc, SceneObjectPart host) { // Add to timer SensorInfo ts = new SensorInfo(); ts.localID = m_localID; ts.itemID = m_itemID; ts.interval = 0; ts.name = name; ts.keyID = keyID; ts.type = type; if (range > maximumRange) ts.range = maximumRange; else ts.range = range; ts.arc = arc; ts.host = host; SensorSweep(ts); } private void SensorSweep(SensorInfo ts) { if (ts.host == null) { return; } List<SensedEntity> sensedEntities = new List<SensedEntity>(); // Is the sensor type is AGENT and not SCRIPTED then include agents if ((ts.type & (AGENT | AGENT_BY_USERNAME | NPC)) != 0 && (ts.type & SCRIPTED) == 0) { sensedEntities.AddRange(doAgentSensor(ts)); } // If SCRIPTED or PASSIVE or ACTIVE check objects if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0) { sensedEntities.AddRange(doObjectSensor(ts)); } lock (SenseLock) { if (sensedEntities.Count == 0) { // send a "no_sensor" // Add it to queue m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID, new EventParams("no_sensor", new Object[0], new DetectParams[0])); } else { // Sort the list to get everything ordered by distance sensedEntities.Sort(); int count = sensedEntities.Count; int idx; List<DetectParams> detected = new List<DetectParams>(); for (idx = 0; idx < count; idx++) { try { DetectParams detect = new DetectParams(); detect.Key = sensedEntities[idx].itemID; detect.Populate(m_CmdManager.m_ScriptEngine.World); detected.Add(detect); } catch (Exception) { // Ignore errors, the object has been deleted or the avatar has gone and // there was a problem in detect.Populate so nothing added to the list } if (detected.Count == maximumToReturn) break; } if (detected.Count == 0) { // To get here with zero in the list there must have been some sort of problem // like the object being deleted or the avatar leaving to have caused some // difficulty during the Populate above so fire a no_sensor event m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID, new EventParams("no_sensor", new Object[0], new DetectParams[0])); } else { m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID, new EventParams("sensor", new Object[] {new LSL_Types.LSLInteger(detected.Count) }, detected.ToArray())); } } } } private List<SensedEntity> doObjectSensor(SensorInfo ts) { List<EntityBase> Entities; List<SensedEntity> sensedEntities = new List<SensedEntity>(); // If this is an object sense by key try to get it directly // rather than getting a list to scan through if (ts.keyID != UUID.Zero) { EntityBase e = null; m_CmdManager.m_ScriptEngine.World.Entities.TryGetValue(ts.keyID, out e); if (e == null) return sensedEntities; Entities = new List<EntityBase>(); Entities.Add(e); } else { Entities = new List<EntityBase>(m_CmdManager.m_ScriptEngine.World.GetEntities()); } SceneObjectPart SensePoint = ts.host; Vector3 fromRegionPos = SensePoint.GetWorldPosition(); // pre define some things to avoid repeated definitions in the loop body Vector3 toRegionPos; double dis; int objtype; SceneObjectPart part; float dx; float dy; float dz; // Quaternion q = SensePoint.RotationOffset; Quaternion q = SensePoint.GetWorldRotation(); // non-attached prim Sensor *always* uses World rotation! if (SensePoint.ParentGroup.IsAttachment) { // In attachments, rotate the sensor cone with the // avatar rotation. This may include a nonzero elevation if // in mouselook. // This will not include the rotation and position of the // attachment point (e.g. your head when a sensor is in your // hair attached to your scull. Your hair will turn with // your head but the sensor will stay with your (global) // avatar rotation and position. // Position of a sensor in a child prim attached to an avatar // will be still wrong. ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.AttachedAvatar); // Don't proceed if the avatar for this attachment has since been removed from the scene. if (avatar == null) return sensedEntities; fromRegionPos = avatar.AbsolutePosition; q = avatar.Rotation; } LSL_Types.Quaternion r = new LSL_Types.Quaternion(q); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); Vector3 ZeroVector = new Vector3(0, 0, 0); bool nameSearch = !string.IsNullOrEmpty(ts.name); foreach (EntityBase ent in Entities) { bool keep = true; if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search continue; if (ent.IsDeleted) // taken so long to do this it has gone from the scene continue; if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar continue; toRegionPos = ent.AbsolutePosition; // Calculation is in line for speed dx = toRegionPos.X - fromRegionPos.X; dy = toRegionPos.Y - fromRegionPos.Y; dz = toRegionPos.Z - fromRegionPos.Z; // Weed out those that will not fit in a cube the size of the range // no point calculating if they are within a sphere the size of the range // if they arent even in the cube if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range) dis = ts.range + 1.0; else dis = Math.Sqrt(dx * dx + dy * dy + dz * dz); if (keep && dis <= ts.range && ts.host.UUID != ent.UUID) { // In Range and not the object containing the script, is it the right Type ? objtype = 0; part = ((SceneObjectGroup)ent).RootPart; if (part.ParentGroup.RootPart.Shape.PCode != (byte)PCode.Tree && part.ParentGroup.RootPart.Shape.PCode != (byte)PCode.NewTree && part.ParentGroup.AttachmentPoint != 0) // Attached so ignore continue; if (part.Inventory.ContainsScripts()) { objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ... } else { if (ent.Velocity.Equals(ZeroVector)) { objtype |= PASSIVE; // Passive non-moving } else { objtype |= ACTIVE; // moving so active } } // If any of the objects attributes match any in the requested scan type if (((ts.type & objtype) != 0)) { // Right type too, what about the other params , key and name ? if (ts.arc < Math.PI) { // not omni-directional. Can you see it ? // vec forward_dir = llRot2Fwd(llGetRot()) // vec obj_dir = toRegionPos-fromRegionPos // dot=dot(forward_dir,obj_dir) // mag_fwd = mag(forward_dir) // mag_obj = mag(obj_dir) // ang = acos(dot /(mag_fwd*mag_obj)) double ang_obj = 0; try { Vector3 diff = toRegionPos - fromRegionPos; double dot = LSL_Types.Vector3.Dot(forward_dir, diff); double mag_obj = LSL_Types.Vector3.Mag(diff); ang_obj = Math.Acos(dot / (mag_fwd * mag_obj)); } catch { } if (ang_obj > ts.arc) keep = false; } if (keep == true) { // add distance for sorting purposes later sensedEntities.Add(new SensedEntity(dis, ent.UUID)); } } } } return sensedEntities; } private List<SensedEntity> doAgentSensor(SensorInfo ts) { List<SensedEntity> sensedEntities = new List<SensedEntity>(); // If nobody about quit fast if (m_CmdManager.m_ScriptEngine.World.GetRootAgentCount() == 0) return sensedEntities; SceneObjectPart SensePoint = ts.host; Vector3 fromRegionPos = SensePoint.GetWorldPosition(); Quaternion q = SensePoint.GetWorldRotation(); if (SensePoint.ParentGroup.IsAttachment) { // In attachments, rotate the sensor cone with the // avatar rotation. This may include a nonzero elevation if // in mouselook. // This will not include the rotation and position of the // attachment point (e.g. your head when a sensor is in your // hair attached to your scull. Your hair will turn with // your head but the sensor will stay with your (global) // avatar rotation and position. // Position of a sensor in a child prim attached to an avatar // will be still wrong. ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.AttachedAvatar); // Don't proceed if the avatar for this attachment has since been removed from the scene. if (avatar == null) return sensedEntities; fromRegionPos = avatar.AbsolutePosition; q = avatar.Rotation; } LSL_Types.Quaternion r = new LSL_Types.Quaternion(q); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); bool attached = (SensePoint.ParentGroup.AttachmentPoint != 0); Vector3 toRegionPos; double dis; Action<ScenePresence> senseEntity = new Action<ScenePresence>(presence => { // m_log.DebugFormat( // "[SENSOR REPEAT]: Inspecting scene presence {0}, type {1} on sensor sweep for {2}, type {3}", // presence.Name, presence.PresenceType, ts.name, ts.type); if ((ts.type & NPC) == 0 && presence.PresenceType == PresenceType.Npc) { INPC npcData = m_npcModule.GetNPC(presence.UUID, presence.Scene); if (npcData == null || !npcData.SenseAsAgent) { // m_log.DebugFormat( // "[SENSOR REPEAT]: Discarding NPC {0} from agent sense sweep for script item id {1}", // presence.Name, ts.itemID); return; } } if ((ts.type & AGENT) == 0) { if (presence.PresenceType == PresenceType.User) { return; } else { INPC npcData = m_npcModule.GetNPC(presence.UUID, presence.Scene); if (npcData != null && npcData.SenseAsAgent) { // m_log.DebugFormat( // "[SENSOR REPEAT]: Discarding NPC {0} from non-agent sense sweep for script item id {1}", // presence.Name, ts.itemID); return; } } } if (presence.IsDeleted || presence.IsChildAgent || presence.IsViewerUIGod) return; // if the object the script is in is attached and the avatar is the owner // then this one is not wanted if (attached && presence.UUID == SensePoint.OwnerID) return; toRegionPos = presence.AbsolutePosition; dis = Vector3.Distance(toRegionPos, fromRegionPos); if (presence.IsSatOnObject && presence.ParentPart != null && presence.ParentPart.ParentGroup != null && presence.ParentPart.ParentGroup.RootPart != null) { Vector3 rpos = presence.ParentPart.ParentGroup.RootPart.AbsolutePosition; double dis2 = Vector3.Distance(rpos, fromRegionPos); if (dis > dis2) dis = dis2; } // Disabled for now since all osNpc* methods check for appropriate ownership permission. // Perhaps could be re-enabled as an NPC setting at some point since being able to make NPCs not // sensed might be useful. // if (presence.PresenceType == PresenceType.Npc && npcModule != null) // { // UUID npcOwner = npcModule.GetOwner(presence.UUID); // if (npcOwner != UUID.Zero && npcOwner != SensePoint.OwnerID) // return; // } // are they in range if (dis <= ts.range) { // Are they in the required angle of view if (ts.arc < Math.PI) { // not omni-directional. Can you see it ? // vec forward_dir = llRot2Fwd(llGetRot()) // vec obj_dir = toRegionPos-fromRegionPos // dot=dot(forward_dir,obj_dir) // mag_fwd = mag(forward_dir) // mag_obj = mag(obj_dir) // ang = acos(dot /(mag_fwd*mag_obj)) double ang_obj = 0; try { LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3( toRegionPos - fromRegionPos); double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir); double mag_obj = LSL_Types.Vector3.Mag(obj_dir); ang_obj = Math.Acos(dot / (mag_fwd * mag_obj)); } catch { } if (ang_obj <= ts.arc) { sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } else { sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } }); // If this is an avatar sense by key try to get them directly // rather than getting a list to scan through if (ts.keyID != UUID.Zero) { ScenePresence sp; // Try direct lookup by UUID if (!m_CmdManager.m_ScriptEngine.World.TryGetScenePresence(ts.keyID, out sp)) return sensedEntities; senseEntity(sp); } else if (!string.IsNullOrEmpty(ts.name)) { ScenePresence sp; // Try lookup by name will return if/when found if (((ts.type & AGENT) != 0) && m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp)) senseEntity(sp); if ((ts.type & AGENT_BY_USERNAME) != 0) { m_CmdManager.m_ScriptEngine.World.ForEachRootScenePresence( delegate (ScenePresence ssp) { if (ssp.Lastname == "Resident") { if (ssp.Firstname.ToLower() == ts.name) senseEntity(ssp); return; } if (ssp.Name.Replace(" ", ".").ToLower() == ts.name) senseEntity(ssp); } ); } return sensedEntities; } else { m_CmdManager.m_ScriptEngine.World.ForEachRootScenePresence(senseEntity); } return sensedEntities; } public Object[] GetSerializationData(UUID itemID) { List<Object> data = new List<Object>(); foreach (SensorInfo ts in SenseRepeaters) { if (ts.itemID == itemID) { data.Add(ts.interval); data.Add(ts.name); data.Add(ts.keyID); data.Add(ts.type); data.Add(ts.range); data.Add(ts.arc); } } return data.ToArray(); } public void CreateFromData(uint localID, UUID itemID, UUID objectID, Object[] data) { SceneObjectPart part = m_CmdManager.m_ScriptEngine.World.GetSceneObjectPart( objectID); if (part == null) return; int idx = 0; while (idx < data.Length) { SensorInfo ts = new SensorInfo(); ts.localID = localID; ts.itemID = itemID; ts.interval = (double)data[idx]; ts.name = (string)data[idx+1]; ts.keyID = (UUID)data[idx+2]; ts.type = (int)data[idx+3]; ts.range = (double)data[idx+4]; ts.arc = (double)data[idx+5]; ts.host = part; ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); AddSenseRepeater(ts); idx += 6; } } public List<SensorInfo> GetSensorInfo() { List<SensorInfo> retList = new List<SensorInfo>(); lock (SenseRepeatListLock) { foreach (SensorInfo i in SenseRepeaters) retList.Add(i.Clone()); } return retList; } } }
// // MD2Test.cs - NUnit Test Cases for MD2 (RFC1319) // // Author: // Sebastien Pouliot ([email protected]) // // (C) 2002 Motus Technologies Inc. (http://www.motus.com) // (C) 2004 Novell (http://www.novell.com) // using System; using System.IO; using System.Security.Cryptography; using System.Text; using Mono.Security.Cryptography; using NUnit.Framework; namespace MonoTests.Mono.Security.Cryptography { // References: // a. The MD2 Message-Digest Algorithm // http://www.ietf.org/rfc/rfc1319.txt // MD2 is a abstract class - so ALL of the test included here wont be tested // on the abstract class but should be tested in ALL its descendants. public class MD2Test : Assertion { protected MD2 hash; // because most crypto stuff works with byte[] buffers static public void AssertEquals (string msg, byte[] array1, byte[] array2) { if ((array1 == null) && (array2 == null)) return; if (array1 == null) Fail (msg + " -> First array is NULL"); if (array2 == null) Fail (msg + " -> Second array is NULL"); bool a = (array1.Length == array2.Length); if (a) { for (int i = 0; i < array1.Length; i++) { if (array1 [i] != array2 [i]) { a = false; break; } } } if (array1.Length > 0) { msg += " -> Expected " + BitConverter.ToString (array1, 0); msg += " is different than " + BitConverter.ToString (array2, 0); } Assert (msg, a); } // MD2 ("") = 8350e5a3e24c153df2275c9f80692773 [Test] public void RFC1319_Test1 () { string className = hash.ToString (); byte[] result = { 0x83, 0x50, 0xe5, 0xa3, 0xe2, 0x4c, 0x15, 0x3d, 0xf2, 0x27, 0x5c, 0x9f, 0x80, 0x69, 0x27, 0x73 }; byte[] input = new byte [0]; string testName = className + " 1"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); // N/A RFC1319_e (testName, hash, input, result); } // MD2 ("a") = 32ec01ec4a6dac72c0ab96fb34c0b5d1 [Test] public void RFC1319_Test2 () { string className = hash.ToString (); byte[] result = { 0x32, 0xec, 0x01, 0xec, 0x4a, 0x6d, 0xac, 0x72, 0xc0, 0xab, 0x96, 0xfb, 0x34, 0xc0, 0xb5, 0xd1 }; byte[] input = Encoding.Default.GetBytes ("a"); string testName = className + " 2"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); RFC1319_e (testName, hash, input, result); } // MD2 ("abc") = da853b0d3f88d99b30283a69e6ded6bb [Test] public void RFC1319_Test3 () { string className = hash.ToString (); byte[] result = { 0xda, 0x85, 0x3b, 0x0d, 0x3f, 0x88, 0xd9, 0x9b, 0x30, 0x28, 0x3a, 0x69, 0xe6, 0xde, 0xd6, 0xbb }; byte[] input = Encoding.Default.GetBytes ("abc"); string testName = className + " 3"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); RFC1319_e (testName, hash, input, result); } // MD2 ("message digest") = ab4f496bfb2a530b219ff33031fe06b0 [Test] public void RFC1319_Test4 () { string className = hash.ToString (); byte[] result = { 0xab, 0x4f, 0x49, 0x6b, 0xfb, 0x2a, 0x53, 0x0b, 0x21, 0x9f, 0xf3, 0x30, 0x31, 0xfe, 0x06, 0xb0 }; byte[] input = Encoding.Default.GetBytes ("message digest"); string testName = className + " 4"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); RFC1319_e (testName, hash, input, result); } // MD2 ("abcdefghijklmnopqrstuvwxyz") = 4e8ddff3650292ab5a4108c3aa47940b [Test] public void RFC1319_Test5 () { string className = hash.ToString (); byte[] result = { 0x4e, 0x8d, 0xdf, 0xf3, 0x65, 0x02, 0x92, 0xab, 0x5a, 0x41, 0x08, 0xc3, 0xaa, 0x47, 0x94, 0x0b }; byte[] input = Encoding.Default.GetBytes ("abcdefghijklmnopqrstuvwxyz"); string testName = className + " 5"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); RFC1319_e (testName, hash, input, result); } // MD2 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = // da33def2a42df13975352846c30338cd [Test] public void RFC1319_Test6 () { string className = hash.ToString (); byte[] result = { 0xda, 0x33, 0xde, 0xf2, 0xa4, 0x2d, 0xf1, 0x39, 0x75, 0x35, 0x28, 0x46, 0xc3, 0x03, 0x38, 0xcd }; byte[] input = Encoding.Default.GetBytes ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); string testName = className + " 6"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); RFC1319_e (testName, hash, input, result); } // MD2 ("123456789012345678901234567890123456789012345678901234567890123456 // 78901234567890") = d5976f79d83d3a0dc9806c3c66f3efd8 [Test] public void RFC1319_Test7 () { string className = hash.ToString (); byte[] result = { 0xd5, 0x97, 0x6f, 0x79, 0xd8, 0x3d, 0x3a, 0x0d, 0xc9, 0x80, 0x6c, 0x3c, 0x66, 0xf3, 0xef, 0xd8 }; byte[] input = Encoding.Default.GetBytes ("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); string testName = className + " 7"; RFC1319_a (testName, hash, input, result); RFC1319_b (testName, hash, input, result); RFC1319_c (testName, hash, input, result); RFC1319_d (testName, hash, input, result); RFC1319_e (testName, hash, input, result); } public void RFC1319_a (string testName, MD2 hash, byte[] input, byte[] result) { byte[] output = hash.ComputeHash (input); AssertEquals (testName + ".a.1", result, output); AssertEquals (testName + ".a.2", result, hash.Hash); // required or next operation will still return old hash hash.Initialize (); } public void RFC1319_b (string testName, MD2 hash, byte[] input, byte[] result) { byte[] output = hash.ComputeHash (input, 0, input.Length); AssertEquals (testName + ".b.1", result, output); AssertEquals (testName + ".b.2", result, hash.Hash); // required or next operation will still return old hash hash.Initialize (); } public void RFC1319_c (string testName, MD2 hash, byte[] input, byte[] result) { MemoryStream ms = new MemoryStream (input); byte[] output = hash.ComputeHash (ms); AssertEquals (testName + ".c.1", result, output); AssertEquals (testName + ".c.2", result, hash.Hash); // required or next operation will still return old hash hash.Initialize (); } public void RFC1319_d (string testName, MD2 hash, byte[] input, byte[] result) { byte[] output = hash.TransformFinalBlock (input, 0, input.Length); AssertEquals (testName + ".d.1", input, output); AssertEquals (testName + ".d.2", result, hash.Hash); // required or next operation will still return old hash hash.Initialize (); } public void RFC1319_e (string testName, MD2 hash, byte[] input, byte[] result) { byte[] copy = new byte [input.Length]; for (int i=0; i < input.Length - 1; i++) hash.TransformBlock (input, i, 1, copy, i); byte[] output = hash.TransformFinalBlock (input, input.Length - 1, 1); AssertEquals (testName + ".e.1", input [input.Length - 1], output [0]); AssertEquals (testName + ".e.2", result, hash.Hash); // required or next operation will still return old hash hash.Initialize (); } // none of those values changes for any implementation of MD2 [Test] public virtual void StaticInfo () { string className = hash.ToString (); AssertEquals (className + ".HashSize", 128, hash.HashSize); AssertEquals (className + ".InputBlockSize", 1, hash.InputBlockSize); AssertEquals (className + ".OutputBlockSize", 1, hash.OutputBlockSize); } [Test] public virtual void Create () { // create the default implementation HashAlgorithm h = MD2.Create (); Assert ("MD2Managed", (h is MD2Managed)); // Note: will fail is default is changed in machine.config } } }
// ----- // Copyright 2010 Deyan Timnev // This file is part of the Matrix Platform (www.matrixplatform.com). // The Matrix Platform 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 3 of the License, or (at your option) any later version. The Matrix Platform 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 the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html // ----- using System; using System.Collections.Generic; using System.Reflection.Emit; using System.Reflection; namespace Matrix.Common.Core { /// <summary> /// This class uses runtime code generation, to overcome the problem of slow runtime invocation. /// A new method is generated on runtime and calls are passed trough it. /// As seen here: /// http://www.codeproject.com/KB/cs/FastMethodInvoker.aspx /// </summary> public static class FastInvokeHelper { /// <summary> /// The caching mechanism used, allows to reuse Delegate instances /// accross calls over time; and is thus rather fast. /// </summary> static Dictionary<MethodInfo, FastInvokeHandlerDelegate> _cache = new Dictionary<MethodInfo, FastInvokeHandlerDelegate>(); /// <summary> /// The delegate that is used to perform the actual fast invocation. /// </summary> /// <param name="target"></param> /// <param name="parameters"></param> /// <returns></returns> public delegate object FastInvokeHandlerDelegate(object target, object[] parameters); /// <summary> /// Perform an invoke, using a fast delegate. Will try to use the delegate /// cache, so only the first call will be delayed while the delegate is generated. /// </summary> public static object CachedInvoke(MethodInfo methodInfo, object target, object[] parameters) { FastInvokeHandlerDelegate delegateInstance = GetMethodInvoker(methodInfo, true, true); return delegateInstance.Invoke(target, parameters); } /// <summary> /// This method generates the new method on runtime and passes a delegate to it. /// The actual generation is a *slow process* (only the very first run, if cache is used), so make sure to save the delegate /// for later usage, instead of generating each time. /// </summary> /// <param name="methodInfo"></param> /// <returns></returns> public static FastInvokeHandlerDelegate GetMethodInvoker(MethodInfo methodInfo, bool useCache, bool skipVisibility) { if (useCache) { lock (_cache) { FastInvokeHandlerDelegate result = null; if (_cache.TryGetValue(methodInfo, out result)) { return result; } } } DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module, skipVisibility); ILGenerator il = dynamicMethod.GetILGenerator(); ParameterInfo[] ps = methodInfo.GetParameters(); Type[] paramTypes = new Type[ps.Length]; for (int i = 0; i < paramTypes.Length; i++) { if (ps[i].ParameterType.IsByRef) { paramTypes[i] = ps[i].ParameterType.GetElementType(); } else { paramTypes[i] = ps[i].ParameterType; } } LocalBuilder[] locals = new LocalBuilder[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) { locals[i] = il.DeclareLocal(paramTypes[i], true); } for (int i = 0; i < paramTypes.Length; i++) { il.Emit(OpCodes.Ldarg_1); EmitFastInt(il, i); il.Emit(OpCodes.Ldelem_Ref); EmitCastToReference(il, paramTypes[i]); il.Emit(OpCodes.Stloc, locals[i]); } if (!methodInfo.IsStatic) { il.Emit(OpCodes.Ldarg_0); } for (int i = 0; i < paramTypes.Length; i++) { if (ps[i].ParameterType.IsByRef) { il.Emit(OpCodes.Ldloca_S, locals[i]); } else { il.Emit(OpCodes.Ldloc, locals[i]); } } if (methodInfo.IsStatic) il.EmitCall(OpCodes.Call, methodInfo, null); else il.EmitCall(OpCodes.Callvirt, methodInfo, null); if (methodInfo.ReturnType == typeof(void)) il.Emit(OpCodes.Ldnull); else EmitBoxIfNeeded(il, methodInfo.ReturnType); for (int i = 0; i < paramTypes.Length; i++) { if (ps[i].ParameterType.IsByRef) { il.Emit(OpCodes.Ldarg_1); EmitFastInt(il, i); il.Emit(OpCodes.Ldloc, locals[i]); if (locals[i].LocalType.IsValueType) il.Emit(OpCodes.Box, locals[i].LocalType); il.Emit(OpCodes.Stelem_Ref); } } il.Emit(OpCodes.Ret); FastInvokeHandlerDelegate invoder = (FastInvokeHandlerDelegate)dynamicMethod.CreateDelegate(typeof(FastInvokeHandlerDelegate)); if (useCache) { lock (_cache) {// Possible multiple entry. _cache[methodInfo] = invoder; } } return invoder; } private static void EmitCastToReference(ILGenerator il, System.Type type) { if (type.IsValueType) { il.Emit(OpCodes.Unbox_Any, type); } else { il.Emit(OpCodes.Castclass, type); } } private static void EmitBoxIfNeeded(ILGenerator il, System.Type type) { if (type.IsValueType) { il.Emit(OpCodes.Box, type); } } private static void EmitFastInt(ILGenerator il, int value) { switch (value) { case -1: il.Emit(OpCodes.Ldc_I4_M1); return; case 0: il.Emit(OpCodes.Ldc_I4_0); return; case 1: il.Emit(OpCodes.Ldc_I4_1); return; case 2: il.Emit(OpCodes.Ldc_I4_2); return; case 3: il.Emit(OpCodes.Ldc_I4_3); return; case 4: il.Emit(OpCodes.Ldc_I4_4); return; case 5: il.Emit(OpCodes.Ldc_I4_5); return; case 6: il.Emit(OpCodes.Ldc_I4_6); return; case 7: il.Emit(OpCodes.Ldc_I4_7); return; case 8: il.Emit(OpCodes.Ldc_I4_8); return; } if (value > -129 && value < 128) { il.Emit(OpCodes.Ldc_I4_S, (SByte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } } } }
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 NServiceBus.Facade.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using ProtoBuf; using OpenMetaverse; namespace OpenSim.Framework.Communications.Messages { /// <summary> /// Message that corresponds to a PUT on /agent2/. This indicates a user is crossing over /// or teleporting from another region and carries all the data we may need to authenticate /// and service them /// </summary> [ProtoContract] public class AgentPutMessage { [ProtoMember(1)] public Guid AgentId; [ProtoMember(2)] public ulong RegionHandle; [ProtoMember(3)] public uint CircuitCode; [ProtoMember(4)] public Guid SessionId; [ProtoMember(5)] public Vector3 Position; [ProtoMember(6)] public Vector3 Velocity; [ProtoMember(7)] public Vector3 Center; [ProtoMember(8)] public Vector3 Size; [ProtoMember(9)] public Vector3 AtAxis; [ProtoMember(10)] public Vector3 LeftAxis; [ProtoMember(11)] public Vector3 UpAxis; [ProtoMember(12)] public float Far; [ProtoMember(13)] public float Aspect; [ProtoMember(14)] public byte[] Throttles; [ProtoMember(15)] public uint LocomotionState; [ProtoMember(16)] public Quaternion HeadRotation; [ProtoMember(17)] public Quaternion BodyRotation; [ProtoMember(18)] public uint ControlFlags; [ProtoMember(19)] public float EnergyLevel; [ProtoMember(20)] public Byte GodLevel; [ProtoMember(21)] public bool AlwaysRun; [ProtoMember(22)] public Guid PreyAgent; [ProtoMember(23)] public byte AgentAccess; [ProtoMember(24)] public Guid ActiveGroupID; [ProtoMember(25)] public PackedGroupMembership[] Groups; [ProtoMember(26)] public PackedAnimation[] Anims; [ProtoMember(27)] public string CallbackURI; [ProtoMember(28)] public Guid SatOnGroup; [ProtoMember(29)] public Guid SatOnPrim; [ProtoMember(30)] public Vector3 SatOnPrimOffset; [ProtoMember(31)] public PackedAppearance Appearance; [ProtoMember(32)] public List<byte[]> SerializedAttachments; [ProtoMember(33)] public int LocomotionFlags; [ProtoMember(34)] public List<RemotePresenceInfo> RemoteAgents; [ProtoMember(35)] public OpenMetaverse.Vector3 ConstantForces; [ProtoMember(36)] public bool ConstantForcesAreLocal; static AgentPutMessage() { ProtoBuf.Serializer.PrepareSerializer<AgentPutMessage>(); } internal static AgentPutMessage FromAgentData(AgentData data) { AgentPutMessage message = new AgentPutMessage { ActiveGroupID = data.ActiveGroupID.Guid, AgentAccess = data.AgentAccess, AgentId = data.AgentID.Guid, AlwaysRun = data.AlwaysRun, Anims = PackedAnimation.FromAnimations(data.Anims), Appearance = PackedAppearance.FromAppearance(data.Appearance), Aspect = data.Aspect, AtAxis = data.AtAxis, BodyRotation = data.BodyRotation, CallbackURI = data.CallbackURI, Center = data.Center, CircuitCode = data.CircuitCode, ControlFlags = data.ControlFlags, EnergyLevel = data.EnergyLevel, Far = data.Far, GodLevel = data.GodLevel, Groups = PackedGroupMembership.FromGroups(data.Groups), HeadRotation = data.HeadRotation, LeftAxis = data.LeftAxis, LocomotionState = data.LocomotionState, LocomotionFlags = (int)data.LocomotionFlags, Position = data.Position, PreyAgent = data.PreyAgent.Guid, RegionHandle = data.RegionHandle, SatOnGroup = data.SatOnGroup.Guid, SatOnPrim = data.SatOnPrim.Guid, SatOnPrimOffset = data.SatOnPrimOffset, SerializedAttachments = data.SerializedAttachments, SessionId = data.SessionID.Guid, Size = data.Size, Throttles = data.Throttles, UpAxis = data.UpAxis, Velocity = data.Velocity, RemoteAgents = data.RemoteAgents, ConstantForces = data.ConstantForces, ConstantForcesAreLocal = data.ConstantForcesAreLocal }; return message; } public AgentData ToAgentData() { UUID agentId = new UUID(this.AgentId); AgentData agentData = new AgentData { ActiveGroupID = new UUID(this.ActiveGroupID), AgentAccess = this.AgentAccess, AgentID = agentId, AlwaysRun = this.AlwaysRun, Anims = PackedAnimation.ToAnimations(this.Anims), Appearance = this.Appearance.ToAppearance(agentId), Aspect = this.Aspect, AtAxis = this.AtAxis, BodyRotation = this.BodyRotation, CallbackURI = this.CallbackURI, Center = this.Center, ChangedGrid = false, CircuitCode = this.CircuitCode, ControlFlags = this.ControlFlags, EnergyLevel = this.EnergyLevel, Far = this.Far, GodLevel = this.GodLevel, Groups = PackedGroupMembership.ToGroups(this.Groups), HeadRotation = this.HeadRotation, LeftAxis = this.LeftAxis, LocomotionState = this.LocomotionState, LocomotionFlags = (AgentLocomotionFlags)this.LocomotionFlags, Position = this.Position, PreyAgent = new UUID(this.PreyAgent), RegionHandle = this.RegionHandle, SatOnGroup = new UUID(this.SatOnGroup), SatOnPrim = new UUID(this.SatOnPrim), SatOnPrimOffset = this.SatOnPrimOffset, SerializedAttachments = this.SerializedAttachments, SessionID = new UUID(this.SessionId), Size = this.Size, Throttles = this.Throttles, UpAxis = this.UpAxis, Velocity = this.Velocity, RemoteAgents = this.RemoteAgents, ConstantForces = this.ConstantForces, ConstantForcesAreLocal = this.ConstantForcesAreLocal }; return agentData; } } }
// 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; using System.Collections.Generic; using System.Diagnostics; namespace System { internal sealed class ArrayEnumerator : IEnumerator, ICloneable { private Array array; private int index; private int endIndex; private int startIndex; // Save for Reset. private int[] _indices; // The current position in a multidim array private bool _complete; internal ArrayEnumerator(Array array, int index, int count) { this.array = array; this.index = index - 1; startIndex = index; endIndex = index + count; _indices = new int[array.Rank]; int checkForZero = 1; // Check for dimensions of size 0. for (int i = 0; i < array.Rank; i++) { _indices[i] = array.GetLowerBound(i); checkForZero *= array.GetLength(i); } // To make MoveNext simpler, decrement least significant index. _indices[_indices.Length - 1]--; _complete = (checkForZero == 0); } private void IncArray() { // This method advances us to the next valid array index, // handling all the multiple dimension & bounds correctly. // Think of it like an odometer in your car - we start with // the last digit, increment it, and check for rollover. If // it rolls over, we set all digits to the right and including // the current to the appropriate lower bound. Do these overflow // checks for each dimension, and if the most significant digit // has rolled over it's upper bound, we're done. // int rank = array.Rank; _indices[rank - 1]++; for (int dim = rank - 1; dim >= 0; dim--) { if (_indices[dim] > array.GetUpperBound(dim)) { if (dim == 0) { _complete = true; break; } for (int j = dim; j < rank; j++) _indices[j] = array.GetLowerBound(j); _indices[dim - 1]++; } } } public object Clone() { return MemberwiseClone(); } public bool MoveNext() { if (_complete) { index = endIndex; return false; } index++; IncArray(); return !_complete; } public object? Current { get { if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return array.GetValue(_indices); } } public void Reset() { index = startIndex - 1; int checkForZero = 1; for (int i = 0; i < array.Rank; i++) { _indices[i] = array.GetLowerBound(i); checkForZero *= array.GetLength(i); } _complete = (checkForZero == 0); // To make MoveNext simpler, decrement least significant index. _indices[_indices.Length - 1]--; } } internal sealed class SZArrayEnumerator : IEnumerator, ICloneable { private readonly Array _array; private int _index; private int _endIndex; // Cache Array.Length, since it's a little slow. internal SZArrayEnumerator(Array array) { Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero."); _array = array; _index = -1; _endIndex = array.Length; } public object Clone() { return MemberwiseClone(); } public bool MoveNext() { if (_index < _endIndex) { _index++; return (_index < _endIndex); } return false; } public object? Current { get { if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return _array.GetValue(_index); } } public void Reset() { _index = -1; } } internal sealed class SZGenericArrayEnumerator<T> : IEnumerator<T> { private readonly T[] _array; private int _index; // Array.Empty is intentionally omitted here, since we don't want to pay for generic instantiations that // wouldn't have otherwise been used. internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(new T[0]); internal SZGenericArrayEnumerator(T[] array) { Debug.Assert(array != null); _array = array; _index = -1; } public bool MoveNext() { int index = _index + 1; if ((uint)index >= (uint)_array.Length) { _index = _array.Length; return false; } _index = index; return true; } public T Current { get { int index = _index; T[] array = _array; if ((uint)index >= (uint)array.Length) { ThrowHelper.ThrowInvalidOperationException_EnumCurrent(index); } return array[index]; } } object? IEnumerator.Current => Current; void IEnumerator.Reset() => _index = -1; public void Dispose() { } } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Htc.Vita.Core.Log; namespace Htc.Vita.Core.Crypto { public abstract partial class Md5 { /// <summary> /// Generates the checksum value in Base64 form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <returns>Task&lt;System.String&gt;.</returns> public Task<string> GenerateInBase64Async(FileInfo file) { return GenerateInBase64Async( file, CancellationToken.None ); } /// <summary> /// Generates the checksum value in Base64 form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.String&gt;.</returns> public async Task<string> GenerateInBase64Async( FileInfo file, CancellationToken cancellationToken) { if (file == null || !file.Exists) { return string.Empty; } var result = string.Empty; try { result = await OnGenerateInBase64Async( file, cancellationToken ).ConfigureAwait(false); } catch (OperationCanceledException) { Logger.GetInstance(typeof(Md5)).Warn("Generating checksum in base64 in async cancelled"); } catch (Exception e) { Logger.GetInstance(typeof(Md5)).Fatal($"Generating checksum in base64 in async error: {e}"); } return result; } /// <summary> /// Generates the checksum value in hexadecimal form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <returns>Task&lt;System.String&gt;.</returns> public Task<string> GenerateInHexAsync(FileInfo file) { return GenerateInHexAsync( file, CancellationToken.None ); } /// <summary> /// Generates the checksum value in hexadecimal form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.String&gt;.</returns> public async Task<string> GenerateInHexAsync( FileInfo file, CancellationToken cancellationToken) { if (file == null || !file.Exists) { return string.Empty; } var result = string.Empty; try { result = await OnGenerateInHexAsync( file, cancellationToken ).ConfigureAwait(false); } catch (OperationCanceledException) { Logger.GetInstance(typeof(Md5)).Warn("Generating checksum in hex in async cancelled"); } catch (Exception e) { Logger.GetInstance(typeof(Md5)).Fatal($"Generating checksum in hex in async error: {e}"); } return result; } /// <summary> /// Validates the file in all checksum form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="checksum">The checksum.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public Task<bool> ValidateInAllAsync( FileInfo file, string checksum) { return ValidateInAllAsync( file, checksum, CancellationToken.None ); } /// <summary> /// Validates the file in all checksum form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="checksum">The checksum.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public async Task<bool> ValidateInAllAsync( FileInfo file, string checksum, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(checksum)) { return false; } if (checksum.Length == Base64FormLength) { return await ValidateInBase64Async( file, checksum, cancellationToken ).ConfigureAwait(false); } if (checksum.Length == HexFormLength) { return await ValidateInHexAsync( file, checksum, cancellationToken ).ConfigureAwait(false); } return false; } /// <summary> /// Validates the file in Base64 form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="checksum">The checksum.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public Task<bool> ValidateInBase64Async( FileInfo file, string checksum) { return ValidateInBase64Async( file, checksum, CancellationToken.None ); } /// <summary> /// Validates the file in Base64 form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="checksum">The checksum.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public async Task<bool> ValidateInBase64Async( FileInfo file, string checksum, CancellationToken cancellationToken) { if (file == null || !file.Exists || string.IsNullOrWhiteSpace(checksum)) { return false; } var result = false; try { result = checksum.Equals(await OnGenerateInBase64Async( file, cancellationToken ).ConfigureAwait(false)); } catch (OperationCanceledException) { Logger.GetInstance(typeof(Md5)).Warn("Validating checksum in base64 in async cancelled"); } catch (Exception e) { Logger.GetInstance(typeof(Md5)).Fatal($"Validating checksum in base64 in async error: {e}"); } return result; } /// <summary> /// Validates the file in hexadecimal form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="checksum">The checksum.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public Task<bool> ValidateInHexAsync( FileInfo file, string checksum) { return ValidateInHexAsync( file, checksum, CancellationToken.None ); } /// <summary> /// Validates the file in hexadecimal form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="checksum">The checksum.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public async Task<bool> ValidateInHexAsync( FileInfo file, string checksum, CancellationToken cancellationToken) { if (file == null || !file.Exists || string.IsNullOrWhiteSpace(checksum)) { return false; } var result = false; try { result = checksum.ToLowerInvariant().Equals(await OnGenerateInHexAsync( file, cancellationToken ).ConfigureAwait(false)); } catch (OperationCanceledException) { Logger.GetInstance(typeof(Md5)).Warn("Validating checksum in hex in async cancelled"); } catch (Exception e) { Logger.GetInstance(typeof(Md5)).Fatal($"Validating checksum in hex in async error: {e}"); } return result; } /// <summary> /// Called when generating the checksum in Base64 form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.String&gt;.</returns> protected abstract Task<string> OnGenerateInBase64Async( FileInfo file, CancellationToken cancellationToken ); /// <summary> /// Called when generating the checksum in hexadecimal form asynchronously. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task&lt;System.String&gt;.</returns> protected abstract Task<string> OnGenerateInHexAsync( FileInfo file, CancellationToken cancellationToken ); } }
using Android.App; using Android.Content; using Android.Content.PM; using Android.Gms.Analytics; using Android.OS; using Android.Views; using Android.Widget; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.Serialization; using Teaching.Skills.Contexts; using Teaching.Skills.Droid.Adapters; using Teaching.Skills.Models; namespace Teaching.Skills.Droid.Activities { [Activity(Label = "@string/item_title", Name = Core.Program.PackageName + ".ItemActivity", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)] public class ItemActivity : BaseActivity { private Category category; public Category Category { get { return category; } } private IEnumerable<Question> questions; private User user; private int activeIndex; public int ActiveIndex { get { return activeIndex; } } private SeekBar seekBarItem; private TextView textViewItemIndicator; private TextView textViewItemTitle; private TextView textViewItemDescription; private TextView textViewItemValue; private Button buttonNext; protected override void OnCreate(Bundle savedInstanceState) { SetContentView(Resource.Layout.Item); base.OnCreate(savedInstanceState); var serializer = new XmlSerializer(typeof(Category)); var buffer = Intent.GetByteArrayExtra("Model"); var modelStream = new MemoryStream(buffer); category = (Category)serializer.Deserialize(modelStream); this.Title = category.Name; this.SupportActionBar.Title = this.Title; seekBarItem = FindViewById<SeekBar>(Resource.Id.seekBarItem); textViewItemValue = FindViewById<TextView>(Resource.Id.textViewItemValue); textViewItemIndicator = FindViewById<TextView>(Resource.Id.textViewItemIndicator); textViewItemTitle = FindViewById<TextView>(Resource.Id.textViewItemTitle); textViewItemDescription = FindViewById<TextView>(Resource.Id.textViewItemDescription); buttonNext = FindViewById<Button>(Resource.Id.buttonNext); seekBarItem.ProgressChanged += seekBarItem_ProgressChanged; seekBarItem_ProgressChanged(seekBarItem, new SeekBar.ProgressChangedEventArgs(seekBarItem, 0, true)); buttonNext.Click += buttonNext_Click; user = DefaultContext.Instance.Users.FirstOrDefault(u => u.Id == Helpers.Settings.AppUserId); questions = (from item in category.Indicators select item.Questions.Select((a) => { a.Indicator = item; return a; })).SelectMany((q) => q); setQuestion(activeIndex); } private void setQuestion(int id) { if (activeIndex < questions.Count()) { var item = questions.ToArray()[id]; textViewItemIndicator.Text = item.Indicator.Name; textViewItemTitle.Text = item.Name; textViewItemDescription.Text = item.Description; seekBarItem.Progress = 0; if (user != null && user.Answers != null) { var answer = user.Answers.LastOrDefault(a => a.Question != null && a.Question.Id == item.Id); if (answer != null) seekBarItem.Progress = answer.Value; } (Application as MainApplication).DefaultTracker.SetScreenName(item.Indicator.Name); (Application as MainApplication).DefaultTracker.Send(new HitBuilders.ScreenViewBuilder().Build()); } buttonNext.Text = Resources.GetString((activeIndex < questions.Count() - 1 ? Resource.String.item_next : Resource.String.item_last)); } private async Task SaveAnswer() { if (user != null) { if (user.Answers == null) user.Answers = new HashSet<Answer>(); var question = questions.ToArray()[activeIndex]; var answer = user.Answers.FirstOrDefault(a => a.Question != null && a.Question.Id == question.Id); if (answer == null) { user.Answers.Add(new Answer() { Id = Guid.NewGuid(), Date = DateTime.Now, Question = question, User = user, Value = seekBarItem.Progress }); } else { answer = new Answer() { Date = DateTime.Now, Value = seekBarItem.Progress }; } if ((int)Build.VERSION.SdkInt < 23 || ((int)Build.VERSION.SdkInt >= 23 && Permissions.Request(this))) await DefaultContext.Instance.SaveAsync(); } } public override void OnBackPressed() { if (activeIndex == 0 || activeIndex >= questions.Count()) { var intent = new Intent(this, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); StartActivity(intent); } else { activeIndex--; setQuestion(activeIndex); } } public override bool OnOptionsItemSelected(IMenuItem item) { if (item.ItemId == Android.Resource.Id.Home) OnBackPressed(); return true; } private void seekBarItem_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { switch (e.Progress) { case 1: textViewItemValue.Text = Resources.GetString(Resource.String.likert_level_1); break; case 2: textViewItemValue.Text = Resources.GetString(Resource.String.likert_level_2); break; case 3: textViewItemValue.Text = Resources.GetString(Resource.String.likert_level_3); break; case 4: textViewItemValue.Text = Resources.GetString(Resource.String.likert_level_4); break; default: textViewItemValue.Text = Resources.GetString(Resource.String.likert_level_0); break; } } private async void buttonNext_Click(object sender, EventArgs e) { await SaveAnswer(); activeIndex++; if (activeIndex >= questions.Count()) { var item = DefaultContext.Instance.Categories.First(c => c.Id == category.Id); var avg = (short)Math.Round(SummaryAdapter.GetAverage(user, item), 0); Feedback.displayAlert(this, avg, OnBackPressed); } else setQuestion(activeIndex); } } }
/* * 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.Linq; using System.Threading; using Apache.Ignite.Core.Binary; 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.GetCluster().GetNodes().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.GetCluster().GetNodes().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) { BinaryConfiguration portCfg = new BinaryConfiguration(); ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>(); GetBinaryTypeConfigurations(portTypeCfgs); portCfg.TypeConfigurations = portTypeCfgs; cfg.BinaryConfiguration = 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 binary types. /// </summary> /// <param name="portTypeCfgs">Binary type configurations.</param> protected virtual void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs) { // No-op. } /// <summary> /// Gets the server count. /// </summary> protected int GetServerCount() { return Grid1.GetCluster().GetNodes().Count(x => !x.IsClient); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Windows Azure Network management API provides a RESTful set of web /// services that interact with Windows Azure Networks service to manage /// your network resrources. The API has entities that capture the /// relationship between an end user and the Windows Azure Networks /// service. /// </summary> public static partial class NetworkInterfaceOperationsExtensions { /// <summary> /// The Put NetworkInterface operation creates/updates a /// networkInterface /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update NetworkInterface /// operation /// </param> /// <returns> /// Response for PutNetworkInterface Api servive call /// </returns> public static NetworkInterfacePutResponse BeginCreateOrUpdating(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, networkInterfaceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkInterface operation creates/updates a /// networkInterface /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update NetworkInterface /// operation /// </param> /// <returns> /// Response for PutNetworkInterface Api servive call /// </returns> public static Task<NetworkInterfacePutResponse> BeginCreateOrUpdatingAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return operations.BeginCreateOrUpdatingAsync(resourceGroupName, networkInterfaceName, parameters, CancellationToken.None); } /// <summary> /// The delete netwokInterface operation deletes the specified /// netwokInterface. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public static UpdateOperationResponse BeginDeleting(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).BeginDeletingAsync(resourceGroupName, networkInterfaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete netwokInterface operation deletes the specified /// netwokInterface. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public static Task<UpdateOperationResponse> BeginDeletingAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.BeginDeletingAsync(resourceGroupName, networkInterfaceName, CancellationToken.None); } /// <summary> /// The Put NetworkInterface operation creates/updates a /// networkInterface /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update NetworkInterface /// operation /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse CreateOrUpdate(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkInterface operation creates/updates a /// networkInterface /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update NetworkInterface /// operation /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).DeleteAsync(resourceGroupName, networkInterfaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.DeleteAsync(resourceGroupName, networkInterfaceName, CancellationToken.None); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// Response for GetNetworkInterface Api service call /// </returns> public static NetworkInterfaceGetResponse Get(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).GetAsync(resourceGroupName, networkInterfaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// Response for GetNetworkInterface Api service call /// </returns> public static Task<NetworkInterfaceGetResponse> GetAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.GetAsync(resourceGroupName, networkInterfaceName, CancellationToken.None); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface in a virtual machine scale set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// Required. The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// Required. The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// Response for GetNetworkInterface Api service call /// </returns> public static NetworkInterfaceGetResponse GetVirtualMachineScaleSetNetworkInterface(this INetworkInterfaceOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).GetVirtualMachineScaleSetNetworkInterfaceAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface in a virtual machine scale set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// Required. The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// Required. The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <returns> /// Response for GetNetworkInterface Api service call /// </returns> public static Task<NetworkInterfaceGetResponse> GetVirtualMachineScaleSetNetworkInterfaceAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName) { return operations.GetVirtualMachineScaleSetNetworkInterfaceAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, CancellationToken.None); } /// <summary> /// The List networkInterfaces opertion retrieves all the /// networkInterfaces in a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static NetworkInterfaceListResponse List(this INetworkInterfaceOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List networkInterfaces opertion retrieves all the /// networkInterfaces in a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static Task<NetworkInterfaceListResponse> ListAsync(this INetworkInterfaceOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// The List networkInterfaces opertion retrieves all the /// networkInterfaces in a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static NetworkInterfaceListResponse ListAll(this INetworkInterfaceOperations operations) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).ListAllAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List networkInterfaces opertion retrieves all the /// networkInterfaces in a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static Task<NetworkInterfaceListResponse> ListAllAsync(this INetworkInterfaceOperations operations) { return operations.ListAllAsync(CancellationToken.None); } /// <summary> /// The list network interface operation retrieves information about /// all network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// Required. The name of the virtual machine scale set. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static NetworkInterfaceListResponse ListVirtualMachineScaleSetNetworkInterfaces(this INetworkInterfaceOperations operations, string resourceGroupName, string virtualMachineScaleSetName) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).ListVirtualMachineScaleSetNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list network interface operation retrieves information about /// all network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// Required. The name of the virtual machine scale set. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static Task<NetworkInterfaceListResponse> ListVirtualMachineScaleSetNetworkInterfacesAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string virtualMachineScaleSetName) { return operations.ListVirtualMachineScaleSetNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, CancellationToken.None); } /// <summary> /// The list network interface operation retrieves information about /// all network interfaces in a virtual machine from a virtual machine /// scale set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// Required. The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// Required. The virtual machine index. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static NetworkInterfaceListResponse ListVirtualMachineScaleSetVMNetworkInterfaces(this INetworkInterfaceOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex) { return Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).ListVirtualMachineScaleSetVMNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list network interface operation retrieves information about /// all network interfaces in a virtual machine from a virtual machine /// scale set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// Required. The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// Required. The virtual machine index. /// </param> /// <returns> /// Response for ListNetworkInterface Api service call /// </returns> public static Task<NetworkInterfaceListResponse> ListVirtualMachineScaleSetVMNetworkInterfacesAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex) { return operations.ListVirtualMachineScaleSetVMNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, CancellationToken.None); } } }
/* 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: * * * 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. * * 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.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using XenAPI; using XenAdmin.Core; namespace XenAdmin.Dialogs { public partial class RoleSelectionDialog : XenDialogBase { private Subject[] subjects; private Pool pool; private Dictionary<Role, List<Subject>> roleAssignment; // Used to stop 'changes made' checks during a batch select bool batchChange = false; public RoleSelectionDialog() { InitializeComponent(); } public RoleSelectionDialog(Subject[] subjects, Pool pool) : this() { this.subjects = subjects; this.pool = pool; roleAssignment = new Dictionary<Role,List<Subject>>(); if (subjects.Length == 1) { Subject subject = subjects[0]; string sName = (subject.DisplayName ?? subject.SubjectName ?? Messages.UNKNOWN_AD_USER).Ellipsise(30); if (subject.IsGroup) { labelBlurb.Text = String.Format(Messages.AD_SELECT_ROLE_GROUP, sName); pictureBoxSubjectType.Image = XenAdmin.Properties.Resources._000_UserAndGroup_h32bit_32; } else { labelBlurb.Text = String.Format(Messages.AD_SELECT_ROLE_USER, sName); pictureBoxSubjectType.Image = XenAdmin.Properties.Resources._000_User_h32bit_16; } } else { labelBlurb.Text = Messages.AD_SELECT_ROLE_MIXED; pictureBoxSubjectType.Image = XenAdmin.Properties.Resources._000_User_h32bit_16; } // Get the list of roles off the server and arrange them into rank List<Role> serverRoles = new List<Role>(pool.Connection.Cache.Roles); //hide basic permissions, we only want the roles. serverRoles.RemoveAll(delegate(Role r){return r.subroles.Count < 1;}); serverRoles.Sort(); serverRoles.Reverse(); foreach (Role r in serverRoles) { roleAssignment.Add(r, new List<Subject>()); } foreach (Subject s in subjects) { List<Role> subjectRoles = (List<Role>)pool.Connection.ResolveAll<Role>(s.roles); foreach (Role r in subjectRoles) { roleAssignment[r].Add(s); } } foreach (Role role in serverRoles) { DataGridViewRow r = new DataGridViewRow(); DataGridViewCheckBoxCellEx c1 = new DataGridViewCheckBoxCellEx(); c1.ThreeState = true; if (roleAssignment[role].Count == subjects.Length) { c1.Value = CheckState.Checked; c1.CheckState = CheckState.Checked; } else if (roleAssignment[role].Count == 0) { c1.Value = CheckState.Unchecked; c1.CheckState = CheckState.Unchecked; } else { c1.Value = CheckState.Indeterminate; c1.CheckState = CheckState.Indeterminate; } DataGridViewTextBoxCell c2 = new DataGridViewTextBoxCell(); c2.Value = role.FriendlyName; r.Cells.Add(c1); r.Cells.Add(c2); r.Tag = role; gridRoles.Rows.Add(r); } setRoleDescription(); } private void setRoleDescription() { if (gridRoles.SelectedRows.Count < 1) return; Role r = gridRoles.SelectedRows[0].Tag as Role; if (r == null) return; labelDescription.Text = r.FriendlyDescription; } private void buttonSave_Click(object sender, EventArgs e) { foreach (Subject s in subjects) { List<Role> rolesToAdd = new List<Role>(); List<Role> rolesToRemove = new List<Role>(); foreach (DataGridViewRow r in gridRoles.Rows) { bool check = (bool)r.Cells[0].Value; Role role = r.Tag as Role; if (check && !(roleAssignment[role].Contains(s))) rolesToAdd.Add(role); else if (!check && (roleAssignment[role].Contains(s))) rolesToRemove.Add(role); } XenAdmin.Actions.AddRemoveRolesAction a = new XenAdmin.Actions.AddRemoveRolesAction(pool, s, rolesToAdd, rolesToRemove); a.RunAsync(); } Close(); } private bool changesMade() { foreach (DataGridViewRow r in gridRoles.Rows) { Role role = r.Tag as Role; DataGridViewCheckBoxCellEx c = r.Cells[0] as DataGridViewCheckBoxCellEx; if (c.CheckState == CheckState.Checked && roleAssignment[role].Count < subjects.Length) { return true; } else if (c.CheckState == CheckState.Unchecked && roleAssignment[role].Count > 0) { return true; } // Don't care about intermediate values, it's not possible to set them in the dialog } return false; } private void buttonCancel_Click(object sender, EventArgs e) { Close(); } private void gridRoles_SelectionChanged(object sender, EventArgs e) { setRoleDescription(); } // We want to allow the user to select rows without changing the check boxes so they can browse the descriptions // so handle mouseclicks only on the check box column // Only allow them to select a single role, which also means all that tri state rubbish dissapears as soon as they make a selection private void gridRoles_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex != 0 || e.RowIndex < 0 || batchChange) return; selectIndex(e.RowIndex); buttonSave.Enabled = changesMade(); } // We want to allow the user to select rows without changing the check boxes so they can browse the descriptions // but we want it to be keyboard accessible. Capture the select keypress and toggle the checkbox private void gridRoles_KeyPress(object sender, KeyPressEventArgs e) { // makes assumption about multiselect System.Diagnostics.Trace.Assert(!gridRoles.MultiSelect); if (batchChange || e.KeyChar != ' ') return; selectIndex(gridRoles.SelectedRows[0].Index); buttonSave.Enabled = changesMade(); } private void selectIndex(int i) { batchChange = true; foreach (DataGridViewRow r in gridRoles.Rows) { if (i == r.Index) { r.Cells[0].Value = true; ((DataGridViewCheckBoxCellEx)(r.Cells[0])).CheckState = CheckState.Checked; continue; } r.Cells[0].Value = false; ((DataGridViewCheckBoxCellEx)(r.Cells[0])).CheckState = CheckState.Unchecked; } batchChange = false; } // Data grid view check box cells dont commit their value immeadiately, though the UI updates (edit mode). // To prevent messing around we handle the check state value ourselves. class DataGridViewCheckBoxCellEx : DataGridViewCheckBoxCell { public CheckState CheckState = CheckState.Unchecked; } } }
/* Copyright(c) 2009, Stefan Simek Copyright(c) 2016, Vladyslav Taranov MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; #if FEAT_IKVM using IKVM.Reflection; using IKVM.Reflection.Emit; using Type = IKVM.Reflection.Type; using MissingMethodException = System.MissingMethodException; using MissingMemberException = System.MissingMemberException; using DefaultMemberAttribute = System.Reflection.DefaultMemberAttribute; using Attribute = IKVM.Reflection.CustomAttributeData; using BindingFlags = IKVM.Reflection.BindingFlags; #else using System.Reflection; using System.Reflection.Emit; #endif namespace TriAxis.RunSharp { using Operands; public interface IMemberInfo { MemberInfo Member { get; } string Name { get; } Type ReturnType { get; } Type[] ParameterTypes { get; } bool IsParameterArray { get; } bool IsStatic { get; } bool IsOverride { get; } } public interface ITypeInfoProvider { IEnumerable<IMemberInfo> GetConstructors(); IEnumerable<IMemberInfo> GetFields(); IEnumerable<IMemberInfo> GetProperties(); IEnumerable<IMemberInfo> GetEvents(); IEnumerable<IMemberInfo> GetMethods(); string DefaultMember { get; } } public class TypeInfo : ITypeInfo { readonly Dictionary<Type, ITypeInfoProvider> _providers = new Dictionary<Type, ITypeInfoProvider>(); readonly Dictionary<Type, WeakReference> _cache = new Dictionary<Type, WeakReference>(); public TypeInfo(ITypeMapper typeMapper) { TypeMapper = typeMapper; } public ITypeMapper TypeMapper { get; private set; } class CacheEntry { readonly Type _t; IMemberInfo[] _constructors, _fields, _properties, _events, _methods; static readonly string _nullStr = "$NULL"; string _defaultMember = _nullStr; readonly TypeInfo _; public CacheEntry(Type t, TypeInfo owner) { _ = owner; _t = t; #if !FEAT_IKVM if (t.GetType() != typeof(object).GetType()) { // not a runtime type, TypeInfoProvider missing - return nothing _constructors = _fields = _properties = _events = _methods = _empty; _defaultMember = null; } #endif } ~CacheEntry() { lock (_._cache) { WeakReference wr; if (_._cache.TryGetValue(_t, out wr) && (wr.Target == this || wr.Target == null)) _._cache.Remove(_t); } } static readonly IMemberInfo[] _empty = { }; public IMemberInfo[] Constructors { get { if (_constructors == null) { ConstructorInfo[] ctors = _t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance); _constructors = ConvertAll<ConstructorInfo, IMemberInfo>(ctors, delegate(ConstructorInfo ci) { return new StdMethodInfo(ci, _); }); } return _constructors; } } public IMemberInfo[] Fields { get { if (_fields == null) { FieldInfo[] fis = _t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); _fields = ConvertAll<FieldInfo, IMemberInfo>(fis, delegate(FieldInfo fi) { return new StdFieldInfo(fi); }); } return _fields; } } public IMemberInfo[] Properties { get { if (_properties == null) { PropertyInfo[] pis = _t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); _properties = ConvertAll<PropertyInfo, IMemberInfo>(pis, delegate(PropertyInfo pi) { return new StdPropertyInfo(pi, _); }); } return _properties; } } public IMemberInfo[] Events { get { if (_events == null) { EventInfo[] eis = _t.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); _events = ConvertAll<EventInfo, IMemberInfo>(eis, delegate(EventInfo ei) { return new StdEventInfo(ei); }); } return _events; } } public IMemberInfo[] Methods { get { if (_methods == null) { MethodInfo[] mis = _t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); _methods = ConvertAll<MethodInfo, IMemberInfo>(mis, delegate(MethodInfo mi) { return new StdMethodInfo(mi, _); }); } return _methods; } } static TOut[] ConvertAll<TIn, TOut>(TIn[] array, Converter<TIn, TOut> converter) { TOut[] newArray = new TOut[array.Length]; for (int i = 0; i < array.Length; i++) { newArray[i] = converter(array[i]); } return newArray; } public string DefaultMember { get { if (_defaultMember == _nullStr) { foreach (var dma in Helpers.GetCustomAttributes(_t, typeof(DefaultMemberAttribute), true, _.TypeMapper)) { #if FEAT_IKVM return _defaultMember = dma.ConstructorArguments[0].Value as string; #else return _defaultMember = ((DefaultMemberAttribute)dma).MemberName; #endif } _defaultMember = null; } return _defaultMember; } } } public void RegisterProvider(Type t, ITypeInfoProvider prov) { _providers[t] = prov; } public void UnregisterProvider(Type t) { _providers.Remove(t); } CacheEntry GetCacheEntry(Type t) { #if !PHONE8 if (t is TypeBuilder) t = t.UnderlyingSystemType; #endif lock (_cache) { CacheEntry ce; WeakReference wr; if (_cache.TryGetValue(t, out wr)) { ce = wr.Target as CacheEntry; if (ce != null) return ce; } ce = new CacheEntry(t, this); _cache[t] = new WeakReference(ce); return ce; } } public IEnumerable<IMemberInfo> GetConstructors(Type t) { ITypeInfoProvider prov; if (_providers.TryGetValue(t, out prov)) return prov.GetConstructors(); return GetCacheEntry(t).Constructors; } public IEnumerable<IMemberInfo> GetFields(Type t) { ITypeInfoProvider prov; if (_providers.TryGetValue(t, out prov)) return prov.GetFields(); return GetCacheEntry(t).Fields; } public IEnumerable<IMemberInfo> GetProperties(Type t) { ITypeInfoProvider prov; if (_providers.TryGetValue(t, out prov)) return prov.GetProperties(); return GetCacheEntry(t).Properties; } public IEnumerable<IMemberInfo> GetEvents(Type t) { ITypeInfoProvider prov; if (_providers.TryGetValue(t, out prov)) return prov.GetEvents(); return GetCacheEntry(t).Events; } public IEnumerable<IMemberInfo> GetMethods(Type t) { ITypeInfoProvider prov; if (_providers.TryGetValue(t, out prov)) return prov.GetMethods(); return GetCacheEntry(t).Methods; } public string GetDefaultMember(Type t) { ITypeInfoProvider prov; if (_providers.TryGetValue(t, out prov)) return prov.DefaultMember; return GetCacheEntry(t).DefaultMember; } public IEnumerable<IMemberInfo> Filter(IEnumerable<IMemberInfo> source, string name, bool ignoreCase, bool isStatic, bool allowOverrides) { foreach (IMemberInfo mi in source) { if (mi.IsStatic != isStatic) continue; if (!allowOverrides && mi.IsOverride) continue; if (name != null) { if (ignoreCase) { if (!mi.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) continue; } else { if (mi.Name != name) continue; } } yield return mi; } } public ApplicableFunction FindConstructor(Type t, Operand[] args) { ApplicableFunction ctor = OverloadResolver.Resolve(GetConstructors(t), TypeMapper, args); if (ctor == null) throw new MissingMemberException(Properties.Messages.ErrMissingConstructor); return ctor; } public IMemberInfo FindField(Type t, string name, bool @static) { foreach (Type type in SearchableTypes(t)) { foreach (IMemberInfo mi in GetFields(type)) { if (mi.Name == name && mi.IsStatic == @static) return mi; } } //for (; t != null; t = t.BaseType) //{ // foreach (IMemberInfo mi in GetFields(t)) // { // if (mi.Name == name && mi.IsStatic == @static) // return mi; // } //} throw new MissingFieldException(Properties.Messages.ErrMissingField); } public ApplicableFunction FindProperty(Type t, string name, Operand[] indexes, bool @static) { if (name == null) name = GetDefaultMember(t); foreach (Type type in SearchableTypes(t)) { ApplicableFunction af = OverloadResolver.Resolve(Filter(GetProperties(type), name, false, @static, !t.IsValueType), TypeMapper, indexes); if (af != null) return af; } foreach (Type type in SearchableTypes(t)) { ApplicableFunction af = OverloadResolver.Resolve(Filter(GetProperties(type), name, false, @static, true), TypeMapper, indexes); if (af != null) return af; } //for (; t != null; t = t.BaseType) //{ //} throw new MissingMemberException(Properties.Messages.ErrMissingProperty); } public IMemberInfo FindEvent(Type t, string name, bool @static) { foreach (Type type in SearchableTypes(t)) { foreach (IMemberInfo mi in GetEvents(type)) { if (mi.Name == name && mi.IsStatic == @static) return mi; } } throw new MissingMemberException(Properties.Messages.ErrMissingEvent); } private IEnumerable<Type> SearchableTypes(Type t) { if (t.IsInterface) { foreach (Type @interface in SearchInterfaces(t)) { yield return @interface; } foreach (Type baseType in SearchBaseTypes(TypeMapper.MapType(typeof(object)))) { yield return baseType; } } else { foreach (Type baseType in SearchBaseTypes(t)) { yield return baseType; } } } private IEnumerable<Type> SearchBaseTypes(Type t) { yield return t; t = t.BaseType; if (t != null) { foreach (Type baseType in SearchBaseTypes(t)) { yield return baseType; } } } public IEnumerable<Type> SearchInterfaces(Type t) { yield return t; foreach (Type @interface in t.GetInterfaces()) { foreach (Type baseInterface in SearchInterfaces(@interface)) { yield return baseInterface; } } } public ApplicableFunction FindMethod(MethodInfo method) { var t = method.ReflectedType; foreach (Type type in SearchableTypes(t)) { IEnumerable<IMemberInfo> methods = GetMethods(type); IEnumerable<IMemberInfo> filter = Filter(methods, method.Name, false, method.IsStatic, !type.IsValueType); ApplicableFunction af = OverloadResolver.ResolveStrict(filter, TypeMapper, ArrayUtils.GetTypes(method.GetParameters())); if (af != null) return af; } throw new MissingMethodException(Properties.Messages.ErrMissingMethod + ": " + method.ToString()); } public ApplicableFunction FindMethod(Type t, string name, Operand[] args, bool @static) { foreach (Type type in SearchableTypes(t)) { IEnumerable<IMemberInfo> methods = GetMethods(type); IEnumerable<IMemberInfo> filter = Filter(methods, name, false, @static, !type.IsValueType); ApplicableFunction af = OverloadResolver.Resolve(filter, TypeMapper, args); if (af != null) return af; } foreach (Type type in SearchableTypes(t)) { IEnumerable<IMemberInfo> methods = GetMethods(type); IEnumerable<IMemberInfo> filter = Filter(methods, name, false, @static, true); ApplicableFunction af = OverloadResolver.Resolve(filter, TypeMapper, args); if (af != null) return af; } #if DEBUG Debugger.Break(); #endif var sb = new StringBuilder(); sb.Append(" " + t.Name + "." + name); sb.Append("("); for (int i = 0; i < args.Length; i++) { var arg = args[i]; if (i != 0) sb.Append(", "); sb.Append(arg?.GetReturnType(TypeMapper).ToString() ?? "<null>"); } sb.AppendLine(")"); sb.AppendLine("Candidates: "); foreach (Type type in SearchableTypes(t)) { IEnumerable<IMemberInfo> methods = GetMethods(type); IEnumerable<IMemberInfo> filter = Filter(methods, name, false, @static, false); foreach (var m in filter) { sb.AppendLine(m.Member.ToString()); } } throw new MissingMethodException(Properties.Messages.ErrMissingMethod + ": "+ sb.ToString()); } class StdMethodInfo : IMemberInfo { readonly MethodBase _mb; readonly MethodInfo _mi; string _name; Type _returnType; Type[] _parameterTypes; bool _hasVar; TypeInfo _; public StdMethodInfo(MethodInfo mi, TypeInfo owner) : this((MethodBase)mi, owner) { _mi = mi; } public StdMethodInfo(ConstructorInfo ci, TypeInfo owner) : this((MethodBase)ci, owner) { _returnType = owner.TypeMapper.MapType(typeof(void)); } public StdMethodInfo(MethodBase mb, TypeInfo owner) { _mb = mb; _ = owner; } void RequireParameters() { if (_parameterTypes == null) { ParameterInfo[] pis = _mb.GetParameters(); _parameterTypes = ArrayUtils.GetTypes(pis); _hasVar = pis.Length > 0 && Helpers.GetCustomAttributes(pis[pis.Length - 1], typeof(ParamArrayAttribute), false, _.TypeMapper).Count> 0; } } public MemberInfo Member => _mb; public string Name { get { if (_name == null) _name = _mb.Name; return _name; } } public Type ReturnType { get { if (_returnType == null) _returnType = _mi.ReturnType; return _returnType; } } public Type[] ParameterTypes { get { RequireParameters(); return _parameterTypes; } } public bool IsParameterArray { get { RequireParameters(); return _hasVar; } } public bool IsStatic => _mb.IsStatic; public bool IsOverride => Utils.IsOverride(_mb.Attributes); public override string ToString() { return _mb.ToString(); } } class StdPropertyInfo : IMemberInfo { readonly PropertyInfo _pi; string _name; readonly MethodInfo _mi; Type _returnType; Type[] _parameterTypes; bool _hasVar; readonly TypeInfo _; public StdPropertyInfo(PropertyInfo pi, TypeInfo owner) { _pi = pi; _ = owner; _mi = pi.GetGetMethod(); if (_mi == null) _mi = pi.GetSetMethod(); // mi will remain null for abstract properties } void RequireParameters() { if (_parameterTypes == null) { ParameterInfo[] pis = _pi.GetIndexParameters(); _parameterTypes = ArrayUtils.GetTypes(pis); _hasVar = pis.Length > 0 && Helpers.GetCustomAttributes(pis[pis.Length - 1], typeof(ParamArrayAttribute), false, _.TypeMapper).Count > 0; } } public MemberInfo Member => _pi; public string Name { get { if (_name == null) _name = _pi.Name; return _name; } } public Type ReturnType { get { if (_returnType == null) _returnType = _pi.PropertyType; return _returnType; } } public Type[] ParameterTypes { get { RequireParameters(); return _parameterTypes; } } public bool IsParameterArray { get { RequireParameters(); return _hasVar; } } public bool IsOverride => _mi == null ? false : Utils.IsOverride(_mi.Attributes); public bool IsStatic => _mi == null ? false : _mi.IsStatic; public override string ToString() { return _pi.ToString(); } } class StdEventInfo : IMemberInfo { readonly EventInfo _ei; readonly MethodInfo _mi; public StdEventInfo(EventInfo ei) { _ei = ei; Name = ei.Name; _mi = ei.GetAddMethod(); if (_mi == null) _mi = ei.GetRemoveMethod(); // mi will remain null for abstract properties } public MemberInfo Member => _ei; public string Name { get; } public Type ReturnType => _ei.EventHandlerType; public Type[] ParameterTypes => Type.EmptyTypes; public bool IsParameterArray => false; public bool IsOverride => _mi == null ? false : Utils.IsOverride(_mi.Attributes); public bool IsStatic => _mi == null ? false : _mi.IsStatic; public override string ToString() { return _ei.ToString(); } } class StdFieldInfo : IMemberInfo { readonly FieldInfo _fi; public StdFieldInfo(FieldInfo fi) { _fi = fi; Name = fi.Name; } public MemberInfo Member => _fi; public string Name { get; } public Type ReturnType => _fi.FieldType; public Type[] ParameterTypes => Type.EmptyTypes; public bool IsParameterArray => false; public bool IsOverride => false; public bool IsStatic => _fi.IsStatic; public override string ToString() { return _fi.ToString(); } } } }
using System; using System.Collections; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Rendering/Global Fog")] public class GlobalFog : PostEffectsBase { [Tooltip("Apply distance-based fog?")] public bool distanceFog = true; [Tooltip("Exclude far plane pixels from distance-based fog? (Skybox or clear color)")] public bool excludeFarPixels = true; [Tooltip("Distance fog is based on radial distance from camera when checked")] public bool useRadialDistance = false; [Tooltip("Apply height-based fog?")] public bool heightFog = true; [Tooltip("Fog top Y coordinate")] public float height = 1.0f; [Range(0.001f,10.0f)] public float heightDensity = 2.0f; [SerializeField] [Tooltip("Push fog away from the camera by this amount")] private float startDistance = 0.0f; [SerializeField] [Range(1, 1000)] private float accumulatedDistance = 3; [SerializeField] [Range(1, 1000)] private float dissipatedDistance = 10; public Shader fogShader = null; private Material fogMaterial = null; private bool fading; public float AccumulatedDistance { set { this.accumulatedDistance = value; } } public void SetFogStartDistance(float value) { startDistance = value; } public override bool CheckResources() { CheckSupport(true); fogMaterial = CheckShaderAndCreateMaterial(fogShader, fogMaterial); if (!isSupported) ReportAutoDisable(); return isSupported; } public void Dissipate(float time) { if(fading) this.StopAllCoroutines(); this.StartCoroutine(_Fade(time, this.dissipatedDistance, false)); } public void Accumulate(float time) { if (fading) this.StopAllCoroutines(); this.StartCoroutine(_Fade(time, this.accumulatedDistance, true)); } private IEnumerator _Fade(float time, float targetDistance, bool activate) { this.fading = true; if (activate) this.distanceFog = true; if (startDistance != targetDistance) { if (time > 0) { float elapsed = Time.deltaTime; do { startDistance = Mathf.Lerp(this.startDistance, targetDistance, elapsed / time); yield return null; elapsed += Time.deltaTime; } while (time > elapsed && Mathf.Abs(targetDistance - startDistance) > .1f); } startDistance = targetDistance; } if (!activate) this.distanceFog = false; this.fading = false; } [ImageEffectOpaque] void OnRenderImage (RenderTexture source, RenderTexture destination) { if (CheckResources()==false || (!distanceFog && !heightFog)) { Graphics.Blit (source, destination); return; } Camera cam = GetComponent<Camera>(); Transform camtr = cam.transform; float camNear = cam.nearClipPlane; float camFar = cam.farClipPlane; float camFov = cam.fieldOfView; float camAspect = cam.aspect; Matrix4x4 frustumCorners = Matrix4x4.identity; float fovWHalf = camFov * 0.5f; Vector3 toRight = camtr.right * camNear * Mathf.Tan (fovWHalf * Mathf.Deg2Rad) * camAspect; Vector3 toTop = camtr.up * camNear * Mathf.Tan (fovWHalf * Mathf.Deg2Rad); Vector3 topLeft = (camtr.forward * camNear - toRight + toTop); float camScale = topLeft.magnitude * camFar/camNear; topLeft.Normalize(); topLeft *= camScale; Vector3 topRight = (camtr.forward * camNear + toRight + toTop); topRight.Normalize(); topRight *= camScale; Vector3 bottomRight = (camtr.forward * camNear + toRight - toTop); bottomRight.Normalize(); bottomRight *= camScale; Vector3 bottomLeft = (camtr.forward * camNear - toRight - toTop); bottomLeft.Normalize(); bottomLeft *= camScale; frustumCorners.SetRow (0, topLeft); frustumCorners.SetRow (1, topRight); frustumCorners.SetRow (2, bottomRight); frustumCorners.SetRow (3, bottomLeft); var camPos= camtr.position; float FdotC = camPos.y-height; float paramK = (FdotC <= 0.0f ? 1.0f : 0.0f); float excludeDepth = (excludeFarPixels ? 1.0f : 2.0f); fogMaterial.SetMatrix ("_FrustumCornersWS", frustumCorners); fogMaterial.SetVector ("_CameraWS", camPos); fogMaterial.SetVector ("_HeightParams", new Vector4 (height, FdotC, paramK, heightDensity*0.5f)); fogMaterial.SetVector ("_DistanceParams", new Vector4 (-Mathf.Max(startDistance,0.0f), excludeDepth, 0, 0)); var sceneMode= RenderSettings.fogMode; var sceneDensity= RenderSettings.fogDensity; var sceneStart= RenderSettings.fogStartDistance; var sceneEnd= RenderSettings.fogEndDistance; Vector4 sceneParams; bool linear = (sceneMode == FogMode.Linear); float diff = linear ? sceneEnd - sceneStart : 0.0f; float invDiff = Mathf.Abs(diff) > 0.0001f ? 1.0f / diff : 0.0f; sceneParams.x = sceneDensity * 1.2011224087f; // density / sqrt(ln(2)), used by Exp2 fog mode sceneParams.y = sceneDensity * 1.4426950408f; // density / ln(2), used by Exp fog mode sceneParams.z = linear ? -invDiff : 0.0f; sceneParams.w = linear ? sceneEnd * invDiff : 0.0f; fogMaterial.SetVector ("_SceneFogParams", sceneParams); fogMaterial.SetVector ("_SceneFogMode", new Vector4((int)sceneMode, useRadialDistance ? 1 : 0, 0, 0)); int pass = 0; if (distanceFog && heightFog) pass = 0; // distance + height else if (distanceFog) pass = 1; // distance only else pass = 2; // height only CustomGraphicsBlit (source, destination, fogMaterial, pass); } static void CustomGraphicsBlit (RenderTexture source, RenderTexture dest, Material fxMaterial, int passNr) { RenderTexture.active = dest; fxMaterial.SetTexture ("_MainTex", source); GL.PushMatrix (); GL.LoadOrtho (); fxMaterial.SetPass (passNr); GL.Begin (GL.QUADS); GL.MultiTexCoord2 (0, 0.0f, 0.0f); GL.Vertex3 (0.0f, 0.0f, 3.0f); // BL GL.MultiTexCoord2 (0, 1.0f, 0.0f); GL.Vertex3 (1.0f, 0.0f, 2.0f); // BR GL.MultiTexCoord2 (0, 1.0f, 1.0f); GL.Vertex3 (1.0f, 1.0f, 1.0f); // TR GL.MultiTexCoord2 (0, 0.0f, 1.0f); GL.Vertex3 (0.0f, 1.0f, 0.0f); // TL GL.End (); GL.PopMatrix (); } } }
using System; using System.Collections; using Tutor.Structure; using Tutor.Patterns; using Tutor.Production; using Tutor.RuleSystem; namespace Tutor.Theory { /// <summary> /// Summary description for NaiveFactoring. /// </summary> public class NFLowestPower : Rule { #region Rule Members public Equation TestAndApply(Equation E, ReasonBuilder RB) { try { if(E is EquAddition) { if( ((EquAddition)E)._Terms.Count < 3 ) return null; Polynomial P = PolynomialTester.Test(E); if(P.MinDegree > 0) { EquAddition Res = new EquAddition(); foreach(PolynomialTerm PT in P._Elements) { long newDegree = PT.Degree - P.MinDegree; if(newDegree==0) { Res._Terms.Add(PT.Coef); } else if(newDegree == 1) { if(PT.Coef is EquConstant) { if ( ((EquConstant) PT.Coef).Value == 1) { Res._Terms.Add( P.X ); } else { Res._Terms.Add(new EquMultiplication(PT.Coef, P.X)); } } else { Res._Terms.Add(new EquMultiplication(PT.Coef, P.X)); } } else { if(PT.Coef is EquConstant) { if ( ((EquConstant) PT.Coef).Value == 1) { Res._Terms.Add( new EquPower(P.X, new EquConstant(newDegree))); } else { Res._Terms.Add(new EquMultiplication(PT.Coef, new EquPower(P.X, new EquConstant(newDegree)))); } } else { Res._Terms.Add(new EquMultiplication(PT.Coef, new EquPower(P.X, new EquConstant(newDegree)))); } } } PatternMatching.MatchEnvironment Gamma = new PatternMatching.MatchEnvironment(); Gamma.BindTree(P.X,"X"); RB.Write("Factor out the least power [X]",Gamma); if(P.MinDegree == 1) return new EquMultiplication( P.X, Res); return new EquMultiplication( new EquPower(P.X, new EquConstant(P.MinDegree)), Res); } } } catch(PatternMatching.NoMatch NM) { } return null; } #endregion } public class NFQuadratic : Rule { #region Rule Members // assume a and b are positive private static long gcd_p(long a, long b) { if(b == 0) return a; if(b > a) { return gcd(b,a); } long x = a / b; return gcd(a - x * b, b); } public static long gcd(long a, long b) { return gcd_p(Math.Abs(a),Math.Abs(b)); } public static Equation LinearTerm(long coef, Equation X, long root) { if(coef==1 && root==0) return X; if(coef!=1 && root==0) return new EquMultiplication(new EquConstant(coef),X); if(coef==1 && root!=0) return new EquAddition(X,new EquConstant(-root)); return new EquAddition(new EquMultiplication(new EquConstant(coef),X),new EquConstant(-root)); } public Equation TestAndApply(Polynomial P, ReasonBuilder RB) { if(P.MinDegree == 0 && P.MaxDegree == 2) { long Front = 1; long a = 0; long b = 0; long c = 0; //Console.WriteLine("Trying q-Factor with: " + P.X.str()); // build the outer denominator foreach(PolynomialTerm PT in P._Elements) { if(PT.Coef is EquDivide) { Front *= ((EquConstant) ((EquDivide) PT.Coef).Denominator).Value; } } // collect the coef foreach(PolynomialTerm PT in P._Elements) { long coef = 0; if(PT.Coef is EquDivide) { coef = ((EquConstant) ((EquDivide) PT.Coef).Numerator).Value * Front / ((EquConstant) ((EquDivide) PT.Coef).Denominator).Value; } else { coef = ((EquConstant) PT.Coef).Value * Front; } if(PT.Degree == 0) c += coef; if(PT.Degree == 1) b += coef; if(PT.Degree == 2) a += coef; } //Console.WriteLine("(" + a + "x^2 + " + b + "x + " + c +")/"+Front); long det = b*b - 4 * a * c; long sqrdet = (long) Math.Sqrt(det); if(det == sqrdet * sqrdet) { long denom0 = 2 * a; long denom1 = 2 * a; long root0 = -b + sqrdet; long root1 = -b - sqrdet; long gcd0 = gcd(Math.Abs(denom0), Math.Abs(root0)); long gcd1 = gcd(Math.Abs(denom1), Math.Abs(root1)); denom0 /= gcd0; denom1 /= gcd1; root0 /= gcd0; root1 /= gcd1; long front = a; long coef0 = gcd(Math.Abs(front),Math.Abs(denom0)); if(coef0 > 1) { denom0 /= coef0; front /= coef0; } long coef1 = gcd(Math.Abs(front),Math.Abs(denom1)); if(coef1 > 1) { denom1 /= coef1; front /= coef1; } if(denom0 != 1 && denom1 != 1) { return null; } long checkA = front * coef0 * coef1; long checkB = - front * (coef0 * root1 + coef1 * root0); long checkC = front * root0 * root1; if(a != checkA || checkB != b || checkC != c) { return null; } //Console.WriteLine("" + front + ":" + checkA + ":" + checkB + ":" + checkC + ":"); if(Front == 1) { Equation Eek = null; if(root0==root1 && coef0==coef1) { Eek = new EquPower(LinearTerm(coef0,P.X,root0), new EquConstant(2)); } else { Eek = new EquMultiplication(LinearTerm(coef0,P.X,root0), LinearTerm(coef1,P.X,root1)); } if(front == 1) { RB.Write("Naive qFactoring", new PatternMatching.MatchEnvironment()); return Eek; } else { RB.Write("Naive qFactoring", new PatternMatching.MatchEnvironment()); return new EquMultiplication(Eek, new EquConstant(front)); } } else { Equation Eek = null; if(root0==root1 && coef0==coef1) { Eek = new EquPower(LinearTerm(coef0,P.X,root0), new EquConstant(2)); } else { Eek = new EquMultiplication(LinearTerm(coef0,P.X,root0), LinearTerm(coef1,P.X,root1)); } RB.Write("Naive qFactoring", new PatternMatching.MatchEnvironment()); return new EquMultiplication(Eek, new EquDivide(new EquConstant(front), new EquConstant(Front))); } } } return null; } public Equation TestAndApply(Equation E, ReasonBuilder RB) { try { if(E is EquAddition) { if( ((EquAddition)E)._Terms.Count < 2 ) return null; ArrayList List = PolynomialTester.GetAllPolynomials(E); foreach(Polynomial P in List) { Equation R = TestAndApply(P, RB); if(R != null) { // Console.WriteLine("found: " + R); return R; } } return null; } } catch(PatternMatching.NoMatch NM) { } return null; } #endregion } }
using System; using System.IO; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.MessageUI; using Cheapster.ViewControllers.Comparable; using Cheapster.ViewControllers.Comparison; using Cheapster.ViewControllers.Shared; using LibZipArchive; namespace Cheapster.ViewControllers { public class HomeListNavigationController : UINavigationController { private HomeListViewController _homeListViewController; private ComparableViewController _comparableViewController; private ComparisonViewController _comparisonViewController; private ComparisonLineupViewController _comparisonLineupViewController; private UINavigationController _aboutNavigationController; private AboutViewController _aboutViewController; private MFMailComposeViewController _emailController; private const string _urlFormat = "itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id={0}"; public void PrepareForRestore(Action<Action> preparedCallback) { _comparableViewController = null; _comparisonViewController = null; _comparisonLineupViewController = null; _aboutNavigationController = null; _aboutViewController = null; _emailController = null; _homeListViewController.PrepareForRestore(preparedCallback); PopToRootViewController(true); } public override void ViewDidLoad() { Console.WriteLine("HomeListNavigationController ViewDidLoad"); _homeListViewController = new HomeListViewController(); NavigationBar.TintColor = UIColor.DarkGray; // go to new comparison view if add button is touched _homeListViewController.OnAddComparison += (sender, args) => { _comparisonViewController = new ComparisonViewController(); // when a new comparison is added // select the created comparison in the shopping list controller _comparisonViewController.OnFinished += (sender_, args_) => { if(_comparisonViewController.Comparison == null) { throw new Exception("New comparison id was not set."); } _homeListViewController.EnableTrashButton(); _homeListViewController.AddComparison(_comparisonViewController.Comparison); DismissModalViewControllerAnimated(true); _comparableViewController = null; }; _comparisonViewController.OnCanceled += (sender_, args_) => { DismissModalViewControllerAnimated(true); _comparisonViewController = null; }; PresentModalViewController(_comparisonViewController, true); }; // go to the created comparison's lineup view when a comparison is selected _homeListViewController.OnComparisonSelected += (sender, args) => { _comparisonLineupViewController = new ComparisonLineupViewController(_homeListViewController.SelectedComparison); // new comparable _comparisonLineupViewController.OnAddComparable += (sender_, args_) => { _comparableViewController = new ComparableViewController(_comparisonLineupViewController.ComparisonId); _comparableViewController.OnFinished += (sender__, args__) => { _comparisonLineupViewController.EnableTrashButton(); _comparisonLineupViewController.AddComparable(_comparableViewController.Comparable); DismissModalViewControllerAnimated(true); _comparableViewController = null; }; _comparableViewController.OnCanceled += (sender__, args__) => { DismissModalViewControllerAnimated(true); _comparableViewController = null; }; var navController = new UINavigationController(_comparableViewController); PresentModalViewController(navController, true); }; // edit comparable _comparisonLineupViewController.OnComparableSelected += (sender_, args_) => { _comparableViewController = new ComparableViewController(_comparisonLineupViewController.GetSelectedComparable()); _comparableViewController.OnFinished += (sender__, args__) => { // this fixes the bug where changing the "winning" // comparable name was not reflected on the home list view _homeListViewController.ReloadRowForComparison(_comparisonLineupViewController.ComparisonId); _comparisonLineupViewController.RepositionRowForComparable(_comparisonLineupViewController.GetSelectedComparable().Id); PopViewControllerAnimated(true); _comparableViewController = null; }; _comparableViewController.OnCanceled += (sender__, args__) => { PopViewControllerAnimated(true); _comparableViewController = null; }; PushViewController(_comparableViewController, true); }; // edit comparison _comparisonLineupViewController.OnModify += (sender_, args_) => { _comparisonViewController = new ComparisonViewController(_homeListViewController.SelectedComparison); _comparisonViewController.OnCanceled += (sender__, args__) => { DismissModalViewControllerAnimated(true); }; _comparisonViewController.OnFinished += (sender__, args__) => { _comparisonLineupViewController.ReloadOnAppeared(); _homeListViewController.ReloadRowForComparison(_comparisonLineupViewController.ComparisonId); _homeListViewController.RepositionRowForComparison(_comparisonLineupViewController.ComparisonId); DismissModalViewControllerAnimated(true); }; PresentModalViewController(_comparisonViewController, true); }; _comparisonLineupViewController.OnNewCheaper += (sender__, args__) => { _homeListViewController.ReloadRowForComparison(_comparisonLineupViewController.ComparisonId); }; PushViewController(_comparisonLineupViewController, true); }; _homeListViewController.OnInfoButton += (sender, args) => { _aboutViewController = new AboutViewController(); _aboutViewController.OnDone += (sender_, args_) => { DismissModalViewControllerAnimated(true); _aboutViewController = null; _aboutNavigationController = null; _emailController = null; }; _aboutViewController.OnFeedback += (sender_, args_) => { _emailController = new MFMailComposeViewController(); _emailController.SetToRecipients(new string[] { "[email protected]" }); _emailController.SetSubject("Feedback and bugs"); _emailController.Finished += (sender__, args__) => { if(args__.Result == MFMailComposeResult.Sent) { new UIAlertView("Thank you", "We appreciate your feedback and you'll hear back from us soon!", null, "Ok").Show(); } _aboutViewController.DismissModalViewControllerAnimated(true); _emailController = null; }; _aboutViewController.PresentModalViewController(_emailController, true); }; _aboutViewController.OnBackupData += (sender_, args_) => { var attachmentFileName = string.Format("CheapsterBackup_{0}.cdbk", DateTime.Now.ToString("yyyyMMdd")); if(!Directory.Exists(Configuration.TEMP_FOLDER)) { Directory.CreateDirectory(Configuration.TEMP_FOLDER); } // compress the database var zipFile = new LibZipArchive.ZipArchive(); zipFile.CreateZipFile2(Configuration.USER_DB_TEMP_ZIP_PATH); zipFile.AddFile(Configuration.USER_DB_INSTALLED_PATH, Configuration.USER_DB_FILENAME); zipFile.CloseZipFile2(); var fileData = NSData.FromFile(Configuration.USER_DB_TEMP_ZIP_PATH); _emailController = new MFMailComposeViewController(); _emailController.SetSubject(string.Format("Cheapster Data Backup {0}", DateTime.Now.ToShortDateString())); _emailController.SetMessageBody("Here is your Cheapster data. \n\n To restore from this backup, open this email in the Mail app, touch the file and hold down until a menu appears with an option for \"Open in Cheapster\".", false); _emailController.AddAttachmentData(fileData, "Cheapster/x-cdbk", attachmentFileName); _emailController.Finished += (sender__, args__) => { if(args__.Result == MFMailComposeResult.Sent) { new UIAlertView("Email Sent", "", null, "Ok").Show(); } _aboutViewController.DismissModalViewControllerAnimated(true); _emailController = null; }; _aboutViewController.PresentModalViewController(_emailController, true); }; _aboutViewController.OnRateThisApp += (sender__, args__) => { var url = string.Format(_urlFormat, "375611783"); //UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(url)); UIApplication.SharedApplication.OpenUrl(NSUrl.FromString("http://itunes.apple.com/us/app/cheapster/id426078800?mt=8&ls=1")); }; _aboutViewController.OnTwitter += (sender__, args__) => { UIApplication.SharedApplication.OpenUrl(NSUrl.FromString("http://twitter.com/cheapsterapp")); }; _aboutViewController.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal; _aboutNavigationController = new UINavigationController(); _aboutNavigationController.PushViewController(_aboutViewController, false); PresentModalViewController(_aboutNavigationController, true); }; PushViewController(_homeListViewController, true); base.ViewDidLoad(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.Net.Sockets { public partial class SafeSocketHandle { private int _receiveTimeout = -1; private int _sendTimeout = -1; private bool _nonBlocking; private bool _underlyingHandleNonBlocking; private SocketAsyncContext _asyncContext; private TrackedSocketOptions _trackedOptions; internal bool LastConnectFailed { get; set; } internal bool DualMode { get; set; } internal bool ExposedHandleOrUntrackedConfiguration { get; private set; } internal void RegisterConnectResult(SocketError error) { switch (error) { case SocketError.Success: case SocketError.WouldBlock: break; default: LastConnectFailed = true; break; } } internal void TransferTrackedState(SafeSocketHandle target) { target._trackedOptions = _trackedOptions; target.LastConnectFailed = LastConnectFailed; target.DualMode = DualMode; target.ExposedHandleOrUntrackedConfiguration = ExposedHandleOrUntrackedConfiguration; } internal void SetExposed() => ExposedHandleOrUntrackedConfiguration = true; internal bool IsTrackedOption(TrackedSocketOptions option) => (_trackedOptions & option) != 0; internal void TrackOption(SocketOptionLevel level, SocketOptionName name) { // As long as only these options are set, we can support Connect{Async}(IPAddress[], ...). switch (level) { case SocketOptionLevel.Tcp: switch (name) { case SocketOptionName.NoDelay: _trackedOptions |= TrackedSocketOptions.NoDelay; return; } break; case SocketOptionLevel.IP: switch (name) { case SocketOptionName.DontFragment: _trackedOptions |= TrackedSocketOptions.DontFragment; return; case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return; } break; case SocketOptionLevel.IPv6: switch (name) { case SocketOptionName.IPv6Only: _trackedOptions |= TrackedSocketOptions.DualMode; return; case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return; } break; case SocketOptionLevel.Socket: switch (name) { case SocketOptionName.Broadcast: _trackedOptions |= TrackedSocketOptions.EnableBroadcast; return; case SocketOptionName.Linger: _trackedOptions |= TrackedSocketOptions.LingerState; return; case SocketOptionName.ReceiveBuffer: _trackedOptions |= TrackedSocketOptions.ReceiveBufferSize; return; case SocketOptionName.ReceiveTimeout: _trackedOptions |= TrackedSocketOptions.ReceiveTimeout; return; case SocketOptionName.SendBuffer: _trackedOptions |= TrackedSocketOptions.SendBufferSize; return; case SocketOptionName.SendTimeout: _trackedOptions |= TrackedSocketOptions.SendTimeout; return; } break; } // For any other settings, we need to track that they were used so that we can error out // if a Connect{Async}(IPAddress[],...) attempt is made. ExposedHandleOrUntrackedConfiguration = true; } internal SocketAsyncContext AsyncContext { get { if (Volatile.Read(ref _asyncContext) == null) { Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null); } return _asyncContext; } } // This will set the underlying OS handle to be nonblocking, for whatever reason -- // performing an async operation or using a timeout will cause this to happen. // Once the OS handle is nonblocking, it never transitions back to blocking. private void SetHandleNonBlocking() { // We don't care about synchronization because this is idempotent if (!_underlyingHandleNonBlocking) { AsyncContext.SetNonBlocking(); _underlyingHandleNonBlocking = true; } } internal bool IsNonBlocking { get { return _nonBlocking; } set { _nonBlocking = value; // // If transitioning to non-blocking, we need to set the native socket to non-blocking mode. // If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate // blocking. This avoids problems with switching to native blocking while there are pending async // operations. // if (value) { SetHandleNonBlocking(); } } } internal bool IsUnderlyingBlocking { get { return !_underlyingHandleNonBlocking; } } internal int ReceiveTimeout { get { return _receiveTimeout; } set { Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}"); _receiveTimeout = value; } } internal int SendTimeout { get { return _sendTimeout; } set { Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}"); _sendTimeout = value; } } internal bool IsDisconnected { get; private set; } = false; internal void SetToDisconnected() { IsDisconnected = true; } /// <returns>Returns whether operations were canceled.</returns> private bool OnHandleClose() { // If we've aborted async operations, return true to cause an abortive close. return _asyncContext?.StopAndAbort() ?? false; } /// <returns>Returns whether operations were canceled.</returns> private unsafe bool TryUnblockSocket(bool abortive) { // Calling 'close' on a socket that has pending blocking calls (e.g. recv, send, accept, ...) // may block indefinitely. This is a best-effort attempt to not get blocked and make those operations return. // We need to ensure we keep the expected TCP behavior that is observed by the socket peer (FIN vs RST close). // What we do here isn't specified by POSIX and doesn't work on all OSes. // On Linux this works well. // On OSX, TCP connections will be closed with a FIN close instead of an abortive RST close. // And, pending TCP connect operations and UDP receive are not abortable. // Unless we're doing an abortive close, don't touch sockets which don't have the CLOEXEC flag set. // These may be shared with other processes and we want to avoid disconnecting them. if (!abortive) { int fdFlags = Interop.Sys.Fcntl.GetFD(handle); if (fdFlags == 0) { return false; } } int type = 0; int optLen = sizeof(int); Interop.Error err = Interop.Sys.GetSockOpt(handle, SocketOptionLevel.Socket, SocketOptionName.Type, (byte*)&type, &optLen); if (err == Interop.Error.SUCCESS) { // For TCP (SocketType.Stream), perform an abortive close. // Unless the user requested a normal close using Socket.Shutdown. if (type == (int)SocketType.Stream && !_hasShutdownSend) { Interop.Sys.Disconnect(handle); } else { Interop.Sys.Shutdown(handle, SocketShutdown.Both); } } return true; } private unsafe SocketError DoCloseHandle(bool abortive) { Interop.Error errorCode = Interop.Error.SUCCESS; // If abortive is not set, we're not running on the finalizer thread, so it's safe to block here. // We can honor the linger options set on the socket. It also means closesocket() might return // EWOULDBLOCK, in which case we need to do some recovery. if (!abortive) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle} Following 'non-abortive' branch."); // Close, and if its errno is other than EWOULDBLOCK, there's nothing more to do - we either succeeded or failed. errorCode = CloseHandle(handle); if (errorCode != Interop.Error.EWOULDBLOCK) { return SocketPal.GetSocketErrorForErrorCode(errorCode); } // The socket must be non-blocking with a linger timeout set. // We have to set the socket to blocking. if (Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0) == 0) { // The socket successfully made blocking; retry the close(). return SocketPal.GetSocketErrorForErrorCode(CloseHandle(handle)); } // The socket could not be made blocking; fall through to the regular abortive close. } // By default or if the non-abortive path failed, set linger timeout to zero to get an abortive close (RST). var linger = new Interop.Sys.LingerOption { OnOff = 1, Seconds = 0 }; errorCode = Interop.Sys.SetLingerOption(handle, &linger); #if DEBUG _closeSocketLinger = SocketPal.GetSocketErrorForErrorCode(errorCode); #endif if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}"); switch (errorCode) { case Interop.Error.SUCCESS: case Interop.Error.EINVAL: case Interop.Error.ENOPROTOOPT: errorCode = CloseHandle(handle); break; // For other errors, it's too dangerous to try closesocket() - it might block! } return SocketPal.GetSocketErrorForErrorCode(errorCode); } private Interop.Error CloseHandle(IntPtr handle) { Interop.Error errorCode = Interop.Error.SUCCESS; bool remappedError = false; if (Interop.Sys.Close(handle) != 0) { errorCode = Interop.Sys.GetLastError(); if (errorCode == Interop.Error.ECONNRESET) { // Some Unix platforms (e.g. FreeBSD) non-compliantly return ECONNRESET from close(). // For our purposes, we want to ignore such a "failure" and treat it as success. // In such a case, the file descriptor was still closed and there's no corrective // action to take. errorCode = Interop.Error.SUCCESS; remappedError = true; } } if (NetEventSource.IsEnabled) { NetEventSource.Info(this, remappedError ? $"handle:{handle}, close():ECONNRESET, but treating it as SUCCESS" : $"handle:{handle}, close():{errorCode}"); } #if DEBUG _closeSocketResult = SocketPal.GetSocketErrorForErrorCode(errorCode); #endif return errorCode; } } /// <summary>Flags that correspond to exposed options on Socket.</summary> [Flags] internal enum TrackedSocketOptions : short { DontFragment = 0x1, DualMode = 0x2, EnableBroadcast = 0x4, LingerState = 0x8, NoDelay = 0x10, ReceiveBufferSize = 0x20, ReceiveTimeout = 0x40, SendBufferSize = 0x80, SendTimeout = 0x100, Ttl = 0x200, } }
/* * Copyright (c) 2009, Stefan Simek * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Reflection.Emit; namespace TriAxis.RunSharp { interface IStandardOperation { void Emit(CodeGen g, Operator op); bool IsUnsigned { get; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Other name would be unclear")] public sealed class Operator { internal delegate IEnumerable<IMemberInfo> StandardCandidateProvider(Operand[] operands); #region Standard operations static IMemberInfo[] stdPlusOperators = { UnaryOp<int>.Instance, UnaryOp<uint>.Instance, UnaryOp<long>.Instance, UnaryOp<ulong>.Instance, UnaryOp<float>.Instance, UnaryOp<double>.Instance }; static IMemberInfo[] stdMinusOperators = { UnaryOp<int>.Instance, UnaryOp<long>.Instance, UnaryOp<float>.Instance, UnaryOp<double>.Instance }; static IMemberInfo[] stdNotOperators = { UnaryOp<int>.Instance, UnaryOp<uint>.Instance, UnaryOp<long>.Instance, UnaryOp<ulong>.Instance, }; static SpecificOperatorProvider[] stdNotTemplates = { UnaryEnumSpecific }; static IMemberInfo[] stdUnaryBoolOperators = { UnaryOp<bool>.Instance }; static IMemberInfo[] stdIncOperators = { IncOp<sbyte>.Instance, IncOp<byte>.Instance, IncOp<short>.Instance, IncOp<ushort>.Instance, IncOp<int>.Instance, IncOp<uint>.Instance, IncOp<long>.Instance, IncOp<ulong>.Instance, IncOp<char>.Instance, IncOp<float>.Instance, IncOp<double>.Instance }; static SpecificOperatorProvider[] stdIncTemplates = { IncEnumSpecific }; static IMemberInfo[] stdAddOperators = { SameOp<int>.Instance, SameOp<uint>.Instance, SameOp<long>.Instance, SameOp<ulong>.Instance, SameOp<float>.Instance, SameOp<double>.Instance, StringConcatOp<string, string>.Instance, StringConcatOp<string, object>.Instance, StringConcatOp<object, string>.Instance }; static SpecificOperatorProvider[] stdAddTemplates = { AddEnumSpecific, AddDelegateSpecific }; static IMemberInfo[] stdSubOperators = { SameOp<int>.Instance, SameOp<uint>.Instance, SameOp<long>.Instance, SameOp<ulong>.Instance, SameOp<float>.Instance, SameOp<double>.Instance }; static SpecificOperatorProvider[] stdSubTemplates = { SubEnumSpecific, SubDelegateSpecific }; static IMemberInfo[] stdArithOperators = { SameOp<int>.Instance, SameOp<uint>.Instance, SameOp<long>.Instance, SameOp<ulong>.Instance, SameOp<float>.Instance, SameOp<double>.Instance }; static IMemberInfo[] stdBitOperators = { SameOp<bool>.Instance, SameOp<int>.Instance, SameOp<uint>.Instance, SameOp<long>.Instance, SameOp<ulong>.Instance }; static SpecificOperatorProvider[] stdBitTemplates = { BitEnumSpecific }; static IMemberInfo[] stdShiftOperators = { ShiftOp<int>.Instance, ShiftOp<uint>.Instance, ShiftOp<long>.Instance, ShiftOp<ulong>.Instance }; static IMemberInfo[] stdEqOperators = { CmpOp<bool>.Instance, CmpOp<int>.Instance, CmpOp<uint>.Instance, CmpOp<long>.Instance, CmpOp<ulong>.Instance, CmpOp<float>.Instance, CmpOp<double>.Instance, CmpOp<object>.Instance }; static SpecificOperatorProvider[] stdEqTemplates = { CmpEnumSpecific }; static IMemberInfo[] stdCmpOperators = { CmpOp<int>.Instance, CmpOp<uint>.Instance, CmpOp<long>.Instance, CmpOp<ulong>.Instance, CmpOp<float>.Instance, CmpOp<double>.Instance }; static SpecificOperatorProvider[] stdCmpTemplates = { CmpEnumSpecific }; static IMemberInfo[] stdNone = { }; sealed class UnaryOp<T> : StdOp { public static readonly UnaryOp<T> Instance = new UnaryOp<T>(); private UnaryOp() : base(typeof(T), typeof(T)) { } } static IMemberInfo[] UnaryEnumSpecific(Operand[] args) { Type t = Operand.GetType(args[0]); if (t == null || !t.IsEnum) return stdNone; return new IMemberInfo[] { new StdOp(t, t) }; } sealed class IncOp<T> : IncOp { public static readonly IncOp<T> Instance = new IncOp<T>(); private IncOp() : base(typeof(T)) { } } class IncOp : StdOp { OpCode convCode; public IncOp(Type t) : base(t, t) { switch (Type.GetTypeCode(t)) { case TypeCode.Single: convCode = OpCodes.Conv_R4; break; case TypeCode.Double: convCode = OpCodes.Conv_R8; break; case TypeCode.Int64: case TypeCode.UInt64: convCode = OpCodes.Conv_I8; break; default: convCode = OpCodes.Nop; break; } } public override void Emit(CodeGen g, Operator op) { g.IL.Emit(OpCodes.Ldc_I4_1); if (convCode != OpCodes.Nop) g.IL.Emit(convCode); base.Emit(g, op); } } static IMemberInfo[] IncEnumSpecific(Operand[] args) { Type t = Operand.GetType(args[0]); if (t == null || !t.IsEnum) return stdNone; return new IMemberInfo[] { new IncOp(t) }; } sealed class SameOp<T> : StdOp { public static readonly SameOp<T> Instance = new SameOp<T>(); private SameOp() : base(typeof(T), typeof(T), typeof(T)) { } } static IMemberInfo[] AddEnumSpecific(Operand[] args) { Type t1 = Operand.GetType(args[0]), t2 = Operand.GetType(args[1]); if (t1 == null || t2 == null || t1.IsEnum == t2.IsEnum) // if none or both types are enum, no operator can be valid return stdNone; Type e = t1.IsEnum ? t1 : t2; Type u = Enum.GetUnderlyingType(e); return new IMemberInfo[] { new StdOp(e, e, u), new StdOp(e, u, e) }; } static IMemberInfo[] AddDelegateSpecific(Operand[] args) { Type t1 = Operand.GetType(args[0]), t2 = Operand.GetType(args[1]); if (t1 != t2 || t1 == null || !t1.IsSubclassOf(typeof(Delegate))) // if the types are not the same, no operator can be valid return stdNone; return new IMemberInfo[] { new DelegateCombineOp(t1) }; } sealed class DelegateCombineOp : StdOp { public DelegateCombineOp(Type t) : base(t, t, t) { } static MethodInfo miCombine = typeof(Delegate).GetMethod("Combine", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(Delegate), typeof(Delegate) }, null); public override void Emit(CodeGen g, Operator op) { g.IL.Emit(OpCodes.Call, miCombine); g.IL.Emit(OpCodes.Castclass, ReturnType); } } static IMemberInfo[] SubEnumSpecific(Operand[] args) { Type t1 = Operand.GetType(args[0]), t2 = Operand.GetType(args[1]); if (t1 == null || t2 == null || !t1.IsEnum || (t2.IsEnum && t2 != t1)) // if the types are not the same, no operator can be valid return stdNone; Type e = t1; Type u = Enum.GetUnderlyingType(e); return new IMemberInfo[] { new StdOp(u, e, e), new StdOp(e, e, u) }; } static IMemberInfo[] SubDelegateSpecific(Operand[] args) { Type t1 = Operand.GetType(args[0]), t2 = Operand.GetType(args[1]); if (t1 != t2 || t1 == null || !t1.IsSubclassOf(typeof(Delegate))) // if the types are not the same, no operator can be valid return stdNone; return new IMemberInfo[] { new DelegateRemoveOp(t1) }; } sealed class DelegateRemoveOp : StdOp { public DelegateRemoveOp(Type t) : base(t, t, t) { } static MethodInfo miRemove = typeof(Delegate).GetMethod("Remove", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(Delegate), typeof(Delegate) }, null); public override void Emit(CodeGen g, Operator op) { g.IL.Emit(OpCodes.Call, miRemove); g.IL.Emit(OpCodes.Castclass, ReturnType); } } sealed class StringConcatOp<T1, T2> : StdOp { public static readonly StringConcatOp<T1, T2> Instance = new StringConcatOp<T1, T2>(); MethodInfo method; private StringConcatOp() : base(typeof(string), typeof(T1), typeof(T2)) { method = typeof(string).GetMethod("Concat", BindingFlags.Public | BindingFlags.Static, null, ParameterTypes, null); } public override void Emit(CodeGen g, Operator op) { g.IL.Emit(OpCodes.Call, method); } } static IMemberInfo[] BitEnumSpecific(Operand[] args) { Type t1 = Operand.GetType(args[0]), t2 = Operand.GetType(args[1]); if (t1 != t2 || t1 == null || !t1.IsEnum) // if both types are not the same enum, no operator can be valid return stdNone; return new IMemberInfo[] { new StdOp(t1, t1, t1) }; } sealed class ShiftOp<T> : StdOp { public static readonly ShiftOp<T> Instance = new ShiftOp<T>(); private ShiftOp() : base(typeof(T), typeof(T), typeof(int)) { } public override void Emit(CodeGen g, Operator op) { base.Emit(g, op); } } sealed class CmpOp<T> : StdOp { public static readonly CmpOp<T> Instance = new CmpOp<T>(); private CmpOp() : base(typeof(bool), typeof(T), typeof(T)) { // unsigned is calculated from return type by default unsigned = IsUnsigned(typeof(T)); } } static IMemberInfo[] CmpEnumSpecific(Operand[] args) { Type t1 = args[0].Type, t2 = args[1].Type; if (t1 != t2 || t1 == null || !t1.IsEnum) // if both types are not the same enum, no operator can be valid return stdNone; return new IMemberInfo[] { new StdOp(typeof(bool), t1, t1) }; } class StdOp : IMemberInfo, IStandardOperation { Type retType; Type[] opTypes; protected bool unsigned; public StdOp(Type returnType, params Type[] opTypes) { this.retType = returnType; this.opTypes = opTypes; unsigned = IsUnsigned(returnType); } protected static bool IsUnsigned(Type t) { switch (Type.GetTypeCode(t)) { case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Char: return true; default: return false; } } bool IStandardOperation.IsUnsigned { get { return unsigned; } } #region IMemberInfo Members public System.Reflection.MemberInfo Member { get { return null; } } public string Name { get { return null; } } public Type ReturnType { get { return retType; } } public Type[] ParameterTypes { get { return opTypes; } } public bool IsParameterArray { get { return false; } } public bool IsStatic { get { return true; } } public bool IsOverride { get { return false; } } #endregion #region IStandardOperation Members public virtual void Emit(CodeGen g, Operator op) { if (op.opCode != OpCodes.Nop) g.IL.Emit(unsigned ? op.opCodeUn : op.opCode); if (op.invertOpResult) { g.IL.Emit(OpCodes.Ldc_I4_0); g.IL.Emit(OpCodes.Ceq); } } #endregion } delegate IMemberInfo[] SpecificOperatorProvider(Operand[] args); #endregion [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Plus = new Operator(OpCodes.Nop, false, 0, "UnaryPlus", stdPlusOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Minus = new Operator(OpCodes.Neg, false, 0, "UnaryMinus", stdMinusOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator LogicalNot = new Operator(OpCodes.Nop, true, BranchInstruction.False, "LogicalNot", stdUnaryBoolOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Not = new Operator(OpCodes.Not, false, 0, "OnesComplement", stdNotOperators, stdNotTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Increment = new Operator(OpCodes.Add, OpCodes.Add, OpCodes.Add_Ovf, OpCodes.Add_Ovf_Un, false, 0, "Increment", stdIncOperators, stdIncTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Decrement = new Operator(OpCodes.Sub, OpCodes.Sub, OpCodes.Sub_Ovf, OpCodes.Sub_Ovf_Un, false, 0, "Decrement", stdIncOperators, stdIncTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator True = new Operator(OpCodes.Nop, false, BranchInstruction.True, "True", stdUnaryBoolOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator False = new Operator(OpCodes.Nop, true, BranchInstruction.False, "False", stdUnaryBoolOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Add = new Operator(OpCodes.Add, OpCodes.Add, OpCodes.Add_Ovf, OpCodes.Add_Ovf_Un, false, 0, "Addition", stdAddOperators, stdAddTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Subtract = new Operator(OpCodes.Sub, OpCodes.Sub, OpCodes.Sub_Ovf, OpCodes.Sub_Ovf_Un, false, 0, "Subtraction", stdSubOperators, stdSubTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Multiply = new Operator(OpCodes.Mul, OpCodes.Mul, OpCodes.Mul_Ovf, OpCodes.Mul_Ovf_Un, false, 0, "Multiply", stdArithOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Divide = new Operator(OpCodes.Div, OpCodes.Div_Un, false, 0, "Division", stdArithOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Modulus = new Operator(OpCodes.Rem, OpCodes.Rem_Un, false, 0, "Modulus", stdArithOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator And = new Operator(OpCodes.And, false, 0, "BitwiseAnd", stdBitOperators, stdBitTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Or = new Operator(OpCodes.Or, false, 0, "BitwiseOr", stdBitOperators, stdBitTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Xor = new Operator(OpCodes.Xor, false, 0, "ExclusiveOr", stdBitOperators, stdBitTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator LeftShift = new Operator(OpCodes.Shl, false, 0, "LeftShift", stdShiftOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator RightShift = new Operator(OpCodes.Shr, OpCodes.Shr_Un, false, 0, "RightShift", stdShiftOperators, null); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Equality = new Operator(OpCodes.Ceq, false, BranchInstruction.Eq, "Equality", stdEqOperators, stdEqTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator Inequality = new Operator(OpCodes.Ceq, true, BranchInstruction.Ne, "Inequality", stdEqOperators, stdEqTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator LessThan = new Operator(OpCodes.Clt, OpCodes.Clt_Un, false, BranchInstruction.Lt, "LessThan", stdCmpOperators, stdCmpTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator LessThanOrEqual = new Operator(OpCodes.Cgt, OpCodes.Cgt_Un, true, BranchInstruction.Le, "LessThanOrEqual", stdCmpOperators, stdCmpTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator GreaterThan = new Operator(OpCodes.Cgt, OpCodes.Cgt_Un, false, BranchInstruction.Gt, "GreaterThan", stdCmpOperators, stdCmpTemplates); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The type is immutable")] public static readonly Operator GreaterThanOrEqual = new Operator(OpCodes.Clt, OpCodes.Clt_Un, true, BranchInstruction.Ge, "GreaterThanOrEqual", stdCmpOperators, stdCmpTemplates); internal readonly OpCode opCode, opCodeUn; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Prepared for future use")] internal readonly OpCode opCodeChk, opCodeChkUn; internal readonly bool invertOpResult; internal readonly BranchInstruction branchOp; internal readonly string methodName; readonly IMemberInfo[] standardCandidates; readonly SpecificOperatorProvider[] standardTemplates; private Operator(OpCode opCode, bool invertOpResult, BranchInstruction branchOp, string methodName, IMemberInfo[] standardCandidates, SpecificOperatorProvider[] standardTemplates) { this.opCode = this.opCodeUn = this.opCodeChk = this.opCodeChkUn = opCode; this.invertOpResult = invertOpResult; this.branchOp = branchOp; this.methodName = methodName; this.standardCandidates = standardCandidates; this.standardTemplates = standardTemplates; } private Operator(OpCode opCode, OpCode opCodeUn, bool invertOpResult, BranchInstruction branchOp, string methodName, IMemberInfo[] standardCandidates, SpecificOperatorProvider[] standardTemplates) { this.opCode = this.opCodeChk = opCode; this.opCodeUn = this.opCodeChkUn = opCodeUn; this.invertOpResult = invertOpResult; this.branchOp = branchOp; this.methodName = methodName; this.standardCandidates = standardCandidates; this.standardTemplates = standardTemplates; } private Operator(OpCode opCode, OpCode opCodeUn, OpCode opCodeChk, OpCode opCodeChkUn, bool invertOpResult, BranchInstruction branchOp, string methodName, IMemberInfo[] standardCandidates, SpecificOperatorProvider[] standardTemplates) { this.opCode = opCode; this.opCodeUn = opCodeUn; this.opCodeChk = opCodeChk; this.opCodeChkUn = opCodeChkUn; this.invertOpResult = invertOpResult; this.branchOp = branchOp; this.methodName = methodName; this.standardCandidates = standardCandidates; this.standardTemplates = standardTemplates; } internal IEnumerable<IMemberInfo> GetStandardCandidates(params Operand[] args) { if (standardTemplates == null) return standardCandidates; else return GetStandardCandidatesT(args); } IEnumerable<IMemberInfo> GetStandardCandidatesT(Operand[] args) { foreach (IMemberInfo op in standardCandidates) yield return op; foreach (SpecificOperatorProvider tpl in standardTemplates) { foreach (IMemberInfo inst in tpl(args)) yield return inst; } } internal List<ApplicableFunction> FindUserCandidates(params Operand[] args) { List<Type> usedTypes = new List<Type>(); List<ApplicableFunction> candidates = null; string name = "op_" + methodName; bool expandedCandidates = false; foreach (Operand arg in args) { for (Type t = Operand.GetType(arg); t != null && t != typeof(object) && (t.IsClass || t.IsValueType) && !usedTypes.Contains(t); t = t.IsValueType ? null : t.BaseType) { usedTypes.Add(t); OverloadResolver.FindApplicable(ref candidates, ref expandedCandidates, TypeInfo.Filter(TypeInfo.GetMethods(t), name, true, true, false), args); } } if (expandedCandidates) OverloadResolver.RemoveExpanded(candidates); return candidates; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using SubSonic.DataProviders; using SubSonic.Extensions; using System.Linq.Expressions; using SubSonic.Schema; using SubSonic.Repository; using System.Data.Common; using SubSonic.SqlGeneration.Schema; namespace Solution.DataAccess.DataModel { /// <summary> /// A class which represents the adJustRest_D table in the HKHR Database. /// </summary> public partial class adJustRest_D: IActiveRecord { #region Built-in testing static TestRepository<adJustRest_D> _testRepo; static void SetTestRepo(){ _testRepo = _testRepo ?? new TestRepository<adJustRest_D>(new Solution.DataAccess.DataModel.HKHRDB()); } public static void ResetTestRepo(){ _testRepo = null; SetTestRepo(); } public static void Setup(List<adJustRest_D> testlist){ SetTestRepo(); foreach (var item in testlist) { _testRepo._items.Add(item); } } public static void Setup(adJustRest_D item) { SetTestRepo(); _testRepo._items.Add(item); } public static void Setup(int testItems) { SetTestRepo(); for(int i=0;i<testItems;i++){ adJustRest_D item=new adJustRest_D(); _testRepo._items.Add(item); } } public bool TestMode = false; #endregion IRepository<adJustRest_D> _repo; ITable tbl; bool _isNew; public bool IsNew(){ return _isNew; } public void SetIsLoaded(bool isLoaded){ _isLoaded=isLoaded; if(isLoaded) OnLoaded(); } public void SetIsNew(bool isNew){ _isNew=isNew; } bool _isLoaded; public bool IsLoaded(){ return _isLoaded; } List<IColumn> _dirtyColumns; public bool IsDirty(){ return _dirtyColumns.Count>0; } public List<IColumn> GetDirtyColumns (){ return _dirtyColumns; } Solution.DataAccess.DataModel.HKHRDB _db; public adJustRest_D(string connectionString, string providerName) { _db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); Init(); } void Init(){ TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); _dirtyColumns=new List<IColumn>(); if(TestMode){ adJustRest_D.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<adJustRest_D>(_db); } tbl=_repo.GetTable(); SetIsNew(true); OnCreated(); } public adJustRest_D(){ _db=new Solution.DataAccess.DataModel.HKHRDB(); Init(); } public void ORMapping(IDataRecord dataRecord) { IReadRecord readRecord = SqlReadRecord.GetIReadRecord(); readRecord.DataRecord = dataRecord; Id = readRecord.get_int("Id",null); bill_id = readRecord.get_string("bill_id",null); emp_id = readRecord.get_string("emp_id",null); join_id = readRecord.get_int("join_id",null); depart_id = readRecord.get_string("depart_id",null); ori_date = readRecord.get_datetime("ori_date",null); ori_btime = readRecord.get_datetime("ori_btime",null); ori_etime = readRecord.get_datetime("ori_etime",null); rest_date = readRecord.get_datetime("rest_date",null); rest_btime = readRecord.get_datetime("rest_btime",null); rest_etime = readRecord.get_datetime("rest_etime",null); checker = readRecord.get_string("checker",null); check_date = readRecord.get_datetime("check_date",null); op_user = readRecord.get_string("op_user",null); op_date = readRecord.get_datetime("op_date",null); audit = readRecord.get_short("audit",null); memo = readRecord.get_string("memo",null); all_day = readRecord.get_short("all_day",null); kind = readRecord.get_string("kind",null); refuse_reason = readRecord.get_string("refuse_reason",null); CHECKER2 = readRecord.get_string("CHECKER2",null); audit2 = readRecord.get_short("audit2",null); check_date2 = readRecord.get_datetime("check_date2",null); } partial void OnCreated(); partial void OnLoaded(); partial void OnSaved(); partial void OnChanged(); public IList<IColumn> Columns{ get{ return tbl.Columns; } } public adJustRest_D(Expression<Func<adJustRest_D, bool>> expression):this() { SetIsLoaded(_repo.Load(this,expression)); } internal static IRepository<adJustRest_D> GetRepo(string connectionString, string providerName){ Solution.DataAccess.DataModel.HKHRDB db; if(String.IsNullOrEmpty(connectionString)){ db=new Solution.DataAccess.DataModel.HKHRDB(); }else{ db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); } IRepository<adJustRest_D> _repo; if(db.TestMode){ adJustRest_D.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<adJustRest_D>(db); } return _repo; } internal static IRepository<adJustRest_D> GetRepo(){ return GetRepo("",""); } public static adJustRest_D SingleOrDefault(Expression<Func<adJustRest_D, bool>> expression) { var repo = GetRepo(); var results=repo.Find(expression); adJustRest_D single=null; if(results.Count() > 0){ single=results.ToList()[0]; single.OnLoaded(); single.SetIsLoaded(true); single.SetIsNew(false); } return single; } public static adJustRest_D SingleOrDefault(Expression<Func<adJustRest_D, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); var results=repo.Find(expression); adJustRest_D single=null; if(results.Count() > 0){ single=results.ToList()[0]; } return single; } public static bool Exists(Expression<Func<adJustRest_D, bool>> expression,string connectionString, string providerName) { return All(connectionString,providerName).Any(expression); } public static bool Exists(Expression<Func<adJustRest_D, bool>> expression) { return All().Any(expression); } public static IList<adJustRest_D> Find(Expression<Func<adJustRest_D, bool>> expression) { var repo = GetRepo(); return repo.Find(expression).ToList(); } public static IList<adJustRest_D> Find(Expression<Func<adJustRest_D, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); return repo.Find(expression).ToList(); } public static IQueryable<adJustRest_D> All(string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetAll(); } public static IQueryable<adJustRest_D> All() { return GetRepo().GetAll(); } public static PagedList<adJustRest_D> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<adJustRest_D> GetPaged(string sortBy, int pageIndex, int pageSize) { return GetRepo().GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<adJustRest_D> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); } public static PagedList<adJustRest_D> GetPaged(int pageIndex, int pageSize) { return GetRepo().GetPaged(pageIndex, pageSize); } public string KeyName() { return "Id"; } public object KeyValue() { return this.Id; } public void SetKeyValue(object value) { if (value != null && value!=DBNull.Value) { var settable = value.ChangeTypeTo<int>(); this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); } } public override string ToString(){ var sb = new StringBuilder(); sb.Append("Id=" + Id + "; "); sb.Append("bill_id=" + bill_id + "; "); sb.Append("emp_id=" + emp_id + "; "); sb.Append("join_id=" + join_id + "; "); sb.Append("depart_id=" + depart_id + "; "); sb.Append("ori_date=" + ori_date + "; "); sb.Append("ori_btime=" + ori_btime + "; "); sb.Append("ori_etime=" + ori_etime + "; "); sb.Append("rest_date=" + rest_date + "; "); sb.Append("rest_btime=" + rest_btime + "; "); sb.Append("rest_etime=" + rest_etime + "; "); sb.Append("checker=" + checker + "; "); sb.Append("check_date=" + check_date + "; "); sb.Append("op_user=" + op_user + "; "); sb.Append("op_date=" + op_date + "; "); sb.Append("audit=" + audit + "; "); sb.Append("memo=" + memo + "; "); sb.Append("all_day=" + all_day + "; "); sb.Append("kind=" + kind + "; "); sb.Append("refuse_reason=" + refuse_reason + "; "); sb.Append("CHECKER2=" + CHECKER2 + "; "); sb.Append("audit2=" + audit2 + "; "); sb.Append("check_date2=" + check_date2 + "; "); return sb.ToString(); } public override bool Equals(object obj){ if(obj.GetType()==typeof(adJustRest_D)){ adJustRest_D compare=(adJustRest_D)obj; return compare.KeyValue()==this.KeyValue(); }else{ return base.Equals(obj); } } public override int GetHashCode() { return this.Id; } public string DescriptorValue() { return this.bill_id.ToString(); } public string DescriptorColumn() { return "bill_id"; } public static string GetKeyColumn() { return "Id"; } public static string GetDescriptorColumn() { return "bill_id"; } #region ' Foreign Keys ' #endregion int _Id; /// <summary> /// /// </summary> [SubSonicPrimaryKey] public int Id { get { return _Id; } set { if(_Id!=value || _isLoaded){ _Id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _bill_id; /// <summary> /// /// </summary> public string bill_id { get { return _bill_id; } set { if(_bill_id!=value || _isLoaded){ _bill_id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="bill_id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _emp_id; /// <summary> /// /// </summary> public string emp_id { get { return _emp_id; } set { if(_emp_id!=value || _isLoaded){ _emp_id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="emp_id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int _join_id; /// <summary> /// /// </summary> public int join_id { get { return _join_id; } set { if(_join_id!=value || _isLoaded){ _join_id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="join_id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _depart_id; /// <summary> /// /// </summary> public string depart_id { get { return _depart_id; } set { if(_depart_id!=value || _isLoaded){ _depart_id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="depart_id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _ori_date; /// <summary> /// /// </summary> public DateTime? ori_date { get { return _ori_date; } set { if(_ori_date!=value || _isLoaded){ _ori_date=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ori_date"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _ori_btime; /// <summary> /// /// </summary> public DateTime? ori_btime { get { return _ori_btime; } set { if(_ori_btime!=value || _isLoaded){ _ori_btime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ori_btime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _ori_etime; /// <summary> /// /// </summary> public DateTime? ori_etime { get { return _ori_etime; } set { if(_ori_etime!=value || _isLoaded){ _ori_etime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ori_etime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime _rest_date; /// <summary> /// /// </summary> public DateTime rest_date { get { return _rest_date; } set { if(_rest_date!=value || _isLoaded){ _rest_date=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="rest_date"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _rest_btime; /// <summary> /// /// </summary> public DateTime? rest_btime { get { return _rest_btime; } set { if(_rest_btime!=value || _isLoaded){ _rest_btime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="rest_btime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _rest_etime; /// <summary> /// /// </summary> public DateTime? rest_etime { get { return _rest_etime; } set { if(_rest_etime!=value || _isLoaded){ _rest_etime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="rest_etime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _checker; /// <summary> /// /// </summary> public string checker { get { return _checker; } set { if(_checker!=value || _isLoaded){ _checker=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="checker"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _check_date; /// <summary> /// /// </summary> public DateTime? check_date { get { return _check_date; } set { if(_check_date!=value || _isLoaded){ _check_date=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="check_date"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _op_user; /// <summary> /// /// </summary> public string op_user { get { return _op_user; } set { if(_op_user!=value || _isLoaded){ _op_user=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="op_user"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _op_date; /// <summary> /// /// </summary> public DateTime? op_date { get { return _op_date; } set { if(_op_date!=value || _isLoaded){ _op_date=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="op_date"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _audit; /// <summary> /// /// </summary> public short? audit { get { return _audit; } set { if(_audit!=value || _isLoaded){ _audit=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="audit"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _memo; /// <summary> /// /// </summary> public string memo { get { return _memo; } set { if(_memo!=value || _isLoaded){ _memo=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="memo"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _all_day; /// <summary> /// /// </summary> public short? all_day { get { return _all_day; } set { if(_all_day!=value || _isLoaded){ _all_day=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="all_day"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _kind; /// <summary> /// /// </summary> public string kind { get { return _kind; } set { if(_kind!=value || _isLoaded){ _kind=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="kind"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _refuse_reason; /// <summary> /// /// </summary> public string refuse_reason { get { return _refuse_reason; } set { if(_refuse_reason!=value || _isLoaded){ _refuse_reason=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="refuse_reason"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _CHECKER2; /// <summary> /// /// </summary> public string CHECKER2 { get { return _CHECKER2; } set { if(_CHECKER2!=value || _isLoaded){ _CHECKER2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CHECKER2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _audit2; /// <summary> /// /// </summary> public short? audit2 { get { return _audit2; } set { if(_audit2!=value || _isLoaded){ _audit2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="audit2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _check_date2; /// <summary> /// /// </summary> public DateTime? check_date2 { get { return _check_date2; } set { if(_check_date2!=value || _isLoaded){ _check_date2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="check_date2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } public DbCommand GetUpdateCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetInsertCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetDeleteCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); } public void Update(){ Update(_db.DataProvider); } public void Update(IDataProvider provider){ if(this._dirtyColumns.Count>0){ _repo.Update(this,provider); _dirtyColumns.Clear(); } OnSaved(); } public void Add(){ Add(_db.DataProvider); } public void Add(IDataProvider provider){ var key=KeyValue(); if(key==null){ var newKey=_repo.Add(this,provider); this.SetKeyValue(newKey); }else{ _repo.Add(this,provider); } SetIsNew(false); OnSaved(); } public void Save() { Save(_db.DataProvider); } public void Save(IDataProvider provider) { if (_isNew) { Add(provider); } else { Update(provider); } } public void Delete(IDataProvider provider) { _repo.Delete(KeyValue()); } public void Delete() { Delete(_db.DataProvider); } public static void Delete(Expression<Func<adJustRest_D, bool>> expression) { var repo = GetRepo(); repo.DeleteMany(expression); } public void Load(IDataReader rdr) { Load(rdr, true); } public void Load(IDataReader rdr, bool closeReader) { if (rdr.Read()) { try { rdr.Load(this); SetIsNew(false); SetIsLoaded(true); } catch { SetIsLoaded(false); throw; } }else{ SetIsLoaded(false); } if (closeReader) rdr.Dispose(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /* * The registry wrapper provides a common interface to both the transacted * and non-transacted registry APIs. It is used exclusively by the registry provider * to perform registry operations. In most cases, the wrapper simply forwards the * call to the appropriate registry API. */ using System; using System.Globalization; using Microsoft.Win32; using System.Security.AccessControl; using System.Management.Automation.Provider; using Microsoft.PowerShell.Commands.Internal; namespace Microsoft.PowerShell.Commands { internal interface IRegistryWrapper { void SetValue(string name, object value); void SetValue(string name, object value, RegistryValueKind valueKind); string[] GetValueNames(); void DeleteValue(string name); string[] GetSubKeyNames(); IRegistryWrapper CreateSubKey(string subkey); IRegistryWrapper OpenSubKey(string name, bool writable); void DeleteSubKeyTree(string subkey); object GetValue(string name); object GetValue(string name, object defaultValue, RegistryValueOptions options); RegistryValueKind GetValueKind(string name); object RegistryKey { get; } void SetAccessControl(ObjectSecurity securityDescriptor); ObjectSecurity GetAccessControl(AccessControlSections includeSections); void Close(); string Name { get; } int SubKeyCount { get; } } internal static class RegistryWrapperUtils { public static object ConvertValueToUIntFromRegistryIfNeeded(string name, object value, RegistryValueKind kind) { try { // Workaround for CLR bug that doesn't support full range of DWORD or QWORD if (kind == RegistryValueKind.DWord) { value = (int)value; if ((int)value < 0) { value = BitConverter.ToUInt32(BitConverter.GetBytes((int)value), 0); } } else if (kind == RegistryValueKind.QWord) { value = (long)value; if ((long)value < 0) { value = BitConverter.ToUInt64(BitConverter.GetBytes((long)value), 0); } } } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } public static object ConvertUIntToValueForRegistryIfNeeded(object value, RegistryValueKind kind) { // Workaround for CLR bug that doesn't support full range of DWORD or QWORD if (kind == RegistryValueKind.DWord) { UInt32 intValue = 0; // See if it's already a positive number try { intValue = Convert.ToUInt32(value, CultureInfo.InvariantCulture); value = BitConverter.ToInt32(BitConverter.GetBytes(intValue), 0); } catch (OverflowException) { // It must be a negative Int32, and therefore need no more conversion } } else if (kind == RegistryValueKind.QWord) { UInt64 intValue = 0; // See if it's already a positive number try { intValue = Convert.ToUInt64(value, CultureInfo.InvariantCulture); value = BitConverter.ToInt64(BitConverter.GetBytes(intValue), 0); } catch (OverflowException) { // It must be a negative Int64, and therefore need no more conversion } } return value; } } internal class RegistryWrapper : IRegistryWrapper { private RegistryKey _regKey; internal RegistryWrapper(RegistryKey regKey) { _regKey = regKey; } #region IRegistryWrapper Members public void SetValue(string name, object value) { _regKey.SetValue(name, value); } public void SetValue(string name, object value, RegistryValueKind valueKind) { value = System.Management.Automation.PSObject.Base(value); value = RegistryWrapperUtils.ConvertUIntToValueForRegistryIfNeeded(value, valueKind); _regKey.SetValue(name, value, valueKind); } public string[] GetValueNames() { return _regKey.GetValueNames(); } public void DeleteValue(string name) { _regKey.DeleteValue(name); } public string[] GetSubKeyNames() { return _regKey.GetSubKeyNames(); } public IRegistryWrapper CreateSubKey(string subkey) { RegistryKey newKey = _regKey.CreateSubKey(subkey); if (newKey == null) return null; else return new RegistryWrapper(newKey); } public IRegistryWrapper OpenSubKey(string name, bool writable) { RegistryKey newKey = _regKey.OpenSubKey(name, writable); if (newKey == null) return null; else return new RegistryWrapper(newKey); } public void DeleteSubKeyTree(string subkey) { _regKey.DeleteSubKeyTree(subkey); } public object GetValue(string name) { object value = _regKey.GetValue(name); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { object value = _regKey.GetValue(name, defaultValue, options); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } public RegistryValueKind GetValueKind(string name) { return _regKey.GetValueKind(name); } public void Close() { _regKey.Dispose(); } public string Name { get { return _regKey.Name; } } public int SubKeyCount { get { return _regKey.SubKeyCount; } } public object RegistryKey { get { return _regKey; } } public void SetAccessControl(ObjectSecurity securityDescriptor) { _regKey.SetAccessControl((RegistrySecurity)securityDescriptor); } public ObjectSecurity GetAccessControl(AccessControlSections includeSections) { return _regKey.GetAccessControl(includeSections); } #endregion } internal class TransactedRegistryWrapper : IRegistryWrapper { private TransactedRegistryKey _txRegKey; private CmdletProvider _provider; internal TransactedRegistryWrapper(TransactedRegistryKey txRegKey, CmdletProvider provider) { _txRegKey = txRegKey; _provider = provider; } #region IRegistryWrapper Members public void SetValue(string name, object value) { using (_provider.CurrentPSTransaction) { _txRegKey.SetValue(name, value); } } public void SetValue(string name, object value, RegistryValueKind valueKind) { using (_provider.CurrentPSTransaction) { value = System.Management.Automation.PSObject.Base(value); value = RegistryWrapperUtils.ConvertUIntToValueForRegistryIfNeeded(value, valueKind); _txRegKey.SetValue(name, value, valueKind); } } public string[] GetValueNames() { using (_provider.CurrentPSTransaction) { return _txRegKey.GetValueNames(); } } public void DeleteValue(string name) { using (_provider.CurrentPSTransaction) { _txRegKey.DeleteValue(name); } } public string[] GetSubKeyNames() { using (_provider.CurrentPSTransaction) { return _txRegKey.GetSubKeyNames(); } } public IRegistryWrapper CreateSubKey(string subkey) { using (_provider.CurrentPSTransaction) { TransactedRegistryKey newKey = _txRegKey.CreateSubKey(subkey); if (newKey == null) return null; else return new TransactedRegistryWrapper(newKey, _provider); } } public IRegistryWrapper OpenSubKey(string name, bool writable) { using (_provider.CurrentPSTransaction) { TransactedRegistryKey newKey = _txRegKey.OpenSubKey(name, writable); if (newKey == null) return null; else return new TransactedRegistryWrapper(newKey, _provider); } } public void DeleteSubKeyTree(string subkey) { using (_provider.CurrentPSTransaction) { _txRegKey.DeleteSubKeyTree(subkey); } } public object GetValue(string name) { using (_provider.CurrentPSTransaction) { object value = _txRegKey.GetValue(name); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { using (_provider.CurrentPSTransaction) { object value = _txRegKey.GetValue(name, defaultValue, options); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } } public RegistryValueKind GetValueKind(string name) { using (_provider.CurrentPSTransaction) { return _txRegKey.GetValueKind(name); } } public void Close() { using (_provider.CurrentPSTransaction) { _txRegKey.Close(); } } public string Name { get { using (_provider.CurrentPSTransaction) { return _txRegKey.Name; } } } public int SubKeyCount { get { using (_provider.CurrentPSTransaction) { return _txRegKey.SubKeyCount; } } } public object RegistryKey { get { return _txRegKey; } } public void SetAccessControl(ObjectSecurity securityDescriptor) { using (_provider.CurrentPSTransaction) { _txRegKey.SetAccessControl((TransactedRegistrySecurity)securityDescriptor); } } public ObjectSecurity GetAccessControl(AccessControlSections includeSections) { using (_provider.CurrentPSTransaction) { return _txRegKey.GetAccessControl(includeSections); } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for RoutesOperations. /// </summary> public static partial class RoutesOperationsExtensions { /// <summary> /// The delete route operation deletes the specified route from a route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> public static void Delete(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName) { Task.Factory.StartNew(s => ((IRoutesOperations)s).DeleteAsync(resourceGroupName, routeTableName, routeName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete route operation deletes the specified route from a route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The delete route operation deletes the specified route from a route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> public static void BeginDelete(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName) { Task.Factory.StartNew(s => ((IRoutesOperations)s).BeginDeleteAsync(resourceGroupName, routeTableName, routeName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete route operation deletes the specified route from a route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get route operation retrieves information about the specified route /// from the route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> public static Route Get(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName) { return Task.Factory.StartNew(s => ((IRoutesOperations)s).GetAsync(resourceGroupName, routeTableName, routeName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get route operation retrieves information about the specified route /// from the route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Route> GetAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put route operation creates/updates a route in the specified route /// table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create/update route operation /// </param> public static Route CreateOrUpdate(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters) { return Task.Factory.StartNew(s => ((IRoutesOperations)s).CreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put route operation creates/updates a route in the specified route /// table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create/update route operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Route> CreateOrUpdateAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put route operation creates/updates a route in the specified route /// table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create/update route operation /// </param> public static Route BeginCreateOrUpdate(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters) { return Task.Factory.StartNew(s => ((IRoutesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put route operation creates/updates a route in the specified route /// table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create/update route operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Route> BeginCreateOrUpdateAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The List network security rule operation retrieves all the routes in a /// route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> public static IPage<Route> List(this IRoutesOperations operations, string resourceGroupName, string routeTableName) { return Task.Factory.StartNew(s => ((IRoutesOperations)s).ListAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List network security rule operation retrieves all the routes in a /// route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Route>> ListAsync(this IRoutesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The List network security rule operation retrieves all the routes in a /// route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Route> ListNext(this IRoutesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IRoutesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List network security rule operation retrieves all the routes in a /// route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Route>> ListNextAsync(this IRoutesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Threading; namespace Shielded { /// <summary> /// Makes your data thread safe. Works with structs, or simple value types, /// and the language does the necessary cloning. If T is a class, then only /// the reference itself is protected. /// </summary> public class Shielded<T> : ICommutableShielded { private class ValueKeeper { public long Version; public T Value; public ValueKeeper Older; } private ValueKeeper _current; // once negotiated, kept until commit or rollback private volatile WriteStamp _writerStamp; private readonly LocalStorage<ValueKeeper> _locals = new LocalStorage<ValueKeeper>(); private readonly StampLocker _locker = new StampLocker(); private readonly object _owner; /// <summary> /// Constructs a new Shielded container, containing default value of type T. /// </summary> /// <param name="owner">If this is given, then in WhenCommitting subscriptions /// this shielded will report its owner instead of itself.</param> public Shielded(object owner = null) { _current = new ValueKeeper(); _owner = owner ?? this; } /// <summary> /// Constructs a new Shielded container, containing the given initial value. /// </summary> /// <param name="initial">Initial value to contain.</param> /// <param name="owner">If this is given, then in WhenCommitting subscriptions /// this shielded will report its owner instead of itself.</param> public Shielded(T initial, object owner = null) { _current = new ValueKeeper(); _current.Value = initial; _owner = owner ?? this; } bool LockCheck() { var w = _writerStamp; return w == null || w.Version == null || w.Version > Shield.ReadStamp; } /// <summary> /// Enlists the field in the current transaction and, if this is the first /// access, checks the write lock. Will spin-wait (or Monitor.Wait if SERVER /// is defined) if the write stamp &lt;= <see cref="Shield.ReadStamp"/>, until /// write lock is released. Since write stamps are increasing, this is /// likely to happen only at the beginning of transactions. /// </summary> private void CheckLockAndEnlist(bool write) { // if already enlisted, no need to check lock. if (!Shield.Enlist(this, _locals.HasValue, write)) return; if (!LockCheck()) _locker.WaitUntil(LockCheck); } private ValueKeeper CurrentTransactionOldValue() { var point = _current; while (point.Version > Shield.ReadStamp) point = point.Older; return point; } /// <summary> /// Gets the value that this Shielded contained at transaction opening. During /// a transaction, this is constant. /// </summary> public T GetOldValue() { CheckLockAndEnlist(false); return CurrentTransactionOldValue().Value; } private ValueKeeper PrepareForWriting(bool prepareOld) { CheckLockAndEnlist(true); if (_current.Version > Shield.ReadStamp) throw new TransException("Write collision."); if (_locals.HasValue) return _locals.Value; var v = new ValueKeeper(); if (prepareOld) v.Value = CurrentTransactionOldValue().Value; _locals.Value = v; return v; } /// <summary> /// Reads or writes into the content of the field. Reading can be /// done out of transaction, but writes must be inside. /// </summary> public T Value { get { if (!Shield.IsInTransaction) return _current.Value; CheckLockAndEnlist(false); if (!_locals.HasValue) return CurrentTransactionOldValue().Value; else if (_current.Version > Shield.ReadStamp) throw new TransException("Writable read collision."); return _locals.Value.Value; } set { PrepareForWriting(false).Value = value; Changed.Raise(this, EventArgs.Empty); } } /// <summary> /// Delegate type used for modifications, i.e. read and write operations. /// It has the advantage of working directly on the internal, thread-local /// storage copy, to which it gets a reference. This is more efficient if /// the type T is a big value-type. /// </summary> public delegate void ModificationDelegate(ref T value); /// <summary> /// Modifies the content of the field, i.e. read and write operation. /// It has the advantage of working directly on the internal, thread-local /// storage copy, to which it gets a reference. This is more efficient if /// the type T is a big value-type. /// </summary> public void Modify(ModificationDelegate d) { d(ref PrepareForWriting(true).Value); Changed.Raise(this, EventArgs.Empty); } /// <summary> /// The action is performed just before commit, and reads the latest /// data. If it conflicts, only it is retried. If it succeeds, /// we (try to) commit with the same write stamp along with it. /// But, if you access this Shielded, it gets executed directly in this transaction. /// The Changed event is raised only when the commute is enlisted, and not /// when (and every time, given possible repetitions..) it executes. /// </summary> public void Commute(ModificationDelegate perform) { Shield.EnlistStrictCommute( () => perform(ref PrepareForWriting(true).Value), this); Changed.Raise(this, EventArgs.Empty); } /// <summary> /// For use by the ProxyGen, since the users of it know only about the base type used /// to generate the proxy. The struct used internally is not exposed, and so users /// of proxy classes could not write a ModificationDelegate which works on an argument /// whose type is that hidden struct. /// </summary> public void Commute(Action perform) { Shield.EnlistStrictCommute(perform, this); Changed.Raise(this, EventArgs.Empty); } /// <summary> /// Event raised after any change, and directly in the transaction that changed it. /// Subscriptions are transactional. In case of a commute, event is raised immediately /// after the commute is enlisted, and your handler can easily cause commutes to /// degenerate. /// </summary> public readonly ShieldedEvent<EventArgs> Changed = new ShieldedEvent<EventArgs>(); /// <summary> /// Returns the current <see cref="Value"/>. /// </summary> public static implicit operator T(Shielded<T> obj) { return obj.Value; } bool IShielded.HasChanges { get { return _locals.HasValue; } } object IShielded.Owner { get { return _owner; } } bool IShielded.CanCommit(WriteStamp writeStamp) { var res = _writerStamp == null && _current.Version <= Shield.ReadStamp; if (res && _locals.HasValue) _writerStamp = writeStamp; return res; } void IShielded.Commit() { if (!_locals.HasValue) return; var newCurrent = _locals.Value; newCurrent.Older = _current; newCurrent.Version = _writerStamp.Version.Value; _current = newCurrent; _locals.Release(); _writerStamp = null; _locker.Release(); } void IShielded.Rollback() { if (!_locals.HasValue) return; _locals.Release(); var ws = _writerStamp; if (ws != null && ws.ThreadId == Thread.CurrentThread.ManagedThreadId) { _writerStamp = null; _locker.Release(); } } void IShielded.TrimCopies(long smallestOpenTransactionId) { // NB the "smallest transaction" and others can freely read while // we're doing this. var point = _current; while (point.Version > smallestOpenTransactionId) point = point.Older; // point is the last accessible - his Older is not needed. point.Older = null; } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace grpc.testing { /// <summary> /// TestService (this is handwritten version of code that will normally be generated). /// </summary> public class TestServiceGrpc { readonly static Marshaller<Empty> emptyMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), Empty.ParseFrom); readonly static Marshaller<SimpleRequest> simpleRequestMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), SimpleRequest.ParseFrom); readonly static Marshaller<SimpleResponse> simpleResponseMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), SimpleResponse.ParseFrom); readonly static Marshaller<StreamingOutputCallRequest> streamingOutputCallRequestMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingOutputCallRequest.ParseFrom); readonly static Marshaller<StreamingOutputCallResponse> streamingOutputCallResponseMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingOutputCallResponse.ParseFrom); readonly static Marshaller<StreamingInputCallRequest> streamingInputCallRequestMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingInputCallRequest.ParseFrom); readonly static Marshaller<StreamingInputCallResponse> streamingInputCallResponseMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingInputCallResponse.ParseFrom); readonly static Method<Empty, Empty> emptyCallMethod = new Method<Empty, Empty>( MethodType.Unary, "/grpc.testing.TestService/EmptyCall", emptyMarshaller, emptyMarshaller ); readonly static Method<SimpleRequest, SimpleResponse> unaryCallMethod = new Method<SimpleRequest, SimpleResponse>( MethodType.Unary, "/grpc.testing.TestService/UnaryCall", simpleRequestMarshaller, simpleResponseMarshaller ); readonly static Method<StreamingOutputCallRequest, StreamingOutputCallResponse> streamingOutputCallMethod = new Method<StreamingOutputCallRequest, StreamingOutputCallResponse>( MethodType.ServerStreaming, "/grpc.testing.TestService/StreamingOutputCall", streamingOutputCallRequestMarshaller, streamingOutputCallResponseMarshaller ); readonly static Method<StreamingInputCallRequest, StreamingInputCallResponse> streamingInputCallMethod = new Method<StreamingInputCallRequest, StreamingInputCallResponse>( MethodType.ClientStreaming, "/grpc.testing.TestService/StreamingInputCall", streamingInputCallRequestMarshaller, streamingInputCallResponseMarshaller ); readonly static Method<StreamingOutputCallRequest, StreamingOutputCallResponse> fullDuplexCallMethod = new Method<StreamingOutputCallRequest, StreamingOutputCallResponse>( MethodType.DuplexStreaming, "/grpc.testing.TestService/FullDuplexCall", streamingOutputCallRequestMarshaller, streamingOutputCallResponseMarshaller ); readonly static Method<StreamingOutputCallRequest, StreamingOutputCallResponse> halfDuplexCallMethod = new Method<StreamingOutputCallRequest, StreamingOutputCallResponse>( MethodType.DuplexStreaming, "/grpc.testing.TestService/HalfDuplexCall", streamingOutputCallRequestMarshaller, streamingOutputCallResponseMarshaller ); public interface ITestServiceClient { Empty EmptyCall(Empty request, CancellationToken token = default(CancellationToken)); Task<Empty> EmptyCallAsync(Empty request, CancellationToken token = default(CancellationToken)); SimpleResponse UnaryCall(SimpleRequest request, CancellationToken token = default(CancellationToken)); Task<SimpleResponse> UnaryCallAsync(SimpleRequest request, CancellationToken token = default(CancellationToken)); void StreamingOutputCall(StreamingOutputCallRequest request, IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)); ClientStreamingAsyncResult<StreamingInputCallRequest, StreamingInputCallResponse> StreamingInputCall(CancellationToken token = default(CancellationToken)); IObserver<StreamingOutputCallRequest> FullDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)); IObserver<StreamingOutputCallRequest> HalfDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)); } public class TestServiceClientStub : ITestServiceClient { readonly Channel channel; public TestServiceClientStub(Channel channel) { this.channel = channel; } public Empty EmptyCall(Empty request, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<Empty, Empty>(emptyCallMethod, channel); return Calls.BlockingUnaryCall(call, request, token); } public Task<Empty> EmptyCallAsync(Empty request, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<Empty, Empty>(emptyCallMethod, channel); return Calls.AsyncUnaryCall(call, request, token); } public SimpleResponse UnaryCall(SimpleRequest request, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); return Calls.BlockingUnaryCall(call, request, token); } public Task<SimpleResponse> UnaryCallAsync(SimpleRequest request, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); return Calls.AsyncUnaryCall(call, request, token); } public void StreamingOutputCall(StreamingOutputCallRequest request, IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(streamingOutputCallMethod, channel); Calls.AsyncServerStreamingCall(call, request, responseObserver, token); } public ClientStreamingAsyncResult<StreamingInputCallRequest, StreamingInputCallResponse> StreamingInputCall(CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<StreamingInputCallRequest, StreamingInputCallResponse>(streamingInputCallMethod, channel); return Calls.AsyncClientStreamingCall(call, token); } public IObserver<StreamingOutputCallRequest> FullDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(fullDuplexCallMethod, channel); return Calls.DuplexStreamingCall(call, responseObserver, token); } public IObserver<StreamingOutputCallRequest> HalfDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(halfDuplexCallMethod, channel); return Calls.DuplexStreamingCall(call, responseObserver, token); } } // server-side interface public interface ITestService { void EmptyCall(Empty request, IObserver<Empty> responseObserver); void UnaryCall(SimpleRequest request, IObserver<SimpleResponse> responseObserver); void StreamingOutputCall(StreamingOutputCallRequest request, IObserver<StreamingOutputCallResponse> responseObserver); IObserver<StreamingInputCallRequest> StreamingInputCall(IObserver<StreamingInputCallResponse> responseObserver); IObserver<StreamingOutputCallRequest> FullDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver); IObserver<StreamingOutputCallRequest> HalfDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver); } public static ServerServiceDefinition BindService(ITestService serviceImpl) { return ServerServiceDefinition.CreateBuilder("/grpc.testing.TestService/") .AddMethod(emptyCallMethod, serviceImpl.EmptyCall) .AddMethod(unaryCallMethod, serviceImpl.UnaryCall) .AddMethod(streamingOutputCallMethod, serviceImpl.StreamingOutputCall) .AddMethod(streamingInputCallMethod, serviceImpl.StreamingInputCall) .AddMethod(fullDuplexCallMethod, serviceImpl.FullDuplexCall) .AddMethod(halfDuplexCallMethod, serviceImpl.HalfDuplexCall) .Build(); } public static ITestServiceClient NewStub(Channel channel) { return new TestServiceClientStub(channel); } } }
// 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.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private bool _disposed; private Stream _contentReadStream; private bool _canCalculateLength; internal const long MaxBufferSize = Int32.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !NETNative // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !NETNative // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(GetComputedOrBufferLength); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } #if NETNative internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, false, true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { if (_bufferedContent == null) { return false; } return _bufferedContent.TryGetBuffer(out buffer); } #endif protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", null); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null); } public Task<string> ReadAsStringAsync() { CheckDisposed(); var tcs = new TaskCompletionSource<string>(this); LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<string>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { return; } if (innerThis._bufferedContent.Length == 0) { innerTcs.TrySetResult(string.Empty); return; } // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; byte[] data = innerThis.GetDataBuffer(innerThis._bufferedContent); int dataLength = (int)innerThis._bufferedContent.Length; // Data is the raw buffer, it may not be full. // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if ((innerThis.Headers.ContentType != null) && (innerThis.Headers.ContentType.CharSet != null)) { try { encoding = Encoding.GetEncoding(innerThis.Headers.ContentType.CharSet); // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(data, dataLength, encoding); } catch (ArgumentException e) { innerTcs.TrySetException(new InvalidOperationException(SR.net_http_content_invalid_charset, e)); return; } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(data, dataLength, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } try { // Drop the BOM when decoding the data. string result = encoding.GetString(data, bomLength, dataLength - bomLength); innerTcs.TrySetResult(result); } catch (Exception ex) { innerTcs.TrySetException(ex); } }); return tcs.Task; } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); var tcs = new TaskCompletionSource<byte[]>(this); LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<byte[]>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerTcs.TrySetResult(innerThis._bufferedContent.ToArray()); } }); return tcs.Task; } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>(this); if (_contentReadStream == null && IsBuffered) { byte[] data = this.GetDataBuffer(_bufferedContent); // We can cast bufferedContent.Length to 'int' since the length will always be in the 'int' range // The .NET Framework doesn't support array lengths > int.MaxValue. Debug.Assert(_bufferedContent.Length <= (long)int.MaxValue); _contentReadStream = new MemoryStream(data, 0, (int)_bufferedContent.Length, false); } if (_contentReadStream != null) { tcs.TrySetResult(_contentReadStream); return tcs.Task; } CreateContentReadStreamAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<Stream>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerThis._contentReadStream = task.Result; innerTcs.TrySetResult(innerThis._contentReadStream); } }); return tcs.Task; } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); public Task CopyToAsync(Stream stream, TransportContext context) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException("stream"); } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); try { Task task = null; if (IsBuffered) { byte[] data = this.GetDataBuffer(_bufferedContent); task = stream.WriteAsync(data, 0, (int)_bufferedContent.Length); } else { task = SerializeToStreamAsync(stream, context); CheckTaskNotNull(task); } // If the copy operation fails, wrap the exception in an HttpRequestException() if appropriate. task.ContinueWithStandard(tcs, (copyTask, state) => { var innerTcs = (TaskCompletionSource<object>)state; if (copyTask.IsFaulted) { innerTcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException())); } else if (copyTask.IsCanceled) { innerTcs.TrySetCanceled(); } else { innerTcs.TrySetResult(null); } }); } catch (IOException e) { tcs.TrySetException(GetStreamCopyException(e)); } catch (ObjectDisposedException e) { tcs.TrySetException(GetStreamCopyException(e)); } return tcs.Task; } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return CreateCompletedTask(); } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): set the task as faulted and return the task. Debug.Assert(error != null); tcs.TrySetException(error); } else { try { Task task = SerializeToStreamAsync(tempBuffer, null); CheckTaskNotNull(task); task.ContinueWithStandard(copyTask => { try { if (copyTask.IsFaulted) { tempBuffer.Dispose(); // Cleanup partially filled stream. tcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException())); return; } if (copyTask.IsCanceled) { tempBuffer.Dispose(); // Cleanup partially filled stream. tcs.TrySetCanceled(); return; } tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; tcs.TrySetResult(null); } catch (Exception e) { // Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer. tcs.TrySetException(e); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "LoadIntoBufferAsync", e); } }); } catch (IOException e) { tcs.TrySetException(GetStreamCopyException(e)); } catch (ObjectDisposedException e) { tcs.TrySetException(GetStreamCopyException(e)); } } return tcs.Task; } protected virtual Task<Stream> CreateContentReadStreamAsync() { var tcs = new TaskCompletionSource<Stream>(this); // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<Stream>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerTcs.TrySetResult(innerThis._bufferedContent); } }); return tcs.Task; } // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); private long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { Contract.Ensures((Contract.Result<MemoryStream>() != null) || (Contract.ValueAtReturn<Exception>(out error) != null)); error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } private byte[] GetDataBuffer(MemoryStream stream) { // TODO: Use TryGetBuffer() instead of ToArray(). return stream.ToArray(); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null) { _contentReadStream.Dispose(); } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_content_no_task_returned_copytoasync, this.GetType().ToString())); throw new InvalidOperationException(SR.net_http_content_no_task_returned); } } private static Task CreateCompletedTask() { TaskCompletionSource<object> completed = new TaskCompletionSource<object>(); bool resultSet = completed.TrySetResult(null); Debug.Assert(resultSet, "Can't set Task as completed."); return completed.Task; } private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. Exception result = originalException; if ((result is IOException) || (result is ObjectDisposedException)) { result = new HttpRequestException(SR.net_http_content_stream_copy_error, result); } return result; } private static int GetPreambleLength(byte[] data, int dataLength, Encoding encoding) { Debug.Assert(data != null); Debug.Assert(dataLength <= data.Length); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[0] == UTF8PreambleByte0 && data[1] == UTF8PreambleByte1 && data[2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !NETNative // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[0] == UTF32PreambleByte0 && data[1] == UTF32PreambleByte1 && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[0] == UnicodePreambleByte0 && data[1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[0] == BigEndianUnicodePreambleByte0 && data[1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return ByteArrayHasPrefix(data, dataLength, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(byte[] data, int dataLength, out Encoding encoding, out int preambleLength) { Debug.Assert(data != null); Debug.Assert(dataLength <= data.Length); if (dataLength >= 2) { int first2Bytes = data[0] << 8 | data[1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !NETNative // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool ByteArrayHasPrefix(byte[] byteArray, int dataLength, byte[] prefix) { if (prefix == null || byteArray == null || prefix.Length > dataLength || prefix.Length == 0) return false; for (int i = 0; i < prefix.Length; i++) { if (prefix[i] != byteArray[i]) return false; } return true; } #endregion Helpers private class LimitMemoryStream : MemoryStream { private int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { _maxSize = maxSize; } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, _maxSize)); } } } } }
using System; using System.IO; using System.Collections.Generic; using System.Drawing; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Preferences; using Emgu.CV; using Emgu.CV.Structure; using Emgu.Util; namespace com.bytewild.imaging.cropper { public class ImageProcessor { private Bitmap imageBitmap; public ImageProcessor(Bitmap bitmap) { //dummy code to load the opencv libraries CvInvoke.CV_FOURCC('m', 'j', 'p', 'g'); this.imageBitmap = bitmap; } public RectF GetCropRect() { using( var image = new Image<Bgr, Byte>(imageBitmap)) { using(var edgeImage = GetImageOutline(image)) { var boxes = GetQuadrilaterals(edgeImage); var box = GetLargestQuadrilateral(boxes); var vertices = box.GetVertices(); return new RectF(GetCoordinate("left", vertices), GetCoordinate("top", vertices), GetCoordinate("right", vertices), GetCoordinate("bottom", vertices)); } } } public MCvBox2D GetCropBox() { using (var image = new Image<Bgr, Byte>(imageBitmap)) { using (var edgeImage = GetImageOutline(image)) { var boxes = GetQuadrilaterals(edgeImage); return GetLargestQuadrilateral(boxes); } } } public CropPolygon GetCropPolygon() { using (var image = new Image<Bgr, Byte>(imageBitmap)) { using (var edgeImage = GetImageOutline(image)) { var polys = GetPolygons(edgeImage); return GetLargestPolygon(polys); } } } private Image<Gray, Byte> GetImageOutline(Image<Bgr, Byte> image) { // Convert to GreyScale Image<Gray, Byte> imageGray = image.Convert<Gray, Byte>().PyrDown().PyrUp(); //Canny Edge Detector //Image<Gray, Byte> cannyGray = imageGray.Canny(120, 180); Image<Gray, Byte> cannyGray = imageGray.Canny(10, 180); Image<Gray, Byte> imageDilate = cannyGray.Dilate(1); Image<Gray, Byte> imageErode = imageDilate.Erode(1); imageGray.Dispose(); cannyGray.Dispose(); imageDilate.Dispose(); return imageErode; } private float GetCoordinate(string position, System.Drawing.PointF[] vertices) { float thePoint = float.MinValue; switch (position) { case "bottom": { // Find max y foreach (var v in vertices) { if (v.Y > thePoint || thePoint == float.MinValue) thePoint = v.Y; } break; } case "top": { // Find min y foreach (var v in vertices) { if (v.Y < thePoint || thePoint == float.MinValue) thePoint = v.Y; } break; } case "right": { // Find max x foreach (var v in vertices) { if (v.X > thePoint || thePoint == float.MinValue) thePoint = v.X; } break; } case "left": { foreach (var v in vertices) { if (v.X < thePoint || thePoint == float.MinValue) thePoint = v.X; } break; } } return thePoint; } private List<MCvBox2D> GetQuadrilaterals(Image<Gray, Byte> image) { //List to store rectangles List<MCvBox2D> rectList = new List<MCvBox2D>(); using (MemStorage storage1 = new MemStorage()) for (Contour<System.Drawing.Point> contours1 = image.FindContours(); contours1 != null; contours1 = contours1.HNext) { //Polygon Approximations Contour<System.Drawing.Point> contoursAP = contours1.ApproxPoly(contours1.Perimeter * 0.05, storage1); //Use area to wipe out the unnecessary result if (contours1.Area >= 200) { //Use vertices to determine the shape if (contoursAP.Total == 4) { //Rectangle bool isRectangle = true; System.Drawing.Point[] points = contoursAP.ToArray(); LineSegment2D[] edges = PointCollection.PolyLine(points, true); //degree within the range of [75, 105] will be detected for (int i = 0; i < edges.Length; i++) { double angle = Math.Abs(edges[(i + 1) % edges.Length].GetExteriorAngleDegree(edges[i])); if (angle < 75 || angle > 105) { isRectangle = false; break; } } if (isRectangle) { rectList.Add(contoursAP.GetMinAreaRect()); } } } } return rectList; } private MCvBox2D GetLargestQuadrilateral(List<MCvBox2D> rectList) { double maxArea = 0; MCvBox2D largestRect = new MCvBox2D(); foreach (MCvBox2D rect in rectList) { if (maxArea < (rect.size.Height * rect.size.Width)) { maxArea = rect.size.Height * rect.size.Width; largestRect = rect; } } return largestRect; } private List<CropPolygon> GetPolygons(Image<Gray, Byte> image) { //List to store rectangles List<CropPolygon> polyList = new List<CropPolygon>(); using (MemStorage storage1 = new MemStorage()) for (Contour<System.Drawing.Point> contours1 = image.FindContours(); contours1 != null; contours1 = contours1.HNext) { //Polygon Approximations Contour<System.Drawing.Point> contoursAP = contours1.ApproxPoly(contours1.Perimeter * 0.015, storage1); // 0.05 //Use area to wipe out the unnecessary result if (contours1.Area >= 200) { //Use vertices to determine the shape if (contoursAP.Total >= 4) // > 4 { System.Drawing.Point[] points = contoursAP.ToArray(); polyList.Add(new CropPolygon(points)); } } } return polyList; } private CropPolygon GetLargestPolygon(List<CropPolygon> polyList) { double maxArea = 0; CropPolygon largetPoly = new CropPolygon(); foreach (CropPolygon p in polyList) { if (maxArea < p.Area()) { maxArea = p.Area(); largetPoly = p; } } return largetPoly; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Newtonsoft.Json; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Util; namespace QuantConnect { /// <summary> /// Defines a unique identifier for securities /// </summary> /// <remarks> /// The SecurityIdentifier contains information about a specific security. /// This includes the symbol and other data specific to the SecurityType. /// The symbol is limited to 12 characters /// </remarks> [JsonConverter(typeof(SecurityIdentifierJsonConverter))] public struct SecurityIdentifier : IEquatable<SecurityIdentifier> { #region Empty, DefaultDate Fields private static readonly string MapFileProviderTypeName = Config.Get("map-file-provider", "LocalDiskMapFileProvider"); private static readonly char[] InvalidCharacters = {'|', ' '}; /// <summary> /// Gets an instance of <see cref="SecurityIdentifier"/> that is empty, that is, one with no symbol specified /// </summary> public static readonly SecurityIdentifier Empty = new SecurityIdentifier(string.Empty, 0); /// <summary> /// Gets the date to be used when it does not apply. /// </summary> public static readonly DateTime DefaultDate = DateTime.FromOADate(0); /// <summary> /// Gets the set of invalids symbol characters /// </summary> public static readonly HashSet<char> InvalidSymbolCharacters = new HashSet<char>(InvalidCharacters); #endregion #region Scales, Widths and Market Maps // these values define the structure of the 'otherData' // the constant width fields are used via modulus, so the width is the number of zeros specified, // {put/call:1}{oa-date:5}{style:1}{strike:6}{strike-scale:2}{market:3}{security-type:2} private const ulong SecurityTypeWidth = 100; private const ulong SecurityTypeOffset = 1; private const ulong MarketWidth = 1000; private const ulong MarketOffset = SecurityTypeOffset * SecurityTypeWidth; private const int StrikeDefaultScale = 4; private static readonly ulong StrikeDefaultScaleExpanded = Pow(10, StrikeDefaultScale); private const ulong StrikeScaleWidth = 100; private const ulong StrikeScaleOffset = MarketOffset * MarketWidth; private const ulong StrikeWidth = 1000000; private const ulong StrikeOffset = StrikeScaleOffset * StrikeScaleWidth; private const ulong OptionStyleWidth = 10; private const ulong OptionStyleOffset = StrikeOffset * StrikeWidth; private const ulong DaysWidth = 100000; private const ulong DaysOffset = OptionStyleOffset * OptionStyleWidth; private const ulong PutCallOffset = DaysOffset * DaysWidth; private const ulong PutCallWidth = 10; #endregion #region Member variables private readonly string _symbol; private readonly ulong _properties; private readonly SidBox _underlying; #endregion #region Properties /// <summary> /// Gets whether or not this <see cref="SecurityIdentifier"/> is a derivative, /// that is, it has a valid <see cref="Underlying"/> property /// </summary> public bool HasUnderlying { get { return _underlying != null; } } /// <summary> /// Gets the underlying security identifier for this security identifier. When there is /// no underlying, this property will return a value of <see cref="Empty"/>. /// </summary> public SecurityIdentifier Underlying { get { if (_underlying == null) { throw new InvalidOperationException("No underlying specified for this identifier. Check that HasUnderlying is true before accessing the Underlying property."); } return _underlying.SecurityIdentifier; } } /// <summary> /// Gets the date component of this identifier. For equities this /// is the first date the security traded. Technically speaking, /// in LEAN, this is the first date mentioned in the map_files. /// For options this is the expiry date. For futures this is the /// settlement date. For forex and cfds this property will throw an /// exception as the field is not specified. /// </summary> public DateTime Date { get { var stype = SecurityType; switch (stype) { case SecurityType.Equity: case SecurityType.Option: case SecurityType.Future: var oadate = ExtractFromProperties(DaysOffset, DaysWidth); return DateTime.FromOADate(oadate); default: throw new InvalidOperationException("Date is only defined for SecurityType.Equity, SecurityType.Option and SecurityType.Future"); } } } /// <summary> /// Gets the original symbol used to generate this security identifier. /// For equities, by convention this is the first ticker symbol for which /// the security traded /// </summary> public string Symbol { get { return _symbol; } } /// <summary> /// Gets the market component of this security identifier. If located in the /// internal mappings, the full string is returned. If the value is unknown, /// the integer value is returned as a string. /// </summary> public string Market { get { var marketCode = ExtractFromProperties(MarketOffset, MarketWidth); var market = QuantConnect.Market.Decode((int)marketCode); // if we couldn't find it, send back the numeric representation return market ?? marketCode.ToString(); } } /// <summary> /// Gets the security type component of this security identifier. /// </summary> public SecurityType SecurityType { get { return (SecurityType)ExtractFromProperties(SecurityTypeOffset, SecurityTypeWidth); } } /// <summary> /// Gets the option strike price. This only applies to SecurityType.Option /// and will thrown anexception if accessed otherwse. /// </summary> public decimal StrikePrice { get { if (SecurityType != SecurityType.Option) { throw new InvalidOperationException("OptionType is only defined for SecurityType.Option"); } var scale = ExtractFromProperties(StrikeScaleOffset, StrikeScaleWidth); var unscaled = ExtractFromProperties(StrikeOffset, StrikeWidth); var pow = Math.Pow(10, (int)scale - StrikeDefaultScale); return unscaled * (decimal)pow; } } /// <summary> /// Gets the option type component of this security identifier. This /// only applies to SecurityType.Open and will throw an exception if /// accessed otherwise. /// </summary> public OptionRight OptionRight { get { if (SecurityType != SecurityType.Option) { throw new InvalidOperationException("OptionRight is only defined for SecurityType.Option"); } return (OptionRight)ExtractFromProperties(PutCallOffset, PutCallWidth); } } /// <summary> /// Gets the option style component of this security identifier. This /// only applies to SecurityType.Open and will throw an exception if /// accessed otherwise. /// </summary> public OptionStyle OptionStyle { get { if (SecurityType != SecurityType.Option) { throw new InvalidOperationException("OptionStyle is only defined for SecurityType.Option"); } return (OptionStyle)(ExtractFromProperties(OptionStyleOffset, OptionStyleWidth)); } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SecurityIdentifier"/> class /// </summary> /// <param name="symbol">The base36 string encoded as a long using alpha [0-9A-Z]</param> /// <param name="properties">Other data defining properties of the symbol including market, /// security type, listing or expiry date, strike/call/put/style for options, ect...</param> public SecurityIdentifier(string symbol, ulong properties) { if (symbol == null) { throw new ArgumentNullException("symbol", "SecurityIdentifier requires a non-null string 'symbol'"); } if (symbol.IndexOfAny(InvalidCharacters) != -1) { throw new ArgumentException("symbol must not contain the characters '|' or ' '.", "symbol"); } _symbol = symbol; _properties = properties; _underlying = null; } /// <summary> /// Initializes a new instance of the <see cref="SecurityIdentifier"/> class /// </summary> /// <param name="symbol">The base36 string encoded as a long using alpha [0-9A-Z]</param> /// <param name="properties">Other data defining properties of the symbol including market, /// security type, listing or expiry date, strike/call/put/style for options, ect...</param> /// <param name="underlying">Specifies a <see cref="SecurityIdentifier"/> that represents the underlying security</param> public SecurityIdentifier(string symbol, ulong properties, SecurityIdentifier underlying) : this(symbol, properties) { if (symbol == null) { throw new ArgumentNullException("symbol", "SecurityIdentifier requires a non-null string 'symbol'"); } _symbol = symbol; _properties = properties; if (underlying != Empty) { _underlying = new SidBox(underlying); } } #endregion #region AddMarket, GetMarketCode, and Generate /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for an option /// </summary> /// <param name="expiry">The date the option expires</param> /// <param name="underlying">The underlying security's symbol</param> /// <param name="market">The market</param> /// <param name="strike">The strike price</param> /// <param name="optionRight">The option type, call or put</param> /// <param name="optionStyle">The option style, American or European</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified option security</returns> public static SecurityIdentifier GenerateOption(DateTime expiry, SecurityIdentifier underlying, string market, decimal strike, OptionRight optionRight, OptionStyle optionStyle) { return Generate(expiry, underlying.Symbol, SecurityType.Option, market, strike, optionRight, optionStyle, underlying); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a future /// </summary> /// <param name="expiry">The date the future expires</param> /// <param name="symbol">The security's symbol</param> /// <param name="market">The market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified futures security</returns> public static SecurityIdentifier GenerateFuture(DateTime expiry, string symbol, string market) { return Generate(expiry, symbol, SecurityType.Future, market); } /// <summary> /// Helper overload that will search the mapfiles to resolve the first date. This implementation /// uses the configured <see cref="IMapFileProvider"/> via the <see cref="Composer.Instance"/> /// </summary> /// <param name="symbol">The symbol as it is known today</param> /// <param name="market">The market</param> /// <param name="mapSymbol">Specifies if symbol should be mapped using map file provider</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified symbol today</returns> public static SecurityIdentifier GenerateEquity(string symbol, string market, bool mapSymbol = true) { if (mapSymbol) { var provider = Composer.Instance.GetExportedValueByTypeName<IMapFileProvider>(MapFileProviderTypeName); var resolver = provider.Get(market); var mapFile = resolver.ResolveMapFile(symbol, DateTime.Today); var firstDate = mapFile.FirstDate; if (mapFile.Any()) { symbol = mapFile.OrderBy(x => x.Date).First().MappedSymbol; } return GenerateEquity(firstDate, symbol, market); } else { return GenerateEquity(DefaultDate, symbol, market); } } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for an equity /// </summary> /// <param name="date">The first date this security traded (in LEAN this is the first date in the map_file</param> /// <param name="symbol">The ticker symbol this security traded under on the <paramref name="date"/></param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified equity security</returns> public static SecurityIdentifier GenerateEquity(DateTime date, string symbol, string market) { return Generate(date, symbol, SecurityType.Equity, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a custom security /// </summary> /// <param name="symbol">The ticker symbol of this security</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified base security</returns> public static SecurityIdentifier GenerateBase(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Base, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a forex pair /// </summary> /// <param name="symbol">The currency pair in the format similar to: 'EURUSD'</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified forex pair</returns> public static SecurityIdentifier GenerateForex(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Forex, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a Crypto pair /// </summary> /// <param name="symbol">The currency pair in the format similar to: 'EURUSD'</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified Crypto pair</returns> public static SecurityIdentifier GenerateCrypto(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Crypto, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a CFD security /// </summary> /// <param name="symbol">The CFD contract symbol</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified CFD security</returns> public static SecurityIdentifier GenerateCfd(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Cfd, market); } /// <summary> /// Generic generate method. This method should be used carefully as some parameters are not required and /// some parameters mean different things for different security types /// </summary> private static SecurityIdentifier Generate(DateTime date, string symbol, SecurityType securityType, string market, decimal strike = 0, OptionRight optionRight = 0, OptionStyle optionStyle = 0, SecurityIdentifier? underlying = null) { if ((ulong)securityType >= SecurityTypeWidth || securityType < 0) { throw new ArgumentOutOfRangeException("securityType", "securityType must be between 0 and 99"); } if ((int)optionRight > 1 || optionRight < 0) { throw new ArgumentOutOfRangeException("optionRight", "optionType must be either 0 or 1"); } // normalize input strings market = market.ToLower(); symbol = symbol.ToUpper(); var marketIdentifier = QuantConnect.Market.Encode(market); if (!marketIdentifier.HasValue) { throw new ArgumentOutOfRangeException("market", string.Format("The specified market wasn't found in the markets lookup. Requested: {0}. " + "You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)", market)); } var days = (ulong)date.ToOADate() * DaysOffset; var marketCode = (ulong)marketIdentifier * MarketOffset; ulong strikeScale; var strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset; strikeScale *= StrikeScaleOffset; var style = (ulong)optionStyle * OptionStyleOffset; var putcall = (ulong)optionRight * PutCallOffset; var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType; return new SecurityIdentifier(symbol, otherData, underlying ?? Empty); } /// <summary> /// Converts an upper case alpha numeric string into a long /// </summary> private static ulong DecodeBase36(string symbol) { var result = 0ul; var baseValue = 1ul; for (var i = symbol.Length - 1; i > -1; i--) { var c = symbol[i]; // assumes alpha numeric upper case only strings var value = (uint)(c <= 57 ? c - '0' : c - 'A' + 10); result += baseValue * value; baseValue *= 36; } return result; } /// <summary> /// Converts a long to an uppercase alpha numeric string /// </summary> private static string EncodeBase36(ulong data) { var stack = new Stack<char>(); while (data != 0) { var value = data % 36; var c = value < 10 ? (char)(value + '0') : (char)(value - 10 + 'A'); stack.Push(c); data /= 36; } return new string(stack.ToArray()); } /// <summary> /// The strike is normalized into deci-cents and then a scale factor /// is also saved to bring it back to un-normalized /// </summary> private static ulong NormalizeStrike(decimal strike, out ulong scale) { var str = strike; if (strike == 0) { scale = 0; return 0; } // convert strike to default scaling, this keeps the scale always positive strike *= StrikeDefaultScaleExpanded; scale = 0; while (strike % 10 == 0) { strike /= 10; scale++; } if (strike >= 1000000) { throw new ArgumentException("The specified strike price's precision is too high: " + str); } return (ulong)strike; } /// <summary> /// Accurately performs the integer exponentiation /// </summary> private static ulong Pow(uint x, int pow) { // don't use Math.Pow(double, double) due to precision issues return (ulong)BigInteger.Pow(x, pow); } #endregion #region Parsing routines /// <summary> /// Parses the specified string into a <see cref="SecurityIdentifier"/> /// The string must be a 40 digit number. The first 20 digits must be parseable /// to a 64 bit unsigned integer and contain ancillary data about the security. /// The second 20 digits must also be parseable as a 64 bit unsigned integer and /// contain the symbol encoded from base36, this provides for 12 alpha numeric case /// insensitive characters. /// </summary> /// <param name="value">The string value to be parsed</param> /// <returns>A new <see cref="SecurityIdentifier"/> instance if the <paramref name="value"/> is able to be parsed.</returns> /// <exception cref="FormatException">This exception is thrown if the string's length is not exactly 40 characters, or /// if the components are unable to be parsed as 64 bit unsigned integers</exception> public static SecurityIdentifier Parse(string value) { Exception exception; SecurityIdentifier identifier; if (!TryParse(value, out identifier, out exception)) { throw exception; } return identifier; } /// <summary> /// Attempts to parse the specified <see paramref="value"/> as a <see cref="SecurityIdentifier"/>. /// </summary> /// <param name="value">The string value to be parsed</param> /// <param name="identifier">The result of parsing, when this function returns true, <paramref name="identifier"/> /// was properly created and reflects the input string, when this function returns false <paramref name="identifier"/> /// will equal default(SecurityIdentifier)</param> /// <returns>True on success, otherwise false</returns> public static bool TryParse(string value, out SecurityIdentifier identifier) { Exception exception; return TryParse(value, out identifier, out exception); } /// <summary> /// Helper method impl to be used by parse and tryparse /// </summary> private static bool TryParse(string value, out SecurityIdentifier identifier, out Exception exception) { if (!TryParseProperties(value, out exception, out identifier)) { return false; } return true; } private static readonly char[] SplitSpace = {' '}; /// <summary> /// Parses the string into its component ulong pieces /// </summary> private static bool TryParseProperties(string value, out Exception exception, out SecurityIdentifier identifier) { exception = null; identifier = Empty; if (string.IsNullOrWhiteSpace(value)) { return true; } try { var sids = value.Split('|'); for (var i = sids.Length - 1; i > -1; i--) { var current = sids[i]; var parts = current.Split(SplitSpace, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { exception = new FormatException("The string must be splittable on space into two parts."); return false; } var symbol = parts[0]; var otherData = parts[1]; var props = DecodeBase36(otherData); // toss the previous in as the underlying, if Empty, ignored by ctor identifier = new SecurityIdentifier(symbol, props, identifier); } } catch (Exception error) { exception = error; Log.Error("SecurityIdentifier.TryParseProperties(): Error parsing SecurityIdentifier: '{0}', Exception: {1}", value, exception); return false; } return true; } /// <summary> /// Extracts the embedded value from _otherData /// </summary> private ulong ExtractFromProperties(ulong offset, ulong width) { return (_properties/offset)%width; } #endregion #region Equality members and ToString /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(SecurityIdentifier other) { return _properties == other._properties && _symbol == other._symbol && _underlying == other._underlying; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// true if the specified object is equal to the current object; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != GetType()) return false; return Equals((SecurityIdentifier)obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> /// <filterpriority>2</filterpriority> public override int GetHashCode() { unchecked { return (_symbol.GetHashCode()*397) ^ _properties.GetHashCode(); } } /// <summary> /// Override equals operator /// </summary> public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right) { return Equals(left, right); } /// <summary> /// Override not equals operator /// </summary> public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right) { return !Equals(left, right); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { var props = EncodeBase36(_properties); if (HasUnderlying) { return _symbol + ' ' + props + '|' + _underlying.SecurityIdentifier; } return _symbol + ' ' + props; } #endregion /// <summary> /// Provides a reference type container for a security identifier instance. /// This is used to maintain a reference to an underlying /// </summary> private sealed class SidBox : IEquatable<SidBox> { public readonly SecurityIdentifier SecurityIdentifier; public SidBox(SecurityIdentifier securityIdentifier) { SecurityIdentifier = securityIdentifier; } public bool Equals(SidBox other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return SecurityIdentifier.Equals(other.SecurityIdentifier); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is SidBox && Equals((SidBox)obj); } public override int GetHashCode() { return SecurityIdentifier.GetHashCode(); } public static bool operator ==(SidBox left, SidBox right) { return Equals(left, right); } public static bool operator !=(SidBox left, SidBox right) { return !Equals(left, right); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using PlayFab.Internal; using UnityEngine; namespace PlayFab.Public { #if !UNITY_WSA && !UNITY_WP8 && !NETFX_CORE public interface IPlayFabLogger { IPAddress ip { get; set; } int port { get; set; } string url { get; set; } // Unity MonoBehaviour callbacks void OnEnable(); void OnDisable(); void OnDestroy(); } /// <summary> /// This is some unity-log capturing logic, and threading tools that allow logging to be caught and processed on another thread /// </summary> public abstract class PlayFabLoggerBase : IPlayFabLogger { private static readonly StringBuilder Sb = new StringBuilder(); private readonly Queue<string> LogMessageQueue = new Queue<string>(); private const int LOG_CACHE_INTERVAL_MS = 10000; private Thread _writeLogThread; private readonly object _threadLock = new object(); private static readonly TimeSpan _threadKillTimeout = TimeSpan.FromSeconds(60); private DateTime _threadKillTime = DateTime.UtcNow + _threadKillTimeout; // Kill the thread after 1 minute of inactivity private bool _isApplicationPlaying = true; private int _pendingLogsCount; public IPAddress ip { get; set; } public int port { get; set; } public string url { get; set; } protected PlayFabLoggerBase() { var gatherer = new PlayFabDataGatherer(); var message = gatherer.GenerateReport(); lock (LogMessageQueue) { LogMessageQueue.Enqueue(message); } } public virtual void OnEnable() { PlayFabHttp.instance.StartCoroutine(RegisterLogger()); // Coroutine helper to set up log-callbacks } private IEnumerator RegisterLogger() { yield return new WaitForEndOfFrame(); // Effectively just a short wait before activating this registration if (!string.IsNullOrEmpty(PlayFabSettings.LoggerHost)) { #if UNITY_5 || UNITY_5_3_OR_NEWER Application.logMessageReceivedThreaded += HandleUnityLog; #else Application.RegisterLogCallback(HandleUnityLog); #endif } } public virtual void OnDisable() { if (!string.IsNullOrEmpty(PlayFabSettings.LoggerHost)) { #if UNITY_5 || UNITY_5_3_OR_NEWER Application.logMessageReceivedThreaded -= HandleUnityLog; #else Application.RegisterLogCallback(null); #endif } } public virtual void OnDestroy() { _isApplicationPlaying = false; } /// <summary> /// Logs are cached and written in bursts /// BeginUploadLog is called at the begining of each burst /// </summary> protected abstract void BeginUploadLog(); /// <summary> /// Logs are cached and written in bursts /// UploadLog is called for each cached log, between BeginUploadLog and EndUploadLog /// </summary> protected abstract void UploadLog(string message); /// <summary> /// Logs are cached and written in bursts /// EndUploadLog is called at the end of each burst /// </summary> protected abstract void EndUploadLog(); /// <summary> /// Handler to process Unity logs into our logging system /// </summary> /// <param name="message"></param> /// <param name="stacktrace"></param> /// <param name="type"></param> private void HandleUnityLog(string message, string stacktrace, LogType type) { if (!PlayFabSettings.EnableRealTimeLogging) return; Sb.Length = 0; if (type == LogType.Log || type == LogType.Warning) { Sb.Append(type).Append(": ").Append(message); message = Sb.ToString(); lock (LogMessageQueue) { LogMessageQueue.Enqueue(message); } } else if (type == LogType.Error || type == LogType.Exception) { Sb.Append(type).Append(": ").Append(message).Append("\n").Append(stacktrace).Append(StackTraceUtility.ExtractStackTrace()); message = Sb.ToString(); lock (LogMessageQueue) { LogMessageQueue.Enqueue(message); } } ActivateThreadWorker(); } private void ActivateThreadWorker() { lock (_threadLock) { if (_writeLogThread != null) { return; } _writeLogThread = new Thread(WriteLogThreadWorker); _writeLogThread.Start(); } } private void WriteLogThreadWorker() { try { bool active; lock (_threadLock) { // Kill the thread after 1 minute of inactivity _threadKillTime = DateTime.UtcNow + _threadKillTimeout; } var localLogQueue = new Queue<string>(); do { lock (LogMessageQueue) { _pendingLogsCount = LogMessageQueue.Count; while (LogMessageQueue.Count > 0) // Transfer the messages to the local queue localLogQueue.Enqueue(LogMessageQueue.Dequeue()); } BeginUploadLog(); while (localLogQueue.Count > 0) // Transfer the messages to the local queue UploadLog(localLogQueue.Dequeue()); EndUploadLog(); #region Expire Thread. // Check if we've been inactive lock (_threadLock) { var now = DateTime.UtcNow; if (_pendingLogsCount > 0 && _isApplicationPlaying) { // Still active, reset the _threadKillTime _threadKillTime = now + _threadKillTimeout; } // Kill the thread after 1 minute of inactivity active = now <= _threadKillTime; if (!active) { _writeLogThread = null; } // This thread will be stopped, so null this now, inside lock (_threadLock) } #endregion Thread.Sleep(LOG_CACHE_INTERVAL_MS); } while (active); } catch (Exception e) { Debug.LogException(e); _writeLogThread = null; } } } #else public interface IPlayFabLogger { string ip { get; set; } int port { get; set; } string url { get; set; } // Unity MonoBehaviour callbacks void OnEnable(); void OnDisable(); void OnDestroy(); } /// <summary> /// This is just a placeholder. WP8 doesn't support direct threading, but instead makes you use the await command. /// </summary> public abstract class PlayFabLoggerBase : IPlayFabLogger { public string ip { get; set; } public int port { get; set; } public string url { get; set; } // Unity MonoBehaviour callbacks public void OnEnable() { } public void OnDisable() { } public void OnDestroy() { } protected abstract void BeginUploadLog(); protected abstract void UploadLog(string message); protected abstract void EndUploadLog(); } #endif /// <summary> /// This translates the logs up to the PlayFab service via a PlayFab restful API /// TODO: PLAYFAB - attach these to the PlayFab API /// </summary> public class PlayFabLogger : PlayFabLoggerBase { /// <summary> /// Logs are cached and written in bursts /// BeginUploadLog is called at the begining of each burst /// </summary> protected override void BeginUploadLog() { } /// <summary> /// Logs are cached and written in bursts /// UploadLog is called for each cached log, between BeginUploadLog and EndUploadLog /// </summary> protected override void UploadLog(string message) { } /// <summary> /// Logs are cached and written in bursts /// EndUploadLog is called at the end of each burst /// </summary> protected override void EndUploadLog() { } } }
// <copyright file="RealtimeManager.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.PInvoke { using System; using System.Linq; using GooglePlayGames.OurUtils; using System.Collections.Generic; using C = GooglePlayGames.Native.Cwrapper.RealTimeMultiplayerManager; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; using MultiplayerStatus = GooglePlayGames.Native.Cwrapper.CommonErrorStatus.MultiplayerStatus; using System.Runtime.InteropServices; internal class RealtimeManager { private readonly GameServices mGameServices; internal RealtimeManager(GameServices gameServices) { this.mGameServices = Misc.CheckNotNull(gameServices); } internal void CreateRoom(RealtimeRoomConfig config, RealTimeEventListenerHelper helper, Action<RealTimeRoomResponse> callback) { C.RealTimeMultiplayerManager_CreateRealTimeRoom(mGameServices.AsHandle(), config.AsPointer(), helper.AsPointer(), InternalRealTimeRoomCallback, ToCallbackPointer(callback)); } internal void ShowPlayerSelectUI(uint minimumPlayers, uint maxiumPlayers, bool allowAutomatching, Action<PlayerSelectUIResponse> callback) { C.RealTimeMultiplayerManager_ShowPlayerSelectUI(mGameServices.AsHandle(), minimumPlayers, maxiumPlayers, allowAutomatching, InternalPlayerSelectUIcallback, Callbacks.ToIntPtr(callback, PlayerSelectUIResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.PlayerSelectUICallback))] internal static void InternalPlayerSelectUIcallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#PlayerSelectUICallback", Callbacks.Type.Temporary, response, data); } [AOT.MonoPInvokeCallback(typeof(C.RealTimeRoomCallback))] internal static void InternalRealTimeRoomCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalRealTimeRoomCallback", Callbacks.Type.Temporary, response, data); } [AOT.MonoPInvokeCallback(typeof(C.RoomInboxUICallback))] internal static void InternalRoomInboxUICallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalRoomInboxUICallback", Callbacks.Type.Temporary, response, data); } internal void ShowRoomInboxUI(Action<RoomInboxUIResponse> callback) { C.RealTimeMultiplayerManager_ShowRoomInboxUI(mGameServices.AsHandle(), InternalRoomInboxUICallback, Callbacks.ToIntPtr(callback, RoomInboxUIResponse.FromPointer)); } internal void ShowWaitingRoomUI(NativeRealTimeRoom room, uint minimumParticipantsBeforeStarting, Action<WaitingRoomUIResponse> callback) { Misc.CheckNotNull(room); C.RealTimeMultiplayerManager_ShowWaitingRoomUI(mGameServices.AsHandle(), room.AsPointer(), minimumParticipantsBeforeStarting, InternalWaitingRoomUICallback, Callbacks.ToIntPtr(callback, WaitingRoomUIResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.WaitingRoomUICallback))] internal static void InternalWaitingRoomUICallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalWaitingRoomUICallback", Callbacks.Type.Temporary, response, data); } [AOT.MonoPInvokeCallback(typeof(C.FetchInvitationsCallback))] internal static void InternalFetchInvitationsCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalFetchInvitationsCallback", Callbacks.Type.Temporary, response, data); } internal void FetchInvitations(Action<FetchInvitationsResponse> callback) { C.RealTimeMultiplayerManager_FetchInvitations(mGameServices.AsHandle(), InternalFetchInvitationsCallback, Callbacks.ToIntPtr(callback, FetchInvitationsResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.LeaveRoomCallback))] internal static void InternalLeaveRoomCallback(Status.ResponseStatus response, IntPtr data) { Logger.d("Entering internal callback for InternalLeaveRoomCallback"); Action<Status.ResponseStatus> callback = Callbacks.IntPtrToTempCallback<Action<Status.ResponseStatus>>(data); if (callback == null) { return; } try { callback(response); } catch (Exception e) { Logger.e("Error encountered executing InternalLeaveRoomCallback. " + "Smothering to avoid passing exception into Native: " + e); } } internal void LeaveRoom(NativeRealTimeRoom room, Action<Status.ResponseStatus> callback) { C.RealTimeMultiplayerManager_LeaveRoom(mGameServices.AsHandle(), room.AsPointer(), InternalLeaveRoomCallback, Callbacks.ToIntPtr(callback)); } internal void AcceptInvitation(MultiplayerInvitation invitation, RealTimeEventListenerHelper listener, Action<RealTimeRoomResponse> callback) { C.RealTimeMultiplayerManager_AcceptInvitation(mGameServices.AsHandle(), invitation.AsPointer(), listener.AsPointer(), InternalRealTimeRoomCallback, ToCallbackPointer(callback)); } internal void DeclineInvitation(MultiplayerInvitation invitation) { C.RealTimeMultiplayerManager_DeclineInvitation(mGameServices.AsHandle(), invitation.AsPointer()); } internal void SendReliableMessage(NativeRealTimeRoom room, MultiplayerParticipant participant, byte[] data, Action<Status.MultiplayerStatus> callback) { C.RealTimeMultiplayerManager_SendReliableMessage(mGameServices.AsHandle(), room.AsPointer(), participant.AsPointer(), data, PInvokeUtilities.ArrayToSizeT(data), InternalSendReliableMessageCallback, Callbacks.ToIntPtr(callback)); } [AOT.MonoPInvokeCallback(typeof(C.SendReliableMessageCallback))] internal static void InternalSendReliableMessageCallback(Status.MultiplayerStatus response, IntPtr data) { Logger.d("Entering internal callback for InternalSendReliableMessageCallback " + response); Action<Status.MultiplayerStatus> callback = Callbacks.IntPtrToTempCallback<Action<Status.MultiplayerStatus>>(data); if (callback == null) { return; } try { callback(response); } catch (Exception e) { Logger.e("Error encountered executing InternalSendReliableMessageCallback. " + "Smothering to avoid passing exception into Native: " + e); } } internal void SendUnreliableMessageToAll(NativeRealTimeRoom room, byte[] data) { C.RealTimeMultiplayerManager_SendUnreliableMessageToOthers(mGameServices.AsHandle(), room.AsPointer(), data, PInvokeUtilities.ArrayToSizeT(data)); } internal void SendUnreliableMessageToSpecificParticipants(NativeRealTimeRoom room, List<MultiplayerParticipant> recipients, byte[] data) { C.RealTimeMultiplayerManager_SendUnreliableMessage( mGameServices.AsHandle(), room.AsPointer(), recipients.Select(r => r.AsPointer()).ToArray(), new UIntPtr((ulong)recipients.LongCount()), data, PInvokeUtilities.ArrayToSizeT(data)); } private static IntPtr ToCallbackPointer(Action<RealTimeRoomResponse> callback) { return Callbacks.ToIntPtr<RealTimeRoomResponse>( callback, RealTimeRoomResponse.FromPointer ); } internal class RealTimeRoomResponse : BaseReferenceHolder { internal RealTimeRoomResponse(IntPtr selfPointer) : base(selfPointer) { } internal Status.MultiplayerStatus ResponseStatus() { return C.RealTimeMultiplayerManager_RealTimeRoomResponse_GetStatus(SelfPtr()); } internal bool RequestSucceeded() { return ResponseStatus() > 0; } internal NativeRealTimeRoom Room() { if (!RequestSucceeded()) { return null; } return new NativeRealTimeRoom( C.RealTimeMultiplayerManager_RealTimeRoomResponse_GetRoom(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_RealTimeRoomResponse_Dispose(selfPointer); } internal static RealTimeRoomResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new RealTimeRoomResponse(pointer); } } internal class RoomInboxUIResponse : BaseReferenceHolder { internal RoomInboxUIResponse(IntPtr selfPointer) : base(selfPointer) { } internal Status.UIStatus ResponseStatus() { return C.RealTimeMultiplayerManager_RoomInboxUIResponse_GetStatus(SelfPtr()); } internal MultiplayerInvitation Invitation() { if (ResponseStatus() != Status.UIStatus.VALID) { return null; } return new MultiplayerInvitation( C.RealTimeMultiplayerManager_RoomInboxUIResponse_GetInvitation(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_RoomInboxUIResponse_Dispose(selfPointer); } internal static RoomInboxUIResponse FromPointer(IntPtr pointer) { if (PInvokeUtilities.IsNull(pointer)) { return null; } return new RoomInboxUIResponse(pointer); } } internal class WaitingRoomUIResponse : BaseReferenceHolder { internal WaitingRoomUIResponse(IntPtr selfPointer) : base(selfPointer) { } internal Status.UIStatus ResponseStatus() { return C.RealTimeMultiplayerManager_WaitingRoomUIResponse_GetStatus(SelfPtr()); } internal NativeRealTimeRoom Room() { if (ResponseStatus() != Status.UIStatus.VALID) { return null; } return new NativeRealTimeRoom( C.RealTimeMultiplayerManager_WaitingRoomUIResponse_GetRoom(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_WaitingRoomUIResponse_Dispose(selfPointer); } internal static WaitingRoomUIResponse FromPointer(IntPtr pointer) { if (PInvokeUtilities.IsNull(pointer)) { return null; } return new WaitingRoomUIResponse(pointer); } } internal class FetchInvitationsResponse : BaseReferenceHolder { internal FetchInvitationsResponse(IntPtr selfPointer) : base(selfPointer) { } internal bool RequestSucceeded() { return ResponseStatus() > 0; } internal Status.ResponseStatus ResponseStatus() { return C.RealTimeMultiplayerManager_FetchInvitationsResponse_GetStatus(SelfPtr()); } internal IEnumerable<MultiplayerInvitation> Invitations() { return PInvokeUtilities.ToEnumerable( C.RealTimeMultiplayerManager_FetchInvitationsResponse_GetInvitations_Length( SelfPtr()), index => new MultiplayerInvitation( C.RealTimeMultiplayerManager_FetchInvitationsResponse_GetInvitations_GetElement( SelfPtr(), index)) ); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_FetchInvitationsResponse_Dispose(selfPointer); } internal static FetchInvitationsResponse FromPointer(IntPtr pointer) { if (PInvokeUtilities.IsNull(pointer)) { return null; } return new FetchInvitationsResponse(pointer); } } } } #endif
/* ==================================================================== 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. ==================================================================== */ /* ==================================================================== This product Contains an ASLv2 licensed version of the OOXML signer package from the eID Applet project http://code.google.com/p/eid-applet/source/browse/tRunk/README.txt Copyright (C) 2008-2014 FedICT. ================================================================= */ namespace NPOI.POIFS.Crypt.Dsig { using NPOI.OpenXml4Net.OPC; using NPOI.Util; using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Xml; using System.Xml.XPath; /** * <p>This class is the default entry point for XML signatures and can be used for * validating an existing signed office document and signing a office document.</p> * * <p><b>Validating a signed office document</b></p> * * <pre> * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ); * SignatureConfig sic = new SignatureConfig(); * sic.setOpcPackage(pkg); * SignatureInfo si = new SignatureInfo(); * si.setSignatureConfig(sic); * boolean isValid = si.validate(); * ... * </pre> * * <p><b>Signing an office document</b></p> * * <pre> * // loading the keystore - pkcs12 is used here, but of course jks &amp; co are also valid * // the keystore needs to contain a private key and it's certificate having a * // 'digitalSignature' key usage * char password[] = "test".toCharArray(); * File file = new File("test.pfx"); * KeyStore keystore = KeyStore.getInstance("PKCS12"); * FileInputStream fis = new FileInputStream(file); * keystore.load(fis, password); * fis.close(); * * // extracting private key and certificate * String alias = "xyz"; // alias of the keystore entry * Key key = keystore.getKey(alias, password); * X509Certificate x509 = (X509Certificate)keystore.getCertificate(alias); * * // filling the SignatureConfig entries (minimum fields, more options are available ...) * SignatureConfig signatureConfig = new SignatureConfig(); * signatureConfig.setKey(keyPair.getPrivate()); * signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ_WRITE); * signatureConfig.setOpcPackage(pkg); * * // adding the signature document to the package * SignatureInfo si = new SignatureInfo(); * si.setSignatureConfig(signatureConfig); * si.confirmSignature(); * // optionally verify the generated signature * boolean b = si.verifySignature(); * assert (b); * // write the changes back to disc * pkg.close(); * </pre> * * <p><b>Implementation notes:</b></p> * * <p>Although there's a XML signature implementation in the Oracle JDKs 6 and higher, * compatibility with IBM JDKs is also in focus (... but maybe not thoroughly tested ...). * Therefore we are using the Apache Santuario libs (xmlsec) instead of the built-in classes, * as the compatibility seems to be provided there.</p> * * <p>To use SignatureInfo and its sibling classes, you'll need to have the following libs * in the classpath:</p> * <ul> * <li>BouncyCastle bcpkix and bcprov (tested against 1.51)</li> * <li>Apache Santuario "xmlsec" (tested against 2.0.1)</li> * <li>and slf4j-api (tested against 1.7.7)</li> * </ul> */ public class SignatureInfo : ISignatureConfigurable { //private static POILogger LOG = POILogFactory.GetLogger(typeof(SignatureInfo)); private static bool IsInitialized = false; protected internal SignatureConfig signatureConfig; public class SignaturePart { private PackagePart signaturePart; private X509Certificate signer; private List<X509Certificate> certChain; private SignaturePart(PackagePart signaturePart) { this.signaturePart = signaturePart; } /** * @return the package part Containing the signature */ public PackagePart GetPackagePart() { return signaturePart; } /** * @return the signer certificate */ public X509Certificate GetSigner() { return signer; } /** * @return the certificate chain of the signer */ public List<X509Certificate> GetCertChain() { return certChain; } /** * Helper method for examining the xml signature * * @return the xml signature document * @throws IOException if the xml signature doesn't exist or can't be read * @throws XmlException if the xml signature is malformed */ //public SignatureDocument GetSignatureDocument() { // // TODO: check for XXE // return SignatureDocument.Parse(signaturePart.InputStream); //} /** * @return true, when the xml signature is valid, false otherwise * * @throws EncryptedDocumentException if the signature can't be extracted or if its malformed */ public bool Validate() { // KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); // try { // XPathDocument doc = DocumentHelper.ReadDocument(signaturePart.InputStream); // XPath xpath = XPathFactory.NewInstance().newXPath(); // NodeList nl = (NodeList)xpath.Compile("//*[@Id]").Evaluate(doc, XPathConstants.NODESET); // for (int i = 0; i < nl.Length; i++) { // ((Element)nl.Item(i)).IdAttribute = (/*setter*/"Id", true); // } // DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, doc); // domValidateContext.Property = (/*setter*/"org.jcp.xml.dsig.validateManifests", Boolean.TRUE); // domValidateContext.URIDereferencer = (/*setter*/signatureConfig.UriDereferencer); // brokenJvmWorkaround(domValidateContext); // XMLSignatureFactory xmlSignatureFactory = signatureConfig.SignatureFactory; // XMLSignature xmlSignature = xmlSignatureFactory.UnmarshalXMLSignature(domValidateContext); // // TODO: replace with property when xml-sec patch is applied // foreach (Reference ref1 in (List<Reference>)xmlSignature.SignedInfo.References) { // SignatureFacet.BrokenJvmWorkaround(ref1); // } // foreach (XMLObject xo in (List<XMLObject>)xmlSignature.Objects) { // foreach (XMLStructure xs in (List<XMLStructure>)xo.Content) { // if (xs is Manifest) { // foreach (Reference ref1 in (List<Reference>)((Manifest)xs).References) { // SignatureFacet.BrokenJvmWorkaround(ref1); // } // } // } // } // bool valid = xmlSignature.Validate(domValidateContext); // if (valid) { // signer = keySelector.Signer; // certChain = keySelector.CertChain; // } // return valid; // } catch (Exception e) { // String s = "error in marshalling and validating the signature"; // LOG.Log(POILogger.ERROR, s, e); // throw new EncryptedDocumentException(s, e); // } throw new NotImplementedException(); } } /** * Constructor Initializes xml signature environment, if it hasn't been Initialized before */ public SignatureInfo() { InitXmlProvider(); } /** * @return the signature config */ public SignatureConfig GetSignatureConfig() { //return signatureConfig; throw new NotImplementedException(); } /** * @param signatureConfig the signature config, needs to be Set before a SignatureInfo object is used */ public void SetSignatureConfig(SignatureConfig signatureConfig) { //this.signatureConfig = signatureConfig; throw new NotImplementedException(); } /** * @return true, if first signature part is valid */ public bool VerifySignature() { // http://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html //foreach (SignaturePart sp in GetSignatureParts()) { // // only validate first part // return sp.Validate(); //} //return false; throw new NotImplementedException(); } /** * add the xml signature to the document * * @throws XMLSignatureException * @throws MarshalException */ public void ConfirmSignature() { XPathDocument document = DocumentHelper.CreateDocument(); // operate //DigestInfo digestInfo = preSign(document, null); // Setup: key material, signature value //byte[] signatureValue = signDigest(digestInfo.digestValue); // operate: postSign //postSign(document, signatureValue); throw new NotImplementedException(); } /** * Sign (encrypt) the digest with the private key. * Currently only rsa is supported. * * @param digest the hashed input * @return the encrypted hash */ public byte[] signDigest(byte[] digest) { Cipher cipher = CryptoFunctions.GetCipher(signatureConfig.GetKey(), CipherAlgorithm.rsa , ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1PAdding"); //try { // MemoryStream digestInfoValueBuf = new MemoryStream(); // digestInfoValueBuf.Write(signatureConfig.GetHashMagic()); // digestInfoValueBuf.Write(digest); // byte[] digestInfoValue = digestInfoValueBuf.ToArray(); // byte[] signatureValue = cipher.DoFinal(digestInfoValue); // return signatureValue; //} catch (Exception e) { // throw new EncryptedDocumentException(e); //} throw new NotImplementedException(); } /** * @return a signature part for each signature document. * the parts can be validated independently. */ public IEnumerable<SignaturePart> GetSignatureParts() { signatureConfig.Init(true); throw new NotImplementedException(); //return new Iterable<SignaturePart>() { // public Iterator<SignaturePart> iterator() { // return new Iterator<SignaturePart>() { // OPCPackage pkg = signatureConfig.OpcPackage; // Iterator<PackageRelationship> sigOrigRels = // pkg.GetRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN).iterator(); // Iterator<PackageRelationship> sigRels = null; // PackagePart sigPart = null; // public bool HasNext() { // while (sigRels == null || !sigRels.HasNext()) { // if (!sigOrigRels.HasNext()) return false; // sigPart = pkg.GetPart(sigOrigRels.Next()); // LOG.Log(POILogger.DEBUG, "Digital Signature Origin part", sigPart); // try { // sigRels = sigPart.GetRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE).iterator(); // } catch (InvalidFormatException e) { // LOG.Log(POILogger.WARN, "Reference to signature is invalid.", e); // } // } // return true; // } // public SignaturePart next() { // PackagePart sigRelPart = null; // do { // try { // if (!hasNext()) throw new NoSuchElementException(); // sigRelPart = sigPart.GetRelatedPart(sigRels.Next()); // LOG.Log(POILogger.DEBUG, "XML Signature part", sigRelPart); // } catch (InvalidFormatException e) { // LOG.Log(POILogger.WARN, "Reference to signature is invalid.", e); // } // } while (sigPart == null); // return new SignaturePart(sigRelPart); // } // public void Remove() { // throw new UnsupportedOperationException(); // } // }; // } //}; } /** * Initialize the xml signing environment and the bouncycastle provider */ protected static void InitXmlProvider() { //if (isInitialized) return; //isInitialized = true; //try { // Init.Init(); // RelationshipTransformService.RegisterDsigProvider(); // CryptoFunctions.RegisterBouncyCastle(); //} catch (Exception e) { // throw new Exception("Xml & BouncyCastle-Provider Initialization failed", e); //} throw new NotImplementedException(); } /** * Helper method for Adding informations before the signing. * Normally {@link #ConfirmSignature()} is sufficient to be used. */ public DigestInfo preSign(XmlDocument document, List<DigestInfo> digestInfos) { signatureConfig.Init(false); //// it's necessary to explicitly Set the mdssi namespace, but the sign() method has no //// normal way to interfere with, so we need to add the namespace under the hand ... //EventTarget target = (EventTarget)document; //EventListener creationListener = signatureConfig.SignatureMarshalListener; //if (creationListener != null) { // if (creationListener is SignatureMarshalListener) { // ((SignatureMarshalListener)creationListener).EventTarget = (/*setter*/target); // } // SignatureMarshalListener.Listener = (/*setter*/target, creationListener, true); //} ///* // * Signature context construction. // */ //XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.Key, document); //URIDereferencer uriDereferencer = signatureConfig.UriDereferencer; //if (null != uriDereferencer) { // xmlSignContext.URIDereferencer = (/*setter*/uriDereferencer); //} //foreach (Map.Entry<String, String> me in signatureConfig.NamespacePrefixes.EntrySet()) { // xmlSignContext.PutNamespacePrefix(me.Key, me.Value); //} //xmlSignContext.DefaultNamespacePrefix = (/*setter*/""); //// signatureConfig.NamespacePrefixes.Get(XML_DIGSIG_NS)); //brokenJvmWorkaround(xmlSignContext); //XMLSignatureFactory signatureFactory = signatureConfig.SignatureFactory; ///* // * Add ds:References that come from signing client local files. // */ //List<Reference> references = new List<Reference>(); //foreach (DigestInfo digestInfo in safe(digestInfos)) { // byte[] documentDigestValue = digestInfo.digestValue; // String uri = new File(digestInfo.description).Name; // Reference reference = SignatureFacet.newReference // (uri, null, null, null, documentDigestValue, signatureConfig); // references.Add(reference); //} ///* // * Invoke the signature facets. // */ //List<XMLObject> objects = new List<XMLObject>(); //foreach (SignatureFacet signatureFacet in signatureConfig.SignatureFacets) { // LOG.Log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.Class.SimpleName); // signatureFacet.PreSign(document, references, objects); //} ///* // * ds:SignedInfo // */ //SignedInfo signedInfo; //try { // SignatureMethod signatureMethod = signatureFactory.newSignatureMethod // (signatureConfig.SignatureMethodUri, null); // CanonicalizationMethod canonicalizationMethod = signatureFactory // .newCanonicalizationMethod(signatureConfig.CanonicalizationMethod, // (C14NMethodParameterSpec)null); // signedInfo = signatureFactory.NewSignedInfo( // canonicalizationMethod, signatureMethod, references); //} catch (GeneralSecurityException e) { // throw new XMLSignatureException(e); //} ///* // * JSR105 ds:Signature creation // */ //String signatureValueId = signatureConfig.PackageSignatureId + "-signature-value"; //javax.xml.Crypto.dsig.XMLSignature xmlSignature = signatureFactory // .newXMLSignature(signedInfo, null, objects, signatureConfig.PackageSignatureId, // signatureValueId); ///* // * ds:Signature Marshalling. // */ //xmlSignature.Sign(xmlSignContext); ///* // * Completion of undigested ds:References in the ds:Manifests. // */ //foreach (XMLObject object1 in objects) { // LOG.Log(POILogger.DEBUG, "object java type: " + object1.Class.Name); // List<XMLStructure> objectContentList = object1.Content; // foreach (XMLStructure objectContent in objectContentList) { // LOG.Log(POILogger.DEBUG, "object content java type: " + objectContent.Class.Name); // if (!(objectContent is Manifest)) continue; // Manifest manifest = (Manifest)objectContent; // List<Reference> manifestReferences = manifest.References; // foreach (Reference manifestReference in manifestReferences) { // if (manifestReference.DigestValue != null) continue; // DOMReference manifestDOMReference = (DOMReference)manifestReference; // manifestDOMReference.Digest(xmlSignContext); // } // } //} ///* // * Completion of undigested ds:References. // */ //List<Reference> signedInfoReferences = signedInfo.References; //foreach (Reference signedInfoReference in signedInfoReferences) { // DOMReference domReference = (DOMReference)signedInfoReference; // // ds:Reference with external digest value // if (domReference.DigestValue != null) continue; // domReference.Digest(xmlSignContext); //} ///* // * Calculation of XML signature digest value. // */ //DOMSignedInfo domSignedInfo = (DOMSignedInfo)signedInfo; //MemoryStream dataStream = new MemoryStream(); //domSignedInfo.Canonicalize(xmlSignContext, dataStream); //byte[] octets = dataStream.ToByteArray(); ///* // * TODO: we could be using DigestOutputStream here to optimize memory // * usage. // */ //MessageDigest md = CryptoFunctions.GetMessageDigest(signatureConfig.DigestAlgo); //byte[] digestValue = md.Digest(octets); //String description = signatureConfig.SignatureDescription; //return new DigestInfo(digestValue, signatureConfig.DigestAlgo, description); throw new NotImplementedException(); } /** * Helper method for Adding informations After the signing. * Normally {@link #ConfirmSignature()} is sufficient to be used. */ public void postSign(XmlDocument document, byte[] signatureValue) { //LOG.Log(POILogger.DEBUG, "postSign"); /* * Check ds:Signature node. */ //String signatureId = signatureConfig.PackageSignatureId; //if (!signatureId.Equals(document.DocumentElement.GetAttribute("Id"))) { // throw new Exception("ds:Signature not found for @Id: " + signatureId); //} ///* // * Insert signature value into the ds:SignatureValue element // */ //NodeList sigValNl = document.GetElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue"); //if (sigValNl.Length != 1) { // throw new Exception("preSign has to be called before postSign"); //} //sigValNl.Item(0).TextContent = (/*setter*/Base64.Encode(signatureValue)); ///* // * Allow signature facets to inject their own stuff. // */ //foreach (SignatureFacet signatureFacet in signatureConfig.SignatureFacets) { // signatureFacet.PostSign(document); //} //WriteDocument(document); throw new NotImplementedException(); } /** * Write XML signature into the OPC package * * @param document the xml signature document * @throws MarshalException */ protected void WriteDocument(XmlDocument document) { //XmlOptions xo = new XmlOptions(); //Dictionary<String, String> namespaceMap = new Dictionary<String, String>(); //foreach (Map.Entry<String, String> entry in signatureConfig.NamespacePrefixes.EntrySet()) { // namespaceMap.Put(entry.Value, entry.Key); //} //xo.SaveSuggestedPrefixes = (/*setter*/namespaceMap); //xo.UseDefaultNamespace(); //LOG.Log(POILogger.DEBUG, "output signed Office OpenXML document"); ///* // * Copy the original OOXML content to the signed OOXML package. During // * copying some files need to Changed. // */ //OPCPackage pkg = signatureConfig.OpcPackage; //PackagePartName sigPartName, sigsPartName; //try { // // <Override PartName="/_xmlsignatures/sig1.xml" ContentType="application/vnd.Openxmlformats-package.digital-signature-xmlsignature+xml"/> // sigPartName = PackagingURIHelper.CreatePartName("/_xmlsignatures/sig1.xml"); // // <Default Extension="sigs" ContentType="application/vnd.Openxmlformats-package.digital-signature-origin"/> // sigsPartName = PackagingURIHelper.CreatePartName("/_xmlsignatures/origin.sigs"); //} catch (InvalidFormatException e) { // throw new MarshalException(e); //} //PackagePart sigPart = pkg.GetPart(sigPartName); //if (sigPart == null) { // sigPart = pkg.CreatePart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART); //} //try { // OutputStream os = sigPart.OutputStream; // SignatureDocument sigDoc = SignatureDocument.Factory.Parse(document); // sigDoc.Save(os, xo); // os.Close(); //} catch (Exception e) { // throw new MarshalException("Unable to write signature document", e); //} //PackagePart sigsPart = pkg.GetPart(sigsPartName); //if (sigsPart == null) { // // touch empty marker file // sigsPart = pkg.CreatePart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART); //} //PackageRelationshipCollection relCol = pkg.GetRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN); //foreach (PackageRelationship pr in relCol) { // pkg.RemoveRelationship(pr.Id); //} //pkg.AddRelationship(sigsPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN); //sigsPart.AddRelationship(sigPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE); } /** * Helper method for null lists, which are Converted to empty lists * * @param other the reference to wrap, if null * @return if other is null, an empty lists is returned, otherwise other is returned */ private static List<T> safe<T>(List<T> other) { //return other == null ? Collections.EMPTY_LIST : other; throw new NotImplementedException(); } //private void brokenJvmWorkaround(XMLSignContext context) { // // workaround for https://bugzilla.redhat.com/Show_bug.cgi?id=1155012 // Provider bcProv = Security.GetProvider("BC"); // if (bcProv != null) { // context.Property = (/*setter*/"org.jcp.xml.dsig.internal.dom.SignatureProvider", bcProv); // } //} //private void brokenJvmWorkaround(XMLValidateContext context) { // // workaround for https://bugzilla.redhat.com/Show_bug.cgi?id=1155012 // Provider bcProv = Security.GetProvider("BC"); // if (bcProv != null) { // context.Property = (/*setter*/"org.jcp.xml.dsig.internal.dom.SignatureProvider", bcProv); // } //} } }
/* * 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.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using pb.locationIntelligence.Client; using pb.locationIntelligence.Model; namespace pb.locationIntelligence.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ILIAPIGeoSearchServiceApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Gets LocationList /// </summary> /// <remarks> /// Gets LocationList /// </remarks> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>GeosearchLocations</returns> GeosearchLocations GeoSearch (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null); /// <summary> /// Gets LocationList /// </summary> /// <remarks> /// Gets LocationList /// </remarks> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>ApiResponse of GeosearchLocations</returns> ApiResponse<GeosearchLocations> GeoSearchWithHttpInfo (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Gets LocationList /// </summary> /// <remarks> /// Gets LocationList /// </remarks> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>Task of GeosearchLocations</returns> System.Threading.Tasks.Task<GeosearchLocations> GeoSearchAsync (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null); /// <summary> /// Gets LocationList /// </summary> /// <remarks> /// Gets LocationList /// </remarks> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>Task of ApiResponse (GeosearchLocations)</returns> System.Threading.Tasks.Task<ApiResponse<GeosearchLocations>> GeoSearchAsyncWithHttpInfo (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class LIAPIGeoSearchServiceApi : ILIAPIGeoSearchServiceApi { private pb.locationIntelligence.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="LIAPIGeoSearchServiceApi"/> class. /// </summary> /// <returns></returns> public LIAPIGeoSearchServiceApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = pb.locationIntelligence.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="LIAPIGeoSearchServiceApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public LIAPIGeoSearchServiceApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = pb.locationIntelligence.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public pb.locationIntelligence.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Gets LocationList Gets LocationList /// </summary> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>GeosearchLocations</returns> public GeosearchLocations GeoSearch (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null) { ApiResponse<GeosearchLocations> localVarResponse = GeoSearchWithHttpInfo(searchText, latitude, longitude, searchRadius, searchRadiusUnit, maxCandidates, country, matchOnAddressNumber, autoDetectLocation, ipAddress, areaName1, areaName3, postCode, returnAdminAreasOnly, includeRangesDetails, searchType); return localVarResponse.Data; } /// <summary> /// Gets LocationList Gets LocationList /// </summary> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>ApiResponse of GeosearchLocations</returns> public ApiResponse< GeosearchLocations > GeoSearchWithHttpInfo (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null) { // verify the required parameter 'searchText' is set if (searchText == null) throw new ApiException(400, "Missing required parameter 'searchText' when calling LIAPIGeoSearchServiceApi->GeoSearch"); var localVarPath = "/geosearch/v2/locations"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/xml", "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (latitude != null) localVarQueryParams.Add("latitude", Configuration.ApiClient.ParameterToString(latitude)); // query parameter if (longitude != null) localVarQueryParams.Add("longitude", Configuration.ApiClient.ParameterToString(longitude)); // query parameter if (searchRadius != null) localVarQueryParams.Add("searchRadius", Configuration.ApiClient.ParameterToString(searchRadius)); // query parameter if (searchRadiusUnit != null) localVarQueryParams.Add("searchRadiusUnit", Configuration.ApiClient.ParameterToString(searchRadiusUnit)); // query parameter if (maxCandidates != null) localVarQueryParams.Add("maxCandidates", Configuration.ApiClient.ParameterToString(maxCandidates)); // query parameter if (country != null) localVarQueryParams.Add("country", Configuration.ApiClient.ParameterToString(country)); // query parameter if (matchOnAddressNumber != null) localVarQueryParams.Add("matchOnAddressNumber", Configuration.ApiClient.ParameterToString(matchOnAddressNumber)); // query parameter if (autoDetectLocation != null) localVarQueryParams.Add("autoDetectLocation", Configuration.ApiClient.ParameterToString(autoDetectLocation)); // query parameter if (ipAddress != null) localVarQueryParams.Add("ipAddress", Configuration.ApiClient.ParameterToString(ipAddress)); // query parameter if (areaName1 != null) localVarQueryParams.Add("areaName1", Configuration.ApiClient.ParameterToString(areaName1)); // query parameter if (areaName3 != null) localVarQueryParams.Add("areaName3", Configuration.ApiClient.ParameterToString(areaName3)); // query parameter if (postCode != null) localVarQueryParams.Add("postCode", Configuration.ApiClient.ParameterToString(postCode)); // query parameter if (returnAdminAreasOnly != null) localVarQueryParams.Add("returnAdminAreasOnly", Configuration.ApiClient.ParameterToString(returnAdminAreasOnly)); // query parameter if (includeRangesDetails != null) localVarQueryParams.Add("includeRangesDetails", Configuration.ApiClient.ParameterToString(includeRangesDetails)); // query parameter if (searchType != null) localVarQueryParams.Add("searchType", Configuration.ApiClient.ParameterToString(searchType)); // query parameter // authentication (oAuth2Password) required // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } else if (!String.IsNullOrEmpty(Configuration.OAuthApiKey) && !String.IsNullOrEmpty(Configuration.OAuthSecret)) { Configuration.ApiClient.GenerateAndSetAccessToken(Configuration.OAuthApiKey,Configuration.OAuthSecret); localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GeoSearch", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<GeosearchLocations>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x1 => x1.Name, x1 => x1.Value.ToString()), (GeosearchLocations) Configuration.ApiClient.Deserialize(localVarResponse, typeof(GeosearchLocations))); } /// <summary> /// Gets LocationList Gets LocationList /// </summary> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>Task of GeosearchLocations</returns> public async System.Threading.Tasks.Task<GeosearchLocations> GeoSearchAsync (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null) { ApiResponse<GeosearchLocations> localVarResponse = await GeoSearchAsyncWithHttpInfo(searchText, latitude, longitude, searchRadius, searchRadiusUnit, maxCandidates, country, matchOnAddressNumber, autoDetectLocation, ipAddress, areaName1, areaName3, postCode, returnAdminAreasOnly, includeRangesDetails, searchType); return localVarResponse.Data; } /// <summary> /// Gets LocationList Gets LocationList /// </summary> /// <exception cref="pb.locationIntelligence.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">The input to be searched.</param> /// <param name="latitude">Latitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="longitude">Longitude of the location. Either the latitude or the longitude must be provided. (optional)</param> /// <param name="searchRadius">Radius range within which search is performed. (optional)</param> /// <param name="searchRadiusUnit">Radius unit such as Feet, Kilometers, Miles or Meters. (optional)</param> /// <param name="maxCandidates">Maximum number of addresses that can be retrieved. (optional)</param> /// <param name="country">Country ISO code. We need to make sure that either Lat/Lng or Country is provided to API (optional)</param> /// <param name="matchOnAddressNumber">Option so that we force api to match on address number (optional)</param> /// <param name="autoDetectLocation">Option to allow API to detect origin of API request automatically (optional, default to true)</param> /// <param name="ipAddress"> (optional)</param> /// <param name="areaName1">State province of the input to be searched (optional)</param> /// <param name="areaName3">City of the input to be searched (optional)</param> /// <param name="postCode">Postal Code of the input to be searched (optional)</param> /// <param name="returnAdminAreasOnly">if value set &#39;Y&#39; then it will only do a matching on postcode or areaName1, areaName2, areaName3 and areaName4 fields in the data (optional, default to N)</param> /// <param name="includeRangesDetails">if value set &#39;Y&#39; then display all unit info of ranges, if value set &#39;N&#39; then don&#39;t show ranges (optional, default to Y)</param> /// <param name="searchType">Preference to control search type of interactive requests. (optional, default to ADDRESS)</param> /// <returns>Task of ApiResponse (GeosearchLocations)</returns> public async System.Threading.Tasks.Task<ApiResponse<GeosearchLocations>> GeoSearchAsyncWithHttpInfo (string searchText, string latitude = null, string longitude = null, string searchRadius = null, string searchRadiusUnit = null, string maxCandidates = null, string country = null, string matchOnAddressNumber = null, string autoDetectLocation = null, string ipAddress = null, string areaName1 = null, string areaName3 = null, string postCode = null, string returnAdminAreasOnly = null, string includeRangesDetails = null, string searchType = null) { // verify the required parameter 'searchText' is set if (searchText == null) throw new ApiException(400, "Missing required parameter 'searchText' when calling LIAPIGeoSearchServiceApi->GeoSearch"); var localVarPath = "/geosearch/v2/locations"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/xml", "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (latitude != null) localVarQueryParams.Add("latitude", Configuration.ApiClient.ParameterToString(latitude)); // query parameter if (longitude != null) localVarQueryParams.Add("longitude", Configuration.ApiClient.ParameterToString(longitude)); // query parameter if (searchRadius != null) localVarQueryParams.Add("searchRadius", Configuration.ApiClient.ParameterToString(searchRadius)); // query parameter if (searchRadiusUnit != null) localVarQueryParams.Add("searchRadiusUnit", Configuration.ApiClient.ParameterToString(searchRadiusUnit)); // query parameter if (maxCandidates != null) localVarQueryParams.Add("maxCandidates", Configuration.ApiClient.ParameterToString(maxCandidates)); // query parameter if (country != null) localVarQueryParams.Add("country", Configuration.ApiClient.ParameterToString(country)); // query parameter if (matchOnAddressNumber != null) localVarQueryParams.Add("matchOnAddressNumber", Configuration.ApiClient.ParameterToString(matchOnAddressNumber)); // query parameter if (autoDetectLocation != null) localVarQueryParams.Add("autoDetectLocation", Configuration.ApiClient.ParameterToString(autoDetectLocation)); // query parameter if (ipAddress != null) localVarQueryParams.Add("ipAddress", Configuration.ApiClient.ParameterToString(ipAddress)); // query parameter if (areaName1 != null) localVarQueryParams.Add("areaName1", Configuration.ApiClient.ParameterToString(areaName1)); // query parameter if (areaName3 != null) localVarQueryParams.Add("areaName3", Configuration.ApiClient.ParameterToString(areaName3)); // query parameter if (postCode != null) localVarQueryParams.Add("postCode", Configuration.ApiClient.ParameterToString(postCode)); // query parameter if (returnAdminAreasOnly != null) localVarQueryParams.Add("returnAdminAreasOnly", Configuration.ApiClient.ParameterToString(returnAdminAreasOnly)); // query parameter if (includeRangesDetails != null) localVarQueryParams.Add("includeRangesDetails", Configuration.ApiClient.ParameterToString(includeRangesDetails)); // query parameter if (searchType != null) localVarQueryParams.Add("searchType", Configuration.ApiClient.ParameterToString(searchType)); // query parameter // authentication (oAuth2Password) required // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } else if (!String.IsNullOrEmpty(Configuration.OAuthApiKey) && !String.IsNullOrEmpty(Configuration.OAuthSecret)) { Configuration.ApiClient.GenerateAndSetAccessToken(Configuration.OAuthApiKey,Configuration.OAuthSecret); localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GeoSearch", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<GeosearchLocations>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x1 => x1.Name, x1 => x1.Value.ToString()), (GeosearchLocations) Configuration.ApiClient.Deserialize(localVarResponse, typeof(GeosearchLocations))); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator : SelectionValidator { public CSharpSelectionValidator( SemanticDocument document, TextSpan textSpan, OptionSet options) : base(document, textSpan, options) { } public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken) { if (!this.ContainsValidSelection) { return NullSelection; } var text = this.SemanticDocument.Text; var root = this.SemanticDocument.Root; var model = this.SemanticDocument.SemanticModel; // go through pipe line and calculate information about the user selection var selectionInfo = GetInitialSelectionInfo(root, text, cancellationToken); selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken); selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken); selectionInfo = AssignFinalSpan(selectionInfo, text, cancellationToken); selectionInfo = ApplySpecialCases(selectionInfo, text, cancellationToken); selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root, cancellationToken); // there was a fatal error that we couldn't even do negative preview, return error result if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return new ErrorSelectionResult(selectionInfo.Status); } var controlFlowSpan = GetControlFlowSpan(selectionInfo); if (!selectionInfo.SelectionInExpression) { var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken); if (statementRange == null) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Can_t_determine_valid_range_of_statements_to_extract)); return new ErrorSelectionResult(selectionInfo.Status); } var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken); if (!isFinalSpanSemanticallyValid) { // check control flow only if we are extracting statement level, not expression // level. you can not have goto that moves control out of scope in expression level // (even in lambda) selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Not_all_code_paths_return)); } } return await CSharpSelectionResult.CreateAsync( selectionInfo.Status, selectionInfo.OriginalSpan, selectionInfo.FinalSpan, this.Options, selectionInfo.SelectionInExpression, this.SemanticDocument, selectionInfo.FirstTokenInFinalSpan, selectionInfo.LastTokenInFinalSpan, cancellationToken).ConfigureAwait(false); } private SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression) { return selectionInfo; } var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); if (!expressionNode.IsAnyAssignExpression()) { return selectionInfo; } var assign = (AssignmentExpressionSyntax)expressionNode; // make sure there is a visible token at right side expression if (assign.Right.GetLastToken().Kind() == SyntaxKind.None) { return selectionInfo; } return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)), text, cancellationToken); } private TextSpan GetControlFlowSpan(SelectionInfo selectionInfo) { return TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End); } private SelectionInfo AdjustFinalTokensBasedOnContext( SelectionInfo selectionInfo, SemanticModel semanticModel, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } // don't need to adjust anything if it is multi-statements case if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement) { return selectionInfo; } // get the node that covers the selection var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); var validNode = Check(semanticModel, node, cancellationToken); if (validNode) { return selectionInfo; } var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken)); if (firstValidNode == null) { // couldn't find any valid node return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Selection_does_not_contain_a_valid_node)) .With(s => s.FirstTokenInFinalSpan = default(SyntaxToken)) .With(s => s.LastTokenInFinalSpan = default(SyntaxToken)); } firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode; return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax) .With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax) .With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true)); } private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text, CancellationToken cancellationToken) { var adjustedSpan = GetAdjustedSpan(text, this.OriginalSpan); var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false); var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false); if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Invalid_selection), OriginalSpan = adjustedSpan }; } if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span)) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Selection_does_not_contain_a_valid_token), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_selection_to_perform_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection); if (commonRoot == null) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.No_common_root_node_for_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } var selectionInExpression = commonRoot is ExpressionSyntax; if (!selectionInExpression && !commonRoot.UnderValidContext()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_selection_to_perform_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } return new SelectionInfo { Status = OperationStatus.Succeeded, OriginalSpan = adjustedSpan, CommonRootFromOriginalSpan = commonRoot, SelectionInExpression = selectionInExpression, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } private SelectionInfo CheckErrorCasesAndAppendDescriptions(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Contains_invalid_selection)); } // get the node that covers the selection var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics()) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.The_selection_contains_syntactic_errors)); } var tokens = root.DescendantTokens(selectionInfo.FinalSpan); if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_cross_over_preprocessor_directives)); } // TODO : check whether this can be handled by control flow analysis engine if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_a_yield_statement)); } // TODO : check behavior of control flow analysis engine around exception and exception handling. if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_throw_statement)); } if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression()) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_be_part_of_constant_initializer_expression)); } if (commonNode.IsUnsafeContext()) { selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, CSharpFeaturesResources.The_selected_code_is_inside_an_unsafe_context)); } // For now patterns are being blanket disabled for extract method. This issue covers designing extractions for them // and re-enabling this. // https://github.com/dotnet/roslyn/issues/9244 if (commonNode.Kind() == SyntaxKind.IsPatternExpression) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_contain_a_pattern_expression)); } var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan; if (selectionChanged) { selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion()); } return selectionInfo; } private SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } if (selectionInfo.SelectionInExpression) { // simple expression case return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true)); } var range = GetStatementRangeContainingSpan<StatementSyntax>( root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End), cancellationToken); if (range == null) { return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_statement_range_to_extract)); } var statement1 = (StatementSyntax)range.Item1; var statement2 = (StatementSyntax)range.Item2; if (statement1 == statement2) { // check one more time to see whether it is an expression case var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>(); if (expression != null && statement1.Span.Contains(expression.Span)) { return selectionInfo.With(s => s.SelectionInExpression = true) .With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true)); } // single statement case return selectionInfo.With(s => s.SelectionInSingleStatement = true) .With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true)); } // move only statements inside of the block return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true)); } private SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } // set final span var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ? Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) : selectionInfo.FirstTokenInFinalSpan.FullSpan.Start; var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ? Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) : selectionInfo.LastTokenInFinalSpan.FullSpan.End; return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end))); } public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion) { return jumpsOutOfRegion.Where(n => !(n is ReturnStatementSyntax)).Any(); } public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion) { var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax); var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault(); if (container == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault())) .Where(p => p.Item2 != null); // now filter return statements to only include the one under outmost container return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1); } public override bool IsFinalSpanSemanticallyValidSpan( SyntaxNode root, TextSpan textSpan, IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken) { // return statement shouldn't contain any return value if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null)) { return false; } var lastToken = root.FindToken(textSpan.End); if (lastToken.Kind() == SyntaxKind.None) { return false; } var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { return false; } var body = container.GetBlockBody(); if (body == null) { return false; } // make sure that next token of the last token in the selection is the close braces of containing block if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true)) { return false; } // alright, for these constructs, it must be okay to be extracted switch (container.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: return true; } // now, only method is okay to be extracted out var method = body.Parent as MethodDeclarationSyntax; if (method == null) { return false; } // make sure this method doesn't have return type. return method.ReturnType.TypeSwitch((PredefinedTypeSyntax p) => p.Keyword.Kind() == SyntaxKind.VoidKeyword); } private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan) { // beginning of a file if (textSpan.IsEmpty || textSpan.End == 0) { return textSpan; } // if it is a start of new line, make it belong to previous line var line = text.Lines.GetLineFromPosition(textSpan.End); if (line.Start != textSpan.End) { return textSpan; } // get previous line Contract.ThrowIfFalse(line.LineNumber > 0); var previousLine = text.Lines[line.LineNumber - 1]; return TextSpan.FromBounds(textSpan.Start, previousLine.End); } private class SelectionInfo { public OperationStatus Status { get; set; } public TextSpan OriginalSpan { get; set; } public TextSpan FinalSpan { get; set; } public SyntaxNode CommonRootFromOriginalSpan { get; set; } public SyntaxToken FirstTokenInOriginalSpan { get; set; } public SyntaxToken LastTokenInOriginalSpan { get; set; } public SyntaxToken FirstTokenInFinalSpan { get; set; } public SyntaxToken LastTokenInFinalSpan { get; set; } public bool SelectionInExpression { get; set; } public bool SelectionInSingleStatement { get; set; } public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter) { return With(s => s.Status = statusGetter(s.Status)); } public SelectionInfo With(Action<SelectionInfo> valueSetter) { var newInfo = this.Clone(); valueSetter(newInfo); return newInfo; } public SelectionInfo Clone() { return (SelectionInfo)this.MemberwiseClone(); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX using System.Security.Cryptography; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Runtime.InteropServices; using DWORD = System.UInt32; namespace System.Management.Automation { /// <summary> /// Defines the possible status when validating integrity of catalog. /// </summary> public enum CatalogValidationStatus { /// <summary> /// Status when catalog is not tampered. /// </summary> Valid, /// <summary> /// Status when catalog is tampered. /// </summary> ValidationFailed } /// <summary> /// Object returned by Catalog Cmdlets. /// </summary> public class CatalogInformation { /// <summary> /// Status of catalog. /// </summary> public CatalogValidationStatus Status { get; set; } /// <summary> /// Hash Algorithm used to calculate the hashes of files in Catalog. /// </summary> public string HashAlgorithm { get; set; } /// <summary> /// Dictionary mapping files relative paths to their hash values found from Catalog. /// </summary> public Dictionary<string, string> CatalogItems { get; set; } /// <summary> /// Dictionary mapping files relative paths to their hash values. /// </summary> public Dictionary<string, string> PathItems { get; set; } /// <summary> /// Signature for the catalog. /// </summary> public Signature Signature { get; set; } } /// <summary> /// Helper functions for Windows Catalog functionality. /// </summary> internal static class CatalogHelper { // Catalog Version is (0X100 = 256) for Catalog Version 1 private const int catalogVersion1 = 256; // Catalog Version is (0X200 = 512) for Catalog Version 2 private const int catalogVersion2 = 512; // Hash Algorithms supported by Windows Catalog private const string HashAlgorithmSHA1 = "SHA1"; private const string HashAlgorithmSHA256 = "SHA256"; private static PSCmdlet _cmdlet = null; /// <summary> /// Find out the Version of Catalog by reading its Meta data. We can have either version 1 or version 2 catalog. /// </summary> /// <param name="catalogHandle">Handle to open catalog file.</param> /// <returns>Version of the catalog.</returns> private static int GetCatalogVersion(IntPtr catalogHandle) { int catalogVersion = -1; IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle); NativeMethods.CRYPTCATSTORE catalogInfo = Marshal.PtrToStructure<NativeMethods.CRYPTCATSTORE>(catalogData); if (catalogInfo.dwPublicVersion == catalogVersion2) { catalogVersion = 2; } // One Windows 7 this API sent version information as decimal 1 not hex (0X100 = 256) // so we are checking for that value as well. Reason we are not checking for version 2 above in // this scenario because catalog version 2 is not supported on win7. else if ((catalogInfo.dwPublicVersion == catalogVersion1) || (catalogInfo.dwPublicVersion == 1)) { catalogVersion = 1; } else { // catalog version we don't understand Exception exception = new InvalidOperationException(StringUtil.Format(CatalogStrings.UnKnownCatalogVersion, catalogVersion1.ToString("X"), catalogVersion2.ToString("X"))); ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return catalogVersion; } /// <summary> /// HashAlgorithm used by the Catalog. It is based on the version of Catalog. /// </summary> /// <param name="catalogVersion">Path of the output catalog file.</param> /// <returns>Version of the catalog.</returns> private static string GetCatalogHashAlgorithm(int catalogVersion) { string hashAlgorithm = string.Empty; if (catalogVersion == 1) { hashAlgorithm = HashAlgorithmSHA1; } else if (catalogVersion == 2) { hashAlgorithm = HashAlgorithmSHA256; } else { // version we don't understand Exception exception = new InvalidOperationException(StringUtil.Format(CatalogStrings.UnKnownCatalogVersion, "1.0", "2.0")); ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return hashAlgorithm; } /// <summary> /// Generate the Catalog Definition File representing files and folders. /// </summary> /// <param name="Path">Path of expected output .cdf file.</param> /// <param name="catalogFilePath">Path of the output catalog file.</param> /// <param name="cdfFilePath">Path of the catalog definition file.</param> /// <param name="catalogVersion">Version of catalog.</param> /// <param name="hashAlgorithm">Hash method used to generate hashes for the Catalog.</param> /// <returns>HashSet for the relative Path for files in Catalog.</returns> internal static string GenerateCDFFile(Collection<string> Path, string catalogFilePath, string cdfFilePath, int catalogVersion, string hashAlgorithm) { HashSet<string> relativePaths = new HashSet<string>(); string cdfHeaderContent = string.Empty; string cdfFilesContent = string.Empty; int catAttributeCount = 0; // First create header and files section for the catalog then write in file cdfHeaderContent += "[CatalogHeader]" + Environment.NewLine; cdfHeaderContent += @"Name=" + catalogFilePath + Environment.NewLine; cdfHeaderContent += "CatalogVersion=" + catalogVersion + Environment.NewLine; cdfHeaderContent += "HashAlgorithms=" + hashAlgorithm + Environment.NewLine; cdfFilesContent += "[CatalogFiles]" + Environment.NewLine; foreach (string catalogFile in Path) { if (System.IO.Directory.Exists(catalogFile)) { var directoryItems = Directory.EnumerateFiles(catalogFile, "*.*", SearchOption.AllDirectories); foreach (string fileItem in directoryItems) { ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(fileItem), new DirectoryInfo(catalogFile), ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); } } else if (System.IO.File.Exists(catalogFile)) { ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(catalogFile), null, ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); } } using (System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(new FileStream(cdfFilePath, FileMode.Create))) { fileWriter.WriteLine(cdfHeaderContent); fileWriter.WriteLine(); fileWriter.WriteLine(cdfFilesContent); } return cdfFilePath; } /// <summary> /// Get file attribute (Relative path in our case) from catalog. /// </summary> /// <param name="fileToHash">File to hash.</param> /// <param name="dirInfo">Directory information about file needed to calculate relative file path.</param> /// <param name="relativePaths">Working set of relative paths of all files.</param> /// <param name="cdfHeaderContent">Content to be added in CatalogHeader section of cdf File.</param> /// <param name="cdfFilesContent">Content to be added in CatalogFiles section of cdf File.</param> /// <param name="catAttributeCount">Indicating the current no of catalog header level attributes.</param> /// <returns>Void.</returns> internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileToHash, DirectoryInfo dirInfo, ref HashSet<string> relativePaths, ref string cdfHeaderContent, ref string cdfFilesContent, ref int catAttributeCount) { string relativePath = string.Empty; if (dirInfo != null) { // Relative path of the file is the path inside the containing folder excluding folder Name relativePath = fileToHash.FullName.AsSpan(dirInfo.FullName.Length).TrimStart('\\').ToString(); } else { relativePath = fileToHash.Name; } if (!relativePaths.Contains(relativePath)) { relativePaths.Add(relativePath); if (fileToHash.Length != 0) { cdfFilesContent += "<HASH>" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine; cdfFilesContent += "<HASH>" + fileToHash.FullName + "ATTR1=0x10010001:FilePath:" + relativePath + Environment.NewLine; } else { // zero length files are added as catalog level attributes because they can not be hashed cdfHeaderContent += "CATATTR" + (++catAttributeCount) + "=0x10010001:FilePath:" + relativePath + Environment.NewLine; } } else { // If Files have same relative paths we can not distinguish them for // Validation. So failing. ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFilesRelativePath, relativePath)), "FoundDuplicateFilesRelativePath", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } } /// <summary> /// Generate the Catalog file for Input Catalog Definition File. /// </summary> /// <param name="cdfFilePath">Path to the Input .cdf file.</param> internal static void GenerateCatalogFile(string cdfFilePath) { string pwszFilePath = cdfFilePath; NativeMethods.CryptCATCDFOpenCallBack catOpenCallBack = new NativeMethods.CryptCATCDFOpenCallBack(ParseErrorCallback); // Open CDF File IntPtr resultCDF = NativeMethods.CryptCATCDFOpen(pwszFilePath, catOpenCallBack); // navigate CDF header and files sections if (resultCDF != IntPtr.Zero) { // First navigate all catalog level attributes entries first, they represent zero size files IntPtr catalogAttr = IntPtr.Zero; do { catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack); if (catalogAttr != IntPtr.Zero) { string filePath = ProcessFilePathAttributeInCatalog(catalogAttr); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, filePath, filePath)); } } while (catalogAttr != IntPtr.Zero); // navigate all the files hash entries in the .cdf file IntPtr memberInfo = IntPtr.Zero; try { IntPtr memberFile = IntPtr.Zero; NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack memberCallBack = new NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack(ParseErrorCallback); string fileName = string.Empty; do { memberFile = NativeMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, memberCallBack, ref memberInfo, true, IntPtr.Zero); fileName = Marshal.PtrToStringUni(memberFile); if (!string.IsNullOrEmpty(fileName)) { IntPtr memberAttr = IntPtr.Zero; string fileRelativePath = string.Empty; do { memberAttr = NativeMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, memberCallBack); if (memberAttr != IntPtr.Zero) { fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr); if (!string.IsNullOrEmpty(fileRelativePath)) { // Found the attribute we are looking for // Filename we read from the above API has <Hash> appended to its name as per CDF file tags convention // Truncating that Information from the string. string itemName = fileName.Substring(6); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); break; } } } while (memberAttr != IntPtr.Zero); } } while (fileName != null); } finally { NativeMethods.CryptCATCDFClose(resultCDF); } } else { // If we are not able to open CDF file we can not continue generating catalog ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile), "UnableToOpenCatalogDefinitionFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } } /// <summary> /// To generate Catalog for the folder. /// </summary> /// <param name="Path">Path to folder or File.</param> /// <param name="catalogFilePath">Catalog File Path.</param> /// <param name="catalogVersion">Catalog File Path.</param> /// <param name="cmdlet">Instance of cmdlet calling this method.</param> /// <returns>True if able to generate .cat file or false.</returns> internal static FileInfo GenerateCatalog(PSCmdlet cmdlet, Collection<string> Path, string catalogFilePath, int catalogVersion) { _cmdlet = cmdlet; string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion); if (!string.IsNullOrEmpty(hashAlgorithm)) { // Generate Path for Catalog Definition File string cdfFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); cdfFilePath += ".cdf"; try { cdfFilePath = GenerateCDFFile(Path, catalogFilePath, cdfFilePath, catalogVersion, hashAlgorithm); if (!File.Exists(cdfFilePath)) { // If we are not able to generate catalog definition file we can not continue generating catalog // throw PSTraceSource.NewInvalidOperationException("catalog", CatalogStrings.CatalogDefinitionFileNotGenerated); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.CatalogDefinitionFileNotGenerated), "CatalogDefinitionFileNotGenerated", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } GenerateCatalogFile(cdfFilePath); if (File.Exists(catalogFilePath)) { return new FileInfo(catalogFilePath); } } finally { File.Delete(cdfFilePath); } } return null; } /// <summary> /// Get file attribute (Relative path in our case) from catalog. /// </summary> /// <param name="memberAttrInfo">Pointer to current attribute of catalog member.</param> /// <returns>Value of the attribute.</returns> internal static string ProcessFilePathAttributeInCatalog(IntPtr memberAttrInfo) { string relativePath = string.Empty; NativeMethods.CRYPTCATATTRIBUTE currentMemberAttr = Marshal.PtrToStructure<NativeMethods.CRYPTCATATTRIBUTE>(memberAttrInfo); // check if this is the attribute we are looking for // catalog generated other way not using New-FileCatalog can have attributes we don't understand if (currentMemberAttr.pwszReferenceTag.Equals("FilePath", StringComparison.OrdinalIgnoreCase)) { // find the size for the current attribute value and then allocate buffer and copy from byte array int attrValueSize = (int)currentMemberAttr.cbValue; byte[] attrValue = new byte[attrValueSize]; Marshal.Copy(currentMemberAttr.pbValue, attrValue, 0, attrValueSize); relativePath = System.Text.Encoding.Unicode.GetString(attrValue); relativePath = relativePath.TrimEnd('\0'); } return relativePath; } /// <summary> /// Make a hash for the file. /// </summary> /// <param name="filePath">Path of the file.</param> /// <param name="hashAlgorithm">Used to calculate Hash.</param> /// <returns>HashValue for the file.</returns> internal static string CalculateFileHash(string filePath, string hashAlgorithm) { string hashValue = string.Empty; IntPtr catAdmin = IntPtr.Zero; // To get handle to the hash algorithm to be used to calculate hashes if (!NativeMethods.CryptCATAdminAcquireContext2(ref catAdmin, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm)), "UnableToAcquireHashAlgorithmContext", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } const DWORD GENERIC_READ = 0x80000000; const DWORD OPEN_EXISTING = 3; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // Open the file that is to be hashed for reading and get its handle IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, IntPtr.Zero); if (fileHandle != INVALID_HANDLE_VALUE) { try { DWORD hashBufferSize = 0; IntPtr hashBuffer = IntPtr.Zero; // Call first time to get the size of expected buffer to hold new hash value if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } int size = (int)hashBufferSize; hashBuffer = Marshal.AllocHGlobal(size); try { // Call second time to actually get the hash value if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } byte[] hashBytes = new byte[size]; Marshal.Copy(hashBuffer, hashBytes, 0, size); hashValue = BitConverter.ToString(hashBytes).Replace("-", string.Empty); } finally { if (hashBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(hashBuffer); } } } finally { NativeMethods.CryptCATAdminReleaseContext(catAdmin, 0); NativeMethods.CloseHandle(fileHandle); } } else { // If we are not able to open file that is to be hashed we can not continue with catalog validation ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath)), "UnableToReadFileToHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return hashValue; } /// <summary> /// Make list of hashes for given Catalog File. /// </summary> /// <param name="catalogFilePath">Path to the folder having catalog file.</param> /// <param name="excludedPatterns"></param> /// <param name="catalogVersion">The version of input catalog we read from catalog meta data after opening it.</param> /// <returns>Dictionary mapping files relative paths to HashValues.</returns> internal static Dictionary<string, string> GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns, out int catalogVersion) { IntPtr resultCatalog = NativeMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); Dictionary<string, string> catalogHashes = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase); catalogVersion = 0; if (resultCatalog != INVALID_HANDLE_VALUE) { try { IntPtr catAttrInfo = IntPtr.Zero; // First traverse all catalog level attributes to get information about zero size file. do { catAttrInfo = NativeMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo); // If we found attribute it is a file information retrieve its relative path // and add it to catalog hash collection if its not in excluded files criteria if (catAttrInfo != IntPtr.Zero) { string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo); if (!string.IsNullOrEmpty(relativePath)) { ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes); } } } while (catAttrInfo != IntPtr.Zero); catalogVersion = GetCatalogVersion(resultCatalog); IntPtr memberInfo = IntPtr.Zero; // Next Navigate all members in Catalog files and get their relative paths and hashes do { memberInfo = NativeMethods.CryptCATEnumerateMember(resultCatalog, memberInfo); if (memberInfo != IntPtr.Zero) { NativeMethods.CRYPTCATMEMBER currentMember = Marshal.PtrToStructure<NativeMethods.CRYPTCATMEMBER>(memberInfo); NativeMethods.SIP_INDIRECT_DATA pIndirectData = Marshal.PtrToStructure<NativeMethods.SIP_INDIRECT_DATA>(currentMember.pIndirectData); // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well // We validate those along with file hashes so we are skipping duplicate entries if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) { string relativePath = string.Empty; IntPtr memberAttrInfo = IntPtr.Zero; do { memberAttrInfo = NativeMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo); if (memberAttrInfo != IntPtr.Zero) { relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo); if (!string.IsNullOrEmpty(relativePath)) { break; } } } while (memberAttrInfo != IntPtr.Zero); // If we did not find any Relative Path for the item in catalog we should quit // This catalog must not be valid for our use as catalogs generated using New-FileCatalog // always contains relative file Paths if (string.IsNullOrEmpty(relativePath)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); } } } while (memberInfo != IntPtr.Zero); } finally { NativeMethods.CryptCATClose(resultCatalog); } } else { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } return catalogHashes; } /// <summary> /// Process file in path for its relative paths. /// </summary> /// <param name="relativePath">Relative path of file found in catalog.</param> /// <param name="fileHash">Hash of file found in catalog.</param> /// <param name="excludedPatterns">Skip file from validation if it matches these patterns.</param> /// <param name="catalogHashes">Collection of hashes of catalog.</param> /// <returns>Void.</returns> internal static void ProcessCatalogFile(string relativePath, string fileHash, WildcardPattern[] excludedPatterns, ref Dictionary<string, string> catalogHashes) { // Found the attribute we are looking for _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.FoundFileHashInCatalogItem, relativePath, fileHash)); // Only add the file for validation if it does not meet exclusion criteria if (!CheckExcludedCriteria((new FileInfo(relativePath)).Name, excludedPatterns)) { // Add relativePath mapping to hashvalue for each file catalogHashes.Add(relativePath, fileHash); } else { // Verbose about skipping file from catalog _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.SkipValidationOfCatalogFile, relativePath)); } } /// <summary> /// Process file in path for its relative paths. /// </summary> /// <param name="fileToHash">File to hash.</param> /// <param name="dirInfo">Directory information about file needed to calculate relative file path.</param> /// <param name="hashAlgorithm">Used to calculate Hash.</param> /// <param name="excludedPatterns">Skip file if it matches these patterns.</param> /// <param name="fileHashes">Collection of hashes of files.</param> /// <returns>Void.</returns> internal static void ProcessPathFile(FileInfo fileToHash, DirectoryInfo dirInfo, string hashAlgorithm, WildcardPattern[] excludedPatterns, ref Dictionary<string, string> fileHashes) { string relativePath = string.Empty; string exclude = string.Empty; if (dirInfo != null) { // Relative path of the file is the path inside the containing folder excluding folder Name relativePath = fileToHash.FullName.AsSpan(dirInfo.FullName.Length).TrimStart('\\').ToString(); exclude = fileToHash.Name; } else { relativePath = fileToHash.Name; exclude = relativePath; } if (!CheckExcludedCriteria(exclude, excludedPatterns)) { string fileHash = string.Empty; if (fileToHash.Length != 0) { fileHash = CalculateFileHash(fileToHash.FullName, hashAlgorithm); } if (fileHashes.TryAdd(relativePath, fileHash)) { _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.FoundFileInPath, relativePath, fileHash)); } else { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFilesRelativePath, relativePath)), "FoundDuplicateFilesRelativePath", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } } else { // Verbose about skipping file from path _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.SkipValidationOfPathFile, relativePath)); } } /// <summary> /// Generate the hashes of all the files in given folder. /// </summary> /// <param name="folderPaths">Path to folder or File.</param> /// <param name="catalogFilePath">Catalog file path it should be skipped when calculating the hashes.</param> /// <param name="hashAlgorithm">Used to calculate Hash.</param> /// <param name="excludedPatterns"></param> /// <returns>Dictionary mapping file relative paths to hashes..</returns> internal static Dictionary<string, string> CalculateHashesFromPath(Collection<string> folderPaths, string catalogFilePath, string hashAlgorithm, WildcardPattern[] excludedPatterns) { // Create a HashTable of file Hashes Dictionary<string, string> fileHashes = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase); foreach (string folderPath in folderPaths) { if (System.IO.Directory.Exists(folderPath)) { var directoryItems = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.AllDirectories); foreach (string fileItem in directoryItems) { // if its the catalog file we are validating we will skip it if (string.Equals(fileItem, catalogFilePath, StringComparison.OrdinalIgnoreCase)) continue; ProcessPathFile(new FileInfo(fileItem), new DirectoryInfo(folderPath), hashAlgorithm, excludedPatterns, ref fileHashes); } } else if (System.IO.File.Exists(folderPath)) { ProcessPathFile(new FileInfo(folderPath), null, hashAlgorithm, excludedPatterns, ref fileHashes); } } return fileHashes; } /// <summary> /// Compare Dictionary objects. /// </summary> /// <param name="catalogItems">Hashes extracted from Catalog.</param> /// <param name="pathItems">Hashes created from folders path.</param> /// <returns>True if both collections are same.</returns> internal static bool CompareDictionaries(Dictionary<string, string> catalogItems, Dictionary<string, string> pathItems) { bool Status = true; List<string> relativePathsFromFolder = pathItems.Keys.ToList(); List<string> relativePathsFromCatalog = catalogItems.Keys.ToList(); // Find entires those are not in both list lists. These should be empty lists for success // Hashes in Catalog should be exact similar to the ones from folder List<string> relativePathsNotInFolder = relativePathsFromFolder.Except(relativePathsFromCatalog, StringComparer.CurrentCultureIgnoreCase).ToList(); List<string> relativePathsNotInCatalog = relativePathsFromCatalog.Except(relativePathsFromFolder, StringComparer.CurrentCultureIgnoreCase).ToList(); // Found extra hashes in Folder if ((relativePathsNotInFolder.Count != 0) || (relativePathsNotInCatalog.Count != 0)) { Status = false; } foreach (KeyValuePair<string, string> item in catalogItems) { string catalogHashValue = (string)catalogItems[item.Key]; if (pathItems.ContainsKey(item.Key)) { string folderHashValue = (string)pathItems[item.Key]; if (folderHashValue.Equals(catalogHashValue)) { continue; } else { Status = false; } } } return Status; } /// <summary> /// To Validate the Integrity of Catalog. /// </summary> /// <param name="catalogFolders">Folder for which catalog is created.</param> /// <param name="catalogFilePath">File Name of the Catalog.</param> /// <param name="excludedPatterns"></param> /// <param name="cmdlet">Instance of cmdlet calling this method.</param> /// <returns>Information about Catalog.</returns> internal static CatalogInformation ValidateCatalog(PSCmdlet cmdlet, Collection<string> catalogFolders, string catalogFilePath, WildcardPattern[] excludedPatterns) { _cmdlet = cmdlet; int catalogVersion = 0; Dictionary<string, string> catalogHashes = GetHashesFromCatalog(catalogFilePath, excludedPatterns, out catalogVersion); string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion); if (!string.IsNullOrEmpty(hashAlgorithm)) { Dictionary<string, string> fileHashes = CalculateHashesFromPath(catalogFolders, catalogFilePath, hashAlgorithm, excludedPatterns); CatalogInformation catalog = new CatalogInformation(); catalog.CatalogItems = catalogHashes; catalog.PathItems = fileHashes; bool status = CompareDictionaries(catalogHashes, fileHashes); if (status) { catalog.Status = CatalogValidationStatus.Valid; } else { catalog.Status = CatalogValidationStatus.ValidationFailed; } catalog.HashAlgorithm = hashAlgorithm; catalog.Signature = SignatureHelper.GetSignature(catalogFilePath, null); return catalog; } return null; } /// <summary> /// Check if file meets the skip validation criteria. /// </summary> /// <param name="filename"></param> /// <param name="excludedPatterns"></param> /// <returns>True if match is found else false.</returns> internal static bool CheckExcludedCriteria(string filename, WildcardPattern[] excludedPatterns) { if (excludedPatterns != null) { foreach (WildcardPattern patternItem in excludedPatterns) { if (patternItem.IsMatch(filename)) { return true; } } } return false; } /// <summary> /// Call back when error is thrown by catalog API's. /// </summary> private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, string pwszLine) { switch (dwErrorArea) { case NativeConstants.CRYPTCAT_E_AREA_HEADER: break; case NativeConstants.CRYPTCAT_E_AREA_MEMBER: break; case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: break; default: break; } switch (dwLocalError) { case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILE_PATH: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToFindFileNameOrPathForCatalogMember, pwszLine)), "UnableToFindFileNameOrPathForCatalogMember", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, pwszLine)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToFindFileToHash, pwszLine)), "UnableToFindFileToHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: break; case NativeConstants.CRYPTCAT_E_CDF_ATTR_TYPECOMBO: break; case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: break; case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: break; case NativeConstants.CRYPTCAT_E_CDF_DUPLICATE: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFileMemberInCatalog, pwszLine)), "FoundDuplicateFileMemberInCatalog", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_TAGNOTFOUND: break; default: break; } } } } #endif
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// AddLibraryItemRequest /// </summary> [DataContract] public partial class AddLibraryItemRequest : IEquatable<AddLibraryItemRequest>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="AddLibraryItemRequest" /> class. /// </summary> /// <param name="attributes">Attributes associated with the library item to contain additional configuration..</param> /// <param name="cjson">Cjson to be added to library.</param> /// <param name="contentType">flow, campaign, cjson, email, transactional_email, postcard or upsell.</param> /// <param name="description">description of library item.</param> /// <param name="emailName">Required if content_type is transactional_email. This is the name of the email template (html, not text). This name should have a .vm file extension. An example is auto_order_cancel_html.vm.</param> /// <param name="emailPath">Required if content_type is transactional_email. This is the full path to the email template stored in the file system. This defines which StoreFront contains the desired email template. An example is /themes/Elements/core/emails/auto_order_cancel_html.vm.</param> /// <param name="screenshots">Screenshot urls for display.</param> /// <param name="storefrontOid">StoreFront oid where content originates necessary for tracking down relative assets.</param> /// <param name="title">title of library item, usually the name of the flow or campaign, or description of cjson.</param> /// <param name="upsellOfferOid">Required if content_type is upsell. This is object identifier of a StoreFront Upsell Offer..</param> /// <param name="uuid">UUID of communication flow, campaign, email, postcard, or null if this item is something else. transactional_email do not have a uuid because they are singleton objects within a storefront and easily identifiable by name.</param> public AddLibraryItemRequest(List<LibraryItemAttribute> attributes = default(List<LibraryItemAttribute>), string cjson = default(string), string contentType = default(string), string description = default(string), string emailName = default(string), string emailPath = default(string), List<LibraryItemScreenshot> screenshots = default(List<LibraryItemScreenshot>), int? storefrontOid = default(int?), string title = default(string), int? upsellOfferOid = default(int?), string uuid = default(string)) { this.Attributes = attributes; this.Cjson = cjson; this.ContentType = contentType; this.Description = description; this.EmailName = emailName; this.EmailPath = emailPath; this.Screenshots = screenshots; this.StorefrontOid = storefrontOid; this.Title = title; this.UpsellOfferOid = upsellOfferOid; this.Uuid = uuid; } /// <summary> /// Attributes associated with the library item to contain additional configuration. /// </summary> /// <value>Attributes associated with the library item to contain additional configuration.</value> [DataMember(Name="attributes", EmitDefaultValue=false)] public List<LibraryItemAttribute> Attributes { get; set; } /// <summary> /// Cjson to be added to library /// </summary> /// <value>Cjson to be added to library</value> [DataMember(Name="cjson", EmitDefaultValue=false)] public string Cjson { get; set; } /// <summary> /// flow, campaign, cjson, email, transactional_email, postcard or upsell /// </summary> /// <value>flow, campaign, cjson, email, transactional_email, postcard or upsell</value> [DataMember(Name="content_type", EmitDefaultValue=false)] public string ContentType { get; set; } /// <summary> /// description of library item /// </summary> /// <value>description of library item</value> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Required if content_type is transactional_email. This is the name of the email template (html, not text). This name should have a .vm file extension. An example is auto_order_cancel_html.vm /// </summary> /// <value>Required if content_type is transactional_email. This is the name of the email template (html, not text). This name should have a .vm file extension. An example is auto_order_cancel_html.vm</value> [DataMember(Name="email_name", EmitDefaultValue=false)] public string EmailName { get; set; } /// <summary> /// Required if content_type is transactional_email. This is the full path to the email template stored in the file system. This defines which StoreFront contains the desired email template. An example is /themes/Elements/core/emails/auto_order_cancel_html.vm /// </summary> /// <value>Required if content_type is transactional_email. This is the full path to the email template stored in the file system. This defines which StoreFront contains the desired email template. An example is /themes/Elements/core/emails/auto_order_cancel_html.vm</value> [DataMember(Name="email_path", EmitDefaultValue=false)] public string EmailPath { get; set; } /// <summary> /// Screenshot urls for display /// </summary> /// <value>Screenshot urls for display</value> [DataMember(Name="screenshots", EmitDefaultValue=false)] public List<LibraryItemScreenshot> Screenshots { get; set; } /// <summary> /// StoreFront oid where content originates necessary for tracking down relative assets /// </summary> /// <value>StoreFront oid where content originates necessary for tracking down relative assets</value> [DataMember(Name="storefront_oid", EmitDefaultValue=false)] public int? StorefrontOid { get; set; } /// <summary> /// title of library item, usually the name of the flow or campaign, or description of cjson /// </summary> /// <value>title of library item, usually the name of the flow or campaign, or description of cjson</value> [DataMember(Name="title", EmitDefaultValue=false)] public string Title { get; set; } /// <summary> /// Required if content_type is upsell. This is object identifier of a StoreFront Upsell Offer. /// </summary> /// <value>Required if content_type is upsell. This is object identifier of a StoreFront Upsell Offer.</value> [DataMember(Name="upsell_offer_oid", EmitDefaultValue=false)] public int? UpsellOfferOid { get; set; } /// <summary> /// UUID of communication flow, campaign, email, postcard, or null if this item is something else. transactional_email do not have a uuid because they are singleton objects within a storefront and easily identifiable by name /// </summary> /// <value>UUID of communication flow, campaign, email, postcard, or null if this item is something else. transactional_email do not have a uuid because they are singleton objects within a storefront and easily identifiable by name</value> [DataMember(Name="uuid", EmitDefaultValue=false)] public string Uuid { 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 AddLibraryItemRequest {\n"); sb.Append(" Attributes: ").Append(Attributes).Append("\n"); sb.Append(" Cjson: ").Append(Cjson).Append("\n"); sb.Append(" ContentType: ").Append(ContentType).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" EmailName: ").Append(EmailName).Append("\n"); sb.Append(" EmailPath: ").Append(EmailPath).Append("\n"); sb.Append(" Screenshots: ").Append(Screenshots).Append("\n"); sb.Append(" StorefrontOid: ").Append(StorefrontOid).Append("\n"); sb.Append(" Title: ").Append(Title).Append("\n"); sb.Append(" UpsellOfferOid: ").Append(UpsellOfferOid).Append("\n"); sb.Append(" Uuid: ").Append(Uuid).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 virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as AddLibraryItemRequest); } /// <summary> /// Returns true if AddLibraryItemRequest instances are equal /// </summary> /// <param name="input">Instance of AddLibraryItemRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(AddLibraryItemRequest input) { if (input == null) return false; return ( this.Attributes == input.Attributes || this.Attributes != null && this.Attributes.SequenceEqual(input.Attributes) ) && ( this.Cjson == input.Cjson || (this.Cjson != null && this.Cjson.Equals(input.Cjson)) ) && ( this.ContentType == input.ContentType || (this.ContentType != null && this.ContentType.Equals(input.ContentType)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.EmailName == input.EmailName || (this.EmailName != null && this.EmailName.Equals(input.EmailName)) ) && ( this.EmailPath == input.EmailPath || (this.EmailPath != null && this.EmailPath.Equals(input.EmailPath)) ) && ( this.Screenshots == input.Screenshots || this.Screenshots != null && this.Screenshots.SequenceEqual(input.Screenshots) ) && ( this.StorefrontOid == input.StorefrontOid || (this.StorefrontOid != null && this.StorefrontOid.Equals(input.StorefrontOid)) ) && ( this.Title == input.Title || (this.Title != null && this.Title.Equals(input.Title)) ) && ( this.UpsellOfferOid == input.UpsellOfferOid || (this.UpsellOfferOid != null && this.UpsellOfferOid.Equals(input.UpsellOfferOid)) ) && ( this.Uuid == input.Uuid || (this.Uuid != null && this.Uuid.Equals(input.Uuid)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Attributes != null) hashCode = hashCode * 59 + this.Attributes.GetHashCode(); if (this.Cjson != null) hashCode = hashCode * 59 + this.Cjson.GetHashCode(); if (this.ContentType != null) hashCode = hashCode * 59 + this.ContentType.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.EmailName != null) hashCode = hashCode * 59 + this.EmailName.GetHashCode(); if (this.EmailPath != null) hashCode = hashCode * 59 + this.EmailPath.GetHashCode(); if (this.Screenshots != null) hashCode = hashCode * 59 + this.Screenshots.GetHashCode(); if (this.StorefrontOid != null) hashCode = hashCode * 59 + this.StorefrontOid.GetHashCode(); if (this.Title != null) hashCode = hashCode * 59 + this.Title.GetHashCode(); if (this.UpsellOfferOid != null) hashCode = hashCode * 59 + this.UpsellOfferOid.GetHashCode(); if (this.Uuid != null) hashCode = hashCode * 59 + this.Uuid.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// 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; using System.Linq; using Xunit; namespace System.Data.SqlClient.Tests { public partial class SqlConnectionTest { private static readonly string[] s_retrieveStatisticsKeys = { "BuffersReceived", "BuffersSent", "BytesReceived", "BytesSent", "CursorOpens", "IduCount", "IduRows", "PreparedExecs", "Prepares", "SelectCount", "SelectRows", "ServerRoundtrips", "SumResultSets", "Transactions", "UnpreparedExecs", "ConnectionTime", "ExecutionTime", "NetworkServerTime" }; [Fact] public void RetrieveStatistics_Success() { var connection = new SqlConnection(); IDictionary d = connection.RetrieveStatistics(); Assert.NotNull(d); Assert.NotSame(d, connection.RetrieveStatistics()); } [Fact] public void RetrieveStatistics_ExpectedKeysInDictionary_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.NotEmpty(d); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count); Assert.NotEmpty(d.Keys); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count); Assert.NotEmpty(d.Values); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count); foreach (string key in s_retrieveStatisticsKeys) { Assert.True(d.Contains(key)); object value = d[key]; Assert.NotNull(value); Assert.IsType<long>(value); Assert.Equal(0L, value); } } [Fact] public void RetrieveStatistics_UnexpectedKeysNotInDictionary_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.False(d.Contains("Foo")); Assert.Null(d["Foo"]); } [Fact] public void RetrieveStatistics_IsSynchronized_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.False(d.IsSynchronized); } [Fact] public void RetrieveStatistics_SyncRoot_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.NotNull(d.SyncRoot); Assert.Same(d.SyncRoot, d.SyncRoot); } [Fact] public void RetrieveStatistics_IsFixedSize_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.False(d.IsFixedSize); } [Fact] public void RetrieveStatistics_IsReadOnly_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.False(d.IsReadOnly); } public static readonly object[][] RetrieveStatisticsKeyValueData = { new object[] { "Foo", 100L }, new object[] { "Foo", null }, new object[] { "Blah", "Blah" }, new object[] { 100, "Value" } }; [Theory] [MemberData(nameof(RetrieveStatisticsKeyValueData))] public void RetrieveStatistics_Add_Success(object key, object value) { IDictionary d = new SqlConnection().RetrieveStatistics(); d.Add(key, value); Assert.True(d.Contains(key)); object v = d[key]; Assert.Same(value, v); } [Fact] public void RetrieveStatistics_Add_ExistingKey_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); string key = s_retrieveStatisticsKeys[0]; AssertExtensions.Throws<ArgumentException>(null, () => d.Add(key, 100L)); } [Fact] public void RetrieveStatistics_Add_NullKey_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); AssertExtensions.Throws<ArgumentNullException>("key", () => d.Add(null, 100L)); } [Theory] [MemberData(nameof(RetrieveStatisticsKeyValueData))] public void RetrieveStatistics_Setter_Success(object key, object value) { IDictionary d = new SqlConnection().RetrieveStatistics(); d[key] = value; Assert.True(d.Contains(key)); object v = d[key]; Assert.Same(value, v); } [Fact] public void RetrieveStatistics_Setter_ExistingKey_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); string key = s_retrieveStatisticsKeys[0]; d[key] = 100L; Assert.Equal(100L, d[key]); } [Fact] public void RetrieveStatistics_Setter_NullKey_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); AssertExtensions.Throws<ArgumentNullException>("key", () => d[null] = 100L); } [Fact] public void RetrieveStatistics_Clear_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); d.Clear(); Assert.Empty(d); Assert.Equal(0, d.Count); Assert.Empty(d.Keys); Assert.Equal(0, d.Keys.Count); Assert.Empty(d.Values); Assert.Equal(0, d.Values.Count); } [Fact] public void RetrieveStatistics_Remove_ExistingKey_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); string key = s_retrieveStatisticsKeys[0]; Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count); Assert.True(d.Contains(key)); Assert.NotNull(d[key]); d.Remove(key); Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Count); Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Keys.Count); Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Values.Count); Assert.False(d.Contains(key)); Assert.Null(d[key]); } [Fact] public void RetrieveStatistics_Remove_NonExistentKey_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); const string key = "Foo"; Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count); Assert.False(d.Contains(key)); Assert.Null(d[key]); d.Remove(key); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count); Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count); Assert.False(d.Contains(key)); Assert.Null(d[key]); } [Fact] public void RetrieveStatistics_Remove_NullKey_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); AssertExtensions.Throws<ArgumentNullException>("key", () => d.Remove(null)); } [Fact] public void RetrieveStatistics_Contains_NullKey_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); AssertExtensions.Throws<ArgumentNullException>("key", () => d.Contains(null)); } [Fact] public void RetrieveStatistics_CopyTo_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); DictionaryEntry[] destination = new DictionaryEntry[d.Count]; d.CopyTo(destination, 0); int i = 0; foreach (DictionaryEntry entry in d) { Assert.Equal(entry, destination[i]); i++; } } [Fact] public void RetrieveStatistics_CopyTo_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); AssertExtensions.Throws<ArgumentNullException>("array", () => d.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentNullException>("array", () => d.CopyTo(null, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => d.CopyTo(new DictionaryEntry[20], -1)); AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[20], 18)); AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[20], 1000)); AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[4, 3], 0)); Assert.Throws<InvalidCastException>(() => d.CopyTo(new string[20], 0)); } [Fact] public void RetrieveStatistics_IDictionary_GetEnumerator_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); IDictionaryEnumerator e = d.GetEnumerator(); Assert.NotNull(e); Assert.NotSame(e, d.GetEnumerator()); for (int i = 0; i < 2; i++) { Assert.Throws<InvalidOperationException>(() => e.Current); foreach (string ignored in s_retrieveStatisticsKeys) { Assert.True(e.MoveNext()); Assert.NotNull(e.Current); Assert.IsType<DictionaryEntry>(e.Current); Assert.NotNull(e.Entry.Key); Assert.IsType<string>(e.Entry.Key); Assert.NotNull(e.Entry.Value); Assert.IsType<long>(e.Entry.Value); Assert.Equal(e.Current, e.Entry); Assert.Same(e.Key, e.Entry.Key); Assert.Same(e.Value, e.Entry.Value); Assert.True(s_retrieveStatisticsKeys.Contains(e.Entry.Key)); } Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Current); e.Reset(); } } [Fact] public void RetrieveStatistics_IEnumerable_GetEnumerator_Success() { // Treat the result as IEnumerable instead of IDictionary. IEnumerable d = new SqlConnection().RetrieveStatistics(); IEnumerator e = d.GetEnumerator(); Assert.NotNull(e); Assert.NotSame(e, d.GetEnumerator()); for (int i = 0; i < 2; i++) { Assert.Throws<InvalidOperationException>(() => e.Current); foreach (string ignored in s_retrieveStatisticsKeys) { Assert.True(e.MoveNext()); Assert.NotNull(e.Current); // Verify the IEnumerable.GetEnumerator enumerator is yielding DictionaryEntry entries, // not KeyValuePair entries. Assert.IsType<DictionaryEntry>(e.Current); DictionaryEntry entry = (DictionaryEntry)e.Current; Assert.NotNull(entry.Key); Assert.IsType<string>(entry.Key); Assert.NotNull(entry.Value); Assert.IsType<long>(entry.Value); Assert.True(s_retrieveStatisticsKeys.Contains(entry.Key)); } Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Current); e.Reset(); } } [Fact] public void RetrieveStatistics_GetEnumerator_ModifyCollection_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); IDictionaryEnumerator e = d.GetEnumerator(); d.Add("Foo", 0L); Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } [Fact] public void RetrieveStatistics_Keys_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.NotNull(d.Keys); Assert.Same(d.Keys, d.Keys); } [Fact] public void RetrieveStatistics_Keys_IsSynchronized_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; Assert.False(c.IsSynchronized); } [Fact] public void RetrieveStatistics_Keys_SyncRoot_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; Assert.NotNull(c.SyncRoot); Assert.Same(c.SyncRoot, c.SyncRoot); } [Fact] public void RetrieveStatistics_Keys_CopyTo_ObjectArray_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; object[] destination = new object[c.Count]; c.CopyTo(destination, 0); Assert.Equal(c.Cast<object>().ToArray(), destination); } [Fact] public void RetrieveStatistics_Keys_CopyTo_StringArray_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; string[] destination = new string[c.Count]; c.CopyTo(destination, 0); Assert.Equal(c.Cast<string>().ToArray(), destination); } [Fact] public void RetrieveStatistics_Keys_CopyTo_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => c.CopyTo(new string[20], -1)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[20], 18)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[20], 1000)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[4, 3], 0)); Assert.Throws<InvalidCastException>(() => c.CopyTo(new Version[20], 0)); } [Fact] public void RetrieveStatistics_Keys_GetEnumerator_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; IEnumerator e = c.GetEnumerator(); Assert.NotNull(e); Assert.NotSame(e, c.GetEnumerator()); for (int i = 0; i < 2; i++) { Assert.Throws<InvalidOperationException>(() => e.Current); foreach (string ignored in s_retrieveStatisticsKeys) { Assert.True(e.MoveNext()); Assert.NotNull(e.Current); Assert.True(s_retrieveStatisticsKeys.Contains(e.Current)); } Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Current); e.Reset(); } } [Fact] public void RetrieveStatistics_Keys_GetEnumerator_ModifyCollection_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Keys; IEnumerator e = c.GetEnumerator(); d.Add("Foo", 0L); Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } [Fact] public void RetrieveStatistics_Values_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); Assert.NotNull(d.Values); Assert.Same(d.Values, d.Values); } [Fact] public void RetrieveStatistics_Values_IsSynchronized_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; Assert.False(c.IsSynchronized); } [Fact] public void RetrieveStatistics_Values_SyncRoot_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; Assert.NotNull(c.SyncRoot); Assert.Same(c.SyncRoot, c.SyncRoot); } [Fact] public void RetrieveStatistics_Values_CopyTo_ObjectArray_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; object[] destination = new object[c.Count]; c.CopyTo(destination, 0); Assert.Equal(c.Cast<object>().ToArray(), destination); } [Fact] public void RetrieveStatistics_Values_CopyTo_Int64Array_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; long[] destination = new long[c.Count]; c.CopyTo(destination, 0); Assert.Equal(c.Cast<long>().ToArray(), destination); } [Fact] public void RetrieveStatistics_Values_CopyTo_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => c.CopyTo(new long[20], -1)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[20], 18)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[20], 1000)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[4, 3], 0)); Assert.Throws<InvalidCastException>(() => c.CopyTo(new Version[20], 0)); } [Fact] public void RetrieveStatistics_Values_GetEnumerator_Success() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; IEnumerator e = c.GetEnumerator(); Assert.NotNull(e); Assert.NotSame(e, c.GetEnumerator()); for (int i = 0; i < 2; i++) { Assert.Throws<InvalidOperationException>(() => e.Current); foreach (string ignored in s_retrieveStatisticsKeys) { Assert.True(e.MoveNext()); Assert.NotNull(e.Current); Assert.Equal(0L, e.Current); } Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Current); e.Reset(); } } [Fact] public void RetrieveStatistics_Values_GetEnumerator_ModifyCollection_Throws() { IDictionary d = new SqlConnection().RetrieveStatistics(); ICollection c = d.Values; IEnumerator e = c.GetEnumerator(); d.Add("Foo", 0L); Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; namespace System.Abstract { /// <summary> /// ServiceCacheRegistrar /// </summary> /// <remarks>[Wrap]SC\\{Anchor.FullName}::{Registration.Name}[#] /// ServiceCacheRegistrar._namePrefix - SC\\{Anchor.FullName}:: /// Registration.AbsoluteName = SC\\{Anchor.FullName}::{Registration.Name}</remarks> public class ServiceCacheRegistrar { static ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(); static Dictionary<Type, ServiceCacheRegistrar> _items = new Dictionary<Type, ServiceCacheRegistrar>(); ReaderWriterLockSlim _setRwLock = new ReaderWriterLockSlim(); HashSet<IServiceCacheRegistration> _set = new HashSet<IServiceCacheRegistration>(); Dictionary<string, IServiceCacheRegistration> _setAsName = new Dictionary<string, IServiceCacheRegistration>(); string _namePrefix; /// <summary> /// IDispatch /// </summary> public interface IDispatch { } internal ServiceCacheRegistrar(Type anchorType) { _namePrefix = "SC\\" + anchorType.FullName + "::"; AnchorType = anchorType; } /// <summary> /// Gets this instance. /// </summary> /// <typeparam name="TAnchor">The type of the anchor.</typeparam> /// <returns>ServiceCacheRegistrar.</returns> public static ServiceCacheRegistrar Get<TAnchor>() => Get(typeof(TAnchor)); /// <summary> /// Gets the specified anchor type. /// </summary> /// <param name="anchorType">Type of the anchor.</param> /// <returns>ServiceCacheRegistrar.</returns> public static ServiceCacheRegistrar Get(Type anchorType) { TryGet(anchorType, out var registrar, true); return registrar; } /// <summary> /// Registers all below. /// </summary> /// <typeparam name="T"></typeparam> public static void RegisterAllBelow<T>() => RegisterAllBelow(typeof(T)); /// <summary> /// Registers all below. /// </summary> /// <param name="type">The type.</param> public static void RegisterAllBelow(Type type) { var registrationType = typeof(IServiceCacheRegistration); var registrar = Get(type); var types = type.GetFields(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic) .Where(f => registrationType.IsAssignableFrom(f.FieldType)) .Select(f => (ServiceCacheRegistration)f.GetValue(null)); foreach (var t in types) registrar.Register(t); // recurse down foreach (var t in type.GetNestedTypes()) RegisterAllBelow(t); } /// <summary> /// Gets the type of the anchor. /// </summary> /// <value>The type of the anchor.</value> public Type AnchorType { get; private set; } /// <summary> /// Registers the specified registration. /// </summary> /// <param name="name">The registration name.</param> /// <param name="builder">The builder.</param> /// <param name="cacheTags">The cache tags.</param> public void Register(string name, CacheItemBuilder builder, params string[] cacheTags) => Register(new ServiceCacheRegistration(name, new CacheItemPolicy(60), builder, cacheTags)); /// <summary> /// Registers the specified registration. /// </summary> /// <param name="name">The registration name.</param> /// <param name="minuteTimeout">The minute timeout.</param> /// <param name="builder">The builder.</param> /// <param name="cacheTags">The cache tags.</param> public void Register(string name, int minuteTimeout, CacheItemBuilder builder, params string[] cacheTags) => Register(new ServiceCacheRegistration(name, new CacheItemPolicy(minuteTimeout), builder, cacheTags)); /// <summary> /// Registers the specified registration. /// </summary> /// <param name="name">The registration name.</param> /// <param name="itemPolicy">The cache command.</param> /// <param name="builder">The builder.</param> /// <param name="cacheTags">The cache tags.</param> public void Register(string name, CacheItemPolicy itemPolicy, CacheItemBuilder builder, params string[] cacheTags) => Register(new ServiceCacheRegistration(name, itemPolicy, builder, cacheTags)); /// <summary> /// Registers the specified registration. /// </summary> /// <param name="registration">The registration.</param> /// <exception cref="ArgumentNullException">registration /// or /// registration.Name</exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="ArgumentException">registration /// or /// registration</exception> public void Register(IServiceCacheRegistration registration) { if (registration == null) throw new ArgumentNullException(nameof(registration)); _setRwLock.EnterWriteLock(); try { if (_set.Contains(registration)) throw new InvalidOperationException(string.Format(Local.RedefineDataCacheAB, AnchorType.ToString(), registration.Name)); // add var registrationName = registration.Name; if (string.IsNullOrEmpty(registrationName)) throw new ArgumentNullException(nameof(registration.Name)); if (registrationName.IndexOf("::") > -1) throw new ArgumentException(string.Format(Local.ScopeCharacterNotAllowedA, registrationName), nameof(registration)); if (_setAsName.ContainsKey(registrationName)) throw new ArgumentException(string.Format(Local.RedefineNameA, registrationName), nameof(registration)); _setAsName.Add(registrationName, registration); _set.Add(registration); // link-in registration.AttachRegistrar(this, _namePrefix + registrationName); } finally { _setRwLock.ExitWriteLock(); } } /// <summary> /// Clears all registrations. /// </summary> public void Clear() { _setRwLock.EnterWriteLock(); try { _setAsName.Clear(); _set.Clear(); } finally { _setRwLock.ExitWriteLock(); } } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="registration">The registration.</param> /// <returns><c>true</c> if the specified key contains key; otherwise, <c>false</c>.</returns> public bool Contains(IServiceCacheRegistration registration) { _setRwLock.EnterReadLock(); try { return _set.Contains(registration); } finally { _setRwLock.ExitReadLock(); } } /// <summary> /// Determines whether the specified name has been registered. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the specified name has been registered; otherwise, <c>false</c>.</returns> public bool Contains(string name) { _setRwLock.EnterReadLock(); try { return _setAsName.ContainsKey(name); } finally { _setRwLock.ExitReadLock(); } } /// <summary> /// Removes the specified registration. /// </summary> /// <param name="registration">The registration.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool Remove(IServiceCacheRegistration registration) { _setRwLock.EnterWriteLock(); try { _setAsName.Remove(registration.Name); return _set.Remove(registration); } finally { _setRwLock.ExitWriteLock(); } } /// <summary> /// Removes the specified registration. /// </summary> /// <param name="name">The registration name.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool Remove(string name) { _setRwLock.EnterWriteLock(); try { var registration = _setAsName[name]; _setAsName.Remove(name); return _set.Remove(registration); } finally { _setRwLock.ExitWriteLock(); } } /// <summary> /// Gets all. /// </summary> /// <value>All.</value> internal IEnumerable<IServiceCacheRegistration> All => _set; /// <summary> /// Tries the get. /// </summary> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrar">The registrar.</param> /// <param name="createIfRequired">if set to <c>true</c> [create if required].</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> /// <exception cref="ArgumentNullException">anchorType</exception> public static bool TryGet(Type anchorType, out ServiceCacheRegistrar registrar, bool createIfRequired) { if (anchorType == null) throw new ArgumentNullException("anchorType"); _rwLock.EnterUpgradeableReadLock(); try { var exists = _items.TryGetValue(anchorType, out registrar); if (exists || !createIfRequired) return exists; _rwLock.EnterWriteLock(); try { if (!_items.TryGetValue(anchorType, out registrar)) { // create registrar = new ServiceCacheRegistrar(anchorType); _items.Add(anchorType, registrar); } } finally { _rwLock.ExitWriteLock(); } return true; } finally { _rwLock.ExitUpgradeableReadLock(); } } /// <summary> /// Tries the get value. /// </summary> /// <param name="registration">The registration.</param> /// <param name="recurses">The recurses.</param> /// <param name="foundRegistration">The found registration.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> /// <exception cref="InvalidOperationException"></exception> public static bool TryGetValue(IServiceCacheRegistration registration, ref int recurses, out IServiceCacheRegistration foundRegistration) { _rwLock.EnterReadLock(); try { var registrar = registration.Registrar; if (registrar != null) { // local check if (!(registration is ServiceCacheForeignRegistration foreignRegistration)) { foundRegistration = registration; return true; } // foreign recurse if (recurses++ > 4) throw new InvalidOperationException(Local.ExceedRecurseCount); // touch - starts foreign static constructor var foreignType = foreignRegistration.ForeignType; foreignType.InvokeMember("Touch", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null); return TryGetValue(foreignType, foreignRegistration.ForeignName, ref recurses, out foundRegistration); } foundRegistration = null; return false; } finally { _rwLock.ExitReadLock(); } } /// <summary> /// Tries the get value. /// </summary> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="recurses">The recurses.</param> /// <param name="foundRegistration">The found registration.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> /// <exception cref="InvalidOperationException"></exception> public static bool TryGetValue(Type anchorType, string registrationName, ref int recurses, out IServiceCacheRegistration foundRegistration) { _rwLock.EnterReadLock(); try { if (_items.TryGetValue(anchorType, out var registrar)) { // registration locals var setRwLock = registrar._setRwLock; var setAsId = registrar._setAsName; setRwLock.EnterReadLock(); try { if (setAsId.TryGetValue(registrationName, out var registration)) { // local check if (!(registration is ServiceCacheForeignRegistration foreignRegistration)) { foundRegistration = registration; return true; } // foreign recurse if (recurses++ > 4) throw new InvalidOperationException(Local.ExceedRecurseCount); // touch - starts foreign static constructor var foreignType = foreignRegistration.ForeignType; foreignType.InvokeMember("Touch", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null); return TryGetValue(foreignType, foreignRegistration.ForeignName, ref recurses, out foundRegistration); } } finally { setRwLock.ExitReadLock(); } } foundRegistration = null; return false; } finally { _rwLock.ExitReadLock(); } } } }
/* * * (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; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ASC.Api.Employee; using ASC.CRM.Core; using ASC.CRM.Core.Entities; using ASC.Specific; using ASC.Web.CRM; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Core.Enums; using Contact = ASC.CRM.Core.Entities.Contact; namespace ASC.Api.CRM.Wrappers { /// <summary> /// Person /// </summary> [DataContract(Name = "person", Namespace = "")] public class PersonWrapper : ContactWrapper { public PersonWrapper(int id) : base(id) { } public PersonWrapper(Person person) : base(person) { FirstName = person.FirstName; LastName = person.LastName; Title = person.JobTitle; } public static PersonWrapper ToPersonWrapperQuick(Person person) { var result = new PersonWrapper(person.ID); result.DisplayName = person.GetTitle(); result.IsPrivate = CRMSecurity.IsPrivate(person); result.IsShared = person.ShareType == ShareType.ReadWrite || person.ShareType == ShareType.Read; result.ShareType = person.ShareType; if (result.IsPrivate) { result.AccessList = CRMSecurity.GetAccessSubjectTo(person) .Select(item => EmployeeWraper.Get(item.Key)); } result.Currency = !String.IsNullOrEmpty(person.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(person.Currency)) : null; result.SmallFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=1", PathProvider.BaseAbsolutePath, person.ID, false); result.MediumFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=2", PathProvider.BaseAbsolutePath, person.ID, false); result.IsCompany = false; result.CanEdit = CRMSecurity.CanEdit(person); //result.CanDelete = CRMSecurity.CanDelete(contact); result.CreateBy = EmployeeWraper.Get(person.CreateBy); result.Created = (ApiDateTime)person.CreateOn; result.About = person.About; result.Industry = person.Industry; result.FirstName = person.FirstName; result.LastName = person.LastName; result.Title = person.JobTitle; return result; } [DataMember(IsRequired = true, EmitDefaultValue = false)] public String FirstName { get; set; } [DataMember(IsRequired = true, EmitDefaultValue = false)] public String LastName { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ContactBaseWrapper Company { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public String Title { get; set; } public new static PersonWrapper GetSample() { return new PersonWrapper(0) { IsPrivate = true, IsShared = false, IsCompany = false, FirstName = "Tadjeddine", LastName = "Bachir", Company = CompanyWrapper.GetSample(), Title = "Programmer", About = "", Created = ApiDateTime.GetSample(), CreateBy = EmployeeWraper.GetSample(), ShareType = ShareType.None }; } } /// <summary> /// Company /// </summary> [DataContract(Name = "company", Namespace = "")] public class CompanyWrapper : ContactWrapper { public CompanyWrapper(int id) : base(id) { } public CompanyWrapper(Company company) : base(company) { CompanyName = company.CompanyName; // PersonsCount = Global.DaoFactory.ContactDao.GetMembersCount(company.ID); } public static CompanyWrapper ToCompanyWrapperQuick(Company company) { var result = new CompanyWrapper(company.ID); result.DisplayName = company.GetTitle(); result.IsPrivate = CRMSecurity.IsPrivate(company); result.IsShared = company.ShareType == ShareType.ReadWrite || company.ShareType == ShareType.Read; result.ShareType = company.ShareType; if (result.IsPrivate) { result.AccessList = CRMSecurity.GetAccessSubjectTo(company) .Select(item => EmployeeWraper.Get(item.Key)); } result.Currency = !String.IsNullOrEmpty(company.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(company.Currency)) : null; result.SmallFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=1", PathProvider.BaseAbsolutePath, company.ID, true); result.MediumFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=2", PathProvider.BaseAbsolutePath, company.ID, true); result.IsCompany = true; result.CanEdit = CRMSecurity.CanEdit(company); //result.CanDelete = CRMSecurity.CanDelete(contact); result.CompanyName = company.CompanyName; result.CreateBy = EmployeeWraper.Get(company.CreateBy); result.Created = (ApiDateTime)company.CreateOn; result.About = company.About; result.Industry = company.Industry; return result; } [DataMember(IsRequired = true, EmitDefaultValue = false)] public String CompanyName { get; set; } [DataMember(IsRequired = true, EmitDefaultValue = false)] public IEnumerable<ContactBaseWrapper> Persons { get; set; } [DataMember(IsRequired = true, EmitDefaultValue = false)] public int PersonsCount { get; set; } public new static CompanyWrapper GetSample() { return new CompanyWrapper(0) { IsPrivate = true, IsShared = false, IsCompany = true, About = "", CompanyName = "Food and Culture Project", PersonsCount = 0 }; } } [DataContract(Name = "contact", Namespace = "")] [KnownType(typeof(PersonWrapper))] [KnownType(typeof(CompanyWrapper))] public abstract class ContactWrapper : ContactBaseWrapper { protected ContactWrapper(int id) : base(id) { } protected ContactWrapper(Contact contact) : base(contact) { CreateBy = EmployeeWraper.Get(contact.CreateBy); Created = (ApiDateTime)contact.CreateOn; About = contact.About; Industry = contact.Industry; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public IEnumerable<Address> Addresses { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public EmployeeWraper CreateBy { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ApiDateTime Created { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public String About { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public String Industry { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ContactStatusBaseWrapper ContactStatus { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ContactTypeBaseWrapper ContactType { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public IEnumerable<ContactInfoWrapper> CommonData { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public IEnumerable<CustomFieldBaseWrapper> CustomFields { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public IEnumerable<String> Tags { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public int TaskCount { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool HaveLateTasks { get; set; } public new static ContactWrapper GetSample() { return new PersonWrapper(0) { IsPrivate = true, IsShared = false, IsCompany = false, FirstName = "Tadjeddine", LastName = "Bachir", Company = CompanyWrapper.GetSample(), Title = "Programmer", About = "", Created = ApiDateTime.GetSample(), CreateBy = EmployeeWraper.GetSample(), CommonData = new List<ContactInfoWrapper>() { ContactInfoWrapper.GetSample() }, CustomFields = new List<CustomFieldBaseWrapper>() { CustomFieldBaseWrapper.GetSample() }, ShareType = ShareType.None, CanDelete = true, CanEdit = true, TaskCount = 0, HaveLateTasks = false }; } } [DataContract(Name = "contactBase", Namespace = "")] public class ContactBaseWithEmailWrapper : ContactBaseWrapper { protected ContactBaseWithEmailWrapper(int id) : base(id) { } public ContactBaseWithEmailWrapper(Contact contact) : base(contact) { } public ContactBaseWithEmailWrapper(ContactWrapper contactWrapper) : base(contactWrapper.ID) { AccessList = contactWrapper.AccessList; CanEdit = contactWrapper.CanEdit; DisplayName = contactWrapper.DisplayName; IsCompany = contactWrapper.IsCompany; IsPrivate = contactWrapper.IsPrivate; IsShared = contactWrapper.IsShared; ShareType = contactWrapper.ShareType; MediumFotoUrl = contactWrapper.MediumFotoUrl; SmallFotoUrl = contactWrapper.SmallFotoUrl; if (contactWrapper.CommonData != null && contactWrapper.CommonData.Count() != 0) { Email = contactWrapper.CommonData.FirstOrDefault(item => item.InfoType == ContactInfoType.Email && item.IsPrimary); } else { Email = null; } } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ContactInfoWrapper Email { get; set; } } [DataContract(Name = "contactBase", Namespace = "")] public class ContactBaseWithPhoneWrapper : ContactBaseWrapper { protected ContactBaseWithPhoneWrapper(int id) : base(id) { } public ContactBaseWithPhoneWrapper(Contact contact) : base(contact) { } public ContactBaseWithPhoneWrapper(ContactWrapper contactWrapper) : base(contactWrapper.ID) { AccessList = contactWrapper.AccessList; CanEdit = contactWrapper.CanEdit; DisplayName = contactWrapper.DisplayName; IsCompany = contactWrapper.IsCompany; IsPrivate = contactWrapper.IsPrivate; IsShared = contactWrapper.IsShared; ShareType = contactWrapper.ShareType; MediumFotoUrl = contactWrapper.MediumFotoUrl; SmallFotoUrl = contactWrapper.SmallFotoUrl; if (contactWrapper.CommonData != null && contactWrapper.CommonData.Count() != 0) { Phone = contactWrapper.CommonData.FirstOrDefault(item => item.InfoType == ContactInfoType.Phone && item.IsPrimary); } else { Phone = null; } } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ContactInfoWrapper Phone { get; set; } } /// <summary> /// Contact base information /// </summary> [DataContract(Name = "contactBase", Namespace = "")] public class ContactBaseWrapper : ObjectWrapperBase { public ContactBaseWrapper(Contact contact) : base(contact.ID) { DisplayName = contact.GetTitle(); IsPrivate = CRMSecurity.IsPrivate(contact); IsShared = contact.ShareType == ShareType.ReadWrite || contact.ShareType == ShareType.Read; ShareType = contact.ShareType; if (IsPrivate) { AccessList = CRMSecurity.GetAccessSubjectTo(contact) .Select(item => EmployeeWraper.Get(item.Key)); } Currency = !String.IsNullOrEmpty(contact.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(contact.Currency)) : null; SmallFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=1", PathProvider.BaseAbsolutePath, contact.ID, contact is Company); MediumFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=2", PathProvider.BaseAbsolutePath, contact.ID, contact is Company); IsCompany = contact is Company; CanEdit = CRMSecurity.CanEdit(contact); CanDelete = CRMSecurity.CanDelete(contact); } public static ContactBaseWrapper ToContactBaseWrapperQuick(Contact contact) { var result = new ContactBaseWrapper(contact.ID); result.DisplayName = contact.GetTitle(); result.IsPrivate = CRMSecurity.IsPrivate(contact); result.IsShared = contact.ShareType == ShareType.ReadWrite || contact.ShareType == ShareType.Read; result.ShareType = contact.ShareType; if (result.IsPrivate) { result.AccessList = CRMSecurity.GetAccessSubjectTo(contact) .Select(item => EmployeeWraper.Get(item.Key)); } result.Currency = !String.IsNullOrEmpty(contact.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(contact.Currency)) : null; result.SmallFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=1", PathProvider.BaseAbsolutePath, contact.ID, contact is Company); result.MediumFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=2", PathProvider.BaseAbsolutePath, contact.ID, contact is Company); result.IsCompany = contact is Company; result.CanEdit = CRMSecurity.CanEdit(contact); //result.CanDelete = CRMSecurity.CanDelete(contact); return result; } protected ContactBaseWrapper(int contactID) : base(contactID) { } [DataMember(IsRequired = false, EmitDefaultValue = false)] public String SmallFotoUrl { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public String MediumFotoUrl { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public String DisplayName { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool IsCompany { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public IEnumerable<EmployeeWraper> AccessList { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool IsPrivate { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool IsShared { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public ShareType ShareType { get; set; } [DataMember] public CurrencyInfoWrapper Currency { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanEdit { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanDelete { get; set; } public static ContactBaseWrapper GetSample() { return new ContactBaseWrapper(0) { IsPrivate = true, IsShared = false, IsCompany = false, DisplayName = "Tadjeddine Bachir", SmallFotoUrl = "url to foto" }; } } [DataContract(Name = "contact_task", Namespace = "")] public class ContactWithTaskWrapper { [DataMember(IsRequired = false, EmitDefaultValue = false)] public TaskBaseWrapper Task { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = false)] public ContactWrapper Contact { get; set; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2016 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections.Generic; using System.Linq; #if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // FEATURE_MPCONTRACT #if NETFX_CORE using System.Reflection; #endif using System.Runtime.CompilerServices; using System.Threading; using System.Security; namespace MsgPack.Serialization { /// <summary> /// Repository for key type with RWlock scheme. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Repository should not be disposable because it may be shared so it is difficult to determine disposition timing" )] #if !NET35 && !UNITY [SecuritySafeCritical] #endif internal class TypeKeyRepository { private readonly ReaderWriterLockSlim _lock; private readonly Dictionary<RuntimeTypeHandle, object> _table; public TypeKeyRepository() : this( default( TypeKeyRepository ) ) { } public TypeKeyRepository( TypeKeyRepository copiedFrom ) { this._lock = new ReaderWriterLockSlim( LockRecursionPolicy.NoRecursion ); if ( copiedFrom == null ) { this._table = new Dictionary<RuntimeTypeHandle, object>(); } else { this._table = copiedFrom.GetClonedTable(); } } public TypeKeyRepository( Dictionary<RuntimeTypeHandle, object> table ) { this._lock = new ReaderWriterLockSlim( LockRecursionPolicy.NoRecursion ); this._table = table; } #if !NET35 && !UNITY [SecuritySafeCritical] #endif #if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] #endif // NET35 || UNITY private Dictionary<RuntimeTypeHandle, object> GetClonedTable() { bool holdsReadLock = false; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { } finally { this._lock.EnterReadLock(); holdsReadLock = true; } return new Dictionary<RuntimeTypeHandle, object>( this._table ); } finally { if ( holdsReadLock ) { this._lock.ExitReadLock(); } } } public bool Get( Type type, out object matched, out object genericDefinitionMatched ) { return this.GetCore( type, out matched, out genericDefinitionMatched ); } #if !NET35 && !UNITY [SecuritySafeCritical] #endif #if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] #endif // NET35 || UNITY private bool GetCore( Type type, out object matched, out object genericDefinitionMatched ) { bool holdsReadLock = false; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { } finally { this._lock.EnterReadLock(); holdsReadLock = true; } object result; if ( this._table.TryGetValue( type.TypeHandle, out result ) ) { matched = result; genericDefinitionMatched = null; return true; } if ( type.GetIsGenericType() ) { if ( this._table.TryGetValue( type.GetGenericTypeDefinition().TypeHandle, out result ) ) { matched = null; genericDefinitionMatched = result; return true; } } matched = null; genericDefinitionMatched = null; return false; } finally { if ( holdsReadLock ) { this._lock.ExitReadLock(); } } } public bool Register( Type type, object entry, Type nullableType, object nullableValue, SerializerRegistrationOptions options ) { Contract.Assert( entry != null, "entry != null" ); return this.RegisterCore( type, entry, nullableType, nullableValue, options ); } #if !NET35 && !UNITY [SecuritySafeCritical] #endif #if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] #endif // NET35 || UNITY private bool RegisterCore( Type key, object value, Type nullableType, object nullableValue, SerializerRegistrationOptions options ) { var allowOverwrite = ( options & SerializerRegistrationOptions.AllowOverride ) != 0; if ( allowOverwrite || !this.ContainsType( key, nullableType ) ) { bool holdsWriteLock = false; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { } finally { this._lock.EnterWriteLock(); holdsWriteLock = true; } if ( allowOverwrite || !this.ContainsType( key, nullableType ) ) { this._table[ key.TypeHandle ] = value; if ( nullableValue != null ) { this._table[ nullableType.TypeHandle ] = nullableValue; } return true; } } finally { if ( holdsWriteLock ) { this._lock.ExitWriteLock(); } } } return false; } private bool ContainsType( Type baseType, Type nullableType ) { if ( nullableType == null ) { return this._table.ContainsKey( baseType.TypeHandle ); } else { return this._table.ContainsKey( baseType.TypeHandle ) && this._table.ContainsKey( nullableType.TypeHandle ); } } public bool Unregister( Type type ) { return this.UnregisterCore( type ); } #if !NET35 && !UNITY [SecuritySafeCritical] #endif #if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] #endif // NET35 || UNITY private bool UnregisterCore( Type key ) { if ( this._table.ContainsKey( key.TypeHandle ) ) { bool holdsWriteLock = false; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { } finally { this._lock.EnterWriteLock(); holdsWriteLock = true; } return this._table.Remove( key.TypeHandle ); } finally { if ( holdsWriteLock ) { this._lock.ExitWriteLock(); } } } return false; } #if !NET35 && !UNITY [SecuritySafeCritical] #endif internal bool Contains( Type type ) { bool holdsReadLock = false; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { } finally { this._lock.EnterReadLock(); holdsReadLock = true; } return this._table.ContainsKey( type.TypeHandle ); } finally { if ( holdsReadLock ) { this._lock.ExitReadLock(); } } } #if !NET35 && !UNITY [SecuritySafeCritical] #endif internal IEnumerable<KeyValuePair<Type, object>> GetEntries() { bool holdsReadLock = false; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 RuntimeHelpers.PrepareConstrainedRegions(); #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 try { } finally { this._lock.EnterReadLock(); holdsReadLock = true; } return this._table.Select( kv => new KeyValuePair<Type, object>( Type.GetTypeFromHandle( kv.Key ), kv.Value ) ).ToArray(); } finally { if ( holdsReadLock ) { this._lock.ExitReadLock(); } } } } }
namespace AutoMapper.UnitTests { using System; using Should; using Xunit; namespace BeforeAfterMapping { public class When_configuring_before_and_after_methods : AutoMapperSpecBase { private Source _src; public class Source { } public class Destination { } protected override void Establish_context() { _src = new Source(); } [Fact] public void Before_and_After_should_be_called() { var beforeMapCalled = false; var afterMapCalled = false; Mapper.CreateMap<Source, Destination>() .BeforeMap((src, dest) => beforeMapCalled = true) .AfterMap((src, dest) => afterMapCalled = true); Mapper.Map<Source, Destination>(_src); beforeMapCalled.ShouldBeTrue(); afterMapCalled.ShouldBeTrue(); } } public class When_configuring_before_and_after_methods_multiple_times : AutoMapperSpecBase { private Source _src; public class Source { } public class Destination { } protected override void Establish_context() { _src = new Source(); } [Fact] public void Before_and_After_should_be_called() { var beforeMapCount = 0; var afterMapCount = 0; Mapper.CreateMap<Source, Destination>() .BeforeMap((src, dest) => beforeMapCount++) .BeforeMap((src, dest) => beforeMapCount++) .AfterMap((src, dest) => afterMapCount++) .AfterMap((src, dest) => afterMapCount++); Mapper.Map<Source, Destination>(_src); beforeMapCount.ShouldEqual(2); afterMapCount.ShouldEqual(2); } } public class When_using_a_class_to_do_before_after_mappings : AutoMapperSpecBase { private Destination _destination; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } public class BeforeMapAction : IMappingAction<Source, Destination> { private readonly int _decrement; public BeforeMapAction(int decrement) { _decrement = decrement; } public void Process(Source source, Destination destination) { source.Value -= _decrement*2; } } public class AfterMapAction : IMappingAction<Source, Destination> { private readonly int _increment; public AfterMapAction(int increment) { _increment = increment; } public void Process(Source source, Destination destination) { destination.Value += _increment*5; } } protected override void Establish_context() { Mapper.Initialize(i => i.ConstructServicesUsing(t => Activator.CreateInstance(t, 2))); Mapper.CreateMap<Source, Destination>() .BeforeMap<BeforeMapAction>() .AfterMap<AfterMapAction>(); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {Value = 4}); } [Fact] public void Should_use_global_constructor_for_building_mapping_actions() { _destination.Value.ShouldEqual(10); } } public class MappingSpecificBeforeMapping : AutoMapperSpecBase { private Dest _dest; public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Dest>() .BeforeMap((src, dest) => src.Value += 10); } protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Value = 5 }, opt => opt.BeforeMap((src, dest) => src.Value += 10)); } [Fact] public void Should_execute_typemap_and_scoped_beforemap() { _dest.Value.ShouldEqual(25); } } public class MappingSpecificAfterMapping : AutoMapperSpecBase { private Dest _dest; public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Dest>() .AfterMap((src, dest) => dest.Value += 10); } protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Value = 5 }, opt => opt.AfterMap((src, dest) => dest.Value += 10)); } [Fact] public void Should_execute_typemap_and_scoped_aftermap() { _dest.Value.ShouldEqual(25); } } } }
// 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.Text; using System.Diagnostics; using System.Globalization; namespace Microsoft.Xml { using System; // // CharEntityEncoderFallback // internal class CharEntityEncoderFallback : EncoderFallback { private CharEntityEncoderFallbackBuffer _fallbackBuffer; private int[] _textContentMarks; private int _endMarkPos; private int _curMarkPos; private int _startOffset; internal CharEntityEncoderFallback() { } public override EncoderFallbackBuffer CreateFallbackBuffer() { if (_fallbackBuffer == null) { _fallbackBuffer = new CharEntityEncoderFallbackBuffer(this); } return _fallbackBuffer; } public override int MaxCharCount { get { return 12; } } internal int StartOffset { get { return _startOffset; } set { _startOffset = value; } } internal void Reset(int[] textContentMarks, int endMarkPos) { _textContentMarks = textContentMarks; _endMarkPos = endMarkPos; _curMarkPos = 0; } internal bool CanReplaceAt(int index) { int mPos = _curMarkPos; int charPos = _startOffset + index; while (mPos < _endMarkPos && charPos >= _textContentMarks[mPos + 1]) { mPos++; } _curMarkPos = mPos; return (mPos & 1) != 0; } } // // CharEntityFallbackBuffer // internal class CharEntityEncoderFallbackBuffer : EncoderFallbackBuffer { private CharEntityEncoderFallback _parent; private string _charEntity = string.Empty; private int _charEntityIndex = -1; internal CharEntityEncoderFallbackBuffer(CharEntityEncoderFallback parent) { _parent = parent; } public override bool Fallback(char charUnknown, int index) { // If we are already in fallback, throw, it's probably at the suspect character in charEntity if (_charEntityIndex >= 0) { (new EncoderExceptionFallback()).CreateFallbackBuffer().Fallback(charUnknown, index); } // find out if we can replace the character with entity if (_parent.CanReplaceAt(index)) { // Create the replacement character entity _charEntity = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", new object[] { (int)charUnknown }); _charEntityIndex = 0; return true; } else { EncoderFallbackBuffer errorFallbackBuffer = (new EncoderExceptionFallback()).CreateFallbackBuffer(); errorFallbackBuffer.Fallback(charUnknown, index); return false; } } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // check input surrogate pair if (!char.IsSurrogatePair(charUnknownHigh, charUnknownLow)) { throw XmlConvert.CreateInvalidSurrogatePairException(charUnknownHigh, charUnknownLow); } // If we are already in fallback, throw, it's probably at the suspect character in charEntity if (_charEntityIndex >= 0) { (new EncoderExceptionFallback()).CreateFallbackBuffer().Fallback(charUnknownHigh, charUnknownLow, index); } if (_parent.CanReplaceAt(index)) { // Create the replacement character entity _charEntity = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", new object[] { SurrogateCharToUtf32(charUnknownHigh, charUnknownLow) }); _charEntityIndex = 0; return true; } else { EncoderFallbackBuffer errorFallbackBuffer = (new EncoderExceptionFallback()).CreateFallbackBuffer(); errorFallbackBuffer.Fallback(charUnknownHigh, charUnknownLow, index); return false; } } public override char GetNextChar() { // Bug fix: 35637. The protocol using GetNextChar() and MovePrevious() called by Encoder is not well documented. // Here we have to to signal to Encoder that the previous read was last character. Only AFTER we can // mark ourself as done (-1). Otherwise MovePrevious() can still be called, but -1 is already incorrectly set // and return false from MovePrevious(). Then Encoder swallowing the rest of the bytes. if (_charEntityIndex == _charEntity.Length) { _charEntityIndex = -1; } if (_charEntityIndex == -1) { return (char)0; } else { Debug.Assert(_charEntityIndex < _charEntity.Length); char ch = _charEntity[_charEntityIndex++]; return ch; } } public override bool MovePrevious() { if (_charEntityIndex == -1) { return false; } else { // Could be == length if just read the last character Debug.Assert(_charEntityIndex <= _charEntity.Length); if (_charEntityIndex > 0) { _charEntityIndex--; return true; } else { return false; } } } public override int Remaining { get { if (_charEntityIndex == -1) { return 0; } else { return _charEntity.Length - _charEntityIndex; } } } public override void Reset() { _charEntityIndex = -1; } private int SurrogateCharToUtf32(char highSurrogate, char lowSurrogate) { return XmlCharType.CombineSurrogateChar(lowSurrogate, highSurrogate); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class zip_InvalidParametersAndStrangeFiles { private static void ConstructorThrows<TException>(Func<ZipArchive> constructor, String Message) where TException : Exception { try { Assert.Throws<TException>(() => { using (ZipArchive archive = constructor()) { } }); } catch (Exception e) { Console.WriteLine(string.Format("{0}: {1}", Message, e.ToString())); throw; } } [Fact] public static async Task InvalidInstanceMethods() { Stream zipFile = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(zipFile, ZipArchiveMode.Update)) { //non-existent entry Assert.True(null == archive.GetEntry("nonExistentEntry")); //"Should return null on non-existent entry name" //null/empty string Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null)); //"Should throw on null entry name" ZipArchiveEntry entry = archive.GetEntry("first.txt"); //null/empty string Assert.Throws<ArgumentException>(() => archive.CreateEntry("")); //"Should throw on empty entry name" Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null)); //"should throw on null entry name" } } [Fact] public static void InvalidConstructors() { //out of range enum values ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(-1)), "Out of range enum"); ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(4)), "out of range enum"); ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(10)), "Out of range enum"); //null/closed stream ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Read), "Null/closed stream"); ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Create), "Null/closed stream"); ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Update), "Null/closed stream"); MemoryStream ms = new MemoryStream(); ms.Dispose(); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Read), "Disposed Base Stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Create), "Disposed Base Stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Update), "Disposed Base Stream"); //non-seekable to update using (LocalMemoryStream nonReadable = new LocalMemoryStream(), nonWriteable = new LocalMemoryStream(), nonSeekable = new LocalMemoryStream()) { nonReadable.SetCanRead(false); nonWriteable.SetCanWrite(false); nonSeekable.SetCanSeek(false); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Read), "Non readable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Create), "Nonwritable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Update), "Non-readable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Update), "Nonwritable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonSeekable, ZipArchiveMode.Update), "Non-seekable stream"); } } [Fact] public static async Task UnsupportedCompression() { //lzma compression method await UnsupportedCompressionRoutine(ZipTest.bad("LZMA.zip"), true); await UnsupportedCompressionRoutine(ZipTest.bad("invalidDeflate.zip"), false); } private static async Task UnsupportedCompressionRoutine(String filename, Boolean throwsOnOpen) { // using (ZipArchive archive = ZipFile.OpenRead(filename)) using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read)) { ZipArchiveEntry e = archive.Entries[0]; if (throwsOnOpen) { Assert.Throws<InvalidDataException>(() => e.Open()); //"should throw on open" } else { using (Stream s = e.Open()) { Assert.Throws<InvalidDataException>(() => s.ReadByte()); //"Unreadable stream" } } } Stream updatedCopy = await StreamHelpers.CreateTempCopyStream(filename); String name; Int64 length, compressedLength; DateTimeOffset lastWriteTime; using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update, true)) { ZipArchiveEntry e = archive.Entries[0]; name = e.FullName; lastWriteTime = e.LastWriteTime; length = e.Length; compressedLength = e.CompressedLength; Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open" } //make sure that update mode preserves that unreadable file using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; Assert.Equal(name, e.FullName); //"Name isn't the same" Assert.Equal(lastWriteTime, e.LastWriteTime); //"LastWriteTime not the same" Assert.Equal(length, e.Length); //"Length isn't the same" Assert.Equal(compressedLength, e.CompressedLength); //"CompressedLength isn't the same" Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open" } } [Fact] public static async Task InvalidDates() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream( ZipTest.bad("invaliddate.zip")), ZipArchiveMode.Read)) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); //"Date isn't correct on invalid date" } using (ZipArchive archive = new ZipArchive(new MemoryStream(), ZipArchiveMode.Create)) { ZipArchiveEntry entry = archive.CreateEntry("test"); Assert.Throws<ArgumentOutOfRangeException>(() => { entry.LastWriteTime = new DateTimeOffset(1979, 12, 3, 5, 6, 2, new TimeSpan()); }); //"should throw on bad date" Assert.Throws<ArgumentOutOfRangeException>(() => { entry.LastWriteTime = new DateTimeOffset(2980, 12, 3, 5, 6, 2, new TimeSpan()); }); //"Should throw on bad date" } } [Fact] public static async Task StrangeFiles1() { ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream( ZipTest.strange(Path.Combine("extradata", "extraDataLHandCDentryAndArchiveComments.zip"))), ZipTest.zfolder("verysmall"), ZipArchiveMode.Update, false, false); } [Fact] public static async Task StrangeFiles2() { ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream( ZipTest.strange(Path.Combine("extradata", "extraDataThenZip64.zip"))), ZipTest.zfolder("verysmall"), ZipArchiveMode.Update, false, false); } [Fact] public static async Task StrangeFiles3() { ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream( ZipTest.strange(Path.Combine("extradata", "zip64ThenExtraData.zip"))), ZipTest.zfolder("verysmall"), ZipArchiveMode.Update, false, false); } [Fact] [ActiveIssue(1904, PlatformID.AnyUnix)] public static async Task StrangeFiles4() { ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream( ZipTest.strange("dataDescriptor.zip")), ZipTest.zfolder("normalWithoutBinary"), ZipArchiveMode.Update, true, false); } [Fact] public static async Task StrangeFiles5() { ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream( ZipTest.strange("filenameTimeAndSizesDifferentInLH.zip")), ZipTest.zfolder("verysmall"), ZipArchiveMode.Update, true, false); } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Linq; using EventStore.Common.Options; using EventStore.Core; using EventStore.Core.Bus; using EventStore.Core.Messages; using EventStore.Core.Messaging; using EventStore.Core.Services.TimerService; using EventStore.Core.Services.Transport.Http; using EventStore.Core.TransactionLog.Chunks; using EventStore.Core.Util; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Messages.EventReaders.Feeds; using EventStore.Projections.Core.Messaging; using EventStore.Projections.Core.Services.Processing; namespace EventStore.Projections.Core { public sealed class ProjectionsSubsystem : ISubsystem { private Projections _projections; private readonly int _projectionWorkerThreadCount; private readonly RunProjections _runProjections; public ProjectionsSubsystem(int projectionWorkerThreadCount, RunProjections runProjections) { if (runProjections <= RunProjections.System) _projectionWorkerThreadCount = 1; else _projectionWorkerThreadCount = projectionWorkerThreadCount; _runProjections = runProjections; } public void Register( TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendService) { _projections = new EventStore.Projections.Core.Projections( db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendService, projectionWorkerThreadCount: _projectionWorkerThreadCount, runProjections: _runProjections); } public void Start() { _projections.Start(); } public void Stop() { _projections.Stop(); } } sealed class Projections { public const int VERSION = 2; private List<QueuedHandler> _coreQueues; private readonly int _projectionWorkerThreadCount; private QueuedHandler _managerInputQueue; private InMemoryBus _managerInputBus; private ProjectionManagerNode _projectionManagerNode; public Projections( TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue, int projectionWorkerThreadCount, RunProjections runProjections) { _projectionWorkerThreadCount = projectionWorkerThreadCount; SetupMessaging( db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendQueue, runProjections); } private void SetupMessaging( TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue, RunProjections runProjections) { _coreQueues = new List<QueuedHandler>(); _managerInputBus = new InMemoryBus("manager input bus"); _managerInputQueue = new QueuedHandler(_managerInputBus, "Projections Master"); while (_coreQueues.Count < _projectionWorkerThreadCount) { var coreInputBus = new InMemoryBus("bus"); var coreQueue = new QueuedHandler( coreInputBus, "Projection Core #" + _coreQueues.Count, groupName: "Projection Core"); var projectionNode = new ProjectionWorkerNode(db, coreQueue, timeProvider, runProjections); projectionNode.SetupMessaging(coreInputBus); var forwarder = new RequestResponseQueueForwarder( inputQueue: coreQueue, externalRequestQueue: mainQueue); // forwarded messages projectionNode.CoreOutput.Subscribe<ClientMessage.ReadEvent>(forwarder); projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder); projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder); projectionNode.CoreOutput.Subscribe<ClientMessage.ReadAllEventsForward>(forwarder); projectionNode.CoreOutput.Subscribe<ClientMessage.WriteEvents>(forwarder); if (runProjections >= RunProjections.System) { projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.StateReport>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.ResultReport>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.StatisticsReport>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.Started>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.Stopped>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.Faulted>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.Prepared>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<CoreProjectionManagementMessage.SlaveProjectionReaderAssigned>( _managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create<ProjectionManagementMessage.ControlMessage>(_managerInputQueue)); } projectionNode.CoreOutput.Subscribe<TimerMessage.Schedule>(timerService); projectionNode.CoreOutput.Subscribe(Forwarder.Create<Message>(coreQueue)); // forward all coreInputBus.Subscribe(new UnwrapEnvelopeHandler()); _coreQueues.Add(coreQueue); } _managerInputBus.Subscribe( Forwarder.CreateBalancing<FeedReaderMessage.ReadPage>(_coreQueues.Cast<IPublisher>().ToArray())); _projectionManagerNode = ProjectionManagerNode.Create( db, _managerInputQueue, httpForwarder, httpServices, networkSendQueue, _coreQueues.Cast<IPublisher>().ToArray(), runProjections); _projectionManagerNode.SetupMessaging(_managerInputBus); { var forwarder = new RequestResponseQueueForwarder( inputQueue: _managerInputQueue, externalRequestQueue: mainQueue); _projectionManagerNode.Output.Subscribe<ClientMessage.ReadEvent>(forwarder); _projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder); _projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder); _projectionManagerNode.Output.Subscribe<ClientMessage.WriteEvents>(forwarder); _projectionManagerNode.Output.Subscribe( Forwarder.Create<ProjectionManagementMessage.RequestSystemProjections>(mainQueue)); _projectionManagerNode.Output.Subscribe(Forwarder.Create<Message>(_managerInputQueue)); _projectionManagerNode.Output.Subscribe<TimerMessage.Schedule>(timerService); // self forward all mainBus.Subscribe(Forwarder.Create<SystemMessage.StateChangeMessage>(_managerInputQueue)); _managerInputBus.Subscribe(new UnwrapEnvelopeHandler()); } } public void Start() { if (_managerInputQueue != null) _managerInputQueue.Start(); foreach (var queue in _coreQueues) queue.Start(); } public void Stop() { if (_managerInputQueue != null) _managerInputQueue.Stop(); foreach (var queue in _coreQueues) queue.Stop(); } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | 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.Windows; using System.Windows.Controls; using System.Windows.Media; using ESRI.ArcLogistics.App.Controls; using ESRI.ArcLogistics.Data; using ESRI.ArcLogistics.DomainObjects; using Xceed.Wpf.DataGrid; using Xceed.Wpf.Controls; using Xceed.Wpf.DataGrid.Views; namespace ESRI.ArcLogistics.App { /// <summary> /// Class for get any elements of xceed visual tree /// </summary> internal class XceedVisualTreeHelper { #region Public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Method searches visual parent with necessary type from visual tree of DependencyObject. /// </summary> /// <typeparam name="T">Type of object which should be found.</typeparam> /// <param name="from">Source object.</param> /// <returns>Found element of visual tree ao null if such element not exist there.</returns> public static T FindParent<T>(DependencyObject from) where T : class { T result = null; DependencyObject parent = VisualTreeHelper.GetParent(from); if (parent is T) result = parent as T; else if (parent != null) result = FindParent<T>(parent); return result; } /// <summary> /// Find table scroll viewer. /// </summary> /// <param name="element">Cell editor.</param> /// <returns>Scroll viewer instance or null if it wasn't found.</returns> public static TableViewScrollViewer FindScrollViewer(FrameworkElement element) { Debug.Assert(element != null); // If element is TableViewScrollViewer - then jsut return it. if (element is TableViewScrollViewer) return element as TableViewScrollViewer; // Find TableViewScrollViewer parent. FrameworkElement curElement = element; while (curElement != null && !(curElement is TableViewScrollViewer)) { curElement = (FrameworkElement)VisualTreeHelper.GetParent(curElement); } return (curElement == null) ? null : (TableViewScrollViewer)curElement; } /// <summary> /// Method returns row from mouse event args /// </summary> /// <param name="e"></param> /// <returns></returns> public static Row GetRowByEventArgs(RoutedEventArgs e) { // Get event source element. DependencyObject element = e.OriginalSource as DependencyObject; if (element == null) return null; // If it is FrameworkContentElement (when we click on Inline elements that are part of TextBlock) // we need to move up and find visual container. while (element != null && element is FrameworkContentElement) element = (element as FrameworkContentElement).Parent; // For some reason we can run into the null case. if (element == null) return null; // Element must be visual here. Debug.Assert(element is Visual); // Then we start to go by visual tree up searching Row visual parent. // If we run into DataGridControlEx or null then we must exit - no need to search any more. while (element != null && !(element is Row) && !(element is DataGridControlEx)) element = VisualTreeHelper.GetParent(element); if (element is Row) return element as Row; // We found row! // We didn't find a row. return null; } /// <summary> /// Method returns Cell from mouse event args /// </summary> /// <param name="e"></param> /// <returns></returns> public static Cell GetCellByEventArgs(RoutedEventArgs e) { Cell cell = null; if (e.OriginalSource is FrameworkElement) cell = _GetCellByFrameworkElement((FrameworkElement)e.OriginalSource); else if (e.OriginalSource is FrameworkContentElement) cell = _GetCellByFrameworkContentElement((FrameworkContentElement)e.OriginalSource); else cell = null; return cell; } /// <summary> /// Method returns parent cell for cell editor /// </summary> /// <param name="cellEditor">Cell editor.s</param> /// <returns>Cell.</returns> public static Cell GetCellByEditor(UIElement cellEditor) { return _GetCellByEditor(cellEditor); } /// <summary> /// Method returns parent grid control for cell editor /// </summary> /// <param name="cellEditor"></param> /// <returns></returns> public static DataGridControl GetGridByEditor(UIElement cellEditor) { DataGridControl dataGrid = null; UIElement control = cellEditor; //NOTE: View visual tree while we're not found DataGridControl //condition "parent != App.Current.MainWindow" added to avoid endless loop when DataGridControl was not found by any reason while (!(control is Xceed.Wpf.DataGrid.DataGridControl) && control != App.Current.MainWindow && control != null) control = (UIElement)VisualTreeHelper.GetParent(control); if (control is DataGridControl) dataGrid = (DataGridControl)control; return dataGrid; // if DataGrid not found - return null } /// <summary> /// Finds ATextBox inside of Framework element. /// </summary> /// <param name="sourceElement">Element to search inside.</param> /// <returns>First found TextBox instance or null if such control is not found.</returns> public static TextBox FindTextBoxInsideElement(FrameworkElement sourceElement) { if (sourceElement == null) return null; int childrenCount = VisualTreeHelper.GetChildrenCount(sourceElement); // Iterate through all the childer until TextBox (or inherited control) is not found. FrameworkElement result = null; for (int child = 0; child < childrenCount && result == null; child++) { var element = VisualTreeHelper.GetChild(sourceElement, child) as FrameworkElement; if (element != null) { if (element is AutoSelectTextBox || element is NumericTextBox || element is TextBox) result = element; // TextBox found. else result = FindTextBoxInsideElement(element); // Try to recursively find // among the element's children. } } Debug.Assert(result is AutoSelectTextBox || result is NumericTextBox || result is TextBox || result == null); return (result is AutoSelectTextBox || result is NumericTextBox || result is TextBox) ? (TextBox)result : null; } #endregion // Public methods #region Private Methods /// <summary> /// Method looks over visual tree (from FrameworkElement to it's parets), finds Cell element in parents and returns it /// if Cell isn't found - return null /// </summary> /// <param name="element">FrameWork Element.</param> /// <returns>Cell.</returns> private static Cell _GetCellByFrameworkElement(FrameworkElement element) { Cell cell = null; while (element.TemplatedParent != null && !(element.TemplatedParent is RowSelector) && !(element.TemplatedParent is DataCell) && !(element.TemplatedParent is DataGridControlEx)) { element = (FrameworkElement)VisualTreeHelper.GetParent((FrameworkElement)element); if (element.TemplatedParent is Control) { cell = _GetCellByEditor(element.TemplatedParent as UIElement); // Get cell by cell editor. break; } } if (element.TemplatedParent is DataCell && cell == null) cell = (DataCell)element.TemplatedParent; return cell; } /// <summary> /// Method looks over visual tree (from FrameworkContentElement to it's parets), finds Cell element in parents and returns it /// if Cell isn't found - return null /// </summary> /// <param name="element">Framework Content element.</param> /// <returns>Cell.</returns> private static Cell _GetCellByFrameworkContentElement(FrameworkContentElement element) { Cell cell = null; FrameworkElement templateElement = null; while (!(element.Parent is FrameworkElement)) element = (FrameworkContentElement)element.Parent; templateElement = (FrameworkElement)element.Parent; while (templateElement.TemplatedParent != null && !(templateElement.TemplatedParent is DataGridControlEx) && !(templateElement.TemplatedParent is DataCell) && !(templateElement.TemplatedParent is RowSelector)) templateElement = (FrameworkElement)VisualTreeHelper.GetParent((FrameworkElement)templateElement); if (templateElement.TemplatedParent is DataCell) cell = (DataCell)templateElement.TemplatedParent; return cell; } /// <summary> /// Method returns parent cell for cell editor /// </summary> /// <returns>Cell</returns> /// <param name="cellEditor">Cell editor.</param> private static Cell _GetCellByEditor(UIElement cellEditor) { Cell cell = null; UIElement control = cellEditor; //NOTE: View visual tree while we're not found Cell //condition "parent != App.Current.MainWindow" added to avoid endless loop when Cell was not found by any reason while (!(control is Xceed.Wpf.DataGrid.Cell) && control != App.Current.MainWindow && control != null) control = (UIElement)VisualTreeHelper.GetParent(control); if (control is Cell) cell = (Cell)control; return cell; // If cell not found - return null } #endregion } }
using System; using System.Collections.Generic; using System.Threading; using System.Globalization; /// <summary> /// System.DateTime.Kind /// </summary> public class DateTimeKind { public static int Main(string[] args) { DateTimeKind kind = new DateTimeKind(); TestLibrary.TestFramework.BeginScenario("Testing System.DateTime.Kind property..."); if (kind.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check Kind property when create an instance using Utc..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Utc); if (myDateTime.Kind != System.DateTimeKind.Utc) { TestLibrary.TestFramework.LogError("001", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check Kind property when create an instance using local..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Local); if (myDateTime.Kind != System.DateTimeKind.Local) { TestLibrary.TestFramework.LogError("003", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check Kind property when create an instance using Unspecified..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Unspecified); if (myDateTime.Kind != System.DateTimeKind.Unspecified) { TestLibrary.TestFramework.LogError("005", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check toUniversalTime is equal to original when create an instance using Utc..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Utc); DateTime toUniversal = myDateTime.ToUniversalTime(); if (myDateTime != toUniversal) { TestLibrary.TestFramework.LogError("007", "The two instances are not equal!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check toLocalTime is equal to original when create an instance using local..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Local); DateTime toLocal = myDateTime.ToLocalTime(); if (myDateTime != toLocal) { TestLibrary.TestFramework.LogError("009", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check an instance created by Unspecified, then compare to local and universal..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Unspecified); DateTime toLocal = myDateTime.ToLocalTime(); DateTime toUniversal = myDateTime.ToUniversalTime(); if (myDateTime == toLocal) { TestLibrary.TestFramework.LogError("011", "The Unspecified myDateTime is regard as local by default!"); retVal = false; } else if (myDateTime == toUniversal) { TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("013", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Drawing; using System.Runtime.InteropServices; namespace OpenLiveWriter.InternalWriterPlugin { public interface IJSMapController { void EnqueueEvent(IMapEvent e); string MapStyle { get; } int ZoomLevel {get; } bool BirdsEyeAvailable { get; } VEBirdseyeScene BirdseyeScene { get; } VELatLong GetCenter(); event EventHandler StyleChanged; event EventHandler ZoomLevelChanged; event EventHandler BirdseyeChanged; event MapContextMenuHandler ShowMapContextMenu; event MapPushpinContextMenuHandler ShowPushpinContextMenu; } public delegate void MapPropertyHandler(MapPropertyEvent e); public delegate void PushpinEventHandler(VEPushpin pushpin); public delegate void MapContextMenuHandler(MapContextMenuEvent e); public delegate void MapPushpinContextMenuHandler(MapContextMenuEvent e, string pushpinId); /// <summary> /// Controller object that is injected into the running Map HTMLDocument and is used to exchange /// data between the .NET and the HTMLDocument runtime. /// </summary> [ComVisible(true)] public class JSMapController : IJSMapController { private Queue _events; //list of events to be processed by the JavaScript runtime private VELatLong _center; internal JSMapController(VELatLong center, string mapStyle, int zoomLevel, VEBirdseyeScene scene ) { _events = new Queue(); _center = center; _birdseyeScene = scene; _mapStyle = mapStyle; _zoomLevel = zoomLevel; } void IJSMapController.EnqueueEvent(IMapEvent e) { _events.Enqueue(e); } #region Internal callbacks used by JS Runtime public IMapEvent NextEvent() { if(_events.Count > 0) { IMapEvent e = (IMapEvent) _events.Dequeue(); return e; } else return null; } public void ShowContextMenu(int x, int y, float latitude, float longitude, string reserved, string pushpinId) { if(reserved == String.Empty) reserved = null; if(pushpinId == "") { OnShowMapContextMenu(new MapContextMenuEvent(x, y, latitude, longitude, reserved)); } else { OnShowPushpinContextMenu(new MapContextMenuEvent(x, y, latitude, longitude, reserved), pushpinId); } } public void JSUpdateBirdsEye(string sceneId, string direction, string sceneThumbUrl ) { BirdseyeScene = new VEBirdseyeScene(sceneId, direction); OnBirdseyeChanged(EventArgs.Empty); } public void SetCenter(float latitude, float longitude, String reserved) { if(reserved == String.Empty) reserved = null; _center = new VELatLong(latitude, longitude, reserved); } #endregion #region JS Runtime Properties/Accessors public VELatLong GetCenter() { return _center; } public bool BirdsEyeAvailable { get { return _birdsEyeAvailable; } set { if(_birdsEyeAvailable != value) { _birdsEyeAvailable = value; OnBirdseyeChanged(EventArgs.Empty); } } } private bool _birdsEyeAvailable; public VEBirdseyeScene BirdseyeScene { get { return _birdseyeScene; } set { if(_birdseyeScene == null || value == null || _birdseyeScene.SceneId != value.SceneId) { _birdseyeScene = value; OnBirdseyeChanged(EventArgs.Empty); } } } private VEBirdseyeScene _birdseyeScene; public string MapStyle { get { return _mapStyle; } set { if(_mapStyle != value) { _mapStyle = value; OnStyleChanged(EventArgs.Empty); } } } private string _mapStyle; public int ZoomLevel { get { return _zoomLevel; } set { if(_zoomLevel != value) { _zoomLevel = value; OnZoomLevelChanged(EventArgs.Empty); } } } private int _zoomLevel; #endregion #region JS Runtime Events public event EventHandler StyleChanged; protected virtual void OnStyleChanged(EventArgs e) { if (StyleChanged != null) StyleChanged(this, e); } public event EventHandler ZoomLevelChanged; protected virtual void OnZoomLevelChanged(EventArgs e) { if (ZoomLevelChanged != null) ZoomLevelChanged(this, e); } public event MapContextMenuHandler ShowMapContextMenu; protected virtual void OnShowMapContextMenu(MapContextMenuEvent e) { if (ShowMapContextMenu != null) ShowMapContextMenu(e); } public event MapPushpinContextMenuHandler ShowPushpinContextMenu; protected virtual void OnShowPushpinContextMenu(MapContextMenuEvent e, string pushpinId) { if (ShowPushpinContextMenu != null) ShowPushpinContextMenu(e, pushpinId); } public event EventHandler BirdseyeChanged; protected virtual void OnBirdseyeChanged(EventArgs e) { if (BirdseyeChanged != null) BirdseyeChanged(this, e); } #endregion } [ComVisible(true)] public class VEBirdseyeScene { public VEBirdseyeScene() { } public VEBirdseyeScene(string sceneId, string orientation) { _sceneId = sceneId; _orientation = (VEOrientation)VEOrientation.Parse(typeof (VEOrientation), orientation); } public VEBirdseyeScene(string sceneId, VEOrientation orientation) { _sceneId = sceneId; _orientation = orientation; } private string _sceneId; public string SceneId { get { return _sceneId; } set { _sceneId = value; } } public VEOrientation Orientation { get { return _orientation; } set { _orientation = value; } } private VEOrientation _orientation; } public class VEBirdseyeSceneThumbnail { private string _sceneId; private BirdseyeSceneAdjacency _adjacency ; private string _url; public VEBirdseyeSceneThumbnail(string sceneId, BirdseyeSceneAdjacency adjacency, string url) { _sceneId = sceneId; _adjacency = adjacency; _url = url; } public string SceneId { get { return _sceneId; } } public BirdseyeSceneAdjacency Adjacency { get { return _adjacency; } } public string Url { get { return _url; } } } public enum BirdseyeSceneAdjacency { SameArea=-1, North=0, NorthEast=1, East=2, SouthEast=3, South=4, SouthWest=5, West=6, NorthWest=7}; public enum VEMapStyle { Road, Aerial, Hybrid, Birdseye }; [ComVisible(true)] public class VELatLong { private float _latitude; private float _longitude; private string _reserved; public VELatLong(float latitude, float longitude, String reserved) { _latitude = latitude; _longitude = longitude; _reserved = reserved; } public float Latitude { get { return _latitude; } } public float Longitude { get { return _longitude; } } public String Reserved { get { return _reserved; } } public override bool Equals(object obj) { VELatLong veLatLong = obj as VELatLong; return veLatLong != null && veLatLong.Latitude == Latitude && veLatLong.Longitude == Longitude && veLatLong.Reserved == Reserved; } public override int GetHashCode() { if(Reserved != null) return Reserved.GetHashCode(); else return Latitude.GetHashCode() | Longitude.GetHashCode(); } } [ComVisible(true)] public interface IMapEvent { int Type { get; } } public enum MapEventTypes { PropertyChanged=1, PushPinAction=2, PanMap=3, ZoomToPixel=4}; public enum VEOrientation { North, South, East, West } [ComVisible(true)] public class MapPropertyEvent : IMapEvent { public MapPropertyEvent(string name, object val) { _name = name; _value = val; } private string _name; private object _value; public string Name { get { return _name; } } public object Value { get { return _value; } } public int Type { get { return (int)MapEventTypes.PropertyChanged; } } } [ComVisible(true)] public class VEPushpin { private string _pinId; private VELatLong _veLatLong; private string _imageFile; private string _title; private string _details; private string _photoUrl; private string _moreInfoUrl; public VEPushpin(string pinId, VELatLong veLatLong, string imageFile, string title, string details, string moreInfoUrl, string photoUrl) { _pinId = pinId; _veLatLong = veLatLong; _imageFile = imageFile; _title = title; _details = details; _moreInfoUrl = moreInfoUrl; _photoUrl = photoUrl; } public string PinId { get { return _pinId; } } public VELatLong VELatLong { get { return _veLatLong; } } public string ImageFile { get { return _imageFile; } } public string Title { get { return _title; } } public string Details { get { return _details; } } public string MoreInfoUrl { get { return _moreInfoUrl; } } public string PhotoUrl { get { return _photoUrl; } } } [ComVisible(true)] public class PushpinEvent : IMapEvent { VEPushpin _pushpin; internal enum PushPinAction { Add=1, Delete=2, DeleteAll=3}; PushPinAction _action; internal PushpinEvent(VEPushpin pushpin, PushPinAction action) { _pushpin = pushpin; _action = action; } public VEPushpin Pushpin { get { return _pushpin; } } public int Action { get { return (int)_action; } } public int Type { get { return (int)MapEventTypes.PushPinAction; } } } [ComVisible(true)] public class PanMapEvent : IMapEvent { private int _deltaX; private int _deltaY; public PanMapEvent(int deltaX, int deltaY) { _deltaX = deltaX; _deltaY = deltaY; } public int DeltaX { get { return _deltaX; } } public int DeltaY { get { return _deltaY; } } public int Type { get { return (int)MapEventTypes.PanMap; } } } [ComVisible(true)] public class MapPixelZoomEvent : IMapEvent { private Point _location; private int _zoomLevel; public MapPixelZoomEvent(Point location, int zoomLevel) { _location = location; _zoomLevel = zoomLevel; } public int X { get { return _location.X; } } public int Y { get { return _location.Y; } } public int ZoomLevel { get { return _zoomLevel; } } public int Type { get { return (int)MapEventTypes.ZoomToPixel; } } } public class MapContextMenuEvent : EventArgs { int _x; int _y; float _latitude; float _longitude; string _reserved; internal MapContextMenuEvent(int x, int y, float latitude, float longitude, string reserved) { _x = x; _y = y; _latitude = latitude; _longitude = longitude; _reserved = reserved; } public int X { get { return _x; } } public int Y { get { return _y; } } public float Latitude { get { return _latitude; } } public float Longitude { get { return _longitude; } } public string Reserved { get { return _reserved; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reactive.Disposables; using System.Linq; using System.Linq.Expressions; using System.Reactive.Subjects; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using System.Reactive.Concurrency; using System.Runtime.CompilerServices; namespace ReactiveUIMicro { /// <summary> /// ReactiveObject is the base object for ViewModel classes, and it /// implements INotifyPropertyChanged. In addition, ReactiveObject provides /// Changing and Changed Observables to monitor object changes. /// </summary> [DataContract] public class ReactiveObject : IReactiveNotifyPropertyChanged, IEnableLogger { [field: IgnoreDataMember] bool rxObjectsSetup = false; [field:IgnoreDataMember] public event PropertyChangingEventHandler PropertyChanging; [field:IgnoreDataMember] public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Represents an Observable that fires *before* a property is about to /// be changed. /// </summary> [IgnoreDataMember] public IObservable<IObservedChange<object, object>> Changing { get { return changingSubject; } } /// <summary> /// Represents an Observable that fires *after* a property has changed. /// </summary> [IgnoreDataMember] public IObservable<IObservedChange<object, object>> Changed { get { #if DEBUG this.Log().Debug("Changed Subject 0x{0:X}", changedSubject.GetHashCode()); #endif return changedSubject; } } [IgnoreDataMember] protected Lazy<PropertyInfo[]> allPublicProperties; [IgnoreDataMember] Subject<IObservedChange<object, object>> changingSubject; [IgnoreDataMember] Subject<IObservedChange<object, object>> changedSubject; [IgnoreDataMember] long changeNotificationsSuppressed = 0; // Constructor protected ReactiveObject() { setupRxObj(); } [OnDeserialized] #if WP7 public #endif void setupRxObj(StreamingContext sc) { setupRxObj(); } void setupRxObj() { if (rxObjectsSetup) return; changingSubject = new Subject<IObservedChange<object, object>>(); changedSubject = new Subject<IObservedChange<object, object>>(); allPublicProperties = new Lazy<PropertyInfo[]>(() => GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToArray()); rxObjectsSetup = true; } /// <summary> /// When this method is called, an object will not fire change /// notifications (neither traditional nor Observable notifications) /// until the return value is disposed. /// </summary> /// <returns>An object that, when disposed, reenables change /// notifications.</returns> public IDisposable SuppressChangeNotifications() { Interlocked.Increment(ref changeNotificationsSuppressed); return Disposable.Create(() => Interlocked.Decrement(ref changeNotificationsSuppressed)); } protected internal virtual void raisePropertyChanging(string propertyName) { Contract.Requires(propertyName != null); verifyPropertyName(propertyName); if (!areChangeNotificationsEnabled || changingSubject == null) return; var handler = this.PropertyChanging; if (handler != null) { var e = new PropertyChangingEventArgs(propertyName); handler(this, e); } notifyObservable(new ObservedChange<object, object>() { PropertyName = propertyName, Sender = this, Value = null }, changingSubject); } protected internal virtual void raisePropertyChanged(string propertyName) { Contract.Requires(propertyName != null); verifyPropertyName(propertyName); this.Log().Debug("{0:X}.{1} changed", this.GetHashCode(), propertyName); if (!areChangeNotificationsEnabled || changedSubject == null) { this.Log().Debug("Suppressed change"); return; } var handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } notifyObservable(new ObservedChange<object, object>() { PropertyName = propertyName, Sender = this, Value = null }, changedSubject); } [Conditional("DEBUG")] [DebuggerStepThrough] void verifyPropertyName(string propertyName) { Contract.Requires(propertyName != null); // If you raise PropertyChanged and do not specify a property name, // all properties on the object are considered to be changed by the binding system. if (String.IsNullOrEmpty(propertyName)) return; #if !SILVERLIGHT && !WINRT // Verify that the property name matches a real, // public, instance property on this object. if (TypeDescriptor.GetProperties(this)[propertyName] == null) { string msg = "Invalid property name: " + propertyName; this.Log().Error(msg); } #endif } protected bool areChangeNotificationsEnabled { get { #if SILVERLIGHT // N.B. On most architectures, machine word aligned reads are // guaranteed to be atomic - sorry WP7, you're out of luck return changeNotificationsSuppressed == 0; #else return (Interlocked.Read(ref changeNotificationsSuppressed) == 0); #endif } } void notifyObservable<T>(T item, Subject<T> subject) { #if DEBUG this.Log().Debug("Firing observable to subject 0x{0:X}", subject.GetHashCode()); #endif try { subject.OnNext(item); } catch (Exception ex) { this.Log().Error(ex); subject.OnError(ex); } } } public static class ReactiveObjectExpressionMixin { /// <summary> /// RaiseAndSetIfChanged fully implements a Setter for a read-write /// property on a ReactiveObject, making the assumption that the /// property has a backing field named "_NameOfProperty". To change this /// assumption, set RxApp.GetFieldNameForPropertyNameFunc. /// </summary> /// <param name="property">An Expression representing the property (i.e. /// 'x => x.SomeProperty'</param> /// <param name="newValue">The new value to set the property to, almost /// always the 'value' keyword.</param> /// <returns>The newly set value, normally discarded.</returns> public static TRet RaiseAndSetIfChanged<TObj, TRet>( this TObj This, Expression<Func<TObj, TRet>> property, TRet newValue) where TObj : ReactiveObject { Contract.Requires(This != null); Contract.Requires(property != null); FieldInfo field; string prop_name = Reflection.SimpleExpressionToPropertyName(property); field = Reflection.GetBackingFieldInfoForProperty<TObj>(prop_name); var field_val = field.GetValue(This); if (EqualityComparer<TRet>.Default.Equals((TRet)field_val, (TRet)newValue)) { return newValue; } This.raisePropertyChanging(prop_name); field.SetValue(This, newValue); This.raisePropertyChanged(prop_name); return newValue; } /// <summary> /// RaiseAndSetIfChanged fully implements a Setter for a read-write /// property on a ReactiveObject, making the assumption that the /// property has a backing field named "_NameOfProperty". To change this /// assumption, set RxApp.GetFieldNameForPropertyNameFunc. This /// overload is intended for Silverlight and WP7 where reflection /// cannot access the private backing field. /// </summary> /// <param name="property">An Expression representing the property (i.e. /// 'x => x.SomeProperty'</param> /// <param name="backingField">A Reference to the backing field for this /// property.</param> /// <param name="newValue">The new value to set the property to, almost /// always the 'value' keyword.</param> /// <returns>The newly set value, normally discarded.</returns> public static TRet RaiseAndSetIfChanged<TObj, TRet>( this TObj This, Expression<Func<TObj, TRet>> property, ref TRet backingField, TRet newValue) where TObj : ReactiveObject { Contract.Requires(This != null); Contract.Requires(property != null); if (EqualityComparer<TRet>.Default.Equals(backingField, newValue)) { return newValue; } string prop_name = Reflection.SimpleExpressionToPropertyName(property); This.raisePropertyChanging(prop_name); backingField = newValue; This.raisePropertyChanged(prop_name); return newValue; } /// <summary> /// Use this method in your ReactiveObject classes when creating custom /// properties where raiseAndSetIfChanged doesn't suffice. /// </summary> /// <param name="property">An Expression representing the property (i.e. /// 'x => x.SomeProperty'</param> public static void RaisePropertyChanging<TObj, TRet>( this TObj This, Expression<Func<TObj, TRet>> property) where TObj : ReactiveObject { var propName = Reflection.SimpleExpressionToPropertyName(property); This.raisePropertyChanging(propName); } /// <summary> /// Use this method in your ReactiveObject classes when creating custom /// properties where raiseAndSetIfChanged doesn't suffice. /// </summary> /// <param name="property">An Expression representing the property (i.e. /// 'x => x.SomeProperty'</param> public static void RaisePropertyChanged<TObj, TRet>( this TObj This, Expression<Func<TObj, TRet>> property) where TObj : ReactiveObject { var propName = Reflection.SimpleExpressionToPropertyName(property); This.raisePropertyChanged(propName); } } public static class ReactiveObjectTestMixin { /// <summary> /// RaisePropertyChanging is a helper method intended for test / mock /// scenarios to manually fake a property change. /// </summary> /// <param name="target">The ReactiveObject to invoke /// raisePropertyChanging on.</param> /// <param name="property">The property that will be faking a change.</param> public static void RaisePropertyChanging(ReactiveObject target, string property) { target.raisePropertyChanging(property); } /// <summary> /// RaisePropertyChanging is a helper method intended for test / mock /// scenarios to manually fake a property change. /// </summary> /// <param name="target">The ReactiveObject to invoke /// raisePropertyChanging on.</param> /// <param name="property">The property that will be faking a change.</param> public static void RaisePropertyChanging<TSender, TValue>(TSender target, Expression<Func<TSender, TValue>> property) where TSender : ReactiveObject { RaisePropertyChanging(target, Reflection.SimpleExpressionToPropertyName(property)); } /// <summary> /// RaisePropertyChanged is a helper method intended for test / mock /// scenarios to manually fake a property change. /// </summary> /// <param name="target">The ReactiveObject to invoke /// raisePropertyChanging on.</param> /// <param name="property">The property that will be faking a change.</param> public static void RaisePropertyChanged(ReactiveObject target, string property) { target.raisePropertyChanged(property); } /// <summary> /// RaisePropertyChanged is a helper method intended for test / mock /// scenarios to manually fake a property change. /// </summary> /// <param name="target">The ReactiveObject to invoke /// raisePropertyChanging on.</param> /// <param name="property">The property that will be faking a change.</param> public static void RaisePropertyChanged<TSender, TValue>(TSender target, Expression<Func<TSender, TValue>> property) where TSender : ReactiveObject { RaisePropertyChanged(target, Reflection.SimpleExpressionToPropertyName(property)); } } } // vim: tw=120 ts=4 sw=4 et :
using UnityEditor.Rendering; using UnityEditorInternal; using UnityEngine; using UnityEngine.Experimental.Rendering.HDPipeline; namespace UnityEditor.Experimental.Rendering.HDPipeline { using CED = CoreEditorDrawer<SerializedDensityVolume>; static partial class DensityVolumeUI { [System.Flags] enum Expandable { Volume = 1 << 0, DensityMaskTexture = 1 << 1 } readonly static ExpandedState<Expandable, DensityVolume> k_ExpandedState = new ExpandedState<Expandable, DensityVolume>(Expandable.Volume | Expandable.DensityMaskTexture, "HDRP"); public static readonly CED.IDrawer Inspector = CED.Group( CED.Group( Drawer_ToolBar, Drawer_PrimarySettings ), CED.space, CED.FoldoutGroup( Styles.k_VolumeHeader, Expandable.Volume, k_ExpandedState, Drawer_AdvancedSwitch, Drawer_VolumeContent ), CED.FoldoutGroup( Styles.k_DensityMaskTextureHeader, Expandable.DensityMaskTexture, k_ExpandedState, Drawer_DensityMaskTextureContent ) ); static void Drawer_ToolBar(SerializedDensityVolume serialized, Editor owner) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditMode.DoInspectorToolbar(new[] { DensityVolumeEditor.k_EditShape, DensityVolumeEditor.k_EditBlend }, Styles.s_Toolbar_Contents, () => { var bounds = new Bounds(); foreach (Component targetObject in owner.targets) { bounds.Encapsulate(targetObject.transform.position); } return bounds; }, owner); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } static void Drawer_PrimarySettings(SerializedDensityVolume serialized, Editor owner) { EditorGUILayout.PropertyField(serialized.albedo, Styles.s_AlbedoLabel); EditorGUILayout.PropertyField(serialized.meanFreePath, Styles.s_MeanFreePathLabel); } static void Drawer_AdvancedSwitch(SerializedDensityVolume serialized, Editor owner) { using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); bool advanced = serialized.editorAdvancedFade.boolValue; advanced = GUILayout.Toggle(advanced, Styles.s_AdvancedModeContent, EditorStyles.miniButton, GUILayout.Width(60f), GUILayout.ExpandWidth(false)); DensityVolumeEditor.s_BlendBox.monoHandle = !advanced; if (serialized.editorAdvancedFade.boolValue ^ advanced) { serialized.editorAdvancedFade.boolValue = advanced; } } } static void Drawer_VolumeContent(SerializedDensityVolume serialized, Editor owner) { //keep previous data as value are stored in percent Vector3 previousSize = serialized.size.vector3Value; float previousUniformFade = serialized.editorUniformFade.floatValue; Vector3 previousPositiveFade = serialized.editorPositiveFade.vector3Value; Vector3 previousNegativeFade = serialized.editorNegativeFade.vector3Value; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(serialized.size, Styles.s_Size); if (EditorGUI.EndChangeCheck()) { Vector3 newSize = serialized.size.vector3Value; newSize.x = Mathf.Max(0f, newSize.x); newSize.y = Mathf.Max(0f, newSize.y); newSize.z = Mathf.Max(0f, newSize.z); serialized.size.vector3Value = newSize; //update advanced mode blend Vector3 newPositiveFade = new Vector3( newSize.x < 0.00001 ? 0 : previousPositiveFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousPositiveFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousPositiveFade.z * previousSize.z / newSize.z ); Vector3 newNegativeFade = new Vector3( newSize.x < 0.00001 ? 0 : previousNegativeFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousNegativeFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousNegativeFade.z * previousSize.z / newSize.z ); for (int axeIndex = 0; axeIndex < 3; ++axeIndex) { if (newPositiveFade[axeIndex] + newNegativeFade[axeIndex] > 1) { float overValue = (newPositiveFade[axeIndex] + newNegativeFade[axeIndex] - 1f) * 0.5f; newPositiveFade[axeIndex] -= overValue; newNegativeFade[axeIndex] -= overValue; if (newPositiveFade[axeIndex] < 0) { newNegativeFade[axeIndex] += newPositiveFade[axeIndex]; newPositiveFade[axeIndex] = 0f; } if (newNegativeFade[axeIndex] < 0) { newPositiveFade[axeIndex] += newNegativeFade[axeIndex]; newNegativeFade[axeIndex] = 0f; } } } serialized.editorPositiveFade.vector3Value = newPositiveFade; serialized.editorNegativeFade.vector3Value = newNegativeFade; //update normal mode blend float max = Mathf.Min(newSize.x, newSize.y, newSize.z) * 0.5f; serialized.editorUniformFade.floatValue = Mathf.Clamp(serialized.editorUniformFade.floatValue, 0f, max); } Vector3 serializedSize = serialized.size.vector3Value; EditorGUI.BeginChangeCheck(); if (serialized.editorAdvancedFade.hasMultipleDifferentValues) { using (new EditorGUI.DisabledScope(true)) EditorGUILayout.LabelField(Styles.s_BlendLabel, EditorGUIUtility.TrTextContent("Multiple values for Advanced mode")); } else if (serialized.editorAdvancedFade.boolValue) { EditorGUI.BeginChangeCheck(); CoreEditorUtils.DrawVector6(Styles.s_BlendLabel, serialized.editorPositiveFade, serialized.editorNegativeFade, Vector3.zero, serializedSize, InfluenceVolumeUI.k_HandlesColor, serialized.size); if (EditorGUI.EndChangeCheck()) { //forbid positive/negative box that doesn't intersect in inspector too Vector3 positive = serialized.editorPositiveFade.vector3Value; Vector3 negative = serialized.editorNegativeFade.vector3Value; for (int axis = 0; axis < 3; ++axis) { if (positive[axis] > 1f - negative[axis]) { if (positive == serialized.editorPositiveFade.vector3Value) { negative[axis] = 1f - positive[axis]; } else { positive[axis] = 1f - negative[axis]; } } } serialized.editorPositiveFade.vector3Value = positive; serialized.editorNegativeFade.vector3Value = negative; } } else { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(serialized.editorUniformFade, Styles.s_BlendLabel); if (EditorGUI.EndChangeCheck()) { float max = Mathf.Min(serializedSize.x, serializedSize.y, serializedSize.z) * 0.5f; serialized.editorUniformFade.floatValue = Mathf.Clamp(serialized.editorUniformFade.floatValue, 0f, max); } } if (EditorGUI.EndChangeCheck()) { Vector3 posFade = new Vector3(); posFade.x = Mathf.Clamp01(serialized.editorPositiveFade.vector3Value.x); posFade.y = Mathf.Clamp01(serialized.editorPositiveFade.vector3Value.y); posFade.z = Mathf.Clamp01(serialized.editorPositiveFade.vector3Value.z); Vector3 negFade = new Vector3(); negFade.x = Mathf.Clamp01(serialized.editorNegativeFade.vector3Value.x); negFade.y = Mathf.Clamp01(serialized.editorNegativeFade.vector3Value.y); negFade.z = Mathf.Clamp01(serialized.editorNegativeFade.vector3Value.z); serialized.editorPositiveFade.vector3Value = posFade; serialized.editorNegativeFade.vector3Value = negFade; } EditorGUILayout.PropertyField(serialized.invertFade, Styles.s_InvertFadeLabel); // Distance fade. { EditorGUI.BeginChangeCheck(); float distanceFadeStart = EditorGUILayout.FloatField(Styles.s_DistanceFadeStartLabel, serialized.distanceFadeStart.floatValue); float distanceFadeEnd = EditorGUILayout.FloatField(Styles.s_DistanceFadeEndLabel, serialized.distanceFadeEnd.floatValue); if (EditorGUI.EndChangeCheck()) { distanceFadeStart = Mathf.Max(0, distanceFadeStart); distanceFadeEnd = Mathf.Max(distanceFadeStart, distanceFadeEnd); serialized.distanceFadeStart.floatValue = distanceFadeStart; serialized.distanceFadeEnd.floatValue = distanceFadeEnd; } } } static void Drawer_DensityMaskTextureContent(SerializedDensityVolume serialized, Editor owner) { EditorGUILayout.PropertyField(serialized.volumeTexture, Styles.s_VolumeTextureLabel); EditorGUILayout.PropertyField(serialized.textureScroll, Styles.s_TextureScrollLabel); EditorGUILayout.PropertyField(serialized.textureTile, Styles.s_TextureTileLabel); } } }
// // AudioCdRipper.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 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.Threading; using System.Runtime.InteropServices; using Mono.Unix; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.MediaProfiles; using Banshee.Configuration.Schema; namespace Banshee.GStreamer { public class AudioCdRipper : IAudioCdRipper { private HandleRef handle; private string encoder_pipeline; private string output_extension; private string output_path; private TrackInfo current_track; private RipperProgressHandler progress_handler; private RipperMimeTypeHandler mimetype_handler; private RipperFinishedHandler finished_handler; private RipperErrorHandler error_handler; public event AudioCdRipperProgressHandler Progress; public event AudioCdRipperTrackFinishedHandler TrackFinished; public event AudioCdRipperErrorHandler Error; public void Begin (string device, bool enableErrorCorrection) { try { Profile profile = null; ProfileConfiguration config = ServiceManager.MediaProfileManager.GetActiveProfileConfiguration ("cd-importing"); if (config != null) { profile = config.Profile; } else { profile = ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/vorbis") ?? ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/flac"); if (profile != null) { Log.InformationFormat ("Using default/fallback encoding profile: {0}", profile.Name); ProfileConfiguration.SaveActiveProfile (profile, "cd-importing"); } } if (profile != null) { encoder_pipeline = profile.Pipeline.GetProcessById ("gstreamer"); output_extension = profile.OutputFileExtension; } if (String.IsNullOrEmpty (encoder_pipeline)) { throw new ApplicationException (); } Hyena.Log.InformationFormat ("Ripping using encoder profile `{0}' with pipeline: {1}", profile.Name, encoder_pipeline); } catch (Exception e) { throw new ApplicationException (Catalog.GetString ("Could not find an encoder for ripping."), e); } try { int paranoia_mode = enableErrorCorrection ? 255 : 0; handle = new HandleRef (this, br_new (device, paranoia_mode, encoder_pipeline)); progress_handler = new RipperProgressHandler (OnNativeProgress); br_set_progress_callback (handle, progress_handler); mimetype_handler = new RipperMimeTypeHandler (OnNativeMimeType); br_set_mimetype_callback (handle, mimetype_handler); finished_handler = new RipperFinishedHandler (OnNativeFinished); br_set_finished_callback (handle, finished_handler); error_handler = new RipperErrorHandler (OnNativeError); br_set_error_callback (handle, error_handler); } catch (Exception e) { throw new ApplicationException (Catalog.GetString ("Could not create CD ripping driver."), e); } } public void Finish () { if (output_path != null) { Banshee.IO.File.Delete (new SafeUri (output_path)); } TrackReset (); encoder_pipeline = null; output_extension = null; br_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); } public void Cancel () { Finish (); } private void TrackReset () { current_track = null; output_path = null; } public void RipTrack (int trackIndex, TrackInfo track, SafeUri outputUri, out bool taggingSupported) { TrackReset (); current_track = track; using (TagList tags = new TagList (track)) { output_path = String.Format ("{0}.{1}", outputUri.LocalPath, output_extension); // Avoid overwriting an existing file int i = 1; while (Banshee.IO.File.Exists (new SafeUri (output_path))) { output_path = String.Format ("{0} ({1}).{2}", outputUri.LocalPath, i++, output_extension); } Log.DebugFormat ("GStreamer ripping track {0} to {1}", trackIndex, output_path); br_rip_track (handle, trackIndex + 1, output_path, tags.Handle, out taggingSupported); } } protected virtual void OnProgress (TrackInfo track, TimeSpan ellapsedTime) { AudioCdRipperProgressHandler handler = Progress; if (handler != null) { handler (this, new AudioCdRipperProgressArgs (track, ellapsedTime, track.Duration)); } } protected virtual void OnTrackFinished (TrackInfo track, SafeUri outputUri) { AudioCdRipperTrackFinishedHandler handler = TrackFinished; if (handler != null) { handler (this, new AudioCdRipperTrackFinishedArgs (track, outputUri)); } } protected virtual void OnError (TrackInfo track, string message) { AudioCdRipperErrorHandler handler = Error; if (handler != null) { handler (this, new AudioCdRipperErrorArgs (track, message)); } } private void OnNativeProgress (IntPtr ripper, int mseconds) { OnProgress (current_track, TimeSpan.FromMilliseconds (mseconds)); } private void OnNativeMimeType (IntPtr ripper, IntPtr mimetype) { if (mimetype != IntPtr.Zero && current_track != null) { string type = GLib.Marshaller.Utf8PtrToString (mimetype); if (type != null) { string [] split = type.Split (';', '.', ' ', '\t'); if (split != null && split.Length > 0) { current_track.MimeType = split[0].Trim (); } else { current_track.MimeType = type.Trim (); } } } } private void OnNativeFinished (IntPtr ripper) { SafeUri uri = new SafeUri (output_path); TrackInfo track = current_track; TrackReset (); OnTrackFinished (track, uri); } private void OnNativeError (IntPtr ripper, IntPtr error, IntPtr debug) { string error_message = GLib.Marshaller.Utf8PtrToString (error); if (debug != IntPtr.Zero) { string debug_string = GLib.Marshaller.Utf8PtrToString (debug); if (!String.IsNullOrEmpty (debug_string)) { error_message = String.Format ("{0}: {1}", error_message, debug_string); } } OnError (current_track, error_message); } private delegate void RipperProgressHandler (IntPtr ripper, int mseconds); private delegate void RipperMimeTypeHandler (IntPtr ripper, IntPtr mimetype); private delegate void RipperFinishedHandler (IntPtr ripper); private delegate void RipperErrorHandler (IntPtr ripper, IntPtr error, IntPtr debug); [DllImport ("libbanshee.dll")] private static extern IntPtr br_new (string device, int paranoia_mode, string encoder_pipeline); [DllImport ("libbanshee.dll")] private static extern void br_destroy (HandleRef handle); [DllImport ("libbanshee.dll")] private static extern void br_rip_track (HandleRef handle, int track_number, string output_path, HandleRef tag_list, out bool tagging_supported); [DllImport ("libbanshee.dll")] private static extern void br_set_progress_callback (HandleRef handle, RipperProgressHandler callback); [DllImport ("libbanshee.dll")] private static extern void br_set_mimetype_callback (HandleRef handle, RipperMimeTypeHandler callback); [DllImport ("libbanshee.dll")] private static extern void br_set_finished_callback (HandleRef handle, RipperFinishedHandler callback); [DllImport ("libbanshee.dll")] private static extern void br_set_error_callback (HandleRef handle, RipperErrorHandler callback); } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Commands.Sql.Location_Capabilities.Model; using Microsoft.Azure.Commands.Sql.Location_Capabilities.Services; using System.Linq; using System.Management.Automation; using System.Text; namespace Microsoft.Azure.Commands.Sql.Location_Capabilities.Cmdlet { /// <summary> /// Defines the Get-AzureRmSqlCapability cmdlet /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmSqlCapability", ConfirmImpact = ConfirmImpact.None, DefaultParameterSetName = _filtered, SupportsShouldProcess = true)] public class GetAzureSqlCapability : AzureRMCmdlet { /// <summary> /// Parameter set name for when the cmdlet is invoked without specifying -Default /// </summary> private const string _filtered = "FilterResults"; /// <summary> /// Parameter set name for when the cmdlet is invoked with the -Default switch specified /// </summary> private const string _default = "DefaultResults"; /// <summary> /// Gets or sets the name of the Location /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "The name of the Location for which to get the capabilities")] [LocationCompleter("Microsoft.Sql/locations/capabilities")] [ValidateNotNullOrEmpty] public string LocationName { get; set; } /// <summary> /// Gets or sets the name of the server version /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the server version for which to get the capabilities", ParameterSetName = _filtered)] [ValidateNotNullOrEmpty] public string ServerVersionName { get; set; } /// <summary> /// Gets or sets the name of the database edition /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the database edition for which to get the capabilities", ParameterSetName = _filtered)] [ValidateNotNullOrEmpty] public string EditionName { get; set; } /// <summary> /// Gets or sets the name of the edition service level objective /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the edition Service Objective for which to get the capabilities", ParameterSetName = _filtered)] [ValidateNotNullOrEmpty] public string ServiceObjectiveName { get; set; } [Parameter(Mandatory = false, HelpMessage = "Indicates that the results should be filtered such that only defaults are shown", ParameterSetName = _default)] public SwitchParameter Defaults { get; set; } /// <summary> /// Executes the cmdlet /// </summary> public override void ExecuteCmdlet() { AzureSqlCapabilitiesAdapter adapter = new AzureSqlCapabilitiesAdapter(DefaultProfile.DefaultContext); LocationCapabilityModel model = adapter.GetLocationCapabilities(LocationName); int depth = 0; switch (ParameterSetName) { case _default: { FilterByDefaults(model); depth = 3; } break; case _filtered: { if (this.MyInvocation.BoundParameters.ContainsKey("ServerVersionName")) { FilterByServerVersion(model); depth = 1; } if (this.MyInvocation.BoundParameters.ContainsKey("EditionName")) { FilterByEditionName(model); depth = 2; } if (this.MyInvocation.BoundParameters.ContainsKey("ServiceObjectiveName")) { FilterByServiceObjectiveName(model); depth = 3; } } break; } if (depth > 0) { model.ExpandedDetails = CreateExpandedDetails(model, depth); } this.WriteObject(model, true); } /// <summary> /// Given a <see cref="LocationCapabilityModel"/> constructs a formatted string of its expanded details to the desired depth. /// </summary> /// <param name="model">The model details</param> /// <param name="depth">The depth to expand to</param> /// <returns>The formatted string containing the model details</returns> private string CreateExpandedDetails(LocationCapabilityModel model, int depth) { StringBuilder builder = new StringBuilder(); foreach (var version in model.SupportedServerVersions) { string versionInfo = GetVersionInformation(version); if (depth > 1) { ExpandEdition(depth, builder, version, versionInfo); } else { builder.AppendLine(versionInfo); } } return builder.ToString(); } /// <summary> /// Formats all the supported editions in <paramref name="version"/> as strings prefixed with <paramref name="prefix"/> /// and appends them to the <paramref name="builder"/> /// </summary> /// <param name="depth">How deep to expand the information</param> /// <param name="builder">The string builder to append the information</param> /// <param name="version">The version object to expand and format</param> /// <param name="prefix">The prefix to apply to the information strings</param> private void ExpandEdition(int depth, StringBuilder builder, ServerVersionCapabilityModel version, string prefix) { foreach (var edition in version.SupportedEditions) { string editionInfo = GetEditionInformation(prefix, edition); if (depth > 2) { ExpandServiceObjective(builder, edition, editionInfo); } else { builder.AppendLine(editionInfo); } } } /// <summary> /// Formats all the supported service objectives in <paramref name="edition"/> as strings prefixed with <paramref name="prefix"/> /// and appends them to the <paramref name="builder"/> /// </summary> /// <param name="builder">The string building to add the formatted string to</param> /// <param name="edition">The edition containing the supported service objectives</param> /// <param name="prefix">The prefix for the formatted string</param> private void ExpandServiceObjective(StringBuilder builder, EditionCapabilityModel edition, string prefix) { foreach (var slo in edition.SupportedServiceObjectives) { string serviceObjectiveInfo = GetServiceObjectiveInformation(prefix, slo); builder.AppendLine(serviceObjectiveInfo); } } /// <summary> /// Gets the string formatting of the server version object /// </summary> /// <param name="version">The server version information to format as a string</param> /// <returns>The formatted string containing the server version information</returns> private string GetVersionInformation(ServerVersionCapabilityModel version) { return string.Format("Version: {0} ({1})", version.ServerVersionName, version.Status); } /// <summary> /// Gets the string formatting of the edition object /// </summary> /// <param name="baseString">The prefix before the edition information</param> /// <param name="edition">The edition information to format and append to the end of the baseString</param> /// <returns>The formatted string containing the edition information</returns> private string GetEditionInformation(string baseString, EditionCapabilityModel edition) { return string.Format("{0} -> Edition: {1} ({2})", baseString, edition.EditionName, edition.Status); } /// <summary> /// Gets the string formatting of the service objective object /// </summary> /// <param name="baseString">The prefix before the service objective information</param> /// <param name="objective">The service objective information to append</param> /// <returns>The formatted string containing the service objective information</returns> private string GetServiceObjectiveInformation(string baseString, ServiceObjectiveCapabilityModel objective) { return string.Format("{0} -> Service Objective: {1} ({2})", baseString, objective.ServiceObjectiveName, objective.Status); } /// <summary> /// Filter the results based on what is marked as status /// </summary> /// <param name="model">The model to filter</param> private void FilterByDefaults(LocationCapabilityModel model) { model.SupportedServerVersions = model.SupportedServerVersions.Where(v => { return v.Status == "Default"; }).ToList(); // Get all defaults var defaultVersion = model.SupportedServerVersions; defaultVersion[0].SupportedEditions = defaultVersion[0].SupportedEditions.Where(v => { return v.Status == "Default"; }).ToList(); var defaultEdition = defaultVersion[0].SupportedEditions; defaultEdition[0].SupportedServiceObjectives = defaultEdition[0].SupportedServiceObjectives.Where(v => { return v.Status == "Default"; }).ToList(); var defaultServiceObjective = defaultEdition[0].SupportedServiceObjectives; // Assign defaults back to model. defaultServiceObjective[0].SupportedMaxSizes = defaultServiceObjective[0].SupportedMaxSizes.Where(v => { return v.Status == "Default"; }).ToList(); defaultEdition[0].SupportedServiceObjectives = defaultServiceObjective; defaultVersion[0].SupportedEditions = defaultEdition; model.SupportedServerVersions = defaultVersion; } /// <summary> /// Filter the results based on the Service Objective Name /// </summary> /// <param name="model">The model to filter</param> private void FilterByServiceObjectiveName(LocationCapabilityModel model) { foreach (var version in model.SupportedServerVersions) { foreach (var edition in version.SupportedEditions) { // Remove all service objectives with a name that does not match the desired value edition.SupportedServiceObjectives = edition.SupportedServiceObjectives .Where(slo => { return slo.ServiceObjectiveName == this.ServiceObjectiveName; }) .ToList(); } // Remove editions that have no supported service objectives after filtering version.SupportedEditions = version.SupportedEditions.Where(e => e.SupportedServiceObjectives.Count > 0).ToList(); } // Remove server versions that have no supported editions after filtering model.SupportedServerVersions = model.SupportedServerVersions.Where(v => v.SupportedEditions.Count > 0).ToList(); } /// <summary> /// Filter the results based on the Edition Name /// </summary> /// <param name="model">The model to filter</param> private void FilterByEditionName(LocationCapabilityModel model) { foreach (var version in model.SupportedServerVersions) { // Remove all editions that do not match the desired edition name version.SupportedEditions = version.SupportedEditions .Where(e => { return e.EditionName == this.EditionName; }) .ToList(); } // Remove server versions that have no supported editions after filtering model.SupportedServerVersions = model.SupportedServerVersions.Where(v => v.SupportedEditions.Count > 0).ToList(); } /// <summary> /// Filter the results based on the server version name /// </summary> /// <param name="model">The model to filter</param> private void FilterByServerVersion(LocationCapabilityModel model) { // Remove all server versions that don't match the desired name model.SupportedServerVersions = model.SupportedServerVersions .Where(obj => { return obj.ServerVersionName == this.ServerVersionName; }) .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Collections.Utilities; using Orleans.Streams; using Orleans.Streams.Endpoints; using Orleans.Streams.Messages; namespace Orleans.Collections { /// <summary> /// Implementation of a containerNode grain. /// </summary> public class ContainerNodeGrain<T> : Grain, IContainerNodeGrain<T> { protected IList<T> Collection; protected SingleStreamProvider<ContainerHostedElement<T>> StreamProvider; private SingleStreamConsumer<T> _streamConsumer; private const string StreamProviderName = "CollectionStreamProvider"; public async Task<IReadOnlyCollection<ContainerElementReference<T>>> AddRange(IEnumerable<T> items) { var newReferences = await InternalAddItems(items); return newReferences; } public async Task EnumerateItems(ICollection<IBatchItemAdder<T>> adders) { await adders.BatchAdd(Collection); } public Task Clear() { Collection.Clear(); return TaskDone.Done; } public Task<bool> Contains(T item) { return Task.FromResult(Collection.Contains(item)); } public Task<int> Count() { return Task.FromResult(Collection.Count); } public async Task<bool> Remove(T item) { return await InternalRemove(item); } protected virtual Task<bool> InternalRemove(T item) { return Task.FromResult(Collection.Remove(item)); } public async Task<bool> Remove(ContainerElementReference<T> reference) { if (!reference.ContainerId.Equals(this.GetPrimaryKey())) { throw new ArgumentException(); } return await InternalRemove(reference); } protected virtual Task<bool> InternalRemove(ContainerElementReference<T> reference) { if (Collection.Count < reference.Offset) { return Task.FromResult(false); } Collection.RemoveAt(reference.Offset); return Task.FromResult(true); } public async Task<int> EnumerateToStream(int? transactionId = null) { var hostedItems = Collection.Select((value, index) => new ContainerHostedElement<T>(GetReferenceForItem(index), value)).ToList(); return await StreamProvider.SendItems(hostedItems, true, transactionId); } public override async Task OnActivateAsync() { Collection = new List<T>(); StreamProvider = new SingleStreamProvider<ContainerHostedElement<T>>(GetStreamProvider(StreamProviderName), this.GetPrimaryKey()); _streamConsumer = new SingleStreamConsumer<T>(GetStreamProvider(StreamProviderName), this, TearDown); await base.OnActivateAsync(); } protected virtual Task<IReadOnlyCollection<ContainerElementReference<T>>> InternalAddItems(IEnumerable<T> batch) { lock (Collection) { var oldCount = Collection.Count; foreach (var item in batch) { Collection.Add(item); } IReadOnlyCollection<ContainerElementReference<T>> newReferences = Enumerable.Range(oldCount, Collection.Count - oldCount).Select(i => GetReferenceForItem(i)).ToList(); return Task.FromResult(newReferences); } } protected T GetItemAt(int offset) { return Collection[offset]; } protected ContainerElementReference<T> GetReferenceForItem(int offset, bool exists = true) { return new ContainerElementReference<T>(this.GetPrimaryKey(), offset, this, this.AsReference<IContainerNodeGrain<T>>(), exists); } public async Task<StreamIdentity<ContainerHostedElement<T>>> GetStreamIdentity() { return await StreamProvider.GetStreamIdentity(); } public async Task SetInput(StreamIdentity<T> inputStream) { await _streamConsumer.SetInput(inputStream); } public Task TransactionComplete(int transactionId) { return _streamConsumer.TransactionComplete(transactionId); } public async Task TearDown() { await StreamProvider.TearDown(); } public async Task<bool> IsTearedDown() { var tearDownStates = await Task.WhenAll(_streamConsumer.IsTearedDown(), StreamProvider.IsTearedDown()); return tearDownStates[0] && tearDownStates[1]; } public Task ExecuteSync(Action<T> action, ContainerElementReference<T> reference = null) { return ExecuteSync((x, state) => action(x), null, reference); } public Task ExecuteSync(Action<T, object> action, object state, ContainerElementReference<T> reference = null) { if (reference != null) { if (!reference.ContainerId.Equals(this.GetPrimaryKey())) { throw new InvalidOperationException(); } var curItem = GetItemAt(reference.Offset); action(curItem, state); } else { foreach (var item in Collection) { action(item, state); } } return TaskDone.Done; } public Task<IList<object>> ExecuteSync(Func<T, object> func) { return ExecuteSync((x, state) => func(x), null); } public Task<object> ExecuteSync(Func<T, object, object> func, object state, ContainerElementReference<T> reference) { if (!this.GetPrimaryKey().Equals(reference.ContainerId)) { throw new InvalidOperationException(); } var curItem = GetItemAt(reference.Offset); var result = func(curItem, state); return Task.FromResult(result); } public Task<IList<object>> ExecuteSync(Func<T, object, object> func, object state) { IList<object> results = Collection.Select(item => func(item, state)).ToList(); return Task.FromResult(results); } public Task<object> ExecuteSync(Func<T, object> func, ContainerElementReference<T> reference = null) { return ExecuteSync((x, state) => func(x), null, reference); } public Task ExecuteAsync(Func<T, Task> func, ContainerElementReference<T> reference = null) { return ExecuteAsync((x, state) => func(x), null, reference); } public async Task ExecuteAsync(Func<T, object, Task> func, object state, ContainerElementReference<T> reference = null) { if (reference != null) { if (!this.GetPrimaryKey().Equals(reference.ContainerId)) { throw new InvalidOperationException(); } var curItem = GetItemAt(reference.Offset); await func(curItem, state); } else { foreach (var item in Collection) { await func(item, state); } } } public Task<IList<object>> ExecuteAsync(Func<T, Task<object>> func) { return ExecuteAsync((x, state) => func(x), null); } public async Task<IList<object>> ExecuteAsync(Func<T, object, Task<object>> func, object state) { var results = Collection.Select(item => func(item, state)).ToList(); var resultSet = await Task.WhenAll(results); return new List<object>(resultSet); } public Task<object> ExecuteAsync(Func<T, Task<object>> func, ContainerElementReference<T> reference) { return ExecuteAsync((x, state) => func(x), null, reference); } public async Task<object> ExecuteAsync(Func<T, object, Task<object>> func, object state, ContainerElementReference<T> reference) { if (!this.GetPrimaryKey().Equals(reference.ContainerId)) { throw new InvalidOperationException(); } var curItem = GetItemAt(reference.Offset); var result = await func(curItem, state); return result; } public async Task Visit(ItemMessage<T> message) { await InternalAddItems(message.Items); } public Task Visit(TransactionMessage transactionMessage) { return TaskDone.Done; } } }
using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class AeroplaneController : MonoBehaviour { [SerializeField] private float maxEnginePower = 40f; // The maximum output of the engine. [SerializeField] private float lift = 0.002f; // The amount of lift generated by the aeroplane moving forwards. [SerializeField] private float zeroLiftSpeed = 300; // The speed at which lift is no longer applied. [SerializeField] private float rollEffect = 1f; // The strength of effect for roll input. [SerializeField] private float pitchEffect = 1f; // The strength of effect for pitch input. [SerializeField] private float yawEffect = 0.2f; // The strength of effect for yaw input. [SerializeField] private float bankedTurnEffect = 0.5f; // The amount of turn from doing a banked turn. [SerializeField] private float aerodynamicEffect = 0.02f; // How much aerodynamics affect the speed of the aeroplane. [SerializeField] private float autoTurnPitch = 0.5f; // How much the aeroplane automatically pitches when in a banked turn. [SerializeField] private float autoRollLevel = 0.2f; // How much the aeroplane tries to level when not rolling. [SerializeField] private float autoPitchLevel = 0.2f; // How much the aeroplane tries to level when not pitching. [SerializeField] private float airBrakesEffect = 3f; // How much the air brakes effect the drag. [SerializeField] private float throttleChangeSpeed = 0.3f; // The speed with which the throttle changes. [SerializeField] private float dragIncreaseFactor = 0.001f; // how much drag should increase with speed. public float Altitude { get; private set; } // The aeroplane's height above the ground. public float Throttle { get; private set; } // The amount of throttle being used. public bool AirBrakes { get; private set; } // Whether or not the air brakes are being applied. public float ForwardSpeed { get; private set; } // How fast the aeroplane is traveling in it's forward direction. public float EnginePower { get; private set; } // How much power the engine is being given. public float MaxEnginePower { get { return maxEnginePower; } } // The maximum output of the engine. public float RollAngle { get; private set; } public float PitchAngle { get; private set; } public float RollInput { get; private set; } public float PitchInput { get; private set; } public float YawInput { get; private set; } public float ThrottleInput { get; private set; } private float originalDrag; // The drag when the scene starts. private float originalAngularDrag; // The angular drag when the scene starts. private float aeroFactor; bool immobilized = false; // used for making the plane uncontrollable, i.e. if it has been hit or crashed. float bankedTurnAmount; void Start () { // Store original drag settings, these are modified during flight. originalDrag = rigidbody.drag; originalAngularDrag = rigidbody.angularDrag; } public void Move(float rollInput, float pitchInput, float yawInput, float throttleInput, bool airBrakes) { // transfer input parameters into properties.s this.RollInput = rollInput; this.PitchInput = pitchInput; this.YawInput = yawInput; this.ThrottleInput = throttleInput; this.AirBrakes = airBrakes; ClampInputs(); CalculateRollAndPitchAngles (); AutoLevel(); CalculateForwardSpeed (); ControlThrottle (); CalculateDrag (); CaluclateAerodynamicEffect (); CalculateLinearForces (); CalculateTorque (); CalculateAltitude (); } void ClampInputs() { // clamp the inputs to -1 to 1 range RollInput = Mathf.Clamp (RollInput, -1, 1); PitchInput = Mathf.Clamp (PitchInput, -1, 1); YawInput = Mathf.Clamp (YawInput, -1, 1); ThrottleInput = Mathf.Clamp (ThrottleInput, -1, 1); } void CalculateRollAndPitchAngles () { // Calculate roll & pitch angles // Calculate the flat forward direction (with no y component). var flatForward = transform.forward; flatForward.y = 0; // If the flat forward vector is non-zero (which would only happen if the plane was pointing exactly straight upwards) if (flatForward.sqrMagnitude > 0) { flatForward.Normalize (); // calculate current pitch angle var localFlatForward = transform.InverseTransformDirection (flatForward); PitchAngle = Mathf.Atan2 (localFlatForward.y, localFlatForward.z); // calculate current roll angle var flatRight = Vector3.Cross (Vector3.up, flatForward); var localFlatRight = transform.InverseTransformDirection (flatRight); RollAngle = Mathf.Atan2 (localFlatRight.y, localFlatRight.x); } } void AutoLevel () { // The banked turn amount (between -1 and 1) is the sine of the roll angle. // this is an amount applied to elevator input if the user is only using the banking controls, // because that's what people expect to happen in games! bankedTurnAmount = Mathf.Sin (RollAngle); // auto level roll, if there's no roll input: if (RollInput == 0f) { RollInput = -RollAngle * autoRollLevel; } // auto correct pitch, if no pitch input (but also apply the banked turn amount) if (PitchInput == 0f) { PitchInput = -PitchAngle * autoPitchLevel; PitchInput -= Mathf.Abs (bankedTurnAmount * bankedTurnAmount * autoTurnPitch); } } void CalculateForwardSpeed () { // Forward speed is the speed in the planes's forward direction (not the same as its velocity, eg if falling in a stall) var localVelocity = transform.InverseTransformDirection (rigidbody.velocity); ForwardSpeed = Mathf.Max (0, localVelocity.z); } void ControlThrottle () { // override throttle if immobilized if (immobilized) { ThrottleInput = -0.5f; } // Adjust throttle based on throttle input (or immobilized state) Throttle = Mathf.Clamp01 (Throttle + ThrottleInput * Time.deltaTime * throttleChangeSpeed); // current engine power is just: EnginePower = Throttle * maxEnginePower; } void CalculateDrag () { // increase the drag based on speed, since a constant drag doesn't seem "Real" (tm) enough float extraDrag = rigidbody.velocity.magnitude * dragIncreaseFactor; // Air brakes work by directly modifying drag. This part is actually pretty realistic! rigidbody.drag = (AirBrakes ? (originalDrag + extraDrag) * airBrakesEffect : originalDrag + extraDrag); // Forward speed affects angular drag - at high forward speed, it's much harder for the plane to spin rigidbody.angularDrag = originalAngularDrag * ForwardSpeed; } void CaluclateAerodynamicEffect () { // "Aerodynamic" calculations. This is a very simple approximation of the effect that a plane // will naturally try to align itself in the direction that it's facing when moving at speed. // Without this, the plane would behave a bit like the asteroids spaceship! if (rigidbody.velocity.magnitude > 0) { // compare the direction we're pointing with the direction we're moving: aeroFactor = Vector3.Dot (transform.forward, rigidbody.velocity.normalized); // multipled by itself results in a desirable rolloff curve of the effect aeroFactor *= aeroFactor; // Finally we calculate a new velocity by bending the current velocity direction towards // the the direction the plane is facing, by an amount based on this aeroFactor var newVelocity = Vector3.Lerp (rigidbody.velocity, transform.forward * ForwardSpeed, aeroFactor * ForwardSpeed * aerodynamicEffect * Time.deltaTime); rigidbody.velocity = newVelocity; // also rotate the plane towards the direction of movement - this should be a very small effect, but means the plane ends up // pointing downwards in a stall rigidbody.rotation = Quaternion.Slerp( rigidbody.rotation, Quaternion.LookRotation(rigidbody.velocity, transform.up), aerodynamicEffect * Time.deltaTime); } } void CalculateLinearForces () { // Now calculate forces acting on the aeroplane: // we accumulate forces into this variable: var forces = Vector3.zero; // Add the engine power in the forward direction forces += EnginePower * transform.forward; // The direction that the lift force is applied is at right angles to the plane's velocity (usually, this is 'up'!) var liftDirection = Vector3.Cross (rigidbody.velocity, transform.right).normalized; // The amount of lift drops off as the plane increases speed - in reality this occurs as the pilot retracts the flaps // shortly after takeoff, giving the plane less drag, but less lift. Because we don't simulate flaps, this is // a simple way of doing it automatically: var zeroLiftFactor = Mathf.InverseLerp (zeroLiftSpeed, 0, ForwardSpeed); // Calculate and add the lift power var liftPower = ForwardSpeed * ForwardSpeed * lift * zeroLiftFactor * aeroFactor; forces += liftPower * liftDirection; // Apply the calculated forces to the the rigidbody rigidbody.AddForce (forces); } void CalculateTorque () { // We accumulate torque forces into this variable: var torque = Vector3.zero; // Add torque for the pitch based on the pitch input. torque += PitchInput * pitchEffect * transform.right; // Add torque for the yaw based on the yaw input. torque += YawInput * yawEffect * transform.up; // Add torque for the roll based on the roll input. torque += -RollInput * rollEffect * transform.forward; // Add torque for banked turning. torque += bankedTurnAmount * bankedTurnEffect * transform.up; // The total torque is multiplied by the forward speed, so the controls have more effect at high speed, // and little effect at low speed, or when not moving in the direction of the nose of the plane // (i.e. falling while stalled) rigidbody.AddTorque (torque * ForwardSpeed * aeroFactor); } void CalculateAltitude () { // Altitude calculations - we raycast downwards from the aeroplane // starting a safe distance below the plane to avoid colliding with any of the plane's own colliders var ray = new Ray (transform.position - Vector3.up * 10, -Vector3.up); RaycastHit hit; if (Physics.Raycast (ray, out hit)) { Altitude = hit.distance + 10; } else { // there is nothing below us! Have we flown off the edge of the world? ah well, just use Y position as altitude Altitude = transform.position.y; } } // Immobilize can be called from other objects, for example if this plane is hit by a weapon and should become uncontrollable public void Immobilize () { immobilized = true; } // Reset is called via the ObjectResetter script, if present. public void Reset() { immobilized = false; } }
/* * 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 ecs-2014-11-13.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ECS.Model; using Amazon.ECS.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ECS { /// <summary> /// Implementation for accessing ECS /// /// <para> /// Amazon EC2 Container Service (Amazon ECS) is a highly scalable, fast, container management /// service that makes it easy to run, stop, and manage Docker containers on a cluster /// of Amazon EC2 instances. Amazon ECS lets you launch and stop container-enabled applications /// with simple API calls, allows you to get the state of your cluster from a centralized /// service, and gives you access to many familiar Amazon EC2 features like security groups, /// Amazon EBS volumes, and IAM roles. /// </para> /// /// <para> /// You can use Amazon ECS to schedule the placement of containers across your cluster /// based on your resource needs, isolation policies, and availability requirements. Amazon /// EC2 Container Service eliminates the need for you to operate your own cluster management /// and configuration management systems or worry about scaling your management infrastructure. /// </para> /// </summary> public partial class AmazonECSClient : AmazonServiceClient, IAmazonECS { #region Constructors /// <summary> /// Constructs AmazonECSClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonECSClient(AWSCredentials credentials) : this(credentials, new AmazonECSConfig()) { } /// <summary> /// Constructs AmazonECSClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonECSClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonECSConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonECSClient with AWS Credentials and an /// AmazonECSClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonECSClient Configuration Object</param> public AmazonECSClient(AWSCredentials credentials, AmazonECSConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonECSClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonECSClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonECSConfig()) { } /// <summary> /// Constructs AmazonECSClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonECSClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonECSConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonECSClient with AWS Access Key ID, AWS Secret Key and an /// AmazonECSClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonECSClient Configuration Object</param> public AmazonECSClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonECSConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonECSClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonECSClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonECSConfig()) { } /// <summary> /// Constructs AmazonECSClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonECSClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonECSConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonECSClient with AWS Access Key ID, AWS Secret Key and an /// AmazonECSClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonECSClient Configuration Object</param> public AmazonECSClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonECSConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CreateCluster internal CreateClusterResponse CreateCluster(CreateClusterRequest request) { var marshaller = new CreateClusterRequestMarshaller(); var unmarshaller = CreateClusterResponseUnmarshaller.Instance; return Invoke<CreateClusterRequest,CreateClusterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateCluster operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCluster operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateClusterResponse> CreateClusterAsync(CreateClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateClusterRequestMarshaller(); var unmarshaller = CreateClusterResponseUnmarshaller.Instance; return InvokeAsync<CreateClusterRequest,CreateClusterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateService internal CreateServiceResponse CreateService(CreateServiceRequest request) { var marshaller = new CreateServiceRequestMarshaller(); var unmarshaller = CreateServiceResponseUnmarshaller.Instance; return Invoke<CreateServiceRequest,CreateServiceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateService operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateService operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateServiceResponse> CreateServiceAsync(CreateServiceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateServiceRequestMarshaller(); var unmarshaller = CreateServiceResponseUnmarshaller.Instance; return InvokeAsync<CreateServiceRequest,CreateServiceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteCluster internal DeleteClusterResponse DeleteCluster(DeleteClusterRequest request) { var marshaller = new DeleteClusterRequestMarshaller(); var unmarshaller = DeleteClusterResponseUnmarshaller.Instance; return Invoke<DeleteClusterRequest,DeleteClusterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteCluster operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCluster operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteClusterResponse> DeleteClusterAsync(DeleteClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteClusterRequestMarshaller(); var unmarshaller = DeleteClusterResponseUnmarshaller.Instance; return InvokeAsync<DeleteClusterRequest,DeleteClusterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteService internal DeleteServiceResponse DeleteService(DeleteServiceRequest request) { var marshaller = new DeleteServiceRequestMarshaller(); var unmarshaller = DeleteServiceResponseUnmarshaller.Instance; return Invoke<DeleteServiceRequest,DeleteServiceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteService operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteService operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteServiceResponse> DeleteServiceAsync(DeleteServiceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteServiceRequestMarshaller(); var unmarshaller = DeleteServiceResponseUnmarshaller.Instance; return InvokeAsync<DeleteServiceRequest,DeleteServiceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeregisterContainerInstance internal DeregisterContainerInstanceResponse DeregisterContainerInstance(DeregisterContainerInstanceRequest request) { var marshaller = new DeregisterContainerInstanceRequestMarshaller(); var unmarshaller = DeregisterContainerInstanceResponseUnmarshaller.Instance; return Invoke<DeregisterContainerInstanceRequest,DeregisterContainerInstanceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeregisterContainerInstance operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeregisterContainerInstance operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeregisterContainerInstanceResponse> DeregisterContainerInstanceAsync(DeregisterContainerInstanceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeregisterContainerInstanceRequestMarshaller(); var unmarshaller = DeregisterContainerInstanceResponseUnmarshaller.Instance; return InvokeAsync<DeregisterContainerInstanceRequest,DeregisterContainerInstanceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeregisterTaskDefinition internal DeregisterTaskDefinitionResponse DeregisterTaskDefinition(DeregisterTaskDefinitionRequest request) { var marshaller = new DeregisterTaskDefinitionRequestMarshaller(); var unmarshaller = DeregisterTaskDefinitionResponseUnmarshaller.Instance; return Invoke<DeregisterTaskDefinitionRequest,DeregisterTaskDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeregisterTaskDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeregisterTaskDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeregisterTaskDefinitionResponse> DeregisterTaskDefinitionAsync(DeregisterTaskDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeregisterTaskDefinitionRequestMarshaller(); var unmarshaller = DeregisterTaskDefinitionResponseUnmarshaller.Instance; return InvokeAsync<DeregisterTaskDefinitionRequest,DeregisterTaskDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeClusters internal DescribeClustersResponse DescribeClusters(DescribeClustersRequest request) { var marshaller = new DescribeClustersRequestMarshaller(); var unmarshaller = DescribeClustersResponseUnmarshaller.Instance; return Invoke<DescribeClustersRequest,DescribeClustersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeClusters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeClusters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeClustersResponse> DescribeClustersAsync(DescribeClustersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeClustersRequestMarshaller(); var unmarshaller = DescribeClustersResponseUnmarshaller.Instance; return InvokeAsync<DescribeClustersRequest,DescribeClustersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeContainerInstances internal DescribeContainerInstancesResponse DescribeContainerInstances(DescribeContainerInstancesRequest request) { var marshaller = new DescribeContainerInstancesRequestMarshaller(); var unmarshaller = DescribeContainerInstancesResponseUnmarshaller.Instance; return Invoke<DescribeContainerInstancesRequest,DescribeContainerInstancesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeContainerInstances operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeContainerInstances operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeContainerInstancesResponse> DescribeContainerInstancesAsync(DescribeContainerInstancesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeContainerInstancesRequestMarshaller(); var unmarshaller = DescribeContainerInstancesResponseUnmarshaller.Instance; return InvokeAsync<DescribeContainerInstancesRequest,DescribeContainerInstancesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeServices internal DescribeServicesResponse DescribeServices(DescribeServicesRequest request) { var marshaller = new DescribeServicesRequestMarshaller(); var unmarshaller = DescribeServicesResponseUnmarshaller.Instance; return Invoke<DescribeServicesRequest,DescribeServicesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeServices operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeServices operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeServicesResponse> DescribeServicesAsync(DescribeServicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeServicesRequestMarshaller(); var unmarshaller = DescribeServicesResponseUnmarshaller.Instance; return InvokeAsync<DescribeServicesRequest,DescribeServicesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeTaskDefinition internal DescribeTaskDefinitionResponse DescribeTaskDefinition(DescribeTaskDefinitionRequest request) { var marshaller = new DescribeTaskDefinitionRequestMarshaller(); var unmarshaller = DescribeTaskDefinitionResponseUnmarshaller.Instance; return Invoke<DescribeTaskDefinitionRequest,DescribeTaskDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeTaskDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeTaskDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeTaskDefinitionResponse> DescribeTaskDefinitionAsync(DescribeTaskDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeTaskDefinitionRequestMarshaller(); var unmarshaller = DescribeTaskDefinitionResponseUnmarshaller.Instance; return InvokeAsync<DescribeTaskDefinitionRequest,DescribeTaskDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeTasks internal DescribeTasksResponse DescribeTasks(DescribeTasksRequest request) { var marshaller = new DescribeTasksRequestMarshaller(); var unmarshaller = DescribeTasksResponseUnmarshaller.Instance; return Invoke<DescribeTasksRequest,DescribeTasksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeTasks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeTasksResponse> DescribeTasksAsync(DescribeTasksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeTasksRequestMarshaller(); var unmarshaller = DescribeTasksResponseUnmarshaller.Instance; return InvokeAsync<DescribeTasksRequest,DescribeTasksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListClusters internal ListClustersResponse ListClusters(ListClustersRequest request) { var marshaller = new ListClustersRequestMarshaller(); var unmarshaller = ListClustersResponseUnmarshaller.Instance; return Invoke<ListClustersRequest,ListClustersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListClusters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListClusters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListClustersResponse> ListClustersAsync(ListClustersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListClustersRequestMarshaller(); var unmarshaller = ListClustersResponseUnmarshaller.Instance; return InvokeAsync<ListClustersRequest,ListClustersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListContainerInstances internal ListContainerInstancesResponse ListContainerInstances(ListContainerInstancesRequest request) { var marshaller = new ListContainerInstancesRequestMarshaller(); var unmarshaller = ListContainerInstancesResponseUnmarshaller.Instance; return Invoke<ListContainerInstancesRequest,ListContainerInstancesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListContainerInstances operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListContainerInstances operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListContainerInstancesResponse> ListContainerInstancesAsync(ListContainerInstancesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListContainerInstancesRequestMarshaller(); var unmarshaller = ListContainerInstancesResponseUnmarshaller.Instance; return InvokeAsync<ListContainerInstancesRequest,ListContainerInstancesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListServices internal ListServicesResponse ListServices(ListServicesRequest request) { var marshaller = new ListServicesRequestMarshaller(); var unmarshaller = ListServicesResponseUnmarshaller.Instance; return Invoke<ListServicesRequest,ListServicesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListServices operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListServices operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListServicesResponse> ListServicesAsync(ListServicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListServicesRequestMarshaller(); var unmarshaller = ListServicesResponseUnmarshaller.Instance; return InvokeAsync<ListServicesRequest,ListServicesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListTaskDefinitionFamilies internal ListTaskDefinitionFamiliesResponse ListTaskDefinitionFamilies(ListTaskDefinitionFamiliesRequest request) { var marshaller = new ListTaskDefinitionFamiliesRequestMarshaller(); var unmarshaller = ListTaskDefinitionFamiliesResponseUnmarshaller.Instance; return Invoke<ListTaskDefinitionFamiliesRequest,ListTaskDefinitionFamiliesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListTaskDefinitionFamilies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTaskDefinitionFamilies operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListTaskDefinitionFamiliesResponse> ListTaskDefinitionFamiliesAsync(ListTaskDefinitionFamiliesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListTaskDefinitionFamiliesRequestMarshaller(); var unmarshaller = ListTaskDefinitionFamiliesResponseUnmarshaller.Instance; return InvokeAsync<ListTaskDefinitionFamiliesRequest,ListTaskDefinitionFamiliesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListTaskDefinitions internal ListTaskDefinitionsResponse ListTaskDefinitions(ListTaskDefinitionsRequest request) { var marshaller = new ListTaskDefinitionsRequestMarshaller(); var unmarshaller = ListTaskDefinitionsResponseUnmarshaller.Instance; return Invoke<ListTaskDefinitionsRequest,ListTaskDefinitionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListTaskDefinitions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTaskDefinitions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListTaskDefinitionsResponse> ListTaskDefinitionsAsync(ListTaskDefinitionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListTaskDefinitionsRequestMarshaller(); var unmarshaller = ListTaskDefinitionsResponseUnmarshaller.Instance; return InvokeAsync<ListTaskDefinitionsRequest,ListTaskDefinitionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListTasks internal ListTasksResponse ListTasks(ListTasksRequest request) { var marshaller = new ListTasksRequestMarshaller(); var unmarshaller = ListTasksResponseUnmarshaller.Instance; return Invoke<ListTasksRequest,ListTasksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTasks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListTasksResponse> ListTasksAsync(ListTasksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListTasksRequestMarshaller(); var unmarshaller = ListTasksResponseUnmarshaller.Instance; return InvokeAsync<ListTasksRequest,ListTasksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RegisterTaskDefinition internal RegisterTaskDefinitionResponse RegisterTaskDefinition(RegisterTaskDefinitionRequest request) { var marshaller = new RegisterTaskDefinitionRequestMarshaller(); var unmarshaller = RegisterTaskDefinitionResponseUnmarshaller.Instance; return Invoke<RegisterTaskDefinitionRequest,RegisterTaskDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RegisterTaskDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RegisterTaskDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RegisterTaskDefinitionResponse> RegisterTaskDefinitionAsync(RegisterTaskDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RegisterTaskDefinitionRequestMarshaller(); var unmarshaller = RegisterTaskDefinitionResponseUnmarshaller.Instance; return InvokeAsync<RegisterTaskDefinitionRequest,RegisterTaskDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RunTask internal RunTaskResponse RunTask(RunTaskRequest request) { var marshaller = new RunTaskRequestMarshaller(); var unmarshaller = RunTaskResponseUnmarshaller.Instance; return Invoke<RunTaskRequest,RunTaskResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RunTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RunTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RunTaskResponse> RunTaskAsync(RunTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RunTaskRequestMarshaller(); var unmarshaller = RunTaskResponseUnmarshaller.Instance; return InvokeAsync<RunTaskRequest,RunTaskResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StartTask internal StartTaskResponse StartTask(StartTaskRequest request) { var marshaller = new StartTaskRequestMarshaller(); var unmarshaller = StartTaskResponseUnmarshaller.Instance; return Invoke<StartTaskRequest,StartTaskResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<StartTaskResponse> StartTaskAsync(StartTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StartTaskRequestMarshaller(); var unmarshaller = StartTaskResponseUnmarshaller.Instance; return InvokeAsync<StartTaskRequest,StartTaskResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StopTask internal StopTaskResponse StopTask(StopTaskRequest request) { var marshaller = new StopTaskRequestMarshaller(); var unmarshaller = StopTaskResponseUnmarshaller.Instance; return Invoke<StopTaskRequest,StopTaskResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StopTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<StopTaskResponse> StopTaskAsync(StopTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StopTaskRequestMarshaller(); var unmarshaller = StopTaskResponseUnmarshaller.Instance; return InvokeAsync<StopTaskRequest,StopTaskResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateContainerAgent internal UpdateContainerAgentResponse UpdateContainerAgent(UpdateContainerAgentRequest request) { var marshaller = new UpdateContainerAgentRequestMarshaller(); var unmarshaller = UpdateContainerAgentResponseUnmarshaller.Instance; return Invoke<UpdateContainerAgentRequest,UpdateContainerAgentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateContainerAgent operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateContainerAgent operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateContainerAgentResponse> UpdateContainerAgentAsync(UpdateContainerAgentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateContainerAgentRequestMarshaller(); var unmarshaller = UpdateContainerAgentResponseUnmarshaller.Instance; return InvokeAsync<UpdateContainerAgentRequest,UpdateContainerAgentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateService internal UpdateServiceResponse UpdateService(UpdateServiceRequest request) { var marshaller = new UpdateServiceRequestMarshaller(); var unmarshaller = UpdateServiceResponseUnmarshaller.Instance; return Invoke<UpdateServiceRequest,UpdateServiceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateService operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateService operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateServiceResponse> UpdateServiceAsync(UpdateServiceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateServiceRequestMarshaller(); var unmarshaller = UpdateServiceResponseUnmarshaller.Instance; return InvokeAsync<UpdateServiceRequest,UpdateServiceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Microsoft.Data.Entity.Relational.Migrations; using Microsoft.Data.Entity.Relational.Migrations.Builders; using Microsoft.Data.Entity.Relational.Migrations.Operations; namespace PartsUnlimited.Models.Migrations { public partial class InitialMigration : Migration { public override void Up(MigrationBuilder migration) { migration.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column(type: "nvarchar(450)", nullable: false), ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), Name = table.Column(type: "nvarchar(max)", nullable: true), NormalizedName = table.Column(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityRole", x => x.Id); }); migration.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column(type: "nvarchar(450)", nullable: false), AccessFailedCount = table.Column(type: "int", nullable: false), ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), Email = table.Column(type: "nvarchar(max)", nullable: true), EmailConfirmed = table.Column(type: "bit", nullable: false), LockoutEnabled = table.Column(type: "bit", nullable: false), LockoutEnd = table.Column(type: "datetimeoffset", nullable: true), Name = table.Column(type: "nvarchar(max)", nullable: true), NormalizedEmail = table.Column(type: "nvarchar(max)", nullable: true), NormalizedUserName = table.Column(type: "nvarchar(max)", nullable: true), PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true), PhoneNumberConfirmed = table.Column(type: "bit", nullable: false), SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true), TwoFactorEnabled = table.Column(type: "bit", nullable: false), UserName = table.Column(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_ApplicationUser", x => x.Id); }); migration.CreateTable( name: "Category", columns: table => new { CategoryId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), Description = table.Column(type: "nvarchar(max)", nullable: true), ImageUrl = table.Column(type: "nvarchar(max)", nullable: true), Name = table.Column(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Category", x => x.CategoryId); }); migration.CreateTable( name: "Order", columns: table => new { OrderId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), Address = table.Column(type: "nvarchar(max)", nullable: true), City = table.Column(type: "nvarchar(max)", nullable: true), Country = table.Column(type: "nvarchar(max)", nullable: true), Email = table.Column(type: "nvarchar(max)", nullable: true), Name = table.Column(type: "nvarchar(max)", nullable: true), OrderDate = table.Column(type: "datetime2", nullable: false), Phone = table.Column(type: "nvarchar(max)", nullable: true), PostalCode = table.Column(type: "nvarchar(max)", nullable: true), Processed = table.Column(type: "bit", nullable: false), State = table.Column(type: "nvarchar(max)", nullable: true), Total = table.Column(type: "decimal(18, 2)", nullable: false), Username = table.Column(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Order", x => x.OrderId); }); migration.CreateTable( name: "Store", columns: table => new { StoreId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), Name = table.Column(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Store", x => x.StoreId); }); migration.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), ClaimType = table.Column(type: "nvarchar(max)", nullable: true), ClaimValue = table.Column(type: "nvarchar(max)", nullable: true), RoleId = table.Column(type: "nvarchar(450)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityRoleClaim<string>", x => x.Id); table.ForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", columns: x => x.RoleId, referencedTable: "AspNetRoles", referencedColumn: "Id"); }); migration.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), ClaimType = table.Column(type: "nvarchar(max)", nullable: true), ClaimValue = table.Column(type: "nvarchar(max)", nullable: true), UserId = table.Column(type: "nvarchar(450)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityUserClaim<string>", x => x.Id); table.ForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", columns: x => x.UserId, referencedTable: "AspNetUsers", referencedColumn: "Id"); }); migration.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), ProviderKey = table.Column(type: "nvarchar(450)", nullable: false), ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), UserId = table.Column(type: "nvarchar(450)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityUserLogin<string>", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", columns: x => x.UserId, referencedTable: "AspNetUsers", referencedColumn: "Id"); }); migration.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column(type: "nvarchar(450)", nullable: false), RoleId = table.Column(type: "nvarchar(450)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserRole<string>", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", columns: x => x.RoleId, referencedTable: "AspNetRoles", referencedColumn: "Id"); table.ForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", columns: x => x.UserId, referencedTable: "AspNetUsers", referencedColumn: "Id"); }); migration.CreateTable( name: "Product", columns: table => new { ProductId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), CategoryId = table.Column(type: "int", nullable: false), Created = table.Column(type: "datetime2", nullable: false), Description = table.Column(type: "nvarchar(max)", nullable: true), Inventory = table.Column(type: "int", nullable: false), LeadTime = table.Column(type: "int", nullable: false), Price = table.Column(type: "decimal(18, 2)", nullable: false), ProductArtUrl = table.Column(type: "nvarchar(max)", nullable: true), ProductDetails = table.Column(type: "nvarchar(max)", nullable: true), RecommendationId = table.Column(type: "int", nullable: false), SalePrice = table.Column(type: "decimal(18, 2)", nullable: false), SkuNumber = table.Column(type: "nvarchar(max)", nullable: true), Title = table.Column(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Product", x => x.ProductId); table.ForeignKey( name: "FK_Product_Category_CategoryId", columns: x => x.CategoryId, referencedTable: "Category", referencedColumn: "CategoryId"); }); migration.CreateTable( name: "CartItem", columns: table => new { CartItemId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), CartId = table.Column(type: "nvarchar(max)", nullable: true), Count = table.Column(type: "int", nullable: false), DateCreated = table.Column(type: "datetime2", nullable: false), ProductId = table.Column(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_CartItem", x => x.CartItemId); table.ForeignKey( name: "FK_CartItem_Product_ProductId", columns: x => x.ProductId, referencedTable: "Product", referencedColumn: "ProductId"); }); migration.CreateTable( name: "OrderDetail", columns: table => new { OrderDetailId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), OrderId = table.Column(type: "int", nullable: false), ProductId = table.Column(type: "int", nullable: false), Quantity = table.Column(type: "int", nullable: false), UnitPrice = table.Column(type: "decimal(18, 2)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_OrderDetail", x => x.OrderDetailId); table.ForeignKey( name: "FK_OrderDetail_Order_OrderId", columns: x => x.OrderId, referencedTable: "Order", referencedColumn: "OrderId"); table.ForeignKey( name: "FK_OrderDetail_Product_ProductId", columns: x => x.ProductId, referencedTable: "Product", referencedColumn: "ProductId"); }); migration.CreateTable( name: "Raincheck", columns: table => new { RaincheckId = table.Column(type: "int", nullable: false) .Annotation("SqlServer:ValueGeneration", "Identity"), Name = table.Column(type: "nvarchar(max)", nullable: true), ProductId = table.Column(type: "int", nullable: false), Quantity = table.Column(type: "int", nullable: false), SalePrice = table.Column(type: "float", nullable: false), StoreId = table.Column(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Raincheck", x => x.RaincheckId); table.ForeignKey( name: "FK_Raincheck_Product_ProductId", columns: x => x.ProductId, referencedTable: "Product", referencedColumn: "ProductId"); table.ForeignKey( name: "FK_Raincheck_Store_StoreId", columns: x => x.StoreId, referencedTable: "Store", referencedColumn: "StoreId"); }); } public override void Down(MigrationBuilder migration) { migration.DropTable("AspNetRoles"); migration.DropTable("AspNetRoleClaims"); migration.DropTable("AspNetUserClaims"); migration.DropTable("AspNetUserLogins"); migration.DropTable("AspNetUserRoles"); migration.DropTable("AspNetUsers"); migration.DropTable("CartItem"); migration.DropTable("Category"); migration.DropTable("Order"); migration.DropTable("OrderDetail"); migration.DropTable("Product"); migration.DropTable("Raincheck"); migration.DropTable("Store"); } } }
namespace Caliburn.Testability { using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; /// <summary> /// Represents a data bound element. /// </summary> public class DependencyObjectElement : IBoundElement { readonly DependencyObject element; readonly BoundType type; readonly BoundType dataContextCheckType; bool checkLogicalChildren = true; /// <summary> /// Initializes a new instance of the <see cref="DependencyObjectElement"/> class. /// </summary> /// <param name="element">The element.</param> /// <param name="boundType">Type of the bound.</param> /// <param name="baseName">Name of the base.</param> internal DependencyObjectElement(DependencyObject element, BoundType boundType, string baseName) { this.element = element; type = EnsureBoundType(boundType); if(type != boundType && type != null) dataContextCheckType = boundType; BaseName = baseName ?? string.Empty; } /// <summary> /// Initializes a new instance of the <see cref="DependencyObjectElement"/> class. /// </summary> /// <param name="element">The element.</param> /// <param name="boundType">Type of the bound.</param> internal DependencyObjectElement(DependencyObject element, BoundType boundType) : this(element, boundType, string.Empty) {} /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public virtual string Name { get { var frameworkElement = Element as FrameworkElement; if(frameworkElement != null) { var name = frameworkElement.GetValue(FrameworkElement.NameProperty) as string; if(!string.IsNullOrEmpty(name)) return BaseName + Element.GetType().Name + ": " + name; } return BaseName + Element.GetType().Name; } } /// <summary> /// Gets or sets the base name used to generate the name. /// </summary> /// <value>The base name.</value> public string BaseName { get; protected set; } /// <summary> /// Gets the element. /// </summary> /// <value>The element.</value> public DependencyObject Element { get { return element; } } /// <summary> /// Gets the type the item is bound to. /// </summary> /// <value>The type.</value> public BoundType Type { get { return type; } } /// <summary> /// Gets the type of the data context check. /// </summary> /// <value>The type of the data context check.</value> public BoundType DataContextCheckType { get { return dataContextCheckType; } } /// <summary> /// Gets or sets a value indicating whether to check child elements. /// </summary> /// <value><c>true</c> to check children; otherwise, <c>false</c>.</value> public bool CheckLogicalChildren { get { return checkLogicalChildren; } set { checkLogicalChildren = value; } } /// <summary> /// Gets the children. /// </summary> /// <value>The children.</value> public IEnumerable<IElement> GetChildren(ElementEnumeratorSettings settings) { if(Type == null) yield break; var checkedProperties = new List<string>(); foreach(var item in CheckContentControl(checkedProperties, settings)) { yield return item; } foreach(var item in CheckItemsControl(checkedProperties, settings)) { yield return item; } var logicalChildren = LogicalTreeHelper.GetChildren(Element).Cast<object>().ToList(); var enumerator = element.GetLocalValueEnumerator(); while(enumerator.MoveNext()) { var entry = enumerator.Current; if(BindingOperations.IsDataBound(element, entry.Property)) continue; if(checkedProperties.Contains(entry.Property.Name)) continue; if(logicalChildren.Contains(entry.Value)) continue; var dataBound = settings.GetBoundProperty(entry.Value, Type, Name); if(dataBound != null) yield return dataBound; } if(!CheckLogicalChildren) yield break; foreach(var child in logicalChildren) { if(child is DependencyObject) { yield return Bound.DependencyObject( child as DependencyObject, Type, Name + ".", (settings.TraverseUserControls || !(child is UserControl)) ); } } } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> public virtual void Accept(IElementVisitor visitor) { visitor.Visit(this); } /// <summary> /// Ensures that the type is accurately represented. /// </summary> /// <param name="boundType">Type of the bound.</param> /// <returns></returns> protected BoundType EnsureBoundType(BoundType boundType) { var frameworkElement = element as FrameworkElement; if(frameworkElement != null) { var binding = BindingOperations.GetBinding( element, FrameworkElement.DataContextProperty ); if(binding.ShouldValidate()) { var propertyPath = binding.Path.Path; return boundType.GetAssociatedType(propertyPath); } } return boundType; } IEnumerable<IElement> CheckContentControl(ICollection<string> checkedProperties, ElementEnumeratorSettings settings) { if(!settings.IncludeTemplates) yield break; var contentControl = Element as ContentControl; if(contentControl != null) { checkedProperties.Add(ContentControl.ContentTemplateProperty.Name); var template = contentControl.ContentTemplate; if(template != null) { var dataType = template.DataType as Type; if(dataType == null) { var binding = BindingOperations.GetBinding( contentControl, ContentControl.ContentProperty ); if(binding != null) yield return Bound.DataTemplate(template, Type.GetAssociatedType(binding.Path.Path), Name); } else yield return Bound.DataTemplate(template, new BoundType(dataType), Name); } foreach(var item in CheckHeaderedContentControl(checkedProperties)) { yield return item; } } } IEnumerable<IElement> CheckHeaderedContentControl(ICollection<string> checkedProperties) { var headeredContentControl = Element as HeaderedContentControl; if(headeredContentControl != null) { checkedProperties.Add(HeaderedContentControl.HeaderTemplateProperty.Name); var template = headeredContentControl.HeaderTemplate; if(template != null) { var dataType = template.DataType as Type; if(dataType == null) { var binding = BindingOperations.GetBinding( headeredContentControl, HeaderedContentControl.HeaderProperty ); if(binding != null) yield return Bound.DataTemplate(template, Type.GetAssociatedType(binding.Path.Path), Name); } else yield return Bound.DataTemplate(template, new BoundType(dataType), Name); } } } IEnumerable<IElement> CheckItemsControl(ICollection<string> checkedProperties, ElementEnumeratorSettings settings) { var itemsControl = Element as ItemsControl; if(itemsControl != null) { checkedProperties.Add(ItemsControl.ItemTemplateProperty.Name); var template = itemsControl.ItemTemplate; if(template != null && settings.IncludeTemplates) { var dataType = template.DataType as Type; if(dataType == null) { var binding = BindingOperations.GetBinding( itemsControl, ItemsControl.ItemsSourceProperty ); if(binding != null) { var enumerableType = Type.GetPropertyType(binding.Path.Path); if (enumerableType != null) { var generics = enumerableType.GetGenericArguments(); if(generics != null && generics.Length == 1) yield return Bound.DataTemplate(template, new BoundType(generics[0]), Name); } } } else yield return Bound.DataTemplate(template, new BoundType(dataType), Name); } if(settings.IncludeStyles) { if(itemsControl.ItemContainerStyle != null) { checkedProperties.Add(ItemsControl.ItemContainerStyleProperty.Name); yield return Bound.Style(itemsControl.ItemContainerStyle, Type, Name); } foreach(var groupStyle in itemsControl.GroupStyle) { checkedProperties.Add("GroupStyle"); yield return Bound.GroupStyle(groupStyle, Type, Name); } } foreach(var item in CheckHeaderedItemsControl(checkedProperties, settings)) { yield return item; } } } IEnumerable<IElement> CheckHeaderedItemsControl(ICollection<string> checkedProperties, ElementEnumeratorSettings settings) { if(!settings.IncludeTemplates) yield break; var headeredItemsControl = Element as HeaderedItemsControl; if(headeredItemsControl != null) { checkedProperties.Add(HeaderedContentControl.HeaderTemplateProperty.Name); var template = headeredItemsControl.HeaderTemplate; if(template != null) { var dataType = template.DataType as Type; if(dataType == null) { var binding = BindingOperations.GetBinding( headeredItemsControl, HeaderedItemsControl.HeaderProperty ); if(binding != null) yield return Bound.DataTemplate(template, Type.GetAssociatedType(binding.Path.Path), Name); } else yield return Bound.DataTemplate(template, new BoundType(dataType), Name); } } } } }
using Lucene.Net.Support; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; 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 DirectoryReader = Lucene.Net.Index.DirectoryReader; using IOUtils = Lucene.Net.Util.IOUtils; /// <summary> /// Keeps track of current plus old <see cref="IndexSearcher"/>s, disposing /// the old ones once they have timed out. /// /// Use it like this: /// /// <code> /// SearcherLifetimeManager mgr = new SearcherLifetimeManager(); /// </code> /// /// Per search-request, if it's a "new" search request, then /// obtain the latest searcher you have (for example, by /// using <see cref="SearcherManager"/>), and then record this /// searcher: /// /// <code> /// // Record the current searcher, and save the returend /// // token into user's search results (eg as a hidden /// // HTML form field): /// long token = mgr.Record(searcher); /// </code> /// /// When a follow-up search arrives, for example the user /// clicks next page, drills down/up, etc., take the token /// that you saved from the previous search and: /// /// <code> /// // If possible, obtain the same searcher as the last /// // search: /// IndexSearcher searcher = mgr.Acquire(token); /// if (searcher != null) /// { /// // Searcher is still here /// try /// { /// // do searching... /// } /// finally /// { /// mgr.Release(searcher); /// // Do not use searcher after this! /// searcher = null; /// } /// } /// else /// { /// // Searcher was pruned -- notify user session timed /// // out, or, pull fresh searcher again /// } /// </code> /// /// Finally, in a separate thread, ideally the same thread /// that's periodically reopening your searchers, you should /// periodically prune old searchers: /// /// <code> /// mgr.Prune(new PruneByAge(600.0)); /// </code> /// /// <para><b>NOTE</b>: keeping many searchers around means /// you'll use more resources (open files, RAM) than a single /// searcher. However, as long as you are using /// <see cref="DirectoryReader.OpenIfChanged(DirectoryReader)"/>, the searchers /// will usually share almost all segments and the added resource usage /// is contained. When a large merge has completed, and /// you reopen, because that is a large change, the new /// searcher will use higher additional RAM than other /// searchers; but large merges don't complete very often and /// it's unlikely you'll hit two of them in your expiration /// window. Still you should budget plenty of heap in the /// runtime to have a good safety margin.</para> /// </summary> public class SearcherLifetimeManager : IDisposable { internal const double NANOS_PER_SEC = 1000000000.0; private sealed class SearcherTracker : IComparable<SearcherTracker>, IDisposable { public IndexSearcher Searcher { get; private set; } public double RecordTimeSec { get; private set; } public long Version { get; private set; } public SearcherTracker(IndexSearcher searcher) { Searcher = searcher; Version = ((DirectoryReader)searcher.IndexReader).Version; searcher.IndexReader.IncRef(); // Use nanoTime not currentTimeMillis since it [in // theory] reduces risk from clock shift RecordTimeSec = Time.NanoTime() / NANOS_PER_SEC; } // Newer searchers are sort before older ones: public int CompareTo(SearcherTracker other) { return other.RecordTimeSec.CompareTo(RecordTimeSec); } public void Dispose() { lock (this) { Searcher.IndexReader.DecRef(); } } } private volatile bool _closed; // TODO: we could get by w/ just a "set"; need to have // Tracker hash by its version and have compareTo(Long) // compare to its version private readonly ConcurrentDictionary<long, Lazy<SearcherTracker>> _searchers = new ConcurrentDictionary<long, Lazy<SearcherTracker>>(); private void EnsureOpen() { if (_closed) { throw new ObjectDisposedException(this.GetType().FullName, "this SearcherLifetimeManager instance is closed"); } } /// <summary> /// Records that you are now using this <see cref="IndexSearcher"/>. /// Always call this when you've obtained a possibly new /// <see cref="IndexSearcher"/>, for example from /// <see cref="SearcherManager"/>. It's fine if you already passed the /// same searcher to this method before. /// /// <para>This returns the <see cref="long"/> token that you can later pass /// to <see cref="Acquire(long)"/> to retrieve the same <see cref="IndexSearcher"/>. /// You should record this <see cref="long"/> token in the search results /// sent to your user, such that if the user performs a /// follow-on action (clicks next page, drills down, etc.) /// the token is returned.</para> /// </summary> public virtual long Record(IndexSearcher searcher) { EnsureOpen(); // TODO: we don't have to use IR.getVersion to track; // could be risky (if it's buggy); we could get better // bug isolation if we assign our own private ID: var version = ((DirectoryReader)searcher.IndexReader).Version; var factoryMethodCalled = false; var tracker = _searchers.GetOrAdd(version, l => new Lazy<SearcherTracker>(() => { factoryMethodCalled = true; return new SearcherTracker(searcher); })).Value; if (!factoryMethodCalled && tracker.Searcher != searcher) { throw new ArgumentException("the provided searcher has the same underlying reader version yet the searcher instance differs from before (new=" + searcher + " vs old=" + tracker.Searcher); } return version; } /// <summary> /// Retrieve a previously recorded <see cref="IndexSearcher"/>, if it /// has not yet been closed. /// /// <para><b>NOTE</b>: this may return <c>null</c> when the /// requested searcher has already timed out. When this /// happens you should notify your user that their session /// timed out and that they'll have to restart their /// search.</para> /// /// <para>If this returns a non-null result, you must match /// later call <see cref="Release(IndexSearcher)"/> on this searcher, best /// from a finally clause.</para> /// </summary> public virtual IndexSearcher Acquire(long version) { EnsureOpen(); Lazy<SearcherTracker> tracker; if (_searchers.TryGetValue(version, out tracker) && tracker.IsValueCreated && tracker.Value.Searcher.IndexReader.TryIncRef()) { return tracker.Value.Searcher; } return null; } /// <summary> /// Release a searcher previously obtained from /// <see cref="Acquire(long)"/>. /// /// <para/><b>NOTE</b>: it's fine to call this after Dispose(). /// </summary> public virtual void Release(IndexSearcher s) { s.IndexReader.DecRef(); } /// <summary> /// See <see cref="Prune(IPruner)"/>. </summary> public interface IPruner { /// <summary> /// Return <c>true</c> if this searcher should be removed. </summary> /// <param name="ageSec"> How much time has passed since this /// searcher was the current (live) searcher </param> /// <param name="searcher"> Searcher </param> bool DoPrune(double ageSec, IndexSearcher searcher); } /// <summary> /// Simple pruner that drops any searcher older by /// more than the specified seconds, than the newest /// searcher. /// </summary> public sealed class PruneByAge : IPruner { private readonly double maxAgeSec; public PruneByAge(double maxAgeSec) { if (maxAgeSec < 0) { throw new ArgumentException("maxAgeSec must be > 0 (got " + maxAgeSec + ")"); } this.maxAgeSec = maxAgeSec; } public bool DoPrune(double ageSec, IndexSearcher searcher) { return ageSec > maxAgeSec; } } /// <summary> /// Calls provided <see cref="IPruner"/> to prune entries. The /// entries are passed to the <see cref="IPruner"/> in sorted (newest to /// oldest <see cref="IndexSearcher"/>) order. /// /// <para/><b>NOTE</b>: you must peridiocally call this, ideally /// from the same background thread that opens new /// searchers. /// </summary> public virtual void Prune(IPruner pruner) { lock (this) { // Cannot just pass searchers.values() to ArrayList ctor // (not thread-safe since the values can change while // ArrayList is init'ing itself); must instead iterate // ourselves: var trackers = _searchers.Values.Select(item => item.Value).ToList(); trackers.Sort(); var lastRecordTimeSec = 0.0; double now = Time.NanoTime() / NANOS_PER_SEC; foreach (var tracker in trackers) { double ageSec; if (lastRecordTimeSec == 0.0) { ageSec = 0.0; } else { ageSec = now - lastRecordTimeSec; } // First tracker is always age 0.0 sec, since it's // still "live"; second tracker's age (= seconds since // it was "live") is now minus first tracker's // recordTime, etc: if (pruner.DoPrune(ageSec, tracker.Searcher)) { //System.out.println("PRUNE version=" + tracker.version + " age=" + ageSec + " ms=" + System.currentTimeMillis()); Lazy<SearcherTracker> _; _searchers.TryRemove(tracker.Version, out _); tracker.Dispose(); } lastRecordTimeSec = tracker.RecordTimeSec; } } } /// <summary> /// Close this to future searching; any searches still in /// process in other threads won't be affected, and they /// should still call <see cref="Release(IndexSearcher)"/> after they are /// done. /// /// <para/><b>NOTE</b>: you must ensure no other threads are /// calling <see cref="Record(IndexSearcher)"/> while you call Dispose(); /// otherwise it's possible not all searcher references /// will be freed. /// </summary> public virtual void Dispose() { lock (this) { _closed = true; IList<SearcherTracker> toClose = new List<SearcherTracker>(_searchers.Values.Select(item => item.Value)); // Remove up front in case exc below, so we don't // over-decRef on double-close: foreach (var tracker in toClose) { Lazy<SearcherTracker> _; _searchers.TryRemove(tracker.Version, out _); } IOUtils.Dispose(toClose); // Make some effort to catch mis-use: if (_searchers.Count != 0) { throw new InvalidOperationException("another thread called record while this SearcherLifetimeManager instance was being closed; not all searchers were closed"); } } } } }
/*``The contents of this file are subject to the Erlang Public License, * Version 1.1, (the "License"); you may not use this file except in * compliance with the License. You should have received a copy of the * Erlang Public License along with this software. If not, it can be * retrieved via the world wide web at http://www.erlang.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Initial Developer of the Original Code is Ericsson Utvecklings AB. * Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings * AB. All Rights Reserved.'' * * Converted from Java to C# by Vlad Dumitrescu ([email protected]) */ namespace Otp.Erlang { using System; /* * Provides a C# representation of Erlang tuples. Tuples are created * from one or more arbitrary Erlang terms. * * <p> The arity of the tuple is the number of elements it contains. * Elements are indexed from 0 to (arity-1) and can be retrieved * individually by using the appropriate index. **/ [Serializable] public class Tuple:Erlang.Object { private Object[] elems = null; /* * Create a unary tuple containing the given element. * * @param elem the element to create the tuple from. * * @exception C#.lang.IllegalArgumentException if the array is * empty (null). * public Tuple(Object elem) { if (elem == null) { throw new System.ArgumentException("Tuple element cannot be null"); } this.elems = new Object[1]; elems[0] = elem; } */ /* * Create a tuple from an array of terms. * * @param elems the array of terms to create the tuple from. * * @exception C#.lang.IllegalArgumentException if the array is * empty (null) or contains null elements. */ public Tuple(Object[] elems):this(elems, 0, elems.Length) { } /* * Create a tuple from an array of terms. * * @param elems the array of terms to create the tuple from. * @param start the offset of the first term to insert. * @param count the number of terms to insert. * * @exception C#.lang.IllegalArgumentException if the array is * empty (null) or contains null elements. */ public Tuple(Object[] elems, int start, int count) { if ((elems == null) || (count < 1)) { throw new System.ArgumentException("Cannot make an empty tuple"); } else { this.elems = new Object[count]; for (int i = 0; i < count; i++) { if (elems[start + i] != null) { this.elems[i] = elems[start + i]; } else { throw new System.ArgumentException("Tuple element cannot be null (element" + (start + i) + ")"); } } } } /* * Create a tuple from an array of terms. * * @param elems the array of terms to create the tuple from. * @param start the offset of the first term to insert. * @param count the number of terms to insert. * * @exception C#.lang.IllegalArgumentException if the array is * empty (null) or contains null elements. **/ public Tuple(params System.Object[] elems) { if (elems == null) elems = new Object[] {}; else { this.elems = new Object[elems.Length]; for (int i = 0; i < elems.Length; i++) { if (elems[i] == null) throw new System.ArgumentException("Tuple element cannot be null (element" + i + ")"); else { System.Object o = elems[i]; if (o is int) this.elems[i] = new Int((int)o); else if (o is string) this.elems[i] = new String((string)o); else if (o is float) this.elems[i] = new Double((float)o); else if (o is double) this.elems[i] = new Double((double)o); else if (o is Erlang.Object) this.elems[i] = (Erlang.Object)o; //else if (o is BigInteger) this.elems[i] = (BigInteger)o; else if (o is uint) this.elems[i] = new UInt((int)o); else if (o is short) this.elems[i] = new Short((short)o); else if (o is ushort) this.elems[i] = new UShort((short)o); else throw new System.ArgumentException("Unknown type of element[" + i + "]: " + o.GetType().ToString()); } } } } /* * Create a tuple from a stream containing an tuple encoded in Erlang * external format. * * @param buf the stream containing the encoded tuple. * * @exception DecodeException if the buffer does not * contain a valid external representation of an Erlang tuple. **/ public Tuple(OtpInputStream buf) { int arity = buf.read_tuple_head(); if (arity > 0) { this.elems = new Object[arity]; for (int i = 0; i < arity; i++) { elems[i] = buf.read_any(); } } } /* * Get the arity of the tuple. * * @return the number of elements contained in the tuple. **/ public virtual int arity() { return elems.Length; } /* * Get the specified element from the tuple. * * @param i the index of the requested element. Tuple elements are * numbered as array elements, starting at 0. * * @return the requested element, of null if i is not a valid * element index. **/ public virtual Object elementAt(int i) { if ((i >= arity()) || (i < 0)) return null; return elems[i]; } /* * Get all the elements from the tuple as an array. * * @return an array containing all of the tuple's elements. **/ public virtual Object[] elements() { Object[] res = new Object[arity()]; Array.Copy(this.elems, 0, res, 0, res.Length); return res; } public Object this[int index] { get { return this.elems[index]; } set { this.elems[index] = value; } } /* * Get the string representation of the tuple. * * @return the string representation of the tuple. **/ public override System.String ToString() { int i; System.Text.StringBuilder s = new System.Text.StringBuilder(); int arity = (int) (elems.Length); s.Append("{"); for (i = 0; i < arity; i++) { if (i > 0) s.Append(","); s.Append(elems[i].ToString()); } s.Append("}"); return s.ToString(); } /* * Convert this tuple to the equivalent Erlang external representation. * * @param buf an output stream to which the encoded tuple should be * written. **/ public override void encode(OtpOutputStream buf) { int arity = (int) (elems.Length); buf.write_tuple_head(arity); for (int i = 0; i < arity; i++) { buf.write_any(elems[i]); } } /* * Determine if two tuples are equal. Tuples are equal if they have * the same arity and all of the elements are equal. * * @param o the tuple to compare to. * * @return true if the tuples have the same arity and all the * elements are equal. **/ public override bool Equals(System.Object o) { if (!(o is Tuple)) return false; Tuple t = (Tuple) o; int a = this.arity(); if (a != t.arity()) return false; for (int i = 0; i < a; i++) { if (!this.elems[i].Equals(t.elems[i])) return false; // early exit } return true; } public override int GetHashCode() { return 1; } public override System.Object clone() { Tuple newTuple = (Tuple) (base.clone()); newTuple.elems = new Object[elems.Length]; elems.CopyTo(newTuple.elems, 0); return newTuple; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // X509Certificate2.cs // // 09/22/2002 // namespace System.Security.Cryptography.X509Certificates { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security.Permissions; using System.Runtime.Versioning; using _FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; public enum X509NameType { SimpleName = 0, EmailName, UpnName, DnsName, DnsFromAlternativeName, UrlName } public enum X509IncludeOption { None = 0, ExcludeRoot, EndCertOnly, WholeChain } public sealed class PublicKey { private AsnEncodedData m_encodedKeyValue; private AsnEncodedData m_encodedParameters; private Oid m_oid; private uint m_aiPubKey = 0; private byte[] m_cspBlobData = null; private AsymmetricAlgorithm m_key = null; private PublicKey() {} public PublicKey (Oid oid, AsnEncodedData parameters, AsnEncodedData keyValue) { m_oid = new Oid(oid); m_encodedParameters = new AsnEncodedData(parameters); m_encodedKeyValue = new AsnEncodedData(keyValue); } internal PublicKey (PublicKey publicKey) { m_oid = new Oid(publicKey.m_oid); m_encodedParameters = new AsnEncodedData(publicKey.m_encodedParameters); m_encodedKeyValue = new AsnEncodedData(publicKey.m_encodedKeyValue); } internal uint AlgorithmId { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_aiPubKey == 0) m_aiPubKey = X509Utils.OidToAlgId(m_oid.Value); return m_aiPubKey; } } private byte[] CspBlobData { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_cspBlobData == null) DecodePublicKeyObject(AlgorithmId, m_encodedKeyValue.RawData, m_encodedParameters.RawData, out m_cspBlobData); return m_cspBlobData; } } public AsymmetricAlgorithm Key { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_key == null) { switch (AlgorithmId) { case CAPI.CALG_RSA_KEYX: case CAPI.CALG_RSA_SIGN: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(CspBlobData); m_key = rsa; break; #if !FEATURE_CORESYSTEM case CAPI.CALG_DSS_SIGN: DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.ImportCspBlob(CspBlobData); m_key = dsa; break; #endif default: throw new NotSupportedException(SR.GetString(SR.NotSupported_KeyAlgorithm)); } } return m_key; } } public Oid Oid { get { return new Oid(m_oid); } } public AsnEncodedData EncodedKeyValue { get { return m_encodedKeyValue; } } public AsnEncodedData EncodedParameters { get { return m_encodedParameters; } } // // private static methods. // #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static void DecodePublicKeyObject(uint aiPubKey, byte[] encodedKeyValue, byte[] encodedParameters, out byte[] decodedData) { // Initialize the out parameter decodedData = null; IntPtr pszStructType = IntPtr.Zero; switch (aiPubKey) { case CAPI.CALG_DSS_SIGN: pszStructType = new IntPtr(CAPI.X509_DSS_PUBLICKEY); break; case CAPI.CALG_RSA_SIGN: case CAPI.CALG_RSA_KEYX: pszStructType = new IntPtr(CAPI.RSA_CSP_PUBLICKEYBLOB); break; case CAPI.CALG_DH_SF: case CAPI.CALG_DH_EPHEM: // We don't support DH for now throw new NotSupportedException(SR.GetString(SR.NotSupported_KeyAlgorithm)); default: // We should never get here Debug.Assert(false); throw new NotSupportedException(SR.GetString(SR.NotSupported_KeyAlgorithm)); } SafeLocalAllocHandle decodedKeyValue = null; uint cbDecodedKeyValue = 0; bool result = CAPI.DecodeObject(pszStructType, encodedKeyValue, out decodedKeyValue, out cbDecodedKeyValue); if (!result) throw new CryptographicException(Marshal.GetLastWin32Error()); if ((uint) pszStructType == CAPI.RSA_CSP_PUBLICKEYBLOB) { decodedData = new byte[cbDecodedKeyValue]; Marshal.Copy(decodedKeyValue.DangerousGetHandle(), decodedData, 0, decodedData.Length); } else if ((uint) pszStructType == CAPI.X509_DSS_PUBLICKEY) { // We need to decode the parameters as well SafeLocalAllocHandle decodedParameters = null; uint cbDecodedParameters = 0; result = CAPI.DecodeObject(new IntPtr(CAPI.X509_DSS_PARAMETERS), encodedParameters, out decodedParameters, out cbDecodedParameters); if (!result) throw new CryptographicException(Marshal.GetLastWin32Error()); decodedData = ConstructDSSPubKeyCspBlob(decodedKeyValue, decodedParameters); decodedParameters.Dispose(); } decodedKeyValue.Dispose(); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static byte[] ConstructDSSPubKeyCspBlob (SafeLocalAllocHandle decodedKeyValue, SafeLocalAllocHandle decodedParameters) { // The CAPI DSS public key representation consists of the following sequence: // - PUBLICKEYSTRUC // - DSSPUBKEY // - rgbP[cbKey] // - rgbQ[20] // - rgbG[cbKey] // - rgbY[cbKey] // - DSSSEED CAPI.CRYPTOAPI_BLOB pDssPubKey = (CAPI.CRYPTOAPI_BLOB) Marshal.PtrToStructure(decodedKeyValue.DangerousGetHandle(), typeof(CAPI.CRYPTOAPI_BLOB)); CAPI.CERT_DSS_PARAMETERS pDssParameters = (CAPI.CERT_DSS_PARAMETERS) Marshal.PtrToStructure(decodedParameters.DangerousGetHandle(), typeof(CAPI.CERT_DSS_PARAMETERS)); uint cbKey = pDssParameters.p.cbData; if (cbKey == 0) throw new CryptographicException(CAPI.NTE_BAD_PUBLIC_KEY); const uint DSS_Q_LEN = 20; uint cbKeyBlob = 8 /* sizeof(CAPI.BLOBHEADER) */ + 8 /* sizeof(CAPI.DSSPUBKEY) */ + cbKey + DSS_Q_LEN + cbKey + cbKey + 24 /* sizeof(CAPI.DSSSEED) */; MemoryStream keyBlob = new MemoryStream((int) cbKeyBlob); BinaryWriter bw = new BinaryWriter(keyBlob); // PUBLICKEYSTRUC bw.Write(CAPI.PUBLICKEYBLOB); // pPubKeyStruc->bType = PUBLICKEYBLOB bw.Write(CAPI.CUR_BLOB_VERSION); // pPubKeyStruc->bVersion = CUR_BLOB_VERSION bw.Write((short) 0); // pPubKeyStruc->reserved = 0; bw.Write(CAPI.CALG_DSS_SIGN); // pPubKeyStruc->aiKeyAlg = CALG_DSS_SIGN; // DSSPUBKEY bw.Write(CAPI.DSS_MAGIC); // pCspPubKey->magic = DSS_MAGIC; We are constructing a DSS1 Csp blob. bw.Write(cbKey * 8); // pCspPubKey->bitlen = cbKey * 8; // rgbP[cbKey] byte[] p = new byte[pDssParameters.p.cbData]; Marshal.Copy(pDssParameters.p.pbData, p, 0, p.Length); bw.Write(p); // rgbQ[20] uint cb = pDssParameters.q.cbData; if (cb == 0 || cb > DSS_Q_LEN) throw new CryptographicException(CAPI.NTE_BAD_PUBLIC_KEY); byte[] q = new byte[pDssParameters.q.cbData]; Marshal.Copy(pDssParameters.q.pbData, q, 0, q.Length); bw.Write(q); if (DSS_Q_LEN > cb) bw.Write(new byte[DSS_Q_LEN - cb]); // rgbG[cbKey] cb = pDssParameters.g.cbData; if (cb == 0 || cb > cbKey) throw new CryptographicException(CAPI.NTE_BAD_PUBLIC_KEY); byte[] g = new byte[pDssParameters.g.cbData]; Marshal.Copy(pDssParameters.g.pbData, g, 0, g.Length); bw.Write(g); if (cbKey > cb) bw.Write(new byte[cbKey - cb]); // rgbY[cbKey] cb = pDssPubKey.cbData; if (cb == 0 || cb > cbKey) throw new CryptographicException(CAPI.NTE_BAD_PUBLIC_KEY); byte[] y = new byte[pDssPubKey.cbData]; Marshal.Copy(pDssPubKey.pbData, y, 0, y.Length); bw.Write(y); if (cbKey > cb) bw.Write(new byte[cbKey - cb]); // DSSSEED: set counter to 0xFFFFFFFF to indicate not available bw.Write(0xFFFFFFFF); bw.Write(new byte[20]); return keyBlob.ToArray(); } } #if !FEATURE_CORESYSTEM [Serializable] #endif public class X509Certificate2 : X509Certificate { private int m_version; private DateTime m_notBefore; private DateTime m_notAfter; private AsymmetricAlgorithm m_privateKey; private PublicKey m_publicKey; private X509ExtensionCollection m_extensions; private Oid m_signatureAlgorithm; private X500DistinguishedName m_subjectName; private X500DistinguishedName m_issuerName; #if FEATURE_CORESYSTEM [SecurityCritical] #endif private SafeCertContextHandle m_safeCertContext = SafeCertContextHandle.InvalidHandle; private static int s_publicKeyOffset; // // public constructors // #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public X509Certificate2 () : base() {} #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public X509Certificate2 (byte[] rawData) : base (rawData) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public X509Certificate2 (byte[] rawData, string password) : base (rawData, password) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if !FEATURE_CORESYSTEM public X509Certificate2 (byte[] rawData, SecureString password) : base (rawData, password) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #endif #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) : base (rawData, password, keyStorageFlags) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if !FEATURE_CORESYSTEM public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) : base (rawData, password, keyStorageFlags) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #endif #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif public X509Certificate2 (string fileName) : base (fileName) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif public X509Certificate2 (string fileName, string password) : base (fileName, password) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if !FEATURE_CORESYSTEM [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate2 (string fileName, SecureString password) : base (fileName, password) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #endif #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags) : base (fileName, password, keyStorageFlags) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if !FEATURE_CORESYSTEM [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) : base (fileName, password, keyStorageFlags) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #endif #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif // Package protected constructor for creating a certificate from a PCCERT_CONTEXT [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public X509Certificate2 (IntPtr handle) : base (handle) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public X509Certificate2 (X509Certificate certificate) : base(certificate) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #if !FEATURE_CORESYSTEM [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected X509Certificate2(SerializationInfo info, StreamingContext context) : base(info, context) { m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } #endif public override string ToString() { return base.ToString(true); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public override string ToString(bool verbose) { if (verbose == false || m_safeCertContext.IsInvalid) return ToString(); StringBuilder sb = new StringBuilder(); string newLine = Environment.NewLine; string newLine2 = newLine + newLine; string newLinesp2 = newLine + " "; // Version sb.Append("[Version]"); sb.Append(newLinesp2); sb.Append("V" + this.Version); // Subject sb.Append(newLine2); sb.Append("[Subject]"); sb.Append(newLinesp2); sb.Append(this.SubjectName.Name); string simpleName = GetNameInfo(X509NameType.SimpleName, false); if (simpleName.Length > 0) { sb.Append(newLinesp2); sb.Append("Simple Name: "); sb.Append(simpleName); } string emailName = GetNameInfo(X509NameType.EmailName, false); if (emailName.Length > 0) { sb.Append(newLinesp2); sb.Append("Email Name: "); sb.Append(emailName); } string upnName = GetNameInfo(X509NameType.UpnName, false); if (upnName.Length > 0) { sb.Append(newLinesp2); sb.Append("UPN Name: "); sb.Append(upnName); } string dnsName = GetNameInfo(X509NameType.DnsName, false); if (dnsName.Length > 0) { sb.Append(newLinesp2); sb.Append("DNS Name: "); sb.Append(dnsName); } // Issuer sb.Append(newLine2); sb.Append("[Issuer]"); sb.Append(newLinesp2); sb.Append(this.IssuerName.Name); simpleName = GetNameInfo(X509NameType.SimpleName, true); if (simpleName.Length > 0) { sb.Append(newLinesp2); sb.Append("Simple Name: "); sb.Append(simpleName); } emailName = GetNameInfo(X509NameType.EmailName, true); if (emailName.Length > 0) { sb.Append(newLinesp2); sb.Append("Email Name: "); sb.Append(emailName); } upnName = GetNameInfo(X509NameType.UpnName, true); if (upnName.Length > 0) { sb.Append(newLinesp2); sb.Append("UPN Name: "); sb.Append(upnName); } dnsName = GetNameInfo(X509NameType.DnsName, true); if (dnsName.Length > 0) { sb.Append(newLinesp2); sb.Append("DNS Name: "); sb.Append(dnsName); } // Serial Number sb.Append(newLine2); sb.Append("[Serial Number]"); sb.Append(newLinesp2); sb.Append(this.SerialNumber); // NotBefore sb.Append(newLine2); sb.Append("[Not Before]"); sb.Append(newLinesp2); sb.Append(FormatDate(this.NotBefore)); // NotAfter sb.Append(newLine2); sb.Append("[Not After]"); sb.Append(newLinesp2); sb.Append(FormatDate(this.NotAfter)); // Thumbprint sb.Append(newLine2); sb.Append("[Thumbprint]"); sb.Append(newLinesp2); sb.Append(this.Thumbprint); // Signature Algorithm sb.Append(newLine2); sb.Append("[Signature Algorithm]"); sb.Append(newLinesp2); sb.Append(this.SignatureAlgorithm.FriendlyName + "(" + this.SignatureAlgorithm.Value + ")"); // Public Key sb.Append(newLine2); sb.Append("[Public Key]"); // It could throw if it's some user-defined CryptoServiceProvider try { PublicKey pubKey = this.PublicKey; string temp = pubKey.Oid.FriendlyName; sb.Append(newLinesp2); sb.Append("Algorithm: "); sb.Append(temp); // So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys try { temp = pubKey.Key.KeySize.ToString(); sb.Append(newLinesp2); sb.Append("Length: "); sb.Append(temp); } catch (NotSupportedException) { } temp = pubKey.EncodedKeyValue.Format(true); sb.Append(newLinesp2); sb.Append("Key Blob: "); sb.Append(temp); temp = pubKey.EncodedParameters.Format(true); sb.Append(newLinesp2); sb.Append("Parameters: "); sb.Append(temp); } catch (CryptographicException) { } // Private key AppendPrivateKeyInfo(sb); // Extensions X509ExtensionCollection extensions = this.Extensions; if (extensions.Count > 0) { sb.Append(newLine2); sb.Append("[Extensions]"); string temp; foreach (X509Extension extension in extensions) { try { temp = extension.Oid.FriendlyName; sb.Append(newLine); sb.Append("* " + temp); sb.Append("(" + extension.Oid.Value + "):"); temp = extension.Format(true); sb.Append(newLinesp2); sb.Append(temp); } catch (CryptographicException) { } } } sb.Append(newLine); return sb.ToString(); } public bool Archived { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); uint cbData = 0; return CAPI.CertGetCertificateContextProperty(m_safeCertContext, CAPI.CERT_ARCHIVED_PROP_ID, SafeLocalAllocHandle.InvalidHandle, ref cbData); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif set { SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; if (value == true) ptr = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB)))); if (!CAPI.CertSetCertificateContextProperty(m_safeCertContext, CAPI.CERT_ARCHIVED_PROP_ID, 0, ptr)) throw new CryptographicException(Marshal.GetLastWin32Error()); ptr.Dispose(); } } public X509ExtensionCollection Extensions { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_extensions == null) m_extensions = new X509ExtensionCollection(m_safeCertContext); return m_extensions; } } public string FriendlyName { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; uint cbData = 0; if (!CAPI.CertGetCertificateContextProperty(m_safeCertContext, CAPI.CERT_FRIENDLY_NAME_PROP_ID, ptr, ref cbData)) return String.Empty; ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbData)); if (!CAPI.CertGetCertificateContextProperty(m_safeCertContext, CAPI.CERT_FRIENDLY_NAME_PROP_ID, ptr, ref cbData)) return String.Empty; string friendlyName = Marshal.PtrToStringUni(ptr.DangerousGetHandle()); ptr.Dispose(); return friendlyName; } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif set { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (value == null) value = String.Empty; SetFriendlyNameExtendedProperty(m_safeCertContext, value); } } public X500DistinguishedName IssuerName { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_issuerName == null) { unsafe { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) m_safeCertContext.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); m_issuerName = new X500DistinguishedName(pCertInfo.Issuer); } } return m_issuerName; } } public DateTime NotAfter { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_notAfter == DateTime.MinValue) { unsafe { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) m_safeCertContext.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); long dt = (((long)(uint)pCertInfo.NotAfter.dwHighDateTime) << 32) | ((long)(uint)pCertInfo.NotAfter.dwLowDateTime); m_notAfter = DateTime.FromFileTime(dt); } } return m_notAfter; } } public DateTime NotBefore { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_notBefore == DateTime.MinValue) { unsafe { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) m_safeCertContext.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); long dt = (((long)(uint)pCertInfo.NotBefore.dwHighDateTime) << 32) | ((long)(uint)pCertInfo.NotBefore.dwLowDateTime); m_notBefore = DateTime.FromFileTime(dt); } } return m_notBefore; } } public bool HasPrivateKey { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); uint cbData = 0; return CAPI.CertGetCertificateContextProperty(m_safeCertContext, CAPI.CERT_KEY_PROV_INFO_PROP_ID, SafeLocalAllocHandle.InvalidHandle, ref cbData); } } public AsymmetricAlgorithm PrivateKey { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (!this.HasPrivateKey) return null; if (m_privateKey == null) { CspParameters parameters = new CspParameters(); if (!GetPrivateKeyInfo(m_safeCertContext, ref parameters)) return null; // We never want to stomp over certificate private keys. parameters.Flags |= CspProviderFlags.UseExistingKey; switch (this.PublicKey.AlgorithmId) { case CAPI.CALG_RSA_KEYX: case CAPI.CALG_RSA_SIGN: m_privateKey = new RSACryptoServiceProvider(parameters); break; #if !FEATURE_CORESYSTEM case CAPI.CALG_DSS_SIGN: m_privateKey = new DSACryptoServiceProvider(parameters); break; #endif default: throw new NotSupportedException(SR.GetString(SR.NotSupported_KeyAlgorithm)); } } return m_privateKey; } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] set { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); // we do not support keys in non-CAPI storage for now. ICspAsymmetricAlgorithm asymmetricAlgorithm = value as ICspAsymmetricAlgorithm; if (value != null && asymmetricAlgorithm == null) throw new NotSupportedException(SR.GetString(SR.NotSupported_InvalidKeyImpl)); // A null value can be passed in to remove the link to the private key from the certificate. if (asymmetricAlgorithm != null) { if (asymmetricAlgorithm.CspKeyContainerInfo == null) throw new ArgumentException("CspKeyContainerInfo"); // check that the public key in the certificate corresponds to the private key passed in. // // note that it should be legal to set a key which matches in every aspect but the usage // i.e. to use a CALG_RSA_KEYX private key to match a CALG_RSA_SIGN public key. A // PUBLICKEYBLOB is defined as: // // BLOBHEADER publickeystruc // RSAPUBKEY rsapubkey // BYTE modulus[rsapubkey.bitlen/8] // // To allow keys which differ by key usage only, we skip over the BLOBHEADER of the key, // and start comparing bytes at the RSAPUBKEY structure. if(s_publicKeyOffset == 0) s_publicKeyOffset = Marshal.SizeOf(typeof(CAPIBase.BLOBHEADER)); ICspAsymmetricAlgorithm publicKey = this.PublicKey.Key as ICspAsymmetricAlgorithm; byte[] array1 = publicKey.ExportCspBlob(false); byte[] array2 = asymmetricAlgorithm.ExportCspBlob(false); if (array1 == null || array2 == null || array1.Length != array2.Length || array1.Length <= s_publicKeyOffset) throw new CryptographicUnexpectedOperationException(SR.GetString(SR.Cryptography_X509_KeyMismatch)); for (int index = s_publicKeyOffset; index < array1.Length; index++) { if (array1[index] != array2[index]) throw new CryptographicUnexpectedOperationException(SR.GetString(SR.Cryptography_X509_KeyMismatch)); } } // Establish the link between the certificate and the key container. SetPrivateKeyProperty(m_safeCertContext, asymmetricAlgorithm); m_privateKey = value; } } public PublicKey PublicKey { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_publicKey == null) { string friendlyName = this.GetKeyAlgorithm(); byte[] parameters = this.GetKeyAlgorithmParameters(); byte[] keyValue = this.GetPublicKey(); Oid oid = new Oid(friendlyName, OidGroup.PublicKeyAlgorithm, true); m_publicKey = new PublicKey(oid, new AsnEncodedData(oid, parameters), new AsnEncodedData(oid, keyValue)); } return m_publicKey; } } public byte[] RawData { get { return GetRawCertData(); } } public string SerialNumber { get { return GetSerialNumberString(); } } public X500DistinguishedName SubjectName { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_subjectName == null) { unsafe { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) m_safeCertContext.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); m_subjectName = new X500DistinguishedName(pCertInfo.Subject); } } return m_subjectName; } } public Oid SignatureAlgorithm { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_signatureAlgorithm == null) m_signatureAlgorithm = GetSignatureAlgorithm(m_safeCertContext); return m_signatureAlgorithm; } } public string Thumbprint { get { return GetCertHashString(); } } public int Version { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); if (m_version == 0) m_version = (int) GetVersion(m_safeCertContext); return m_version; } } #if FEATURE_CORESYSTEM [SecurityCritical] #endif public unsafe string GetNameInfo(X509NameType nameType, bool forIssuer) { uint issuerFlag = forIssuer ? CAPI.CERT_NAME_ISSUER_FLAG : 0; uint type = X509Utils.MapNameType(nameType); switch(type) { case CAPI.CERT_NAME_SIMPLE_DISPLAY_TYPE: return CAPI.GetCertNameInfo(m_safeCertContext, issuerFlag, type); case CAPI.CERT_NAME_EMAIL_TYPE: return CAPI.GetCertNameInfo(m_safeCertContext, issuerFlag, type); } string name = String.Empty; // If the type requested is not supported in downlevel platforms; we try to decode the alt name extension by hand. CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) m_safeCertContext.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); IntPtr[] pAltName = new IntPtr[2]; pAltName[0] = CAPI.CertFindExtension(forIssuer ? CAPI.szOID_ISSUER_ALT_NAME : CAPI.szOID_SUBJECT_ALT_NAME, pCertInfo.cExtension, pCertInfo.rgExtension); pAltName[1] = CAPI.CertFindExtension(forIssuer ? CAPI.szOID_ISSUER_ALT_NAME2 : CAPI.szOID_SUBJECT_ALT_NAME2, pCertInfo.cExtension, pCertInfo.rgExtension); for (int i = 0; i < pAltName.Length; i++) { if (pAltName[i] != IntPtr.Zero) { CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pAltName[i], typeof(CAPI.CERT_EXTENSION)); byte[] rawData = new byte[extension.Value.cbData]; Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length); uint cbDecoded = 0; SafeLocalAllocHandle decoded = null; // Decode the extension. SafeLocalAllocHandle ptr = X509Utils.StringToAnsiPtr(extension.pszObjId); bool result = CAPI.DecodeObject(ptr.DangerousGetHandle(), rawData, out decoded, out cbDecoded); ptr.Dispose(); if (result) { CAPI.CERT_ALT_NAME_INFO altNameInfo = (CAPI.CERT_ALT_NAME_INFO) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_ALT_NAME_INFO)); for (int index = 0; index < altNameInfo.cAltEntry; index++) { IntPtr pAltInfoPtr = new IntPtr((long) altNameInfo.rgAltEntry + index * Marshal.SizeOf(typeof(CAPI.CERT_ALT_NAME_ENTRY))); CAPI.CERT_ALT_NAME_ENTRY altNameEntry = (CAPI.CERT_ALT_NAME_ENTRY) Marshal.PtrToStructure(pAltInfoPtr, typeof(CAPI.CERT_ALT_NAME_ENTRY)); switch(type) { case CAPI.CERT_NAME_UPN_TYPE: if (altNameEntry.dwAltNameChoice == CAPI.CERT_ALT_NAME_OTHER_NAME) { CAPI.CERT_OTHER_NAME otherName = (CAPI.CERT_OTHER_NAME) Marshal.PtrToStructure(altNameEntry.Value.pOtherName, typeof(CAPI.CERT_OTHER_NAME)); if (otherName.pszObjId == CAPI.szOID_NT_PRINCIPAL_NAME) { uint cbUpnName = 0; SafeLocalAllocHandle pUpnName = null; result = CAPI.DecodeObject(new IntPtr(CAPI.X509_UNICODE_ANY_STRING), X509Utils.PtrToByte(otherName.Value.pbData, otherName.Value.cbData), out pUpnName, out cbUpnName); if (result) { CAPI.CERT_NAME_VALUE nameValue = (CAPI.CERT_NAME_VALUE) Marshal.PtrToStructure(pUpnName.DangerousGetHandle(), typeof(CAPI.CERT_NAME_VALUE)); if (X509Utils.IsCertRdnCharString(nameValue.dwValueType)) name = Marshal.PtrToStringUni(nameValue.Value.pbData); pUpnName.Dispose(); } } } break; case CAPI.CERT_NAME_DNS_TYPE: if (altNameEntry.dwAltNameChoice == CAPI.CERT_ALT_NAME_DNS_NAME) name = Marshal.PtrToStringUni(altNameEntry.Value.pwszDNSName); break; case CAPI.CERT_NAME_URL_TYPE: if (altNameEntry.dwAltNameChoice == CAPI.CERT_ALT_NAME_URL) name = Marshal.PtrToStringUni(altNameEntry.Value.pwszURL); break; } } decoded.Dispose(); } } } if (nameType == X509NameType.DnsName) { // If no DNS name is found in the CERT_ALT_NAME extension, return the CommonName. // Commercial CAs such as Verisign don't include a SubjectAltName extension in the certificates they use for SSL server authentication. // Instead they use the CommonName in the subject RDN as the server's DNS name. if (name == null || name.Length == 0) name = CAPI.GetCertNameInfo(m_safeCertContext, issuerFlag, CAPI.CERT_NAME_ATTR_TYPE); } return name; } #if !FEATURE_CORESYSTEM [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public override void Import(byte[] rawData) { Reset(); base.Import(rawData); m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public override void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { Reset(); base.Import(rawData, password, keyStorageFlags); m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public override void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { Reset(); base.Import(rawData, password, keyStorageFlags); m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public override void Import(string fileName) { Reset(); base.Import(fileName); m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { Reset(); base.Import(fileName, password, keyStorageFlags); m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public override void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { Reset(); base.Import(fileName, password, keyStorageFlags); m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public override void Reset () { m_version = 0; m_notBefore = DateTime.MinValue; m_notAfter = DateTime.MinValue; m_privateKey = null; m_publicKey = null; m_extensions = null; m_signatureAlgorithm = null; m_subjectName = null; m_issuerName = null; if (!m_safeCertContext.IsInvalid) { // Free the current certificate handle m_safeCertContext.Dispose(); m_safeCertContext = SafeCertContextHandle.InvalidHandle; } base.Reset(); } #endif // !FEATURE_CORESYSTEM public bool Verify () { if (m_safeCertContext.IsInvalid) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "m_safeCertContext"); int hr = X509Utils.VerifyCertificate(this.CertContext, null, null, X509RevocationMode.Online, // We default to online revocation check. X509RevocationFlag.ExcludeRoot, DateTime.Now, new TimeSpan(0, 0, 0), // default null, new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE), IntPtr.Zero); return (hr == CAPI.S_OK); } // // public static methods // public static X509ContentType GetCertContentType (byte[] rawData) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.GetString(SR.Arg_EmptyOrNullArray), "rawData"); uint contentType = QueryCertBlobType(rawData); return X509Utils.MapContentType(contentType); } [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif public static X509ContentType GetCertContentType (string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); string fullPath = Path.GetFullPath(fileName); #if !FEATURE_CORESYSTEM new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand(); #endif uint contentType = QueryCertFileType(fileName); return X509Utils.MapContentType(contentType); } // // Internal // internal SafeCertContextHandle CertContext { #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif get { return m_safeCertContext; } } #if FEATURE_CORESYSTEM [SecurityCritical] #endif internal static bool GetPrivateKeyInfo (SafeCertContextHandle safeCertContext, ref CspParameters parameters) { SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; uint cbData = 0; if (!CAPI.CertGetCertificateContextProperty(safeCertContext, CAPI.CERT_KEY_PROV_INFO_PROP_ID, ptr, ref cbData)) { int dwErrorCode = Marshal.GetLastWin32Error(); if (dwErrorCode == CAPI.CRYPT_E_NOT_FOUND) return false; else throw new CryptographicException(Marshal.GetLastWin32Error()); } ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbData)); if (!CAPI.CertGetCertificateContextProperty(safeCertContext, CAPI.CERT_KEY_PROV_INFO_PROP_ID, ptr, ref cbData)) { int dwErrorCode = Marshal.GetLastWin32Error(); if (dwErrorCode == CAPI.CRYPT_E_NOT_FOUND) return false; else throw new CryptographicException(Marshal.GetLastWin32Error()); } CAPI.CRYPT_KEY_PROV_INFO pKeyProvInfo = (CAPI.CRYPT_KEY_PROV_INFO) Marshal.PtrToStructure(ptr.DangerousGetHandle(), typeof(CAPI.CRYPT_KEY_PROV_INFO)); parameters.ProviderName = pKeyProvInfo.pwszProvName; parameters.KeyContainerName = pKeyProvInfo.pwszContainerName; parameters.ProviderType = (int) pKeyProvInfo.dwProvType; parameters.KeyNumber = (int) pKeyProvInfo.dwKeySpec; parameters.Flags = (CspProviderFlags) ((pKeyProvInfo.dwFlags & CAPI.CRYPT_MACHINE_KEYSET) == CAPI.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0); ptr.Dispose(); return true; } // // Private // #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private void AppendPrivateKeyInfo (StringBuilder sb) { CspKeyContainerInfo cspKeyContainerInfo = null; try { if (this.HasPrivateKey) { CspParameters parameters = new CspParameters(); if (GetPrivateKeyInfo(m_safeCertContext, ref parameters)) cspKeyContainerInfo = new CspKeyContainerInfo(parameters); } } // We don't have the permission to access the key container. Just return. catch (SecurityException) {} // We could not access the key container. Just return. catch (CryptographicException) {} if (cspKeyContainerInfo == null) return; sb.Append(Environment.NewLine + Environment.NewLine + "[Private Key]"); sb.Append(Environment.NewLine + " Key Store: "); sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User"); sb.Append(Environment.NewLine + " Provider Name: "); sb.Append(cspKeyContainerInfo.ProviderName); sb.Append(Environment.NewLine + " Provider type: "); sb.Append(cspKeyContainerInfo.ProviderType); sb.Append(Environment.NewLine + " Key Spec: "); sb.Append(cspKeyContainerInfo.KeyNumber); sb.Append(Environment.NewLine + " Key Container Name: "); sb.Append(cspKeyContainerInfo.KeyContainerName); try { string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName; sb.Append(Environment.NewLine + " Unique Key Container Name: "); sb.Append(uniqueKeyContainer); } catch (CryptographicException) {} catch (NotSupportedException) {} bool b = false; try { b = cspKeyContainerInfo.HardwareDevice; sb.Append(Environment.NewLine + " Hardware Device: "); sb.Append(b); } catch (CryptographicException) {} try { b = cspKeyContainerInfo.Removable; sb.Append(Environment.NewLine + " Removable: "); sb.Append(b); } catch (CryptographicException) {} try { b = cspKeyContainerInfo.Protected; sb.Append(Environment.NewLine + " Protected: "); sb.Append(b); } catch (CryptographicException) {} catch (NotSupportedException) {} } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static unsafe Oid GetSignatureAlgorithm (SafeCertContextHandle safeCertContextHandle) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); return new Oid(pCertInfo.SignatureAlgorithm.pszObjId, OidGroup.SignatureAlgorithm, false); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static unsafe uint GetVersion (SafeCertContextHandle safeCertContextHandle) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); return (pCertInfo.dwVersion + 1); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.None)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] #endif private static unsafe uint QueryCertBlobType(byte[] rawData) { uint contentType = 0; if (!CAPI.CryptQueryObject(CAPI.CERT_QUERY_OBJECT_BLOB, rawData, CAPI.CERT_QUERY_CONTENT_FLAG_ALL, CAPI.CERT_QUERY_FORMAT_FLAG_ALL, 0, IntPtr.Zero, new IntPtr(&contentType), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) throw new CryptographicException(Marshal.GetLastWin32Error()); return contentType; } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif private static unsafe uint QueryCertFileType(string fileName) { uint contentType = 0; if (!CAPI.CryptQueryObject(CAPI.CERT_QUERY_OBJECT_FILE, fileName, CAPI.CERT_QUERY_CONTENT_FLAG_ALL, CAPI.CERT_QUERY_FORMAT_FLAG_ALL, 0, IntPtr.Zero, new IntPtr(&contentType), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) throw new CryptographicException(Marshal.GetLastWin32Error()); return contentType; } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static unsafe void SetFriendlyNameExtendedProperty (SafeCertContextHandle safeCertContextHandle, string name) { SafeLocalAllocHandle ptr = X509Utils.StringToUniPtr(name); using (ptr) { CAPI.CRYPTOAPI_BLOB DataBlob = new CAPI.CRYPTOAPI_BLOB(); DataBlob.cbData = 2 * ((uint) name.Length + 1); DataBlob.pbData = ptr.DangerousGetHandle(); if (!CAPI.CertSetCertificateContextProperty(safeCertContextHandle, CAPI.CERT_FRIENDLY_NAME_PROP_ID, 0, new IntPtr(&DataBlob))) throw new CryptographicException(Marshal.GetLastWin32Error()); } } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static unsafe void SetPrivateKeyProperty (SafeCertContextHandle safeCertContextHandle, ICspAsymmetricAlgorithm asymmetricAlgorithm) { SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; if (asymmetricAlgorithm != null) { CAPI.CRYPT_KEY_PROV_INFO keyProvInfo = new CAPI.CRYPT_KEY_PROV_INFO(); keyProvInfo.pwszContainerName = asymmetricAlgorithm.CspKeyContainerInfo.KeyContainerName; keyProvInfo.pwszProvName = asymmetricAlgorithm.CspKeyContainerInfo.ProviderName; keyProvInfo.dwProvType = (uint) asymmetricAlgorithm.CspKeyContainerInfo.ProviderType; keyProvInfo.dwFlags = asymmetricAlgorithm.CspKeyContainerInfo.MachineKeyStore ? CAPI.CRYPT_MACHINE_KEYSET : 0; keyProvInfo.cProvParam = 0; keyProvInfo.rgProvParam = IntPtr.Zero; keyProvInfo.dwKeySpec = (uint) asymmetricAlgorithm.CspKeyContainerInfo.KeyNumber; ptr = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPT_KEY_PROV_INFO)))); Marshal.StructureToPtr(keyProvInfo, ptr.DangerousGetHandle(), false); } try { if (!CAPI.CertSetCertificateContextProperty(safeCertContextHandle, CAPI.CERT_KEY_PROV_INFO_PROP_ID, 0, ptr)) throw new CryptographicException(Marshal.GetLastWin32Error()); } finally { if (!ptr.IsInvalid) { Marshal.DestroyStructure(ptr.DangerousGetHandle(), typeof(CAPI.CRYPT_KEY_PROV_INFO)); ptr.Dispose(); } } } } }
using System; using System.IO; using System.Collections; using System.Text; using LumiSoft.Net.IO; namespace LumiSoft.Net.Mime { /// <summary> /// Rfc 2822 Mime Entity. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class MimeEntity { private HeaderFieldCollection m_pHeader = null; private MimeEntity m_pParentEntity = null; private MimeEntityCollection m_pChildEntities = null; private byte[] m_EncodedData = null; private Hashtable m_pHeaderFieldCache = null; /// <summary> /// Default constructor. /// </summary> public MimeEntity() { m_pHeader = new HeaderFieldCollection(); m_pChildEntities = new MimeEntityCollection(this); m_pHeaderFieldCache = new Hashtable(); } #region method Parse /// <summary> /// Parses mime entity from stream. /// </summary> /// <param name="stream">Data stream from where to read data.</param> /// <param name="toBoundary">Entity data is readed to specified boundary.</param> /// <returns>Returns false if last entity. Returns true for mulipart entity, if there are more entities.</returns> internal bool Parse(SmartStream stream,string toBoundary) { // Clear header fields m_pHeader.Clear(); m_pHeaderFieldCache.Clear(); // Parse header m_pHeader.Parse(stream); // Parse entity and child entities if any (Conent-Type: multipart/xxx...) // Multipart entity if((this.ContentType & MediaType_enum.Multipart) != 0){ // There must be be boundary ID (rfc 1341 7.2.1 The Content-Type field for multipart entities requires one parameter, // "boundary", which is used to specify the encapsulation boundary.) string boundaryID = this.ContentType_Boundary; if(boundaryID == null){ // This is invalid message, just skip this mime entity } else{ // There is one or more mime entities // Find first boundary start position SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[8000],SizeExceededAction.JunkAndThrowException); stream.ReadLine(args,false); if(args.Error != null){ throw args.Error; } string lineString = args.LineUtf8; while(lineString != null){ if(lineString.StartsWith("--" + boundaryID)){ break; } stream.ReadLine(args,false); if(args.Error != null){ throw args.Error; } lineString = args.LineUtf8; } // This is invalid entity, boundary start not found. Skip that entity. if(string.IsNullOrEmpty(lineString)){ return false; } // Start parsing child entities of this entity while(true){ // Parse and add child entity MimeEntity childEntity = new MimeEntity(); this.ChildEntities.Add(childEntity); // This is last entity, stop parsing if(childEntity.Parse(stream,boundaryID) == false){ break; } // else{ // There are more entities, parse them } // This entity is child of mulipart entity. // All this entity child entities are parsed, // we need to move stream position to next entity start. if(!string.IsNullOrEmpty(toBoundary)){ stream.ReadLine(args,false); if(args.Error != null){ throw args.Error; } lineString = args.LineUtf8; while(lineString != null){ if(lineString.StartsWith("--" + toBoundary)){ break; } stream.ReadLine(args,false); if(args.Error != null){ throw args.Error; } lineString = args.LineUtf8; } // Invalid boundary end, there can't be more entities if(string.IsNullOrEmpty(lineString)){ return false; } // See if last boundary or there is more. Last boundary ends with -- if(lineString.EndsWith(toBoundary + "--")){ return false; } // else{ // There are more entities return true; } } } // Singlepart entity. else{ // Boundary is specified, read data to specified boundary. if(!string.IsNullOrEmpty(toBoundary)){ MemoryStream entityData = new MemoryStream(); SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[32000],SizeExceededAction.JunkAndThrowException); // Read entity data while get boundary end tag --boundaryID-- or EOS. while(true){ stream.ReadLine(readLineOP,false); if(readLineOP.Error != null){ throw readLineOP.Error; } // End of stream reached. Normally we should get boundary end tag --boundaryID--, but some x mailers won't add it, so // if we reach EOS, consider boundary closed. if(readLineOP.BytesInBuffer == 0){ // Just return data what was readed. m_EncodedData = entityData.ToArray(); return false; } // We readed a line. else{ // We have boundary start/end tag or just "--" at the beginning of line. if(readLineOP.LineBytesInBuffer >= 2 && readLineOP.Buffer[0] == '-' && readLineOP.Buffer[1] == '-'){ string lineString = readLineOP.LineUtf8; // We have boundary end tag, no more boundaries. if(lineString == "--" + toBoundary + "--"){ m_EncodedData = entityData.ToArray(); return false; } // We have new boundary start. else if(lineString == "--" + toBoundary){ m_EncodedData = entityData.ToArray(); return true; } else{ // Just skip } } // Write readed line. entityData.Write(readLineOP.Buffer,0,readLineOP.BytesInBuffer); } } } // Boundary isn't specified, read data to the stream end. else{ MemoryStream ms = new MemoryStream(); stream.ReadAll(ms); m_EncodedData = ms.ToArray(); } } return false; } #endregion #region method ToStream /// <summary> /// Stores mime entity and it's child entities to specified stream. /// </summary> /// <param name="storeStream">Stream where to store mime entity.</param> public void ToStream(Stream storeStream) { // Write headers byte[] data = System.Text.Encoding.Default.GetBytes(FoldHeader(this.HeaderString)); storeStream.Write(data,0,data.Length); // If multipart entity, write child entities.(multipart entity don't contain data, it contains nested entities ) if((this.ContentType & MediaType_enum.Multipart) != 0){ string boundary = this.ContentType_Boundary; foreach(MimeEntity entity in this.ChildEntities){ // Write boundary start. Syntax: <CRLF>--BoundaryID<CRLF> data = System.Text.Encoding.Default.GetBytes("\r\n--" + boundary + "\r\n"); storeStream.Write(data,0,data.Length); // Force child entity to store itself entity.ToStream(storeStream); } // Write boundaries end Syntax: <CRLF>--BoundaryID--<CRLF> data = System.Text.Encoding.Default.GetBytes("\r\n--" + boundary + "--\r\n"); storeStream.Write(data,0,data.Length); } // If singlepart (text,image,audio,video,message, ...), write entity data. else{ // Write blank line between headers and content storeStream.Write(new byte[]{(byte)'\r',(byte)'\n'},0,2); if(this.DataEncoded != null){ storeStream.Write(this.DataEncoded,0,this.DataEncoded.Length); } } } #endregion #region method DataToFile /// <summary> /// Saves this.Data property value to specified file. /// </summary> /// <param name="fileName">File name where to store data.</param> public void DataToFile(string fileName) { using(FileStream fs = File.Create(fileName)){ DataToStream(fs); } } #endregion #region method DataToStream /// <summary> /// Saves this.Data property value to specified stream. /// </summary> /// <param name="stream">Stream where to store data.</param> public void DataToStream(Stream stream) { byte[] data = this.Data; stream.Write(data,0,data.Length); } #endregion #region method DataFromFile /// <summary> /// Loads MimeEntity.Data property from file. /// </summary> /// <param name="fileName">File name.</param> public void DataFromFile(string fileName) { using(FileStream fs = File.OpenRead(fileName)){ DataFromStream(fs); } } #endregion #region method DataFromStream /// <summary> /// Loads MimeEntity.Data property from specified stream. Note: reading starts from current position and stream isn't closed. /// </summary> /// <param name="stream">Data stream.</param> public void DataFromStream(Stream stream) { byte[] data = new byte[stream.Length]; stream.Read(data,0,(int)stream.Length); this.Data = data; } #endregion #region method EncodeData /// <summary> /// Encodes data with specified content transfer encoding. /// </summary> /// <param name="data">Data to encode.</param> /// <param name="encoding">Encoding with what to encode data.</param> private byte[] EncodeData(byte[] data,ContentTransferEncoding_enum encoding) { // Allow only known Content-Transfer-Encoding (ContentTransferEncoding_enum value), // otherwise we don't know how to encode data. if(encoding == ContentTransferEncoding_enum.NotSpecified){ throw new Exception("Please specify Content-Transfer-Encoding first !"); } if(encoding == ContentTransferEncoding_enum.Unknown){ throw new Exception("Not supported Content-Transfer-Encoding. If it's your custom encoding, encode data yourself and set it with DataEncoded property !"); } if(encoding == ContentTransferEncoding_enum.Base64){ return Core.Base64Encode(data); } else if(encoding == ContentTransferEncoding_enum.QuotedPrintable){ return Core.QuotedPrintableEncode(data); } else{ return data; } } #endregion #region method FoldHeader /// <summary> /// Folds header. /// </summary> /// <param name="header">Header string.</param> /// <returns></returns> private string FoldHeader(string header) { /* Rfc 2822 2.2.3 Long Header Fields Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is imply WSP characters), a CRLF may be inserted before any WSP. For example, the header field: Subject: This is a test can be represented as: Subject: This is a test */ // Just fold header fields what contain <TAB> StringBuilder retVal = new StringBuilder(); header = header.Replace("\r\n","\n"); string[] headerLines = header.Split('\n'); foreach(string headerLine in headerLines){ // Folding is needed if(headerLine.IndexOf('\t') > -1){ retVal.Append(headerLine.Replace("\t","\r\n\t") + "\r\n"); } // No folding needed, just write back header line else{ retVal.Append(headerLine + "\r\n"); } } // Split splits last line <CRLF> to element, but we don't need it if(retVal.Length > 1){ return retVal.ToString(0,retVal.Length - 2); } else{ return retVal.ToString(); } } #endregion #region Properties Implementation /// <summary> /// Gets message header. /// </summary> public HeaderFieldCollection Header { get{ return m_pHeader; } } /// <summary> /// Gets header as RFC 2822 message headers. /// </summary> public string HeaderString { get{ return m_pHeader.ToHeaderString("utf-8"); } } /// <summary> /// Gets parent entity of this entity. If this entity is top level, then this property returns null. /// </summary> public MimeEntity ParentEntity { get{ return m_pParentEntity; } } /// <summary> /// Gets child entities. This property is available only if ContentType = multipart/... . /// </summary> public MimeEntityCollection ChildEntities { get{ return m_pChildEntities; } } /// <summary> /// Gets or sets header field "<b>Mime-Version:</b>" value. Returns null if value isn't set. /// </summary> public string MimeVersion { get{ if(m_pHeader.Contains("Mime-Version:")){ return m_pHeader.GetFirst("Mime-Version:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Mime-Version:")){ m_pHeader.GetFirst("Mime-Version:").Value = value; } else{ m_pHeader.Add("Mime-Version:",value); } } } /// <summary> /// Gets or sets header field "<b>Content-class:</b>" value. Returns null if value isn't set.<br/> /// Additional property to support messages of CalendarItem type which have iCal/vCal entries. /// </summary> public string ContentClass { get{ if(m_pHeader.Contains("Content-Class:")){ return m_pHeader.GetFirst("Content-Class:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Content-Class:")){ m_pHeader.GetFirst("Content-Class:").Value = value; } else{ m_pHeader.Add("Content-Class:", value); } } } /// <summary> /// Gets or sets header field "<b>Content-Type:</b>" value. This property specifies what entity data is. /// NOTE: ContentType can't be changed while there is data specified(Exception is thrown) in this mime entity, because it isn't /// possible todo data conversion between different types. For example text/xx has charset parameter and other types don't, /// changing loses it and text data becomes useless. /// </summary> public MediaType_enum ContentType { get{ if(m_pHeader.Contains("Content-Type:")){ string contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")).Value; return MimeUtils.ParseMediaType(contentType); } else{ return MediaType_enum.NotSpecified; } } set{ if(this.DataEncoded != null){ throw new Exception("ContentType can't be changed while there is data specified, set data to null before !"); } if(value == MediaType_enum.Unknown){ throw new Exception("MediaType_enum.Unkown isn't allowed to set !"); } if(value == MediaType_enum.NotSpecified){ throw new Exception("MediaType_enum.NotSpecified isn't allowed to set !"); } string contentType = ""; //--- Text/xxx --------------------------------// if(value == MediaType_enum.Text_plain){ contentType = "text/plain; charset=\"utf-8\""; } else if(value == MediaType_enum.Text_html){ contentType = "text/html; charset=\"utf-8\""; } else if(value == MediaType_enum.Text_xml){ contentType = "text/xml; charset=\"utf-8\""; } else if(value == MediaType_enum.Text_rtf){ contentType = "text/rtf; charset=\"utf-8\""; } else if(value == MediaType_enum.Text){ contentType = "text; charset=\"utf-8\""; } //---------------------------------------------// //--- Image/xxx -------------------------------// else if(value == MediaType_enum.Image_gif){ contentType = "image/gif"; } else if(value == MediaType_enum.Image_tiff){ contentType = "image/tiff"; } else if(value == MediaType_enum.Image_jpeg){ contentType = "image/jpeg"; } else if(value == MediaType_enum.Image){ contentType = "image"; } //---------------------------------------------// //--- Audio/xxx -------------------------------// else if(value == MediaType_enum.Audio){ contentType = "audio"; } //---------------------------------------------// //--- Video/xxx -------------------------------// else if(value == MediaType_enum.Video){ contentType = "video"; } //---------------------------------------------// //--- Application/xxx -------------------------// else if(value == MediaType_enum.Application_octet_stream){ contentType = "application/octet-stream"; } else if(value == MediaType_enum.Application){ contentType = "application"; } //---------------------------------------------// //--- Multipart/xxx ---------------------------// else if(value == MediaType_enum.Multipart_mixed){ contentType = "multipart/mixed; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-","_") + "\""; } else if(value == MediaType_enum.Multipart_alternative){ contentType = "multipart/alternative; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-","_") + "\""; } else if(value == MediaType_enum.Multipart_parallel){ contentType = "multipart/parallel; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-","_") + "\""; } else if(value == MediaType_enum.Multipart_related){ contentType = "multipart/related; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-","_") + "\""; } else if(value == MediaType_enum.Multipart_signed){ contentType = "multipart/signed; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-","_") + "\""; } else if(value == MediaType_enum.Multipart){ contentType = "multipart; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-","_") + "\""; } //---------------------------------------------// //--- Message/xxx -----------------------------// else if(value == MediaType_enum.Message_rfc822){ contentType = "message/rfc822"; } else if(value == MediaType_enum.Message){ contentType = "message"; } //---------------------------------------------// else{ throw new Exception("Invalid flags combination of MediaType_enum was specified !"); } if(m_pHeader.Contains("Content-Type:")){ m_pHeader.GetFirst("Content-Type:").Value = contentType; } else{ m_pHeader.Add("Content-Type:",contentType); } } } /// <summary> /// Gets or sets header field "<b>Content-Type:</b>" value. Returns null if value isn't set. This property specifies what entity data is. /// This property is meant for advanced users, who needs other values what defined MediaType_enum provides. /// Example value: text/plain; charset="utf-8". /// NOTE: ContentType can't be changed while there is data specified(Exception is thrown) in this mime entity, because it isn't /// possible todo data conversion between different types. For example text/xx has charset parameter and other types don't, /// changing loses it and text data becomes useless. /// </summary> public string ContentTypeString { get{ if(m_pHeader.Contains("Content-Type:")){ return m_pHeader.GetFirst("Content-Type:").Value; } else{ return null; } } set{ if(this.DataEncoded != null){ throw new Exception("ContentType can't be changed while there is data specified, set data to null before !"); } if(m_pHeader.Contains("Content-Type:")){ m_pHeader.GetFirst("Content-Type:").Value = value; } else{ m_pHeader.Add("Content-Type:",value); } } } /// <summary> /// Gets or sets header field "<b>Content-Transfer-Encoding:</b>" value. This property specifies how data is encoded/decoded. /// If you set this value, it's recommended that you use QuotedPrintable for text and Base64 for binary data. /// 7bit,_8bit,Binary are today obsolete (used for parsing). /// </summary> public ContentTransferEncoding_enum ContentTransferEncoding { get{ if(m_pHeader.Contains("Content-Transfer-Encoding:")){ return MimeUtils.ParseContentTransferEncoding(m_pHeader.GetFirst("Content-Transfer-Encoding:").Value); } else{ return ContentTransferEncoding_enum.NotSpecified; } } set{ if(value == ContentTransferEncoding_enum.Unknown){ throw new Exception("ContentTransferEncoding_enum.Unknown isn't allowed to set !"); } if(value == ContentTransferEncoding_enum.NotSpecified){ throw new Exception("ContentTransferEncoding_enum.NotSpecified isn't allowed to set !"); } string encoding = MimeUtils.ContentTransferEncodingToString(value); // There is entity data specified and encoding changed, we need to convert existing data if(this.DataEncoded != null){ ContentTransferEncoding_enum oldEncoding = this.ContentTransferEncoding; if(oldEncoding == ContentTransferEncoding_enum.Unknown || oldEncoding == ContentTransferEncoding_enum.NotSpecified){ throw new Exception("Data can't be converted because old encoding '" + MimeUtils.ContentTransferEncodingToString(oldEncoding) + "' is unknown !"); } this.DataEncoded = EncodeData(this.Data,value); } if(m_pHeader.Contains("Content-Transfer-Encoding:")){ m_pHeader.GetFirst("Content-Transfer-Encoding:").Value = encoding; } else{ m_pHeader.Add("Content-Transfer-Encoding:",encoding); } } } /// <summary> /// Gets or sets header field "<b>Content-Disposition:</b>" value. /// </summary> public ContentDisposition_enum ContentDisposition { get{ if(m_pHeader.Contains("Content-Disposition:")){ return MimeUtils.ParseContentDisposition(m_pHeader.GetFirst("Content-Disposition:").Value); } else{ return ContentDisposition_enum.NotSpecified; } } set{ if(value == ContentDisposition_enum.Unknown){ throw new Exception("ContentDisposition_enum.Unknown isn't allowed to set !"); } // Just remove Content-Disposition: header field if exists if(value == ContentDisposition_enum.NotSpecified){ HeaderField disposition = m_pHeader.GetFirst("Content-Disposition:"); if(disposition != null){ m_pHeader.Remove(disposition); } } else{ string disposition = MimeUtils.ContentDispositionToString(value); if(m_pHeader.Contains("Content-Disposition:")){ m_pHeader.GetFirst("Content-Disposition:").Value = disposition; } else{ m_pHeader.Add("Content-Disposition:",disposition); } } } } /// <summary> /// Gets or sets header field "<b>Content-Description:</b>" value. Returns null if value isn't set. /// </summary> public string ContentDescription { get{ if(m_pHeader.Contains("Content-Description:")){ return m_pHeader.GetFirst("Content-Description:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Content-Description:")){ m_pHeader.GetFirst("Content-Description:").Value = value; } else{ m_pHeader.Add("Content-Description:",value); } } } /// <summary> /// Gets or sets header field "<b>Content-ID:</b>" value. Returns null if value isn't set. /// </summary> public string ContentID { get{ if(m_pHeader.Contains("Content-ID:")){ return m_pHeader.GetFirst("Content-ID:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Content-ID:")){ m_pHeader.GetFirst("Content-ID:").Value = value; } else{ m_pHeader.Add("Content-ID:",value); } } } /// <summary> /// Gets or sets "<b>Content-Type:</b>" header field "<b>name</b>" parameter. /// Returns null if Content-Type: header field value isn't set or Content-Type: header field "<b>name</b>" parameter isn't set. /// <p/> /// Note: Content-Type must be application/xxx or exception is thrown. /// This property is obsolete today, it's replaced with <b>Content-Disposition: filename</b> parameter. /// If possible always set FileName property instead of it. /// </summary> public string ContentType_Name { get{ if(m_pHeader.Contains("Content-Type:")){ ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if(contentType.Parameters.Contains("name")){ return contentType.Parameters["name"]; } else{ return null; } } else{ return null; } } set{ if(!m_pHeader.Contains("Content-Type:")){ throw new Exception("Please specify Content-Type first !"); } if((this.ContentType & MediaType_enum.Application) == 0){ throw new Exception("Parameter name is available only for ContentType application/xxx !"); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if(contentType.Parameters.Contains("name")){ contentType.Parameters["name"] = value; } else{ contentType.Parameters.Add("name",value); } } } /// <summary> /// Gets or sets "<b>Content-Type:</b>" header field "<b>charset</b>" parameter. /// Returns null if Content-Type: header field value isn't set or Content-Type: header field "<b>charset</b>" parameter isn't set. /// If you don't know what charset to use then <b>utf-8</b> is recommended, most of times this is sufficient. /// Note: Content-Type must be text/xxx or exception is thrown. /// </summary> public string ContentType_CharSet { get{ if(m_pHeader.Contains("Content-Type:")){ ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if(contentType.Parameters.Contains("charset")){ return contentType.Parameters["charset"]; } else{ return null; } } else{ return null; } } set{ if(!m_pHeader.Contains("Content-Type:")){ throw new Exception("Please specify Content-Type first !"); } if((this.ContentType & MediaType_enum.Text) == 0){ throw new Exception("Parameter boundary is available only for ContentType text/xxx !"); } // There is data specified, we need to convert it because charset changed if(this.DataEncoded != null){ string currentCharSet = this.ContentType_CharSet; if(currentCharSet == null){ currentCharSet = "ascii"; } try{ System.Text.Encoding.GetEncoding(currentCharSet); } catch{ throw new Exception("Data can't be converted because current charset '" + currentCharSet + "' isn't supported !"); } try{ System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(value); this.Data = encoding.GetBytes(this.DataText); } catch{ throw new Exception("Data can't be converted because new charset '" + value + "' isn't supported !"); } } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if(contentType.Parameters.Contains("charset")){ contentType.Parameters["charset"] = value; } else{ contentType.Parameters.Add("charset",value); } } } /// <summary> /// Gets or sets "<b>Content-Type:</b>" header field "<b>boundary</b>" parameter. /// Returns null if Content-Type: header field value isn't set or Content-Type: header field "<b>boundary</b>" parameter isn't set. /// Note: Content-Type must be multipart/xxx or exception is thrown. /// </summary> public string ContentType_Boundary { get{ if(m_pHeader.Contains("Content-Type:")){ ParametizedHeaderField contentDisposition = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if(contentDisposition.Parameters.Contains("boundary")){ return contentDisposition.Parameters["boundary"]; } else{ return null; } } else{ return null; } } set{ if(!m_pHeader.Contains("Content-Type:")){ throw new Exception("Please specify Content-Type first !"); } if((this.ContentType & MediaType_enum.Multipart) == 0){ throw new Exception("Parameter boundary is available only for ContentType multipart/xxx !"); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if(contentType.Parameters.Contains("boundary")){ contentType.Parameters["boundary"] = value; } else{ contentType.Parameters.Add("boundary",value); } } } /// <summary> /// Gets or sets "<b>Content-Disposition:</b>" header field "<b>filename</b>" parameter. /// Returns null if Content-Disposition: header field value isn't set or Content-Disposition: header field "<b>filename</b>" parameter isn't set. /// Note: Content-Disposition must be attachment or inline. /// </summary> public string ContentDisposition_FileName { get{ if(m_pHeader.Contains("Content-Disposition:")){ ParametizedHeaderField contentDisposition = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Disposition:")); if(contentDisposition.Parameters.Contains("filename")){ return MimeUtils.DecodeWords(contentDisposition.Parameters["filename"]); } else{ return null; } } else{ return null; } } set{ if(!m_pHeader.Contains("Content-Disposition:")){ throw new Exception("Please specify Content-Disposition first !"); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Disposition:")); if(contentType.Parameters.Contains("filename")){ contentType.Parameters["filename"] = MimeUtils.EncodeWord(value); } else{ contentType.Parameters.Add("filename",MimeUtils.EncodeWord(value)); } } } /// <summary> /// Gets or sets header field "<b>Date:</b>" value. /// </summary> public DateTime Date { get{ if(m_pHeader.Contains("Date:")){ try{ return LumiSoft.Net.MIME.MIME_Utils.ParseRfc2822DateTime(m_pHeader.GetFirst("Date:").Value); } catch{ return DateTime.MinValue; } } else{ return DateTime.MinValue; } } set{ if(m_pHeader.Contains("Date:")){ m_pHeader.GetFirst("Date:").Value = LumiSoft.Net.MIME.MIME_Utils.DateTimeToRfc2822(value); } else{ m_pHeader.Add("Date:",MimeUtils.DateTimeToRfc2822(value)); } } } /// <summary> /// Gets or sets header field "<b>Message-ID:</b>" value. Returns null if value isn't set. /// Syntax: '&lt;'id-left@id-right'&gt;'. Example: &lt;621bs724bfs8@jnfsjaas4263&gt; /// </summary> public string MessageID { get{ if(m_pHeader.Contains("Message-ID:")){ return m_pHeader.GetFirst("Message-ID:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Message-ID:")){ m_pHeader.GetFirst("Message-ID:").Value = value; } else{ m_pHeader.Add("Message-ID:",value); } } } /// <summary> /// Gets or sets header field "<b>To:</b>" value. Returns null if value isn't set. /// </summary> public AddressList To { get{ if(m_pHeader.Contains("To:")){ // There is already cached version, return it if(m_pHeaderFieldCache.Contains("To:")){ return (AddressList)m_pHeaderFieldCache["To:"]; } // These isn't cached version, we need to create it else{ // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("To:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["To:"] = list; return list; } } else{ return null; } } set{ // Just remove header field if(value == null){ m_pHeader.Remove(m_pHeader.GetFirst("To:")); return; } // Release old address collection if(m_pHeaderFieldCache["To:"] != null){ ((AddressList)m_pHeaderFieldCache["To:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField to = m_pHeader.GetFirst("To:"); if(to == null){ to = new HeaderField("To:",value.ToAddressListString()); m_pHeader.Add(to); } else{ to.Value = value.ToAddressListString(); } value.BoundedHeaderField = to; m_pHeaderFieldCache["To:"] = value; } } /// <summary> /// Gets or sets header field "<b>Cc:</b>" value. Returns null if value isn't set. /// </summary> public AddressList Cc { get{ if(m_pHeader.Contains("Cc:")){ // There is already cached version, return it if(m_pHeaderFieldCache.Contains("Cc:")){ return (AddressList)m_pHeaderFieldCache["Cc:"]; } // These isn't cached version, we need to create it else{ // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("Cc:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["Cc:"] = list; return list; } } else{ return null; } } set{ // Just remove header field if(value == null){ m_pHeader.Remove(m_pHeader.GetFirst("Cc:")); return; } // Release old address collection if(m_pHeaderFieldCache["Cc:"] != null){ ((AddressList)m_pHeaderFieldCache["Cc:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField cc = m_pHeader.GetFirst("Cc:"); if(cc == null){ cc = new HeaderField("Cc:",value.ToAddressListString()); m_pHeader.Add(cc); } else{ cc.Value = value.ToAddressListString(); } value.BoundedHeaderField = cc; m_pHeaderFieldCache["Cc:"] = value; } } /// <summary> /// Gets or sets header field "<b>Bcc:</b>" value. Returns null if value isn't set. /// </summary> public AddressList Bcc { get{ if(m_pHeader.Contains("Bcc:")){ // There is already cached version, return it if(m_pHeaderFieldCache.Contains("Bcc:")){ return (AddressList)m_pHeaderFieldCache["Bcc:"]; } // These isn't cached version, we need to create it else{ // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("Bcc:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["Bcc:"] = list; return list; } } else{ return null; } } set{ // Just remove header field if(value == null){ m_pHeader.Remove(m_pHeader.GetFirst("Bcc:")); return; } // Release old address collection if(m_pHeaderFieldCache["Bcc:"] != null){ ((AddressList)m_pHeaderFieldCache["Bcc:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField bcc = m_pHeader.GetFirst("Bcc:"); if(bcc == null){ bcc = new HeaderField("Bcc:",value.ToAddressListString()); m_pHeader.Add(bcc); } else{ bcc.Value = value.ToAddressListString(); } value.BoundedHeaderField = bcc; m_pHeaderFieldCache["Bcc:"] = value; } } /// <summary> /// Gets or sets header field "<b>From:</b>" value. Returns null if value isn't set. /// </summary> public AddressList From { get{ if(m_pHeader.Contains("From:")){ // There is already cached version, return it if(m_pHeaderFieldCache.Contains("From:")){ return (AddressList)m_pHeaderFieldCache["From:"]; } // These isn't cached version, we need to create it else{ // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("From:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["From:"] = list; return list; } } else{ return null; } } set{ // Just remove header field if(value == null && m_pHeader.Contains("From:")){ m_pHeader.Remove(m_pHeader.GetFirst("From:")); return; } // Release old address collection if(m_pHeaderFieldCache["From:"] != null){ ((AddressList)m_pHeaderFieldCache["From:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField from = m_pHeader.GetFirst("From:"); if(from == null){ from = new HeaderField("From:",value.ToAddressListString()); m_pHeader.Add(from); } else{ from.Value = value.ToAddressListString(); } value.BoundedHeaderField = from; m_pHeaderFieldCache["From:"] = value; } } /// <summary> /// Gets or sets header field "<b>Sender:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress Sender { get{ if(m_pHeader.Contains("Sender:")){ return MailboxAddress.Parse(m_pHeader.GetFirst("Sender:").EncodedValue); } else{ return null; } } set{ if(m_pHeader.Contains("Sender:")){ m_pHeader.GetFirst("Sender:").Value = value.ToMailboxAddressString(); } else{ m_pHeader.Add("Sender:",value.ToMailboxAddressString()); } } } /// <summary> /// Gets or sets header field "<b>Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public AddressList ReplyTo { get{ if(m_pHeader.Contains("Reply-To:")){ // There is already cached version, return it if(m_pHeaderFieldCache.Contains("Reply-To:")){ return (AddressList)m_pHeaderFieldCache["Reply-To:"]; } // These isn't cached version, we need to create it else{ // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("Reply-To:"); AddressList list = new AddressList(); list.Parse(field.Value); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["Reply-To:"] = list; return list; } } else{ return null; } } set{ // Just remove header field if(value == null && m_pHeader.Contains("Reply-To:")){ m_pHeader.Remove(m_pHeader.GetFirst("Reply-To:")); return; } // Release old address collection if(m_pHeaderFieldCache["Reply-To:"] != null){ ((AddressList)m_pHeaderFieldCache["Reply-To:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField replyTo = m_pHeader.GetFirst("Reply-To:"); if(replyTo == null){ replyTo = new HeaderField("Reply-To:",value.ToAddressListString()); m_pHeader.Add(replyTo); } else{ replyTo.Value = value.ToAddressListString(); } value.BoundedHeaderField = replyTo; m_pHeaderFieldCache["Reply-To:"] = value; } } /// <summary> /// Gets or sets header field "<b>In-Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public string InReplyTo { get{ if(m_pHeader.Contains("In-Reply-To:")){ return m_pHeader.GetFirst("In-Reply-To:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("In-Reply-To:")){ m_pHeader.GetFirst("In-Reply-To:").Value = value; } else{ m_pHeader.Add("In-Reply-To:",value); } } } /// <summary> /// Gets or sets header field "<b>Disposition-Notification-To:</b>" value. Returns null if value isn't set. /// </summary> public string DSN { get{ if(m_pHeader.Contains("Disposition-Notification-To:")){ return m_pHeader.GetFirst("Disposition-Notification-To:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Disposition-Notification-To:")){ m_pHeader.GetFirst("Disposition-Notification-To:").Value = value; } else{ m_pHeader.Add("Disposition-Notification-To:",value); } } } /// <summary> /// Gets or sets header field "<b>Subject:</b>" value. Returns null if value isn't set. /// </summary> public string Subject { get{ if(m_pHeader.Contains("Subject:")){ return m_pHeader.GetFirst("Subject:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Subject:")){ m_pHeader.GetFirst("Subject:").Value = value; } else{ m_pHeader.Add("Subject:",value); } } } /// <summary> /// Gets or sets entity data. Data is encoded/decoded with "<b>Content-Transfer-Encoding:</b>" header field value. /// Note: This property can be set only if Content-Type: isn't multipart. /// </summary> public byte[] Data { get{ // Decode Data ContentTransferEncoding_enum encoding = this.ContentTransferEncoding; if(encoding == ContentTransferEncoding_enum.Base64){ return Core.Base64Decode(this.DataEncoded); } else if(encoding == ContentTransferEncoding_enum.QuotedPrintable){ return Core.QuotedPrintableDecode(this.DataEncoded); } else{ return this.DataEncoded; } } set{ if(value == null){ this.DataEncoded = null; return; } ContentTransferEncoding_enum encoding = this.ContentTransferEncoding; this.DataEncoded = EncodeData(value,encoding); } } /// <summary> /// Gets or sets entity text data. Data is encoded/decoded with "<b>Content-Transfer-Encoding:</b>" header field value with this.Charset charset. /// Note: This property is available only if ContentType is Text/xxx... or no content type specified, othwerwise Excpetion is thrown. /// </summary> public string DataText { get{ if((this.ContentType & MediaType_enum.Text) == 0 && (this.ContentType & MediaType_enum.NotSpecified) == 0){ throw new Exception("This property is available only if ContentType is Text/xxx... !"); } try{ string charSet = this.ContentType_CharSet; // Charset isn't specified, use system default if(charSet == null){ return System.Text.Encoding.Default.GetString(this.Data); } else{ return System.Text.Encoding.GetEncoding(charSet).GetString(this.Data); } } // Not supported charset, use default catch{ return System.Text.Encoding.Default.GetString(this.Data); } } set{ if(value == null){ this.DataEncoded = null; return; } // Check charset string charSet = this.ContentType_CharSet; if(charSet == null){ throw new Exception("Please specify CharSet property first !"); } Encoding encoding = null; try{ encoding = Encoding.GetEncoding(charSet); } catch{ throw new Exception("Not supported charset '" + charSet + "' ! If you need to use this charset, then set data through Data or DataEncoded property."); } this.Data = encoding.GetBytes(value); } } /// <summary> /// Gets or sets entity encoded data. If you set this value, be sure that you encode this value as specified by Content-Transfer-Encoding: header field. /// Set this value only if you need custom Content-Transfer-Encoding: what current Mime class won't support, other wise set data through this.Data property. /// Note: This property can be set only if Content-Type: isn't multipart. /// </summary> public byte[] DataEncoded { get{ return m_EncodedData; } set{ m_EncodedData = value; } } #endregion } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The controller is not available for versions of Unity without the // GVR native integration. #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) using UnityEngine; using UnityEngine.VR; using System; using System.Collections; using Gvr.Internal; /// Represents the controller's current connection state. /// All values and semantics below (except for Error) are /// from gvr_types.h in the GVR C API. public enum GvrConnectionState { /// Indicates that an error has occurred. Error = -1, /// Indicates that the controller is disconnected. Disconnected = 0, /// Indicates that the device is scanning for controllers. Scanning = 1, /// Indicates that the device is connecting to a controller. Connecting = 2, /// Indicates that the device is connected to a controller. Connected = 3, }; // Represents the API status of the current controller state. // Values and semantics from gvr_types.h in the GVR C API. public enum GvrControllerApiStatus { // A Unity-localized error occurred. // This is the only value that isn't in gvr_types.h. Error = -1, // API is happy and healthy. This doesn't mean the controller itself // is connected, it just means that the underlying service is working // properly. Ok = 0, /// Any other status represents a permanent failure that requires /// external action to fix: /// API failed because this device does not support controllers (API is too /// low, or other required feature not present). Unsupported = 1, /// This app was not authorized to use the service (e.g., missing permissions, /// the app is blacklisted by the underlying service, etc). NotAuthorized = 2, /// The underlying VR service is not present. Unavailable = 3, /// The underlying VR service is too old, needs upgrade. ApiServiceObsolete = 4, /// The underlying VR service is too new, is incompatible with current client. ApiClientObsolete = 5, /// The underlying VR service is malfunctioning. Try again later. ApiMalfunction = 6, }; /// Main entry point for the Daydream controller API. /// /// To use this API, add this behavior to a GameObject in your scene, or use the /// GvrControllerMain prefab. There can only be one object with this behavior on your scene. /// /// This is a singleton object. /// /// To access the controller state, simply read the static properties of this class. For example, /// to know the controller's current orientation, use GvrController.Orientation. public class GvrController : MonoBehaviour { private static GvrController instance; private static IControllerProvider controllerProvider; private ControllerState controllerState = new ControllerState(); private IEnumerator controllerUpdate; private WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); /// Event handler for receiving button, track pad, and IMU updates from the controller. public delegate void OnControllerUpdateEvent(); public event OnControllerUpdateEvent OnControllerUpdate; public enum EmulatorConnectionMode { OFF, USB, WIFI, } /// Indicates how we connect to the controller emulator. [Tooltip("How to connect to the emulator: USB cable (recommended) or WIFI.")] public EmulatorConnectionMode emulatorConnectionMode = EmulatorConnectionMode.USB; /// Returns the arm model instance associated with the controller. public static GvrArmModel ArmModel { get { return instance != null ? instance.GetComponent<GvrArmModel>() : null; } } /// Returns the controller's current connection state. public static GvrConnectionState State { get { return instance != null ? instance.controllerState.connectionState : GvrConnectionState.Error; } } /// Returns the API status of the current controller state. public static GvrControllerApiStatus ApiStatus { get { return instance != null ? instance.controllerState.apiStatus : GvrControllerApiStatus.Error; } } /// Returns the controller's current orientation in space, as a quaternion. /// The space in which the orientation is represented is the usual Unity space, with /// X pointing to the right, Y pointing up and Z pointing forward. Therefore, to make an /// object in your scene have the same orientation as the controller, simply assign this /// quaternion to the GameObject's transform.rotation. public static Quaternion Orientation { get { return instance != null ? instance.controllerState.orientation : Quaternion.identity; } } /// Returns the controller's gyroscope reading. The gyroscope indicates the angular /// about each of its local axes. The controller's axes are: X points to the right, /// Y points perpendicularly up from the controller's top surface and Z lies /// along the controller's body, pointing towards the front. The angular speed is given /// in radians per second, using the right-hand rule (positive means a right-hand rotation /// about the given axis). public static Vector3 Gyro { get { return instance != null ? instance.controllerState.gyro : Vector3.zero; } } /// Returns the controller's accelerometer reading. The accelerometer indicates the /// effect of acceleration and gravity in the direction of each of the controller's local /// axes. The controller's local axes are: X points to the right, Y points perpendicularly /// up from the controller's top surface and Z lies along the controller's body, pointing /// towards the front. The acceleration is measured in meters per second squared. Note that /// gravity is combined with acceleration, so when the controller is resting on a table top, /// it will measure an acceleration of 9.8 m/s^2 on the Y axis. The accelerometer reading /// will be zero on all three axes only if the controller is in free fall, or if the user /// is in a zero gravity environment like a space station. public static Vector3 Accel { get { return instance != null ? instance.controllerState.accel : Vector3.zero; } } /// If true, the user is currently touching the controller's touchpad. public static bool IsTouching { get { return instance != null ? instance.controllerState.isTouching : false; } } /// If true, the user just started touching the touchpad. This is an event flag (it is true /// for only one frame after the event happens, then reverts to false). public static bool TouchDown { get { return instance != null ? instance.controllerState.touchDown : false; } } /// If true, the user just stopped touching the touchpad. This is an event flag (it is true /// for only one frame after the event happens, then reverts to false). public static bool TouchUp { get { return instance != null ? instance.controllerState.touchUp : false; } } public static Vector2 TouchPos { get { return instance != null ? instance.controllerState.touchPos : Vector2.zero; } } /// If true, the user is currently performing the recentering gesture. Most apps will want /// to pause the interaction while this remains true. public static bool Recentering { get { return instance != null ? instance.controllerState.recentering : false; } } /// If true, the user just completed the recenter gesture. The controller's orientation is /// now being reported in the new recentered coordinate system (the controller's orientation /// when recentering was completed was remapped to mean "forward"). This is an event flag /// (it is true for only one frame after the event happens, then reverts to false). /// The headset is recentered together with the controller. public static bool Recentered { get { return instance != null ? instance.controllerState.recentered : false; } } /// If true, the click button (touchpad button) is currently being pressed. This is not /// an event: it represents the button's state (it remains true while the button is being /// pressed). public static bool ClickButton { get { return instance != null ? instance.controllerState.clickButtonState : false; } } /// If true, the click button (touchpad button) was just pressed. This is an event flag: /// it will be true for only one frame after the event happens. public static bool ClickButtonDown { get { return instance != null ? instance.controllerState.clickButtonDown : false; } } /// If true, the click button (touchpad button) was just released. This is an event flag: /// it will be true for only one frame after the event happens. public static bool ClickButtonUp { get { return instance != null ? instance.controllerState.clickButtonUp : false; } } /// If true, the app button (touchpad button) is currently being pressed. This is not /// an event: it represents the button's state (it remains true while the button is being /// pressed). public static bool AppButton { get { return instance != null ? instance.controllerState.appButtonState : false; } } /// If true, the app button was just pressed. This is an event flag: it will be true for /// only one frame after the event happens. public static bool AppButtonDown { get { return instance != null ? instance.controllerState.appButtonDown : false; } } /// If true, the app button was just released. This is an event flag: it will be true for /// only one frame after the event happens. public static bool AppButtonUp { get { return instance != null ? instance.controllerState.appButtonUp : false; } } /// If State == GvrConnectionState.Error, this contains details about the error. public static string ErrorDetails { get { if (instance != null) { return instance.controllerState.connectionState == GvrConnectionState.Error ? instance.controllerState.errorDetails : ""; } else { return "GvrController instance not found in scene. It may be missing, or it might " + "not have initialized yet."; } } } // Returns the GVR C library controller state pointer (gvr_controller_state*). public static IntPtr StatePtr { get { return instance != null? instance.controllerState.gvrPtr : IntPtr.Zero; } } void Awake() { if (instance != null) { Debug.LogError("More than one GvrController instance was found in your scene. " + "Ensure that there is only one GvrController."); this.enabled = false; return; } instance = this; if (controllerProvider == null) { controllerProvider = ControllerProviderFactory.CreateControllerProvider(this); } // Keep screen on here, in case there isn't a GvrViewerMain prefab in the scene. // This ensures the behaviour for: // (a) Cardboard apps on pre-integration Unity versions - they must have GvrViewerMain in a scene. // (b) Daydream apps - these must be on GVR-integrated Unity versions, and must have GvrControllerMain. // Cardboard-only apps on the native integration are likely to have GvrViewerMain in their scene; otherwise, // the line below can be added to any script of the developer's choice. Screen.sleepTimeout = SleepTimeout.NeverSleep; } void OnDestroy() { instance = null; } private void UpdateController() { controllerProvider.ReadState(controllerState); // If a headset recenter was requested, do it now. if (controllerState.headsetRecenterRequested) { #if UNITY_EDITOR GvrViewer sdk = GvrViewer.Instance; if (sdk) { sdk.Recenter(); } #else InputTracking.Recenter(); #endif // UNITY_EDITOR } } void OnApplicationPause(bool paused) { if (null == controllerProvider) return; if (paused) { controllerProvider.OnPause(); } else { controllerProvider.OnResume(); } } void OnEnable() { controllerUpdate = EndOfFrame(); StartCoroutine(controllerUpdate); } void OnDisable() { StopCoroutine(controllerUpdate); } IEnumerator EndOfFrame() { while (true) { // This must be done at the end of the frame to ensure that all GameObjects had a chance // to read transient controller state (e.g. events, etc) for the current frame before // it gets reset. yield return waitForEndOfFrame; UpdateController(); OnControllerUpdate(); } } } #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
using System.Collections.Generic; using System.Diagnostics; using System.Text; using System; namespace Palaso.Lift.Parsing { /// <summary> /// This class represents the formatting information for a span of text. /// </summary> public class LiftSpan { int _index; // index of first character covered by the span in the string int _length; // length of span in the string string _lang; // lang attribute value for the span, if any string _class; // class attribute value for the span, if any string _linkurl; // href attribute value for the span, if any readonly List<LiftSpan> _spans = new List<LiftSpan>(); /// <summary> /// Constructor. /// </summary> public LiftSpan(int index, int length, string lang, string className, string href) { _index = index; _length = length; _lang = lang; _class = className; _linkurl = href; } /// <summary>This must be overridden for tests to pass.</summary> public override bool Equals(object obj) { LiftSpan that = obj as LiftSpan; if (that == null) return false; if (_index != that._index) return false; if (_length != that._length) return false; if (_lang != that._lang) return false; if (_class != that._class) return false; if (_linkurl != that._linkurl) return false; return true; } /// <summary>Keep ReSharper from complaining about Equals().</summary> public override int GetHashCode() { return base.GetHashCode(); } ///<summary> /// Get the index of this span within the overall LiftMultiText string. ///</summary> public int Index { get { return _index; } } /// <summary> /// Get the length of this span. /// </summary> public int Length { get { return _length; } } /// <summary> /// Get the language of the data in this span. /// </summary> public string Lang { get { return _lang; } } /// <summary> /// Get the class (style) applied to the data in this span. /// </summary> public string Class { get { return _class; } } /// <summary> /// Get the underlying link URL of this span (if any). /// </summary> public string LinkURL { get { return _linkurl; } } /// <summary> /// Return the list of format specifications, if any. /// </summary> public List<LiftSpan> Spans { get { return _spans; } } } /// <summary> /// This class represents a string with optional embedded formatting information. /// </summary> public class LiftString { string _text; readonly List<LiftSpan> _spans = new List<LiftSpan>(); /// <summary> /// Default constructor. /// </summary> public LiftString() { } /// <summary> /// Constructor with simple C# string data. /// </summary> public LiftString(string simpleContent) { Text = simpleContent; } /// <summary> /// Get the text of this string. /// </summary> public string Text { get { return _text; } set { _text = value; } } /// <summary> /// Return the list of format specifications, if any. /// </summary> public List<LiftSpan> Spans { get { return _spans; } } /// <summary>This must be overridden for tests to pass.</summary> public override bool Equals(object obj) { LiftString that = obj as LiftString; if (that == null) return false; if (Text != that.Text) return false; if (Spans.Count != that.Spans.Count) return false; for (int i = 0; i < Spans.Count; ++i) { if (!Spans[i].Equals(that.Spans[i])) return false; } return true; } /// <summary>Keep ReSharper from complaining about Equals().</summary> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// This class represents a multilingual string, possibly with embedded formatting /// information in each of the alternatives. /// </summary> public class LiftMultiText : Dictionary<string, LiftString> { private List<Annotation> _annotations = new List<Annotation>(); private readonly string _OriginalRawXml; /// <summary> /// Default constructor. /// </summary> public LiftMultiText() { } /// <summary> /// Constructor. /// </summary> public LiftMultiText(string rawXml) { _OriginalRawXml = rawXml; } /// <summary> /// Constructor. /// </summary> public LiftMultiText(string key, string simpleContent) { Add(key, new LiftString(simpleContent)); } /// <summary></summary> public override string ToString() { StringBuilder b = new StringBuilder(); foreach (string key in Keys) { b.AppendFormat("{0}={1}|", key, this[key].Text); } return b.ToString(); } /// <summary>This must be overridden for tests to pass.</summary> public override bool Equals(object obj) { LiftMultiText that = obj as LiftMultiText; if (that == null) return false; if (Keys.Count != that.Keys.Count) return false; foreach (string key in Keys) { LiftString otherString; if (!that.TryGetValue(key, out otherString)) return false; if (!this[key].Equals(otherString)) return false; } return true; } /// <summary>Keep ReSharper from complaining about Equals().</summary> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// For WeSay, which doesn't yet understand structured strings /// </summary> public Dictionary<string, string> AsSimpleStrings { get { Dictionary<string, string> result = new Dictionary<string, string>(); foreach (KeyValuePair<string, LiftString> pair in this) { if (pair.Value != null) { result.Add(pair.Key, pair.Value.Text); } } return result; } } /// <summary> /// For WeSay, to allow spans to be carried along even if not used. /// </summary> public Dictionary<string, List<LiftSpan>> AllSpans { get { Dictionary<string, List<LiftSpan>> result = new Dictionary<string, List<LiftSpan>>(); foreach (KeyValuePair<string, LiftString> pair in this) { if (pair.Value != null) { result.Add(pair.Key, pair.Value.Spans); } } return result; } } /// <summary> /// Check whether this LiftMultiText is empty. /// </summary> public bool IsEmpty { get { return Count == 0; } } ///<summary> /// Return the first KeyValuePair in this LiftMultiText. ///</summary> public KeyValuePair<string,LiftString> FirstValue { get { Enumerator enumerator = GetEnumerator(); enumerator.MoveNext(); return enumerator.Current; } } /// <summary> /// Get/set the annotations for this LiftMultiText. /// </summary> public List<Annotation> Annotations { get { return _annotations; } set { _annotations = value; } } /// <summary> /// Get the original XML string used to initialize this LiftMultiText (if any). /// </summary> public string OriginalRawXml { get { return _OriginalRawXml; } } /// <summary> /// Add data to the beginning of a particular alternative of this LiftMultiText. /// </summary> /// <remarks> /// TODO: update the offsets of any spans after the first in that alternative, /// and the length of the first span. /// </remarks> public void Prepend(string key, string prepend) { LiftString existing; if (TryGetValue(key, out existing)) { this[key].Text = prepend + existing.Text; return; } Debug.Fail("Tried to prepend to empty alternative "); //don't need to stop in release versions } // Add this method if you think we really need backward compatibility... //public void Add(string key, string text) //{ // LiftString str = new LiftString(); // str.Text = text; // this.Add(key, str); //} /// <summary> /// if we already have a form in the lang, add the new one after adding the delimiter e.g. "tube; hose" /// </summary> /// <param name="key"></param> /// <param name="newValue"></param> /// <param name="delimiter"></param> public void AddOrAppend(string key, string newValue, string delimiter) { LiftString existing; if (TryGetValue(key, out existing)) { if (String.IsNullOrEmpty(existing.Text)) this[key].Text = newValue; else this[key].Text = existing.Text + delimiter + newValue; } else { LiftString alternative = new LiftString(); alternative.Text = newValue; this[key] = alternative; } } /// <summary> /// Merge another LiftMultiText with a common ancestor into this LiftMultiText. /// </summary> public void Merge(LiftMultiText theirs, LiftMultiText ancestor) { // TODO: implement this?! } /// <summary> /// Return the length of the text stored for the given language code, or zero if that /// alternative doesn't exist. /// </summary> /// <param name="key"></param> /// <returns></returns> public int LengthOfAlternative(string key) { LiftString existing; if (TryGetValue(key, out existing)) return existing.Text == null ? 0 : existing.Text.Length; return 0; } /// <summary> /// Add another alternative to this LiftMultiText. /// </summary> public void Add(string key, string simpleContent) { Add(key, new LiftString(simpleContent)); } /// <summary> /// Add another span to the given alternative, creating the alternative if needed. /// </summary> public LiftSpan AddSpan(string key, string lang, string style, string href, int length) { LiftString alternative; if (!TryGetValue(key, out alternative)) { alternative = new LiftString(); this[key] = alternative; } int start = alternative.Text.Length; if (lang == key) lang = null; var span = new LiftSpan(start, length, lang, style, href); alternative.Spans.Add(span); return span; } } }
using System; using System.Collections.Generic; namespace Orleans.Runtime { internal class IncomingMessageBuffer { private const int Kb = 1024; private const int DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE = 1024 * Kb; // 1mg private const int GROW_MAX_BLOCK_SIZE = 1024 * Kb; // 1mg private readonly List<ArraySegment<byte>> readBuffer; private readonly int maxSustainedBufferSize; private int currentBufferSize; private readonly byte[] lengthBuffer; private int headerLength; private int bodyLength; private int receiveOffset; private int decodeOffset; private readonly bool supportForwarding; private Logger Log; internal const int DEFAULT_RECEIVE_BUFFER_SIZE = 128 * Kb; // 128k public IncomingMessageBuffer(Logger logger, bool supportForwarding = false, int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE, int maxSustainedReceiveBufferSize = DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE) { Log = logger; this.supportForwarding = supportForwarding; currentBufferSize = receiveBufferSize; maxSustainedBufferSize = maxSustainedReceiveBufferSize; lengthBuffer = new byte[Message.LENGTH_HEADER_SIZE]; readBuffer = BufferPool.GlobalPool.GetMultiBuffer(currentBufferSize); receiveOffset = 0; decodeOffset = 0; headerLength = 0; bodyLength = 0; } public List<ArraySegment<byte>> BuildReceiveBuffer() { // Opportunistic reset to start of buffer if (decodeOffset == receiveOffset) { decodeOffset = 0; receiveOffset = 0; } return ByteArrayBuilder.BuildSegmentList(readBuffer, receiveOffset); } // Copies receive buffer into read buffer for futher processing public void UpdateReceivedData(byte[] receiveBuffer, int bytesRead) { var newReceiveOffset = receiveOffset + bytesRead; while (newReceiveOffset > currentBufferSize) { GrowBuffer(); } int receiveBufferOffset = 0; var lengthSoFar = 0; foreach (var segment in readBuffer) { var bytesStillToSkip = receiveOffset - lengthSoFar; lengthSoFar += segment.Count; if (segment.Count <= bytesStillToSkip) { continue; } if(bytesStillToSkip > 0) // This is the first buffer { var bytesToCopy = Math.Min(segment.Count - bytesStillToSkip, bytesRead - receiveBufferOffset); Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, bytesStillToSkip, bytesToCopy); receiveBufferOffset += bytesToCopy; } else { var bytesToCopy = Math.Min(segment.Count, bytesRead - receiveBufferOffset); Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, 0, bytesToCopy); receiveBufferOffset += Math.Min(bytesToCopy, segment.Count); } if (receiveBufferOffset == bytesRead) { break; } } receiveOffset += bytesRead; } public void UpdateReceivedData(int bytesRead) { receiveOffset += bytesRead; } public void Reset() { receiveOffset = 0; decodeOffset = 0; headerLength = 0; bodyLength = 0; } public bool TryDecodeMessage(out Message msg) { msg = null; // Is there enough read into the buffer to continue (at least read the lengths?) if (receiveOffset - decodeOffset < CalculateKnownMessageSize()) return false; // parse lengths if needed if (headerLength == 0 || bodyLength == 0) { // get length segments List<ArraySegment<byte>> lenghts = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, decodeOffset, Message.LENGTH_HEADER_SIZE); // copy length segment to buffer int lengthBufferoffset = 0; foreach (ArraySegment<byte> seg in lenghts) { Buffer.BlockCopy(seg.Array, seg.Offset, lengthBuffer, lengthBufferoffset, seg.Count); lengthBufferoffset += seg.Count; } // read lengths headerLength = BitConverter.ToInt32(lengthBuffer, 0); bodyLength = BitConverter.ToInt32(lengthBuffer, 4); } // If message is too big for current buffer size, grow while (decodeOffset + CalculateKnownMessageSize() > currentBufferSize) { GrowBuffer(); } // Is there enough read into the buffer to read full message if (receiveOffset - decodeOffset < CalculateKnownMessageSize()) return false; // decode header int headerOffset = decodeOffset + Message.LENGTH_HEADER_SIZE; List<ArraySegment<byte>> header = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, headerOffset, headerLength); // decode body int bodyOffset = headerOffset + headerLength; List<ArraySegment<byte>> body = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, bodyOffset, bodyLength); // need to maintain ownership of buffer, so if we are supporting forwarding we need to duplicate the body buffer. if (supportForwarding) { body = DuplicateBuffer(body); } // build message msg = new Message(header, body, !supportForwarding); MessagingStatisticsGroup.OnMessageReceive(msg, headerLength, bodyLength); if (headerLength + bodyLength > Message.LargeMessageSizeThreshold) { Log.Info(ErrorCode.Messaging_LargeMsg_Incoming, "Receiving large message Size={0} HeaderLength={1} BodyLength={2}. Msg={3}", headerLength + bodyLength, headerLength, bodyLength, msg.ToString()); if (Log.IsVerbose3) Log.Verbose3("Received large message {0}", msg.ToLongString()); } // update parse receiveOffset and clear lengths decodeOffset = bodyOffset + bodyLength; headerLength = 0; bodyLength = 0; AdjustBuffer(); return true; } /// <summary> /// This call cleans up the buffer state to make it optimal for next read. /// The leading chunks, used by any processed messages, are removed from the front /// of the buffer and added to the back. Decode and receiver offsets are adjusted accordingly. /// If the buffer was grown over the max sustained buffer size (to read a large message) it is shrunken. /// </summary> private void AdjustBuffer() { // drop buffers consumed by messages and adjust offsets // TODO: This can be optimized further. Linked lists? int consumedBytes = 0; while (readBuffer.Count != 0) { ArraySegment<byte> seg = readBuffer[0]; if (seg.Count <= decodeOffset - consumedBytes) { consumedBytes += seg.Count; readBuffer.Remove(seg); BufferPool.GlobalPool.Release(seg.Array); } else { break; } } decodeOffset -= consumedBytes; receiveOffset -= consumedBytes; // backfill any consumed buffers, to preserve buffer size. if (consumedBytes != 0) { int backfillBytes = consumedBytes; // If buffer is larger than max sustained size, backfill only up to max sustained buffer size. if (currentBufferSize > maxSustainedBufferSize) { backfillBytes = Math.Max(consumedBytes + maxSustainedBufferSize - currentBufferSize, 0); currentBufferSize -= consumedBytes; currentBufferSize += backfillBytes; } if (backfillBytes > 0) { readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(backfillBytes)); } } } private int CalculateKnownMessageSize() { return headerLength + bodyLength + Message.LENGTH_HEADER_SIZE; } private List<ArraySegment<byte>> DuplicateBuffer(List<ArraySegment<byte>> body) { var dupBody = new List<ArraySegment<byte>>(body.Count); foreach (ArraySegment<byte> seg in body) { var dupSeg = new ArraySegment<byte>(BufferPool.GlobalPool.GetBuffer(), seg.Offset, seg.Count); Buffer.BlockCopy(seg.Array, seg.Offset, dupSeg.Array, dupSeg.Offset, seg.Count); dupBody.Add(dupSeg); } return dupBody; } private void GrowBuffer() { //TODO: Add configurable max message size for safety //TODO: Review networking layer and add max size checks to all dictionaries, arrays, or other variable sized containers. // double buffer size up to max grow block size, then only grow it in those intervals int growBlockSize = Math.Min(currentBufferSize, GROW_MAX_BLOCK_SIZE); readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(growBlockSize)); currentBufferSize += growBlockSize; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: CfgParser ** ** ** Purpose: XMLParser and Tree builder internal to BCL ** ** ===========================================================*/ namespace System { using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Security.Permissions; using System.Security; using System.Globalization; using System.IO; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] internal enum ConfigEvents { StartDocument = 0, StartDTD = StartDocument + 1, EndDTD = StartDTD + 1, StartDTDSubset = EndDTD + 1, EndDTDSubset = StartDTDSubset + 1, EndProlog = EndDTDSubset + 1, StartEntity = EndProlog + 1, EndEntity = StartEntity + 1, EndDocument = EndEntity + 1, DataAvailable = EndDocument + 1, LastEvent = DataAvailable } [Serializable] internal enum ConfigNodeType { Element = 1, Attribute = Element + 1, Pi = Attribute + 1, XmlDecl = Pi + 1, DocType = XmlDecl + 1, DTDAttribute = DocType + 1, EntityDecl = DTDAttribute + 1, ElementDecl = EntityDecl + 1, AttlistDecl = ElementDecl + 1, Notation = AttlistDecl + 1, Group = Notation + 1, IncludeSect = Group + 1, PCData = IncludeSect + 1, CData = PCData + 1, IgnoreSect = CData + 1, Comment = IgnoreSect + 1, EntityRef = Comment + 1, Whitespace = EntityRef + 1, Name = Whitespace + 1, NMToken = Name + 1, String = NMToken + 1, Peref = String + 1, Model = Peref + 1, ATTDef = Model + 1, ATTType = ATTDef + 1, ATTPresence = ATTType + 1, DTDSubset = ATTPresence + 1, LastNodeType = DTDSubset + 1 } [Serializable] internal enum ConfigNodeSubType { Version = (int)ConfigNodeType.LastNodeType, Encoding = Version + 1, Standalone = Encoding + 1, NS = Standalone + 1, XMLSpace = NS + 1, XMLLang = XMLSpace + 1, System = XMLLang + 1, Public = System + 1, NData = Public + 1, AtCData = NData + 1, AtId = AtCData + 1, AtIdref = AtId + 1, AtIdrefs = AtIdref + 1, AtEntity = AtIdrefs + 1, AtEntities = AtEntity + 1, AtNmToken = AtEntities + 1, AtNmTokens = AtNmToken + 1, AtNotation = AtNmTokens + 1, AtRequired = AtNotation + 1, AtImplied = AtRequired + 1, AtFixed = AtImplied + 1, PentityDecl = AtFixed + 1, Empty = PentityDecl + 1, Any = Empty + 1, Mixed = Any + 1, Sequence = Mixed + 1, Choice = Sequence + 1, Star = Choice + 1, Plus = Star + 1, Questionmark = Plus + 1, LastSubNodeType = Questionmark + 1 } internal abstract class BaseConfigHandler { // These delegates must be at the very start of the object // This is necessary because unmanaged code takes a dependency on this layout // Any changes made to this must be reflected in ConfigHelper.h in ConfigFactory class protected Delegate[] eventCallbacks; public BaseConfigHandler() { InitializeCallbacks(); } private void InitializeCallbacks() { if (eventCallbacks == null) { eventCallbacks = new Delegate[6]; eventCallbacks[0] = new NotifyEventCallback(this.NotifyEvent); eventCallbacks[1] = new BeginChildrenCallback(this.BeginChildren); eventCallbacks[2] = new EndChildrenCallback(this.EndChildren); eventCallbacks[3] = new ErrorCallback(this.Error); eventCallbacks[4] = new CreateNodeCallback(this.CreateNode); eventCallbacks[5] = new CreateAttributeCallback(this.CreateAttribute); } } private delegate void NotifyEventCallback(ConfigEvents nEvent); public abstract void NotifyEvent(ConfigEvents nEvent); private delegate void BeginChildrenCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); public abstract void BeginChildren(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); private delegate void EndChildrenCallback(int fEmpty, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); public abstract void EndChildren(int fEmpty, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); private delegate void ErrorCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); public abstract void Error(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); private delegate void CreateNodeCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); public abstract void CreateNode(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); private delegate void CreateAttributeCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); public abstract void CreateAttribute(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void RunParser(String fileName); } // Class used to build a DOM like tree of parsed XML internal class ConfigTreeParser : BaseConfigHandler { ConfigNode rootNode = null; ConfigNode currentNode = null; String fileName = null; int attributeEntry; String key = null; String [] treeRootPath = null; // element to start tree bool parsing = false; int depth = 0; int pathDepth = 0; int searchDepth = 0; bool bNoSearchPath = false; // Track state for error message formatting String lastProcessed = null; bool lastProcessedEndElement; // NOTE: This parser takes a path eg. /configuration/system.runtime.remoting // and will return a node which matches this. [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal ConfigNode Parse(String fileName, String configPath) { return Parse(fileName, configPath, false); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); this.fileName = fileName; if (configPath[0] == '/'){ treeRootPath = configPath.Substring(1).Split('/'); pathDepth = treeRootPath.Length - 1; bNoSearchPath = false; } else{ treeRootPath = new String[1]; treeRootPath[0] = configPath; bNoSearchPath = true; } if (!skipSecurityStuff) { (new FileIOPermission( FileIOPermissionAccess.Read, System.IO.Path.GetFullPathInternal( fileName ) )).Demand(); } #pragma warning disable 618 (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert(); #pragma warning restore 618 try { RunParser(fileName); } catch(FileNotFoundException) { throw; // Pass these through unadulterated. } catch(DirectoryNotFoundException) { throw; // Pass these through unadulterated. } catch(UnauthorizedAccessException) { throw; } catch(FileLoadException) { throw; } catch(Exception inner) { String message = GetInvalidSyntaxMessage(); // Neither Exception nor ApplicationException are the "right" exceptions here. // Desktop throws ApplicationException for backwards compatibility. // On Silverlight we don't have ApplicationException, so fall back to Exception. #if FEATURE_CORECLR throw new Exception(message, inner); #else throw new ApplicationException(message, inner); #endif } return rootNode; } public override void NotifyEvent(ConfigEvents nEvent) { BCLDebug.Trace("REMOTE", "NotifyEvent "+((Enum)nEvent).ToString()+"\n"); } public override void BeginChildren(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength) { //Trace("BeginChildren",size,subType,nType,terminal,text,textLength,prefixLength,0); if (!parsing && (!bNoSearchPath && depth == (searchDepth + 1) && String.Compare(text, treeRootPath[searchDepth], StringComparison.Ordinal) == 0)) { searchDepth++; } } public override void EndChildren(int fEmpty, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength) { lastProcessed = text; lastProcessedEndElement = true; if (parsing) { //Trace("EndChildren",size,subType,nType,terminal,text,textLength,prefixLength,fEmpty); if (currentNode == rootNode) { // End of section of tree which is parsed parsing = false; } currentNode = currentNode.Parent; } else if (nType == ConfigNodeType.Element){ if(depth == searchDepth && String.Compare(text, treeRootPath[searchDepth - 1], StringComparison.Ordinal) == 0) { searchDepth--; depth--; } else depth--; } } public override void Error(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength) { //Trace("Error",size,subType,nType,terminal,text,textLength,prefixLength,0); } public override void CreateNode(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength) { //Trace("CreateNode",size,subType,nType,terminal,text,textLength,prefixLength,0); if (nType == ConfigNodeType.Element) { // New Node lastProcessed = text; lastProcessedEndElement = false; if (parsing || (bNoSearchPath && String.Compare(text, treeRootPath[0], StringComparison.OrdinalIgnoreCase) == 0) || (depth == searchDepth && searchDepth == pathDepth && String.Compare(text, treeRootPath[pathDepth], StringComparison.OrdinalIgnoreCase) == 0 )) { parsing = true; ConfigNode parentNode = currentNode; currentNode = new ConfigNode(text, parentNode); if (rootNode == null) rootNode = currentNode; else parentNode.AddChild(currentNode); } else depth++; } else if (nType == ConfigNodeType.PCData) { // Data node if (currentNode != null) { currentNode.Value = text; } } } public override void CreateAttribute(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength) { //Trace("CreateAttribute",size,subType,nType,terminal,text,textLength,prefixLength,0); if (parsing) { // if the value of the attribute is null, the parser doesn't come back, so need to store the attribute when the // attribute name is encountered if (nType == ConfigNodeType.Attribute) { attributeEntry = currentNode.AddAttribute(text, ""); key = text; } else if (nType == ConfigNodeType.PCData) { currentNode.ReplaceAttribute(attributeEntry, key, text); } else { String message = GetInvalidSyntaxMessage(); // Neither Exception nor ApplicationException are the "right" exceptions here. // Desktop throws ApplicationException for backwards compatibility. // On Silverlight we don't have ApplicationException, so fall back to Exception. #if FEATURE_CORECLR throw new Exception(message); #else throw new ApplicationException(message); #endif } } } #if _DEBUG [System.Diagnostics.Conditional("_LOGGING")] private void Trace(String name, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength, int fEmpty) { BCLDebug.Trace("REMOTE","Node "+name); BCLDebug.Trace("REMOTE","text "+text); BCLDebug.Trace("REMOTE","textLength "+textLength); BCLDebug.Trace("REMOTE","size "+size); BCLDebug.Trace("REMOTE","subType "+((Enum)subType).ToString()); BCLDebug.Trace("REMOTE","nType "+((Enum)nType).ToString()); BCLDebug.Trace("REMOTE","terminal "+terminal); BCLDebug.Trace("REMOTE","prefixLength "+prefixLength); BCLDebug.Trace("REMOTE","fEmpty "+fEmpty+"\n"); } #endif private String GetInvalidSyntaxMessage() { String lastProcessedTag = null; if (lastProcessed != null) lastProcessedTag = (lastProcessedEndElement ? "</" : "<") + lastProcessed + ">"; return Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile", fileName, lastProcessedTag); } } // Node in Tree produced by ConfigTreeParser internal class ConfigNode { String m_name = null; String m_value = null; ConfigNode m_parent = null; List<ConfigNode> m_children = new List<ConfigNode>(5); List<DictionaryEntry> m_attributes = new List<DictionaryEntry>(5); internal ConfigNode(String name, ConfigNode parent) { m_name = name; m_parent = parent; } internal String Name { get {return m_name;} } internal String Value { get {return m_value;} set {m_value = value;} } internal ConfigNode Parent { get {return m_parent;} } internal List<ConfigNode> Children { get {return m_children;} } internal List<DictionaryEntry> Attributes { get {return m_attributes;} } internal void AddChild(ConfigNode child) { child.m_parent = this; m_children.Add(child); } internal int AddAttribute(String key, String value) { m_attributes.Add(new DictionaryEntry(key, value)); return m_attributes.Count-1; } internal void ReplaceAttribute(int index, String key, String value) { m_attributes[index] = new DictionaryEntry(key, value); } #if _DEBUG [System.Diagnostics.Conditional("_LOGGING")] internal void Trace() { BCLDebug.Trace("REMOTE","************ConfigNode************"); BCLDebug.Trace("REMOTE","Name = "+m_name); if (m_value != null) BCLDebug.Trace("REMOTE","Value = "+m_value); if (m_parent != null) BCLDebug.Trace("REMOTE","Parent = "+m_parent.Name); for (int i=0; i<m_attributes.Count; i++) { DictionaryEntry de = (DictionaryEntry)m_attributes[i]; BCLDebug.Trace("REMOTE","Key = "+de.Key+" Value = "+de.Value); } for (int i=0; i<m_children.Count; i++) { ((ConfigNode)m_children[i]).Trace(); } } #endif } }
/* * 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 OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using System.Reflection; namespace OpenSim.Server.Handlers { public class UserProfilesHandlers { public UserProfilesHandlers () { } } public class JsonRpcProfileHandlers { static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); public IUserProfilesService Service { get; private set; } public JsonRpcProfileHandlers(IUserProfilesService service) { Service = service; } #region Classifieds /// <summary> /// Request avatar's classified ads. /// </summary> /// <returns> /// An array containing all the calassified uuid and it's name created by the creator id /// </returns> /// <param name='json'> /// Our parameters are in the OSDMap json["params"] /// </param> /// <param name='response'> /// If set to <c>true</c> response. /// </param> public bool AvatarClassifiedsRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Classified Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID creatorId = new UUID(request["creatorId"].AsString()); OSDArray data = (OSDArray) Service.AvatarClassifiedsRequest(creatorId); response.Result = data; return true; } public bool ClassifiedUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "Error parsing classified update request"; m_log.DebugFormat ("Classified Update Request"); return false; } string result = string.Empty; UserClassifiedAdd ad = new UserClassifiedAdd(); object Ad = (object)ad; OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]); if(Service.ClassifiedUpdate(ad, ref result)) { response.Result = OSD.SerializeMembers(ad); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool ClassifiedDelete(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Classified Delete Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID classifiedId = new UUID(request["classifiedId"].AsString()); if (Service.ClassifiedDelete(classifiedId)) return true; response.Error.Code = ErrorCode.InternalError; response.Error.Message = "data error removing record"; return false; } public bool ClassifiedInfoRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Classified Info Request"); return false; } string result = string.Empty; UserClassifiedAdd ad = new UserClassifiedAdd(); object Ad = (object)ad; OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]); if(Service.ClassifiedInfoRequest(ref ad, ref result)) { response.Result = OSD.SerializeMembers(ad); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion Classifieds #region Picks public bool AvatarPicksRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Picks Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID creatorId = new UUID(request["creatorId"].AsString()); OSDArray data = (OSDArray) Service.AvatarPicksRequest(creatorId); response.Result = data; return true; } public bool PickInfoRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Picks Info Request"); return false; } string result = string.Empty; UserProfilePick pick = new UserProfilePick(); object Pick = (object)pick; OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]); if(Service.PickInfoRequest(ref pick, ref result)) { response.Result = OSD.SerializeMembers(pick); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool PicksUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Picks Update Request"); return false; } string result = string.Empty; UserProfilePick pick = new UserProfilePick(); object Pick = (object)pick; OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]); if(Service.PicksUpdate(ref pick, ref result)) { response.Result = OSD.SerializeMembers(pick); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = "unable to update pick"; return false; } public bool PicksDelete(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Picks Delete Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID pickId = new UUID(request["pickId"].AsString()); if(Service.PicksDelete(pickId)) return true; response.Error.Code = ErrorCode.InternalError; response.Error.Message = "data error removing record"; return false; } #endregion Picks #region Notes public bool AvatarNotesRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "Params missing"; m_log.DebugFormat ("Avatar Notes Request"); return false; } string result = string.Empty; UserProfileNotes note = new UserProfileNotes(); object Note = (object)note; OSD.DeserializeMembers(ref Note, (OSDMap)json["params"]); if(Service.AvatarNotesRequest(ref note)) { response.Result = OSD.SerializeMembers(note); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = "Error reading notes"; return false; } public bool NotesUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "No parameters"; m_log.DebugFormat ("Avatar Notes Update Request"); return false; } string result = string.Empty; UserProfileNotes note = new UserProfileNotes(); object Notes = (object) note; OSD.DeserializeMembers(ref Notes, (OSDMap)json["params"]); if(Service.NotesUpdate(ref note, ref result)) { response.Result = OSD.SerializeMembers(note); return true; } return true; } #endregion Notes #region Profile Properties public bool AvatarPropertiesRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Properties Request"); return false; } string result = string.Empty; UserProfileProperties props = new UserProfileProperties(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.AvatarPropertiesRequest(ref props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool AvatarPropertiesUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Properties Update Request"); return false; } string result = string.Empty; UserProfileProperties props = new UserProfileProperties(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.AvatarPropertiesUpdate(ref props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion Profile Properties #region Interests public bool AvatarInterestsUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Interests Update Request"); return false; } string result = string.Empty; UserProfileProperties props = new UserProfileProperties(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.AvatarInterestsUpdate(props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion Interests #region User Preferences public bool UserPreferencesRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("User Preferences Request"); return false; } string result = string.Empty; UserPreferences prefs = new UserPreferences(); object Prefs = (object)prefs; OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]); if(Service.UserPreferencesRequest(ref prefs, ref result)) { response.Result = OSD.SerializeMembers(prefs); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); m_log.InfoFormat("[PROFILES]: User preferences request error - {0}", response.Error.Message); return false; } public bool UserPreferenecesUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("User Preferences Update Request"); return false; } string result = string.Empty; UserPreferences prefs = new UserPreferences(); object Prefs = (object)prefs; OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]); if(Service.UserPreferencesUpdate(ref prefs, ref result)) { response.Result = OSD.SerializeMembers(prefs); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); m_log.InfoFormat("[PROFILES]: User preferences update error - {0}", response.Error.Message); return false; } #endregion User Preferences #region Utility public bool AvatarImageAssetsRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Image Assets Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID avatarId = new UUID(request["avatarId"].AsString()); OSDArray data = (OSDArray) Service.AvatarImageAssetsRequest(avatarId); response.Result = data; return true; } #endregion Utiltiy #region UserData public bool RequestUserAppData(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("User Application Service URL Request: No Parameters!"); return false; } string result = string.Empty; UserAppData props = new UserAppData(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.RequestUserAppData(ref props, ref result)) { OSDMap res = new OSDMap(); res["result"] = OSD.FromString("success"); res["token"] = OSD.FromString (result); response.Result = res; return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool UpdateUserAppData(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("User App Data Update Request"); return false; } string result = string.Empty; UserAppData props = new UserAppData(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.SetUserAppData(props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion UserData } }
//------------------------------------------------------------------------------ // <copyright file="MultiDirectionTestBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace DMLibTest { using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using DMLibTestCodeGen; using Microsoft.VisualStudio.TestTools.UnitTesting; using MS.Test.Common.MsTestLib; public enum StopDMLibType { None, Kill, TestHookCtrlC, BreakNetwork } public enum SourceOrDest { Source, Dest, } public abstract class MultiDirectionTestBase<TDataInfo, TDataType> where TDataInfo : IDataInfo where TDataType : struct { public const string SourceRoot = "sourceroot"; public const string DestRoot = "destroot"; public const string SourceFolder = "sourcefolder"; public const string DestFolder = "destfolder"; protected static Random random = new Random(); private static Dictionary<string, DataAdaptor<TDataInfo>> sourceAdaptors = new Dictionary<string, DataAdaptor<TDataInfo>>(); private static Dictionary<string, DataAdaptor<TDataInfo>> destAdaptors = new Dictionary<string, DataAdaptor<TDataInfo>>(); private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } public static string NetworkShare { get; set; } public static bool CleanupSource { get; set; } public static bool CleanupDestination { get; set; } public static DataAdaptor<TDataInfo> SourceAdaptor { get { return GetSourceAdaptor(MultiDirectionTestContext<TDataType>.SourceType); } } public static DataAdaptor<TDataInfo> DestAdaptor { get { return GetDestAdaptor(MultiDirectionTestContext<TDataType>.DestType); } } public static void BaseClassInitialize(TestContext testContext) { Test.Info("ClassInitialize"); Test.FullClassName = testContext.FullyQualifiedTestClassName; MultiDirectionTestBase<TDataInfo, TDataType>.CleanupSource = true; MultiDirectionTestBase<TDataInfo, TDataType>.CleanupDestination = true; NetworkShare = Test.Data.Get("NetworkFolder"); } public static void BaseClassCleanup() { Test.Info("ClassCleanup"); DeleteAllLocations(sourceAdaptors); DeleteAllLocations(destAdaptors); Test.Info("ClassCleanup done."); } private static void DeleteAllLocations(Dictionary<string, DataAdaptor<TDataInfo>> adaptorDic) { Parallel.ForEach(adaptorDic, pair => { try { pair.Value.DeleteLocation(); } catch { Test.Warn("Fail to delete location for data adaptor: {0}", pair.Key); } }); } public virtual void BaseTestInitialize() { Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName); Test.Info("TestInitialize"); MultiDirectionTestInfo.Cleanup(); } public virtual void BaseTestCleanup() { if (Test.ErrorCount > 0) { MultiDirectionTestInfo.Print(); } Test.Info("TestCleanup"); Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName); try { this.CleanupData(); MultiDirectionTestBase<TDataInfo, TDataType>.SourceAdaptor.Reset(); MultiDirectionTestBase<TDataInfo, TDataType>.DestAdaptor.Reset(); } catch { // ignore exception } } public virtual void CleanupData() { this.CleanupData( MultiDirectionTestBase<TDataInfo, TDataType>.CleanupSource, MultiDirectionTestBase<TDataInfo, TDataType>.CleanupDestination); } protected void CleanupData(bool cleanupSource, bool cleanupDestination) { if (cleanupSource) { MultiDirectionTestBase<TDataInfo, TDataType>.SourceAdaptor.Cleanup(); } if (cleanupDestination) { MultiDirectionTestBase<TDataInfo, TDataType>.DestAdaptor.Cleanup(); } } protected static string GetLocationKey(TDataType dataType) { return dataType.ToString(); } public static DataAdaptor<TDataInfo> GetSourceAdaptor(TDataType dataType) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); if (!sourceAdaptors.ContainsKey(key)) { throw new KeyNotFoundException( string.Format("Can't find key of source data adaptor. DataType:{0}.", dataType.ToString())); } return sourceAdaptors[key]; } public static DataAdaptor<TDataInfo> GetDestAdaptor(TDataType dataType) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); if (!destAdaptors.ContainsKey(key)) { throw new KeyNotFoundException( string.Format("Can't find key of destination data adaptor. DataType:{0}.", dataType.ToString())); } return destAdaptors[key]; } protected static void SetSourceAdaptor(TDataType dataType, DataAdaptor<TDataInfo> adaptor) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); sourceAdaptors[key] = adaptor; } protected static void SetDestAdaptor(TDataType dataType, DataAdaptor<TDataInfo> adaptor) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); destAdaptors[key] = adaptor; } public abstract bool IsCloudService(TDataType dataType); public static CredentialType GetRandomCredentialType() { int credentialCount = Enum.GetNames(typeof(CredentialType)).Length; int randomNum = MultiDirectionTestBase<TDataInfo, TDataType>.random.Next(0, credentialCount); CredentialType result; switch (randomNum) { case 0: result = CredentialType.None; break; case 1: result = CredentialType.Public; break; case 2: result = CredentialType.Key; break; case 3: result = CredentialType.SAS; break; default: result = CredentialType.EmbeddedSAS; break; } Test.Info("Random credential type: {0}", result.ToString()); return result; } protected static string GetRelativePath(string basePath, string fullPath) { string normalizedBasePath = MultiDirectionTestBase<TDataInfo, TDataType>.NormalizePath(basePath); string normalizedFullPath = MultiDirectionTestBase<TDataInfo, TDataType>.NormalizePath(fullPath); int index = normalizedFullPath.IndexOf(normalizedBasePath); if (index < 0) { return null; } return normalizedFullPath.Substring(index + normalizedBasePath.Length); } protected static string NormalizePath(string path) { if (path.StartsWith("\"") && path.EndsWith("\"")) { path = path.Substring(1, path.Length - 2); } try { var uri = new Uri(path); return uri.GetComponents(UriComponents.Path, UriFormat.Unescaped); } catch (UriFormatException) { return path; } } } public enum CredentialType { None = 0, Public, Key, SAS, EmbeddedSAS, } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Boo.Lang.Compiler.TypeSystem { using System; using System.Collections; using System.Reflection; using System.Text; using Boo.Lang.Compiler.Ast; using Attribute = Boo.Lang.Compiler.Ast.Attribute; using Module = Boo.Lang.Compiler.Ast.Module; public class TypeSystemServices { public DuckTypeImpl DuckType; public ExternalType IQuackFuType; public ExternalType MulticastDelegateType; public ExternalType DelegateType; public ExternalType IntPtrType; public ExternalType UIntPtrType; public ExternalType ObjectType; public ExternalType ValueTypeType; public ExternalType EnumType; public ExternalType RegexType; public ExternalType ArrayType; public ExternalType TypeType; public IArrayType ObjectArrayType; public ExternalType VoidType; public ExternalType StringType; public ExternalType BoolType; public ExternalType CharType; public ExternalType SByteType; public ExternalType ByteType; public ExternalType ShortType; public ExternalType UShortType; public ExternalType IntType; public ExternalType UIntType; public ExternalType LongType; public ExternalType ULongType; public ExternalType SingleType; public ExternalType DoubleType; public ExternalType DecimalType; public ExternalType TimeSpanType; protected ExternalType DateTimeType; public ExternalType RuntimeServicesType; public ExternalType BuiltinsType; public ExternalType ListType; public ExternalType HashType; public ExternalType ICallableType; public ExternalType IEnumerableType; public ExternalType IEnumeratorType; public ExternalType IEnumerableGenericType; public ExternalType IEnumeratorGenericType; public ExternalType ICollectionType; public ExternalType IListType; public ExternalType IDictionaryType; public ExternalType SystemAttribute; public ExternalType ConditionalAttribute; protected Hashtable _primitives = new Hashtable(); protected Hashtable _entityCache = new Hashtable(); protected Hashtable _arrayCache = new Hashtable(); public static readonly IType ErrorEntity = Error.Default; public readonly BooCodeBuilder CodeBuilder; private StringBuilder _buffer = new StringBuilder(); private Module _compilerGeneratedTypesModule; private Module _compilerGeneratedExtensionsModule; private ClassDefinition _compilerGeneratedExtensionsClass; protected readonly CompilerContext _context; private readonly AnonymousCallablesManager _anonymousCallablesManager; private readonly GenericsServices _genericsServices; public TypeSystemServices() : this(new CompilerContext()) { } public TypeSystemServices(CompilerContext context) { if (null == context) throw new ArgumentNullException("context"); _context = context; _anonymousCallablesManager = new AnonymousCallablesManager(this); _genericsServices = new GenericsServices(context); CodeBuilder = new BooCodeBuilder(this); Cache(typeof(Builtins.duck), DuckType = new DuckTypeImpl(this)); Cache(IQuackFuType = new ExternalType(this, typeof(IQuackFu))); Cache(VoidType = new VoidTypeImpl(this)); Cache(ObjectType = new ExternalType(this, Types.Object)); Cache(RegexType = new ExternalType(this, Types.Regex)); Cache(ValueTypeType = new ExternalType(this, typeof(ValueType))); Cache(EnumType = new ExternalType(this, typeof(Enum))); Cache(ArrayType = new ExternalType(this, Types.Array)); Cache(TypeType = new ExternalType(this, Types.Type)); Cache(StringType = new ExternalType(this, Types.String)); Cache(BoolType = new ExternalType(this, Types.Bool)); Cache(SByteType = new ExternalType(this, Types.SByte)); Cache(CharType = new ExternalType(this, Types.Char)); Cache(ShortType = new ExternalType(this, Types.Short)); Cache(IntType = new ExternalType(this, Types.Int)); Cache(LongType = new ExternalType(this, Types.Long)); Cache(ByteType = new ExternalType(this, Types.Byte)); Cache(UShortType = new ExternalType(this, Types.UShort)); Cache(UIntType = new ExternalType(this, Types.UInt)); Cache(ULongType = new ExternalType(this, Types.ULong)); Cache(SingleType = new ExternalType(this, Types.Single)); Cache(DoubleType = new ExternalType(this, Types.Double)); Cache(DecimalType = new ExternalType(this, Types.Decimal)); Cache(TimeSpanType = new ExternalType(this, Types.TimeSpan)); Cache(DateTimeType = new ExternalType(this, Types.DateTime)); Cache(RuntimeServicesType = new ExternalType(this, Types.RuntimeServices)); Cache(BuiltinsType = new ExternalType(this, Types.Builtins)); Cache(ListType = new ExternalType(this, Types.List)); Cache(HashType = new ExternalType(this, Types.Hash)); Cache(ICallableType = new ExternalType(this, Types.ICallable)); Cache(IEnumerableType = new ExternalType(this, Types.IEnumerable)); Cache(IEnumeratorType = new ExternalType(this, typeof(IEnumerator))); Cache(ICollectionType = new ExternalType(this, Types.ICollection)); Cache(IListType = new ExternalType(this, Types.IList)); Cache(IDictionaryType = new ExternalType(this, Types.IDictionary)); Cache(IntPtrType = new ExternalType(this, Types.IntPtr)); Cache(UIntPtrType = new ExternalType(this, Types.UIntPtr)); Cache(MulticastDelegateType = new ExternalType(this, Types.MulticastDelegate)); Cache(DelegateType = new ExternalType(this, Types.Delegate)); Cache(SystemAttribute = new ExternalType(this, typeof(System.Attribute))); Cache(ConditionalAttribute = new ExternalType(this, typeof(System.Diagnostics.ConditionalAttribute))); Cache(IEnumerableGenericType = new ExternalType(this, typeof(System.Collections.Generic.IEnumerable<>))); Cache(IEnumeratorGenericType = new ExternalType(this, typeof(System.Collections.Generic.IEnumerator<>))); ObjectArrayType = GetArrayType(ObjectType, 1); PreparePrimitives(); PrepareBuiltinFunctions(); } public CompilerContext Context { get { return _context; } } public GenericsServices GenericsServices { get { return _genericsServices; } } public IType GetMostGenericType(IType current, IType candidate) { if (current.IsAssignableFrom(candidate)) { return current; } if (candidate.IsAssignableFrom(current)) { return candidate; } if (IsNumberOrBool(current) && IsNumberOrBool(candidate)) { return GetPromotedNumberType(current, candidate); } if (IsCallableType(current) && IsCallableType(candidate)) { return ICallableType; } if (current.IsClass && candidate.IsClass) { if (current == ObjectType || candidate == ObjectType) { return ObjectType; } if (current.GetTypeDepth() < candidate.GetTypeDepth()) { return GetMostGenericType(current.BaseType, candidate); } return GetMostGenericType(current, candidate.BaseType); } return ObjectType; } public IType GetPromotedNumberType(IType left, IType right) { if (left == DecimalType || right == DecimalType) { return DecimalType; } if (left == DoubleType || right == DoubleType) { return DoubleType; } if (left == SingleType || right == SingleType) { return SingleType; } if (left == ULongType) { if (right == SByteType || right == ShortType || right == IntType || right == LongType) { // This is against the C# spec but allows expressions like: // ulong x = 4 // y = x + 1 // y will be long. // C# disallows mixing ulongs and signed numbers // but in the above case it promotes the constant to ulong // and the result is ulong. // Since its too late here to promote the constant, // maybe we should return LongType. I didn't chose ULongType // because in other cases <unsigned> <op> <signed> returns <signed>. return LongType; } return ULongType; } if (right == ULongType) { if (left == SByteType || left == ShortType || left == IntType || left == LongType) { // This is against the C# spec but allows expressions like: // ulong x = 4 // y = 1 + x // y will be long. // C# disallows mixing ulongs and signed numbers // but in the above case it promotes the constant to ulong // and the result is ulong. // Since its too late here to promote the constant, // maybe we should return LongType. I didn't chose ULongType // because in other cases <signed> <op> <unsigned> returns <signed>. return LongType; } return ULongType; } if (left == LongType || right == LongType) { return LongType; } if (left == UIntType) { if (right == SByteType || right == ShortType || right == IntType) { // This is allowed per C# spec and y is long: // uint x = 4 // y = x + 1 // C# promotes <uint> <op> <signed> to <long> also // but in the above case it promotes the constant to uint first // and the result of "x + 1" is uint. // Since its too late here to promote the constant, // "y = x + 1" will be long in boo. return LongType; } return UIntType; } if (right == UIntType) { if (left == SByteType || left == ShortType || left == IntType) { // This is allowed per C# spec and y is long: // uint x = 4 // y = 1 + x // C# promotes <signed> <op> <uint> to <long> also // but in the above case it promotes the constant to uint first // and the result of "1 + x" is uint. // Since its too late here to promote the constant, // "y = x + 1" will be long in boo. return LongType; } return UIntType; } if (left == IntType || right == IntType || left == ShortType || right == ShortType || left == UShortType || right == UShortType || left == ByteType || right == ByteType || left == SByteType || right == SByteType) { return IntType; } return left; } public static bool IsReadOnlyField(IField field) { return field.IsInitOnly || field.IsLiteral; } public bool IsCallable(IType type) { return (TypeType == type) || IsCallableType(type) || IsDuckType(type); } public virtual bool IsDuckTyped(Expression expression) { IType type = expression.ExpressionType; return null != type && this.IsDuckType(type); } public bool IsQuackBuiltin(Expression node) { return IsQuackBuiltin(GetOptionalEntity(node)); } public bool IsQuackBuiltin(IEntity entity) { return BuiltinFunction.Quack == entity; } public bool IsDuckType(IType type) { if (null == type) { throw new ArgumentNullException("type"); } return ( (type == DuckType) || KnowsQuackFu(type) || (_context.Parameters.Ducky && (type == ObjectType))); } public bool KnowsQuackFu(IType type) { return type.IsSubclassOf(IQuackFuType); } bool IsCallableType(IType type) { return (ICallableType.IsAssignableFrom(type)) || (type is ICallableType); } public AnonymousCallableType GetCallableType(IMethod method) { CallableSignature signature = new CallableSignature(method); return GetCallableType(signature); } public AnonymousCallableType GetCallableType(CallableSignature signature) { return _anonymousCallablesManager.GetCallableType(signature); } public virtual IType GetConcreteCallableType(Node sourceNode, CallableSignature signature) { return _anonymousCallablesManager.GetConcreteCallableType(sourceNode, signature); } public virtual IType GetConcreteCallableType(Node sourceNode, AnonymousCallableType anonymousType) { return _anonymousCallablesManager.GetConcreteCallableType(sourceNode, anonymousType); } public IType GetEnumeratorItemType(IType iteratorType) { // Arrays are enumerators of their element type if (iteratorType.IsArray) return iteratorType.GetElementType(); // String are enumerators of char if (StringType == iteratorType) return CharType; // Try to use an EnumerableItemType attribute if (iteratorType.IsClass) { IType enumeratorItemType = GetEnumeratorItemTypeFromAttribute(iteratorType); if (null != enumeratorItemType) return enumeratorItemType; } // Try to use a generic IEnumerable interface IType genericItemType = GetGenericEnumerableItemType(iteratorType); if (null != genericItemType) return genericItemType; // If none of these work, the type is an enumerator of object return ObjectType; } public IType GetExpressionType(Expression node) { IType type = node.ExpressionType; if (null == type) { throw CompilerErrorFactory.InvalidNode(node); } return type; } public IType GetConcreteExpressionType(Expression expression) { IType type = GetExpressionType(expression); AnonymousCallableType anonymousType = type as AnonymousCallableType; if (null != anonymousType) { IType concreteType = GetConcreteCallableType(expression, anonymousType); expression.ExpressionType = concreteType; return concreteType; } return type; } public void MapToConcreteExpressionTypes(ExpressionCollection items) { foreach (Expression item in items) { GetConcreteExpressionType(item); } } public ClassDefinition GetCompilerGeneratedExtensionsClass() { if (null == _compilerGeneratedExtensionsClass) { BooClassBuilder builder = CodeBuilder.CreateClass("CompilerGeneratedExtensions"); builder.Modifiers = TypeMemberModifiers.Final|TypeMemberModifiers.Transient|TypeMemberModifiers.Public; builder.AddBaseType(ObjectType); BooMethodBuilder ctor = builder.AddConstructor(); ctor.Modifiers = TypeMemberModifiers.Private; ctor.Body.Add( CodeBuilder.CreateSuperConstructorInvocation(ObjectType)); ClassDefinition cd = builder.ClassDefinition; Module module = GetCompilerGeneratedExtensionsModule(); module.Members.Add(cd); ((ModuleEntity)module.Entity).InitializeModuleClass(cd); _compilerGeneratedExtensionsClass = cd; } return _compilerGeneratedExtensionsClass; } public Module GetCompilerGeneratedExtensionsModule() { if (null == _compilerGeneratedExtensionsModule) { _compilerGeneratedExtensionsModule = NewModule(null, "CompilerGeneratedExtensions"); } return _compilerGeneratedExtensionsModule; } public void AddCompilerGeneratedType(TypeDefinition type) { GetCompilerGeneratedTypesModule().Members.Add(type); } public Module GetCompilerGeneratedTypesModule() { if (null == _compilerGeneratedTypesModule) { _compilerGeneratedTypesModule = NewModule("CompilerGenerated"); } return _compilerGeneratedTypesModule; } private Module NewModule(string nameSpace) { return NewModule(nameSpace, nameSpace); } private Module NewModule(string nameSpace, string moduleName) { Module module = new Module(); module.Name = moduleName; if (null != nameSpace) module.Namespace = new NamespaceDeclaration(nameSpace); module.Entity = new ModuleEntity(_context.NameResolutionService, this, module); _context.CompileUnit.Modules.Add(module); return module; } public ClassDefinition CreateCallableDefinition(string name) { ClassDefinition cd = new ClassDefinition(); cd.IsSynthetic = true; cd.BaseTypes.Add(CodeBuilder.CreateTypeReference(this.MulticastDelegateType)); cd.BaseTypes.Add(CodeBuilder.CreateTypeReference(this.ICallableType)); cd.Name = name; cd.Modifiers = TypeMemberModifiers.Final; cd.Members.Add(CreateCallableConstructor()); cd.Members.Add(CreateCallMethod()); cd.Entity = new InternalCallableType(this, cd); return cd; } Method CreateCallMethod() { Method method = new Method("Call"); method.IsSynthetic = true; method.Modifiers = TypeMemberModifiers.Public|TypeMemberModifiers.Virtual; method.Parameters.Add(CodeBuilder.CreateParameterDeclaration(1, "args", ObjectArrayType)); method.ReturnType = CodeBuilder.CreateTypeReference(ObjectType); method.Entity = new InternalMethod(this, method); return method; } Constructor CreateCallableConstructor() { Constructor constructor = new Constructor(); constructor.IsSynthetic = true; constructor.Modifiers = TypeMemberModifiers.Public; constructor.ImplementationFlags = MethodImplementationFlags.Runtime; constructor.Parameters.Add( CodeBuilder.CreateParameterDeclaration(1, "instance", ObjectType)); constructor.Parameters.Add( CodeBuilder.CreateParameterDeclaration(2, "method", IntPtrType)); constructor.Entity = new InternalConstructor(this, constructor); return constructor; } public bool AreTypesRelated(IType lhs, IType rhs) { ICallableType ctype = lhs as ICallableType; if (null != ctype) { return ctype.IsAssignableFrom(rhs) || ctype.IsSubclassOf(rhs); } return lhs.IsAssignableFrom(rhs) || (lhs.IsInterface && !rhs.IsFinal) || (rhs.IsInterface && !lhs.IsFinal) || CanBeReachedByDownCastOrPromotion(lhs, rhs) || FindImplicitConversionOperator(rhs,lhs) != null; } public IMethod FindExplicitConversionOperator(IType fromType, IType toType) { return FindConversionOperator("op_Explicit", fromType, toType); } public IMethod FindImplicitConversionOperator(IType fromType, IType toType) { return FindConversionOperator("op_Implicit", fromType, toType); } public IMethod FindConversionOperator(string name, IType fromType, IType toType) { while (fromType != this.ObjectType) { IMethod method = FindConversionOperator(name, fromType, toType, fromType.GetMembers()); if (null != method) return method; method = FindConversionOperator(name, fromType, toType, toType.GetMembers()); if (null != method) return method; method = FindConversionOperator(name, fromType, toType, FindExtension(fromType, name)); if (null != method) return method; fromType = fromType.BaseType; if (null == fromType) break; } return null; } private IEntity[] FindExtension(IType fromType, string name) { IEntity extension = _context.NameResolutionService.ResolveExtension(fromType, name); if (null == extension) return Ambiguous.NoEntities; Ambiguous a = extension as Ambiguous; if (null != a) return a.Entities; return new IEntity[] { extension }; } IMethod FindConversionOperator(string name, IType fromType, IType toType, IEntity[] candidates) { foreach (IEntity entity in candidates) { if (EntityType.Method != entity.EntityType || name != entity.Name) continue; IMethod method = (IMethod)entity; if (IsConversionOperator(method, fromType, toType)) return method; } return null; } bool IsConversionOperator(IMethod method, IType fromType, IType toType) { if (!method.IsStatic) return false; if (method.ReturnType != toType) return false; IParameter[] parameters = method.GetParameters(); return (1 == parameters.Length && fromType == parameters[0].Type); } public bool IsCallableTypeAssignableFrom(ICallableType lhs, IType rhs) { if (lhs == rhs) return true; if (Null.Default == rhs) return true; ICallableType other = rhs as ICallableType; if (null == other) return false; CallableSignature lvalue = lhs.GetSignature(); CallableSignature rvalue = other.GetSignature(); if (lvalue == rvalue) return true; IParameter[] lparams = lvalue.Parameters; IParameter[] rparams = rvalue.Parameters; if (lparams.Length < rparams.Length) return false; for (int i=0; i<rparams.Length; ++i) { if (!AreTypesRelated(lparams[i].Type, rparams[i].Type)) return false; } return CompatibleReturnTypes(lvalue, rvalue); } private bool CompatibleReturnTypes(CallableSignature lvalue, CallableSignature rvalue) { if (VoidType != lvalue.ReturnType && VoidType != rvalue.ReturnType) { return AreTypesRelated(lvalue.ReturnType, rvalue.ReturnType); } return true; } public static bool CheckOverrideSignature(IMethod impl, IMethod baseMethod) { if (!GenericsServices.AreOfSameGenerity(impl, baseMethod)) { return false; } CallableSignature baseSignature = GetOverriddenSignature(baseMethod, impl); return CheckOverrideSignature(impl.GetParameters(), baseSignature.Parameters); } public static bool CheckOverrideSignature(IParameter[] implParameters, IParameter[] baseParameters) { return CallableSignature.AreSameParameters(implParameters, baseParameters); } public static CallableSignature GetOverriddenSignature(IMethod baseMethod, IMethod impl) { if (baseMethod.GenericInfo != null && TypeSystem.GenericsServices.AreOfSameGenerity(baseMethod, impl)) { return baseMethod.GenericInfo.ConstructMethod(impl.GenericInfo.GenericParameters).CallableType.GetSignature(); } return baseMethod.CallableType.GetSignature(); } public virtual bool CanBeReachedByDownCastOrPromotion(IType expectedType, IType actualType) { return CanBeReachedByDowncast(expectedType, actualType) || CanBeReachedByPromotion(expectedType, actualType); } public virtual bool CanBeReachedByDowncast(IType expectedType, IType actualType) { return actualType.IsAssignableFrom(expectedType); } public virtual bool CanBeReachedByPromotion(IType expectedType, IType actualType) { return (expectedType.IsValueType && IsNumber(expectedType) && IsNumber(actualType)); } public bool CanBeExplicitlyCastToInteger(IType type) { return type.IsEnum || type == this.CharType; } public static bool ContainsMethodsOnly(List members) { foreach (IEntity member in members) { if (EntityType.Method != member.EntityType) return false; } return true; } public bool IsIntegerNumber(IType type) { return type == this.ShortType || type == this.IntType || type == this.LongType || type == this.SByteType || type == this.UShortType || type == this.UIntType || type == this.ULongType || type == this.ByteType; } public bool IsIntegerOrBool(IType type) { return BoolType == type || IsIntegerNumber(type); } public bool IsNumberOrBool(IType type) { return BoolType == type || IsNumber(type); } public bool IsNumber(IType type) { return IsPrimitiveNumber(type) || type == this.DecimalType; } public bool IsPrimitiveNumber(IType type) { return IsIntegerNumber(type) || type == this.DoubleType || type == this.SingleType; } public static bool IsNullable(IType type) { ExternalType et = type as ExternalType; return (null != et && et.ActualType.IsGenericType && et.ActualType.GetGenericTypeDefinition() == Types.Nullable); } public IType GetNullableUnderlyingType(IType type) { ExternalType et = type as ExternalType; return Map(Nullable.GetUnderlyingType(et.ActualType)); } public static bool IsUnknown(Expression node) { IType type = node.ExpressionType; if (null != type) { return IsUnknown(type); } return false; } public static bool IsUnknown(IType tag) { return EntityType.Unknown == tag.EntityType; } public static bool IsError(Expression node) { IType type = node.ExpressionType; if (null != type) { return IsError(type); } return false; } public static bool IsErrorAny(ExpressionCollection collection) { foreach (Expression n in collection) { if (IsError(n)) { return true; } } return false; } public bool IsBuiltin(IEntity tag) { if (EntityType.Method == tag.EntityType) { return BuiltinsType == ((IMethod)tag).DeclaringType; } return false; } public static bool IsError(IEntity tag) { return EntityType.Error == tag.EntityType; } public static TypeMemberModifiers GetAccess(IAccessibleMember member) { if (member.IsPublic) { return TypeMemberModifiers.Public; } else if (member.IsProtected) { return TypeMemberModifiers.Protected; } return TypeMemberModifiers.Private; } public static IEntity[] GetAllMembers(INamespace entity) { List members = new List(); GetAllMembers(members, entity); return (IEntity[])members.ToArray(new IEntity[members.Count]); } private static void GetAllMembers(List members, INamespace entity) { if (null == entity) return; IType type = entity as IType; if (null != type) { members.ExtendUnique(type.GetMembers()); GetAllMembers(members, type.BaseType); } else { members.Extend(entity.GetMembers()); } } static object EntityAnnotationKey = new object(); public static void Bind(Node node, IEntity entity) { if (null == node) throw new ArgumentNullException("node"); node[EntityAnnotationKey] = entity; } public static IEntity GetOptionalEntity(Node node) { if (null == node) throw new ArgumentNullException("node"); return (IEntity)node[EntityAnnotationKey]; } public static IEntity GetEntity(Node node) { IEntity tag = GetOptionalEntity(node); if (null == tag) InvalidNode(node); return tag; } public static IType GetReferencedType(Expression typeref) { switch (typeref.NodeType) { case NodeType.TypeofExpression: { return GetType(((TypeofExpression)typeref).Type); } case NodeType.ReferenceExpression: case NodeType.MemberReferenceExpression: case NodeType.GenericReferenceExpression: { return typeref.Entity as IType; } } return null; } public virtual bool IsModule(Type type) { return type.IsClass && type.IsSealed && !type.IsNestedPublic && MetadataUtil.IsAttributeDefined(type, Types.ModuleAttribute); } public bool IsAttribute(IType type) { return type.IsSubclassOf(SystemAttribute); } public static IType GetType(Node node) { return ((ITypedEntity)GetEntity(node)).Type; } public IType Map(Type type) { ExternalType entity = (ExternalType)_entityCache[type]; if (null == entity) { if (type.IsArray) return GetArrayType(Map(type.GetElementType()), type.GetArrayRank()); entity = CreateEntityForType(type); Cache(entity); } return entity; } private ExternalType CreateEntityForType(Type type) { if (type.IsGenericParameter) return new ExternalGenericParameter(this, type); if (type.IsSubclassOf(Types.MulticastDelegate)) return new ExternalCallableType(this, type); return new ExternalType(this, type); } public IArrayType GetArrayType(IType elementType, int rank) { ArrayHash key = new ArrayHash(elementType, rank); IArrayType entity = (IArrayType)_arrayCache[key]; if (null == entity) { entity = new ArrayType(this, elementType, rank); _arrayCache.Add(key, entity); } return entity; } protected class ArrayHash { IType _type; int _rank; public ArrayHash(IType elementType, int rank) { _type = elementType; _rank = rank; } public override int GetHashCode() { return _type.GetHashCode() ^ _rank; } public override bool Equals(object obj) { return ((ArrayHash)obj)._type == _type && ((ArrayHash)obj)._rank == _rank; } } public IParameter[] Map(ParameterDeclarationCollection parameters) { IParameter[] mapped = new IParameter[parameters.Count]; for (int i=0; i<mapped.Length; ++i) { mapped[i] = (IParameter)GetEntity(parameters[i]); } return mapped; } public IParameter[] Map(ParameterInfo[] parameters) { IParameter[] mapped = new IParameter[parameters.Length]; for (int i=0; i<parameters.Length; ++i) { mapped[i] = new ExternalParameter(this, parameters[i]); } return mapped; } public IConstructor Map(ConstructorInfo constructor) { object key = GetCacheKey(constructor); IConstructor entity = (IConstructor)_entityCache[key]; if (null == entity) { entity = new ExternalConstructor(this, constructor); _entityCache[key] = entity; } return entity; } public IMethod Map(MethodInfo method) { object key = GetCacheKey(method); IMethod entity = (IMethod)_entityCache[key]; if (null == entity) { entity = new ExternalMethod(this, method); _entityCache[key] = entity; } return entity; } public IEntity Map(MemberInfo[] info) { if (info.Length > 1) { IEntity[] tags = new IEntity[info.Length]; for (int i=0; i<tags.Length; ++i) { tags[i] = Map(info[i]); } return new Ambiguous(tags); } if (info.Length > 0) { return Map(info[0]); } return null; } public IEntity Map(MemberInfo mi) { IEntity tag = (IEntity)_entityCache[GetCacheKey(mi)]; if (null == tag) { switch (mi.MemberType) { case MemberTypes.Method: { return Map((MethodInfo)mi); } case MemberTypes.Constructor: { return Map((ConstructorInfo)mi); } case MemberTypes.Field: { tag = new ExternalField(this, (FieldInfo)mi); break; } case MemberTypes.Property: { tag = new ExternalProperty(this, (PropertyInfo)mi); break; } case MemberTypes.Event: { tag = new ExternalEvent(this, (EventInfo)mi); break; } case MemberTypes.NestedType: { return Map((Type)mi); } default: { throw new NotImplementedException(mi.ToString()); } } _entityCache.Add(GetCacheKey(mi), tag); } return tag; } public string GetSignature(IEntityWithParameters method) { return GetSignature(method, true); } public string GetSignature(IEntityWithParameters method, bool includeFullName) { _buffer.Length = 0; if (includeFullName) { _buffer.Append(method.FullName); } else { _buffer.Append(method.Name); } _buffer.Append("("); IParameter[] parameters = method.GetParameters(); for (int i=0; i<parameters.Length; ++i) { if (i > 0) { _buffer.Append(", "); } if (method.AcceptVarArgs && i == parameters.Length-1) { _buffer.Append('*'); } _buffer.Append(parameters[i].Type); } _buffer.Append(")"); return _buffer.ToString(); } public object GetCacheKey(MemberInfo mi) { return mi; } public IEntity ResolvePrimitive(string name) { return (IEntity)_primitives[name]; } public bool IsPrimitive(string name) { return _primitives.ContainsKey(name); } /// <summary> /// checks if the passed type will be equivalente to /// System.Object in runtime (accounting for the presence /// of duck typing). /// </summary> public bool IsSystemObject(IType type) { return type == ObjectType || type == DuckType; } public bool RequiresBoxing(IType expectedType, IType actualType) { if (!actualType.IsValueType) return false; return IsSystemObject(expectedType); } protected virtual void PreparePrimitives() { AddPrimitiveType("duck", DuckType); AddPrimitiveType("void", VoidType); AddPrimitiveType("object", ObjectType); AddPrimitiveType("bool", BoolType); AddPrimitiveType("sbyte", SByteType); AddPrimitiveType("byte", ByteType); AddPrimitiveType("short", ShortType); AddPrimitiveType("ushort", UShortType); AddPrimitiveType("int", IntType); AddPrimitiveType("uint", UIntType); AddPrimitiveType("long", LongType); AddPrimitiveType("ulong", ULongType); AddPrimitiveType("single", SingleType); AddPrimitiveType("double", DoubleType); AddPrimitiveType("decimal", DecimalType); AddPrimitiveType("char", CharType); AddPrimitiveType("string", StringType); AddPrimitiveType("regex", RegexType); AddPrimitiveType("date", DateTimeType); AddPrimitiveType("timespan", TimeSpanType); AddPrimitiveType("callable", ICallableType); } protected virtual void PrepareBuiltinFunctions() { AddBuiltin(BuiltinFunction.Len); AddBuiltin(BuiltinFunction.AddressOf); AddBuiltin(BuiltinFunction.Eval); AddBuiltin(BuiltinFunction.Switch); } protected void AddPrimitiveType(string name, ExternalType type) { _primitives[name] = type; type.PrimitiveName = name; } protected void AddBuiltin(BuiltinFunction function) { _primitives[function.Name] = function; } protected void Cache(ExternalType tag) { _entityCache[tag.ActualType] = tag; } protected void Cache(object key, IType tag) { _entityCache[key] = tag; } public IConstructor GetDefaultConstructor(IType type) { IConstructor[] constructors = type.GetConstructors(); for (int i=0; i<constructors.Length; ++i) { IConstructor constructor = constructors[i]; if (0 == constructor.GetParameters().Length) { return constructor; } } return null; } IType GetExternalEnumeratorItemType(IType iteratorType) { Type type = ((ExternalType)iteratorType).ActualType; EnumeratorItemTypeAttribute attribute = (EnumeratorItemTypeAttribute)System.Attribute.GetCustomAttribute(type, typeof(EnumeratorItemTypeAttribute)); if (null != attribute) { return Map(attribute.ItemType); } return null; } IType GetEnumeratorItemTypeFromAttribute(IType iteratorType) { // If iterator type is external get its attributes via reflection if (iteratorType is ExternalType) { return GetExternalEnumeratorItemType(iteratorType); } // If iterator type is a generic constructed type, map its attribute from its definition GenericConstructedType constructedType = iteratorType as GenericConstructedType; if (constructedType != null) { return constructedType.GenericMapping.Map( GetEnumeratorItemTypeFromAttribute(constructedType.GenericDefinition)); } // If iterator type is internal get its attributes from its type definition AbstractInternalType internalType = (AbstractInternalType)iteratorType; IType enumeratorItemTypeAttribute = Map(typeof(EnumeratorItemTypeAttribute)); foreach (Attribute attribute in internalType.TypeDefinition.Attributes) { IConstructor constructor = GetEntity(attribute) as IConstructor; if (null != constructor) { if (constructor.DeclaringType == enumeratorItemTypeAttribute) { return GetType(attribute.Arguments[0]); } } } return null; } public IType GetGenericEnumerableItemType(IType iteratorType) { // Arrays implicitly implement IEnumerable[of element type] if (iteratorType is ArrayType) return iteratorType.GetElementType(); // If type is not an array, try to find IEnumerable[of some type] in its interfaces IType itemType = null; foreach (IType type in GenericsServices.FindConstructedTypes(iteratorType, IEnumerableGenericType)) { IType candidateItemType = type.ConstructedInfo.GenericArguments[0]; if (itemType != null) { itemType = GetMostGenericType(itemType, candidateItemType); } else { itemType = candidateItemType; } } return itemType; } public IEntity GetMemberEntity(TypeMember member) { if (null == member.Entity) { member.Entity = CreateEntity(member); } return member.Entity; } private IEntity CreateEntity(TypeMember member) { switch (member.NodeType) { case NodeType.ClassDefinition: return new InternalClass(this, (TypeDefinition) member); case NodeType.Field: return new InternalField((Field)member); case NodeType.EnumMember: return new InternalEnumMember(this, (EnumMember)member); case NodeType.Method: return new InternalMethod(this, (Method)member); case NodeType.Constructor: return new InternalConstructor(this, (Constructor)member); case NodeType.Property: return new InternalProperty(this, (Property)member); case NodeType.Event: return new InternalEvent(this, (Event)member); } throw new ArgumentException("Member type not supported: " + member); } private static void InvalidNode(Node node) { throw CompilerErrorFactory.InvalidNode(node); } public class DuckTypeImpl : ExternalType { public DuckTypeImpl(TypeSystemServices typeSystemServices) : base(typeSystemServices, Types.Object) { } } #region VoidTypeImpl class VoidTypeImpl : ExternalType { internal VoidTypeImpl(TypeSystemServices typeSystemServices) : base(typeSystemServices, Types.Void) { } override public bool Resolve(List targetList, string name, EntityType flags) { return false; } override public bool IsSubclassOf(IType other) { return false; } override public bool IsAssignableFrom(IType other) { return false; } } #endregion public virtual IType ExceptionType { get { return Map(typeof(Exception)); } } public virtual bool IsValidException(IType type) { return ExceptionType.IsAssignableFrom(type); } public virtual IConstructor GetStringExceptionConstructor() { return Map(typeof(Exception).GetConstructor(new Type[] { typeof(string) })); } } }
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 { // The default is 4k we use 16k internal const int DefaultReadBufferSize = 16 * 1024; internal const int DefaultWriteBufferSize = 16 * 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.FieldCaption != null ? field.FieldCaption : 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; } } }
using System; using UnityEngine; using System.Collections.Generic; using UnityEditor; // This is the Editor for the ReactionCollection MonoBehaviour. // However, since the ReactionCollection contains many Reactions, // it requires many sub-editors to display them. // For more details see the EditorWithSubEditors class. // There are two ways of adding Reactions to the ReactionCollection: // a type selection popup with confirmation button and a drag and drop // area. Details on these are found below. [CustomEditor(typeof(ReactionCollection))] public class ReactionCollectionEditor : EditorWithSubEditors<ReactionEditor, Reaction> { private ReactionCollection reactionCollection; // Reference to the target. private SerializedProperty reactionsProperty; // Represents the array of Reactions. private Type[] reactionTypes; // All the non-abstract types which inherit from Reaction. This is used for adding new Reactions. private string[] reactionTypeNames; // The names of all appropriate Reaction types. private int selectedIndex; // The index of the currently selected Reaction type. private const float dropAreaHeight = 50f; // Height in pixels of the area for dropping scripts. private const float controlSpacing = 5f; // Width in pixels between the popup type selection and drop area. private const string reactionsPropName = "reactions"; // Name of the field for the array of Reactions. private readonly float verticalSpacing = EditorGUIUtility.standardVerticalSpacing; // Caching the vertical spacing between GUI elements. private void OnEnable () { // Cache the target. reactionCollection = (ReactionCollection)target; // Cache the SerializedProperty reactionsProperty = serializedObject.FindProperty(reactionsPropName); // If new editors are required for Reactions, create them. CheckAndCreateSubEditors (reactionCollection.reactions); // Set the array of types and type names of subtypes of Reaction. SetReactionNamesArray (); } private void OnDisable () { // Destroy all the subeditors. CleanupEditors (); } // This is called immediately after each ReactionEditor is created. protected override void SubEditorSetup (ReactionEditor editor) { // Make sure the ReactionEditors have a reference to the array that contains their targets. editor.reactionsProperty = reactionsProperty; } public override void OnInspectorGUI () { // Pull all the information from the target into the serializedObject. serializedObject.Update (); // If new editors for Reactions are required, create them. CheckAndCreateSubEditors(reactionCollection.reactions); // Display all the Reactions. for (int i = 0; i < subEditors.Length; i++) { subEditors[i].OnInspectorGUI (); } // If there are Reactions, add a space. if (reactionCollection.reactions.Length > 0) { EditorGUILayout.Space(); EditorGUILayout.Space (); } // Create a Rect for the full width of the inspector with enough height for the drop area. Rect fullWidthRect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(dropAreaHeight + verticalSpacing)); // Create a Rect for the left GUI controls. Rect leftAreaRect = fullWidthRect; // It should be in half a space from the top. leftAreaRect.y += verticalSpacing * 0.5f; // The width should be slightly less than half the width of the inspector. leftAreaRect.width *= 0.5f; leftAreaRect.width -= controlSpacing * 0.5f; // The height should be the same as the drop area. leftAreaRect.height = dropAreaHeight; // Create a Rect for the right GUI controls that is the same as the left Rect except... Rect rightAreaRect = leftAreaRect; // ... it should be on the right. rightAreaRect.x += rightAreaRect.width + controlSpacing; // Display the GUI for the type popup and button on the left. TypeSelectionGUI (leftAreaRect); // Display the GUI for the drag and drop area on the right. DragAndDropAreaGUI (rightAreaRect); // Manage the events for dropping on the right area. DraggingAndDropping(rightAreaRect, this); // Push the information back from the serializedObject to the target. serializedObject.ApplyModifiedProperties (); } private void TypeSelectionGUI (Rect containingRect) { // Create Rects for the top and bottom half. Rect topHalf = containingRect; topHalf.height *= 0.5f; Rect bottomHalf = topHalf; bottomHalf.y += bottomHalf.height; // Display a popup in the top half showing all the reaction types. selectedIndex = EditorGUI.Popup(topHalf, selectedIndex, reactionTypeNames); // Display a button in the bottom half that if clicked... if (GUI.Button (bottomHalf, "Add Selected Reaction")) { // ... finds the type selected by the popup, creates an appropriate reaction and adds it to the array. Type reactionType = reactionTypes[selectedIndex]; Reaction newReaction = ReactionEditor.CreateReaction (reactionType); reactionsProperty.AddToObjectArray (newReaction); } } private static void DragAndDropAreaGUI (Rect containingRect) { // Create a GUI style of a box but with middle aligned text and button text color. GUIStyle centredStyle = GUI.skin.box; centredStyle.alignment = TextAnchor.MiddleCenter; centredStyle.normal.textColor = GUI.skin.button.normal.textColor; // Draw a box over the area with the created style. GUI.Box (containingRect, "Drop new Reactions here", centredStyle); } private static void DraggingAndDropping (Rect dropArea, ReactionCollectionEditor editor) { // Cache the current event. Event currentEvent = Event.current; // If the drop area doesn't contain the mouse then return. if (!dropArea.Contains (currentEvent.mousePosition)) return; switch (currentEvent.type) { // If the mouse is dragging something... case EventType.DragUpdated: // ... change whether or not the drag *can* be performed by changing the visual mode of the cursor based on the IsDragValid function. DragAndDrop.visualMode = IsDragValid () ? DragAndDropVisualMode.Link : DragAndDropVisualMode.Rejected; // Make sure the event isn't used by anything else. currentEvent.Use (); break; // If the mouse was dragging something and has released... case EventType.DragPerform: // ... accept the drag event. DragAndDrop.AcceptDrag(); // Go through all the objects that were being dragged... for (int i = 0; i < DragAndDrop.objectReferences.Length; i++) { // ... and find the script asset that was being dragged... MonoScript script = DragAndDrop.objectReferences[i] as MonoScript; // ... then find the type of that Reaction... Type reactionType = script.GetClass(); // ... and create a Reaction of that type and add it to the array. Reaction newReaction = ReactionEditor.CreateReaction (reactionType); editor.reactionsProperty.AddToObjectArray (newReaction); } // Make sure the event isn't used by anything else. currentEvent.Use(); break; } } private static bool IsDragValid () { // Go through all the objects being dragged... for (int i = 0; i < DragAndDrop.objectReferences.Length; i++) { // ... and if any of them are not script assets, return that the drag is invalid. if (DragAndDrop.objectReferences[i].GetType () != typeof (MonoScript)) return false; // Otherwise find the class contained in the script asset. MonoScript script = DragAndDrop.objectReferences[i] as MonoScript; Type scriptType = script.GetClass (); // If the script does not inherit from Reaction, return that the drag is invalid. if (!scriptType.IsSubclassOf (typeof(Reaction))) return false; // If the script is an abstract, return that the drag is invalid. if (scriptType.IsAbstract) return false; } // If none of the dragging objects returned that the drag was invalid, return that it is valid. return true; } private void SetReactionNamesArray () { // Store the Reaction type. Type reactionType = typeof(Reaction); // Get all the types that are in the same Assembly (all the runtime scripts) as the Reaction type. Type[] allTypes = reactionType.Assembly.GetTypes(); // Create an empty list to store all the types that are subtypes of Reaction. List<Type> reactionSubTypeList = new List<Type>(); // Go through all the types in the Assembly... for (int i = 0; i < allTypes.Length; i++) { // ... and if they are a non-abstract subclass of Reaction then add them to the list. if (allTypes[i].IsSubclassOf(reactionType) && !allTypes[i].IsAbstract) { reactionSubTypeList.Add(allTypes[i]); } } // Convert the list to an array and store it. reactionTypes = reactionSubTypeList.ToArray(); // Create an empty list of strings to store the names of the Reaction types. List<string> reactionTypeNameList = new List<string>(); // Go through all the Reaction types and add their names to the list. for (int i = 0; i < reactionTypes.Length; i++) { reactionTypeNameList.Add(reactionTypes[i].Name); } // Convert the list to an array and store it. reactionTypeNames = reactionTypeNameList.ToArray(); } }