context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Net.Sockets; using System.Runtime.InteropServices; namespace System.Net.NetworkInformation { internal class SystemNetworkInterface : NetworkInterface { private readonly string _name; private readonly string _id; private readonly string _description; private readonly byte[] _physicalAddress; private readonly uint _addressLength; private readonly NetworkInterfaceType _type; private readonly OperationalStatus _operStatus; private readonly long _speed; // Any interface can have two completely different valid indexes for ipv4 and ipv6. private readonly uint _index = 0; private readonly uint _ipv6Index = 0; private readonly Interop.IpHlpApi.AdapterFlags _adapterFlags; private readonly SystemIPInterfaceProperties _interfaceProperties = null; internal static int InternalLoopbackInterfaceIndex { get { return GetBestInterfaceForAddress(IPAddress.Loopback); } } internal static int InternalIPv6LoopbackInterfaceIndex { get { return GetBestInterfaceForAddress(IPAddress.IPv6Loopback); } } private static int GetBestInterfaceForAddress(IPAddress addr) { int index; Internals.SocketAddress address = new Internals.SocketAddress(addr); int error = (int)Interop.IpHlpApi.GetBestInterfaceEx(address.Buffer, out index); if (error != 0) { throw new NetworkInformationException(error); } return index; } internal static bool InternalGetIsNetworkAvailable() { try { NetworkInterface[] networkInterfaces = GetNetworkInterfaces(); foreach (NetworkInterface netInterface in networkInterfaces) { if (netInterface.OperationalStatus == OperationalStatus.Up && netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel && netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback) { return true; } } } catch (NetworkInformationException nie) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.NetworkInformation, "SystemNetworkInterface", "InternalGetIsNetworkAvailable", nie); } } return false; } internal static NetworkInterface[] GetNetworkInterfaces() { Contract.Ensures(Contract.Result<NetworkInterface[]>() != null); AddressFamily family = AddressFamily.Unspecified; uint bufferSize = 0; SafeLocalAllocHandle buffer = null; Interop.IpHlpApi.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo(); List<SystemNetworkInterface> interfaceList = new List<SystemNetworkInterface>(); Interop.IpHlpApi.GetAdaptersAddressesFlags flags = Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeGateways | Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeWins; // Figure out the right buffer size for the adapter information. uint result = Interop.IpHlpApi.GetAdaptersAddresses( family, (uint)flags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref bufferSize); while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW) { // Allocate the buffer and get the adapter info. using (buffer = SafeLocalAllocHandle.LocalAlloc((int)bufferSize)) { result = Interop.IpHlpApi.GetAdaptersAddresses( family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize); // If succeeded, we're going to add each new interface. if (result == Interop.IpHlpApi.ERROR_SUCCESS) { // Linked list of interfaces. IntPtr ptr = buffer.DangerousGetHandle(); while (ptr != IntPtr.Zero) { // Traverse the list, marshal in the native structures, and create new NetworkInterfaces. Interop.IpHlpApi.IpAdapterAddresses adapterAddresses = Marshal.PtrToStructure<Interop.IpHlpApi.IpAdapterAddresses>(ptr); interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses)); ptr = adapterAddresses.next; } } } } // If we don't have any interfaces detected, return empty. if (result == Interop.IpHlpApi.ERROR_NO_DATA || result == Interop.IpHlpApi.ERROR_INVALID_PARAMETER) { return new SystemNetworkInterface[0]; } // Otherwise we throw on an error. if (result != Interop.IpHlpApi.ERROR_SUCCESS) { throw new NetworkInformationException((int)result); } return interfaceList.ToArray(); } internal SystemNetworkInterface(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses) { // Store the common API information. _id = ipAdapterAddresses.AdapterName; _name = ipAdapterAddresses.friendlyName; _description = ipAdapterAddresses.description; _index = ipAdapterAddresses.index; _physicalAddress = ipAdapterAddresses.address; _addressLength = ipAdapterAddresses.addressLength; _type = ipAdapterAddresses.type; _operStatus = ipAdapterAddresses.operStatus; _speed = (long)ipAdapterAddresses.receiveLinkSpeed; // API specific info. _ipv6Index = ipAdapterAddresses.ipv6Index; _adapterFlags = ipAdapterAddresses.flags; _interfaceProperties = new SystemIPInterfaceProperties(fixedInfo, ipAdapterAddresses); } public override string Id { get { return _id; } } public override string Name { get { return _name; } } public override string Description { get { return _description; } } public override PhysicalAddress GetPhysicalAddress() { byte[] newAddr = new byte[_addressLength]; // Buffer.BlockCopy only supports int while addressLength is uint (see IpAdapterAddresses). // Will throw OverflowException if addressLength > Int32.MaxValue. Buffer.BlockCopy(_physicalAddress, 0, newAddr, 0, checked((int)_addressLength)); return new PhysicalAddress(newAddr); } public override NetworkInterfaceType NetworkInterfaceType { get { return _type; } } public override IPInterfaceProperties GetIPProperties() { return _interfaceProperties; } public override IPInterfaceStatistics GetIPStatistics() { return new SystemIPInterfaceStatistics(_index); } public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent) { if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6 && ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0)) { return true; } if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4 && ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0)) { return true; } return false; } // We cache this to be consistent across all platforms. public override OperationalStatus OperationalStatus { get { return _operStatus; } } public override long Speed { get { return _speed; } } public override bool IsReceiveOnly { get { return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.ReceiveOnly) > 0); } } /// <summary>The interface doesn't allow multicast.</summary> public override bool SupportsMulticast { get { return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.NoMulticast) == 0); } } } }
using System; using System.Diagnostics; using NS_IDraw; using Curve=NS_GMath.I_CurveD; using LCurve=NS_GMath.I_LCurveD; namespace NS_GMath { public class LineD : LCurve { private VecD[] cp; /* * CONSTRUCTORS */ private LineD() { this.cp=new VecD[2]; } public LineD(VecD start, VecD end): this() { this.cp[0]=new VecD(start); this.cp[1]=new VecD(end); } public LineD(LCurve lcurve) : this() { this.cp[0]=new VecD(lcurve.Start); this.cp[1]=new VecD(lcurve.End); } /* * METHODS : GEOMETRY */ VecD LCurve.DirTang { get { if (this.IsDegen) return null; return ((1/(this.cp[1]-this.cp[0]).Norm)*(this.cp[1]-this.cp[0])); } } VecD LCurve.DirNorm { get { throw new ExceptionGMath("LineD","DirNorm","NOT IMPLEMENTED"); //return null; } } public int LComplexity { get { return 2; } } Curve Curve.Copy() { return new LineD(this); } public VecD Cp(int i) { if ((i<0)||(i>=1)) return null; return this.cp[i]; } public bool IsSimple { get { return true; } } public bool IsBounded { get { return false; } } public bool IsDegen { get { return (this.cp[0]==this.cp[1]); } } public bool IsValid { get { return (!this.IsDegen); } } public double CurveLength(Param parS, Param parE) { double length=Math.Abs(parE-parS)*(this.cp[1]-this.cp[0]).Norm; if (Math.Abs(length)>=MConsts.Infinity) { length=MConsts.Infinity*Math.Sign(length); } return length; } public double CurveLength() { return MConsts.Infinity; } public void Reverse() { this.cp[1].From(-this.cp[1].X,-this.cp[1].Y); } public Curve Reversed { get { LineD lineRev=new LineD(this); lineRev.Reverse(); return lineRev; } } VecD Curve.DirTang(Param par) { return ((LCurve)this).DirTang; } VecD Curve.DirNorm(Param par) { return ((LCurve)this).DirNorm; } public double Curvature(Param par) { return 0; } public VecD Start { get { return this.cp[0]; } } public VecD End { get { return this.cp[1]; } } public double ParamStart { get { return -Param.Infinity; } } public double ParamEnd { get { return Param.Infinity; } } public double ParamReverse { get { return 0; } } public Param.TypeParam ParamClassify(Param par) { par.Clip(this.ParamStart,this.ParamEnd); if ((par.Val==Param.Invalid)||(par.Val==Param.Degen)) return Param.TypeParam.Invalid; return Param.TypeParam.Inner; } public RayD.TypeParity RayParity(RayD ray, bool isStartOnGeom) { throw new ExceptionGMath("LineD","RayParity","NOT IMPLEMENTED"); //return RayD.TypeParity.ParityUndef; } public void Transform(MatrixD m) { throw new ExceptionGMath("LineD","Transform","NOT IMPLEMENTED"); } public void PowerCoeff(out VecD[] pcf) { pcf=new VecD[2]; pcf[1]=this.cp[1]-this.cp[0]; pcf[0]=this.cp[0]; } public BoxD BBox { get { if (this.IsDegen) { throw new ExceptionGMath("LineD","BBox",null); } BoxD box=new BoxD(-MConsts.Infinity,-MConsts.Infinity,MConsts.Infinity,MConsts.Infinity); return box; } } public bool IsEvaluableWide(Param par) { return ((!par.IsDegen)&&(par.IsValid)); } public bool IsEvaluableStrict(Param par) { return ((!par.IsDegen)&&(par.IsValid)); } public VecD Evaluate(Param par) { if (!this.IsEvaluableWide(par)) { throw new ExceptionGMath("LineD","Evaluate",null); //return null; } if (par.IsInfinite) return null; return (1-par)*this.cp[0]+par*this.cp[1]; } /* * METHODS: I_DRAWABLE */ public void Draw(I_Draw i_draw, DrawParam dp) { DrawParamCurve dpCurve= dp as DrawParamCurve; if (dpCurve!=null) { if (!this.IsDegen) { VecD tang=(this as LCurve).DirTang; VecD startToDraw=this.Start-i_draw.DrawWorldInfinity*tang; VecD endToDraw=this.Start+i_draw.DrawWorldInfinity*tang; i_draw.DrawSeg(startToDraw.X, startToDraw.Y, endToDraw.X, endToDraw.Y, dpCurve.StrColor,dpCurve.ScrWidth); } } if (dpCurve.ToDrawEndPoints) { this.Cp(0).Draw(i_draw,dpCurve.DPEndPoints); this.Cp(1).Draw(i_draw,dpCurve.DPEndPoints); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace EveryplayEditor.XCodeEditor { public class PBXFileReference : PBXObject { protected const string PATH_KEY = "path"; protected const string NAME_KEY = "name"; protected const string SOURCETREE_KEY = "sourceTree"; protected const string EXPLICIT_FILE_TYPE_KEY = "explicitFileType"; protected const string LASTKNOWN_FILE_TYPE_KEY = "lastKnownFileType"; protected const string ENCODING_KEY = "fileEncoding"; public string buildPhase; public readonly Dictionary<TreeEnum, string> trees = new Dictionary<TreeEnum, string> { { TreeEnum.ABSOLUTE, "\"<absolute>\"" }, { TreeEnum.GROUP, "\"<group>\"" }, { TreeEnum.BUILT_PRODUCTS_DIR, "BUILT_PRODUCTS_DIR" }, { TreeEnum.DEVELOPER_DIR, "DEVELOPER_DIR" }, { TreeEnum.SDKROOT, "SDKROOT" }, { TreeEnum.SOURCE_ROOT, "SOURCE_ROOT" } }; public static readonly Dictionary<string, string> typeNames = new Dictionary<string, string> { { ".a", "archive.ar" }, { ".app", "wrapper.application" }, { ".s", "sourcecode.asm" }, { ".c", "sourcecode.c.c" }, { ".cpp", "sourcecode.cpp.cpp" }, { ".cs", "sourcecode.cpp.cpp" }, { ".framework", "wrapper.framework" }, { ".h", "sourcecode.c.h" }, { ".icns", "image.icns" }, { ".m", "sourcecode.c.objc" }, { ".mm", "sourcecode.cpp.objcpp" }, { ".nib", "wrapper.nib" }, { ".plist", "text.plist.xml" }, { ".png", "image.png" }, { ".rtf", "text.rtf" }, { ".tiff", "image.tiff" }, { ".txt", "text" }, { ".xcodeproj", "wrapper.pb-project" }, { ".xib", "file.xib" }, { ".strings", "text.plist.strings" }, { ".bundle", "wrapper.plug-in" }, { ".dylib", "compiled.mach-o.dylib" } }; public static readonly Dictionary<string, string> typePhases = new Dictionary<string, string> { { ".a", "PBXFrameworksBuildPhase" }, { ".app", null }, { ".s", "PBXSourcesBuildPhase" }, { ".c", "PBXSourcesBuildPhase" }, { ".cpp", "PBXSourcesBuildPhase" }, { ".cs", null }, { ".framework", "PBXFrameworksBuildPhase" }, { ".h", null }, { ".icns", "PBXResourcesBuildPhase" }, { ".m", "PBXSourcesBuildPhase" }, { ".mm", "PBXSourcesBuildPhase" }, { ".nib", "PBXResourcesBuildPhase" }, { ".plist", "PBXResourcesBuildPhase" }, { ".png", "PBXResourcesBuildPhase" }, { ".rtf", "PBXResourcesBuildPhase" }, { ".tiff", "PBXResourcesBuildPhase" }, { ".txt", "PBXResourcesBuildPhase" }, { ".xcodeproj", null }, { ".xib", "PBXResourcesBuildPhase" }, { ".strings", "PBXResourcesBuildPhase" }, { ".bundle", "PBXResourcesBuildPhase" }, { ".dylib", "PBXFrameworksBuildPhase" } }; public PBXFileReference(string guid, PBXDictionary dictionary) : base(guid, dictionary) { } public PBXFileReference(string filePath, TreeEnum tree = TreeEnum.SOURCE_ROOT) : base() { string temp = "\"" + filePath + "\""; this.Add(PATH_KEY, temp); this.Add(NAME_KEY, System.IO.Path.GetFileName(filePath)); this.Add(SOURCETREE_KEY, (string) (System.IO.Path.IsPathRooted(filePath) ? trees[TreeEnum.ABSOLUTE] : trees[tree])); this.GuessFileType(); } public string name { get { if (!ContainsKey(NAME_KEY)) { return null; } return (string) _data[NAME_KEY]; } } private void GuessFileType() { this.Remove(EXPLICIT_FILE_TYPE_KEY); this.Remove(LASTKNOWN_FILE_TYPE_KEY); string extension = System.IO.Path.GetExtension((string) _data[NAME_KEY]); if (!PBXFileReference.typeNames.ContainsKey(extension)) { Debug.LogWarning("Unknown file extension: " + extension + "\nPlease add extension and Xcode type to PBXFileReference.types"); return; } this.Add(LASTKNOWN_FILE_TYPE_KEY, PBXFileReference.typeNames[extension]); this.buildPhase = PBXFileReference.typePhases[extension]; } private void SetFileType(string fileType) { this.Remove(EXPLICIT_FILE_TYPE_KEY); this.Remove(LASTKNOWN_FILE_TYPE_KEY); this.Add(EXPLICIT_FILE_TYPE_KEY, fileType); } // class PBXFileReference(PBXType): // def __init__(self, d=None): // PBXType.__init__(self, d) // self.build_phase = None // // types = { // '.a':('archive.ar', 'PBXFrameworksBuildPhase'), // '.app': ('wrapper.application', None), // '.s': ('sourcecode.asm', 'PBXSourcesBuildPhase'), // '.c': ('sourcecode.c.c', 'PBXSourcesBuildPhase'), // '.cpp': ('sourcecode.cpp.cpp', 'PBXSourcesBuildPhase'), // '.framework': ('wrapper.framework','PBXFrameworksBuildPhase'), // '.h': ('sourcecode.c.h', None), // '.icns': ('image.icns','PBXResourcesBuildPhase'), // '.m': ('sourcecode.c.objc', 'PBXSourcesBuildPhase'), // '.mm': ('sourcecode.cpp.objcpp', 'PBXSourcesBuildPhase'), // '.nib': ('wrapper.nib', 'PBXResourcesBuildPhase'), // '.plist': ('text.plist.xml', 'PBXResourcesBuildPhase'), // '.png': ('image.png', 'PBXResourcesBuildPhase'), // '.rtf': ('text.rtf', 'PBXResourcesBuildPhase'), // '.tiff': ('image.tiff', 'PBXResourcesBuildPhase'), // '.txt': ('text', 'PBXResourcesBuildPhase'), // '.xcodeproj': ('wrapper.pb-project', None), // '.xib': ('file.xib', 'PBXResourcesBuildPhase'), // '.strings': ('text.plist.strings', 'PBXResourcesBuildPhase'), // '.bundle': ('wrapper.plug-in', 'PBXResourcesBuildPhase'), // '.dylib': ('compiled.mach-o.dylib', 'PBXFrameworksBuildPhase') // } // // trees = [ // '<absolute>', // '<group>', // 'BUILT_PRODUCTS_DIR', // 'DEVELOPER_DIR', // 'SDKROOT', // 'SOURCE_ROOT', // ] // // def guess_file_type(self): // self.remove('explicitFileType') // self.remove('lastKnownFileType') // ext = os.path.splitext(self.get('name', ''))[1] // // f_type, build_phase = PBXFileReference.types.get(ext, ('?', None)) // // self['lastKnownFileType'] = f_type // self.build_phase = build_phase // // if f_type == '?': // print 'unknown file extension: %s' % ext // print 'please add extension and Xcode type to PBXFileReference.types' // // return f_type // // def set_file_type(self, ft): // self.remove('explicitFileType') // self.remove('lastKnownFileType') // // self['explicitFileType'] = ft // // @classmethod // def Create(cls, os_path, tree='SOURCE_ROOT'): // if tree not in cls.trees: // print 'Not a valid sourceTree type: %s' % tree // return None // // fr = cls() // fr.id = cls.GenerateId() // fr['path'] = os_path // fr['name'] = os.path.split(os_path)[1] // fr['sourceTree'] = '<absolute>' if os.path.isabs(os_path) else tree // fr.guess_file_type() // // return fr } public enum TreeEnum { ABSOLUTE, GROUP, BUILT_PRODUCTS_DIR, DEVELOPER_DIR, SDKROOT, SOURCE_ROOT } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Monitoring.V3 { /// <summary>Settings for <see cref="QueryServiceClient"/> instances.</summary> public sealed partial class QueryServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="QueryServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="QueryServiceSettings"/>.</returns> public static QueryServiceSettings GetDefault() => new QueryServiceSettings(); /// <summary>Constructs a new <see cref="QueryServiceSettings"/> object with default settings.</summary> public QueryServiceSettings() { } private QueryServiceSettings(QueryServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); QueryTimeSeriesSettings = existing.QueryTimeSeriesSettings; OnCopy(existing); } partial void OnCopy(QueryServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>QueryServiceClient.QueryTimeSeries</c> and <c>QueryServiceClient.QueryTimeSeriesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings QueryTimeSeriesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="QueryServiceSettings"/> object.</returns> public QueryServiceSettings Clone() => new QueryServiceSettings(this); } /// <summary> /// Builder class for <see cref="QueryServiceClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class QueryServiceClientBuilder : gaxgrpc::ClientBuilderBase<QueryServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public QueryServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public QueryServiceClientBuilder() { UseJwtAccessWithScopes = QueryServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref QueryServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<QueryServiceClient> task); /// <summary>Builds the resulting client.</summary> public override QueryServiceClient Build() { QueryServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<QueryServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<QueryServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private QueryServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return QueryServiceClient.Create(callInvoker, Settings); } private async stt::Task<QueryServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return QueryServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => QueryServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => QueryServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => QueryServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>QueryService client wrapper, for convenient use.</summary> /// <remarks> /// The QueryService API is used to manage time series data in Stackdriver /// Monitoring. Time series data is a collection of data points that describes /// the time-varying values of a metric. /// </remarks> public abstract partial class QueryServiceClient { /// <summary> /// The default endpoint for the QueryService service, which is a host of "monitoring.googleapis.com" and a port /// of 443. /// </summary> public static string DefaultEndpoint { get; } = "monitoring.googleapis.com:443"; /// <summary>The default QueryService scopes.</summary> /// <remarks> /// The default QueryService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// <item><description>https://www.googleapis.com/auth/monitoring</description></item> /// <item><description>https://www.googleapis.com/auth/monitoring.read</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/monitoring.read", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="QueryServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="QueryServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="QueryServiceClient"/>.</returns> public static stt::Task<QueryServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new QueryServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="QueryServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="QueryServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="QueryServiceClient"/>.</returns> public static QueryServiceClient Create() => new QueryServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="QueryServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="QueryServiceSettings"/>.</param> /// <returns>The created <see cref="QueryServiceClient"/>.</returns> internal static QueryServiceClient Create(grpccore::CallInvoker callInvoker, QueryServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } QueryService.QueryServiceClient grpcClient = new QueryService.QueryServiceClient(callInvoker); return new QueryServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC QueryService client</summary> public virtual QueryService.QueryServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Queries time series using Monitoring Query Language. This method does not require a Workspace. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="TimeSeriesData"/> resources.</returns> public virtual gax::PagedEnumerable<QueryTimeSeriesResponse, TimeSeriesData> QueryTimeSeries(QueryTimeSeriesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Queries time series using Monitoring Query Language. This method does not require a Workspace. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="TimeSeriesData"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<QueryTimeSeriesResponse, TimeSeriesData> QueryTimeSeriesAsync(QueryTimeSeriesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); } /// <summary>QueryService client wrapper implementation, for convenient use.</summary> /// <remarks> /// The QueryService API is used to manage time series data in Stackdriver /// Monitoring. Time series data is a collection of data points that describes /// the time-varying values of a metric. /// </remarks> public sealed partial class QueryServiceClientImpl : QueryServiceClient { private readonly gaxgrpc::ApiCall<QueryTimeSeriesRequest, QueryTimeSeriesResponse> _callQueryTimeSeries; /// <summary> /// Constructs a client wrapper for the QueryService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="QueryServiceSettings"/> used within this client.</param> public QueryServiceClientImpl(QueryService.QueryServiceClient grpcClient, QueryServiceSettings settings) { GrpcClient = grpcClient; QueryServiceSettings effectiveSettings = settings ?? QueryServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callQueryTimeSeries = clientHelper.BuildApiCall<QueryTimeSeriesRequest, QueryTimeSeriesResponse>(grpcClient.QueryTimeSeriesAsync, grpcClient.QueryTimeSeries, effectiveSettings.QueryTimeSeriesSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callQueryTimeSeries); Modify_QueryTimeSeriesApiCall(ref _callQueryTimeSeries); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_QueryTimeSeriesApiCall(ref gaxgrpc::ApiCall<QueryTimeSeriesRequest, QueryTimeSeriesResponse> call); partial void OnConstruction(QueryService.QueryServiceClient grpcClient, QueryServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC QueryService client</summary> public override QueryService.QueryServiceClient GrpcClient { get; } partial void Modify_QueryTimeSeriesRequest(ref QueryTimeSeriesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Queries time series using Monitoring Query Language. This method does not require a Workspace. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="TimeSeriesData"/> resources.</returns> public override gax::PagedEnumerable<QueryTimeSeriesResponse, TimeSeriesData> QueryTimeSeries(QueryTimeSeriesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_QueryTimeSeriesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<QueryTimeSeriesRequest, QueryTimeSeriesResponse, TimeSeriesData>(_callQueryTimeSeries, request, callSettings); } /// <summary> /// Queries time series using Monitoring Query Language. This method does not require a Workspace. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="TimeSeriesData"/> resources.</returns> public override gax::PagedAsyncEnumerable<QueryTimeSeriesResponse, TimeSeriesData> QueryTimeSeriesAsync(QueryTimeSeriesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_QueryTimeSeriesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<QueryTimeSeriesRequest, QueryTimeSeriesResponse, TimeSeriesData>(_callQueryTimeSeries, request, callSettings); } } public partial class QueryTimeSeriesRequest : gaxgrpc::IPageRequest { } public partial class QueryTimeSeriesResponse : gaxgrpc::IPageResponse<TimeSeriesData> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<TimeSeriesData> GetEnumerator() => TimeSeriesData.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
// 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; #if !netcoreapp using System.Linq; #endif using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.IO; namespace System.Data.SqlClient.SNI { /// <summary> /// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient. /// </summary> internal class SNIProxy { private const int DefaultSqlServerPort = 1433; private const int DefaultSqlServerDacPort = 1434; private const string SqlServerSpnHeader = "MSSQLSvc"; internal class SspiClientContextResult { internal const uint OK = 0; internal const uint Failed = 1; internal const uint KerberosTicketMissing = 2; } public static readonly SNIProxy Singleton = new SNIProxy(); /// <summary> /// Terminate SNI /// </summary> public void Terminate() { } /// <summary> /// Enable SSL on a connection /// </summary> /// <param name="handle">Connection handle</param> /// <returns>SNI error code</returns> public uint EnableSsl(SNIHandle handle, uint options) { try { return handle.EnableSsl(options); } catch (Exception e) { return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e); } } /// <summary> /// Disable SSL on a connection /// </summary> /// <param name="handle">Connection handle</param> /// <returns>SNI error code</returns> public uint DisableSsl(SNIHandle handle) { handle.DisableSsl(); return TdsEnums.SNI_SUCCESS; } /// <summary> /// Generate SSPI context /// </summary> /// <param name="handle">SNI connection handle</param> /// <param name="receivedBuff">Receive buffer</param> /// <param name="receivedLength">Received length</param> /// <param name="sendBuff">Send buffer</param> /// <param name="sendLength">Send length</param> /// <param name="serverName">Service Principal Name buffer</param> /// <param name="serverNameLength">Length of Service Principal Name</param> /// <returns>SNI error code</returns> public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName) { SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext; ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags; SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle; string securityPackage = NegotiationInfoClass.Negotiate; if (securityContext == null) { credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false); } SecurityBuffer[] inSecurityBufferArray = null; if (receivedBuff != null) { inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) }; } else { inSecurityBufferArray = Array.Empty<SecurityBuffer>(); } int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage); SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN); ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection | ContextFlagsPal.Confidentiality | ContextFlagsPal.Delegate | ContextFlagsPal.MutualAuth; string serverSPN = System.Text.Encoding.UTF8.GetString(serverName); SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext( credentialsHandle, ref securityContext, serverSPN, requestedContextFlags, inSecurityBufferArray, outSecurityBuffer, ref contextFlags); if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded || statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue) { inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer }; statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray); outSecurityBuffer.token = null; } sendBuff = outSecurityBuffer.token; if (sendBuff == null) { sendBuff = Array.Empty<byte>(); } sspiClientContextStatus.SecurityContext = securityContext; sspiClientContextStatus.ContextFlags = contextFlags; sspiClientContextStatus.CredentialsHandle = credentialsHandle; if (IsErrorStatus(statusCode.ErrorCode)) { // Could not access Kerberos Ticket. // // SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException, // so we don't need to check for a GssApiException here. if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError) { throw new InvalidOperationException(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode); } else { throw new InvalidOperationException(SQLMessage.SSPIGenerateError() + "\n" + statusCode); } } } private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode) { return errorCode != SecurityStatusPalErrorCode.NotSet && errorCode != SecurityStatusPalErrorCode.OK && errorCode != SecurityStatusPalErrorCode.ContinueNeeded && errorCode != SecurityStatusPalErrorCode.CompleteNeeded && errorCode != SecurityStatusPalErrorCode.CompAndContinue && errorCode != SecurityStatusPalErrorCode.ContextExpired && errorCode != SecurityStatusPalErrorCode.CredentialsNeeded && errorCode != SecurityStatusPalErrorCode.Renegotiate; } /// <summary> /// Initialize SSPI /// </summary> /// <param name="maxLength">Max length of SSPI packet</param> /// <returns>SNI error code</returns> public uint InitializeSspiPackage(ref uint maxLength) { throw new PlatformNotSupportedException(); } /// <summary> /// Set connection buffer size /// </summary> /// <param name="handle">SNI handle</param> /// <param name="bufferSize">Buffer size</param> /// <returns>SNI error code</returns> public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize) { handle.SetBufferSize((int)bufferSize); return TdsEnums.SNI_SUCCESS; } /// <summary> /// Copies data in SNIPacket to given byte array parameter /// </summary> /// <param name="packet">SNIPacket object containing data packets</param> /// <param name="inBuff">Destination byte array where data packets are copied to</param> /// <param name="dataSize">Length of data packets</param> /// <returns>SNI error status</returns> public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize) { int dataSizeInt = 0; packet.GetData(inBuff, ref dataSizeInt); dataSize = (uint)dataSizeInt; return TdsEnums.SNI_SUCCESS; } /// <summary> /// Read synchronously /// </summary> /// <param name="handle">SNI handle</param> /// <param name="packet">SNI packet</param> /// <param name="timeout">Timeout</param> /// <returns>SNI error status</returns> public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout) { return handle.Receive(out packet, timeout); } /// <summary> /// Get SNI connection ID /// </summary> /// <param name="handle">SNI handle</param> /// <param name="clientConnectionId">Client connection ID</param> /// <returns>SNI error status</returns> public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId) { clientConnectionId = handle.ConnectionId; return TdsEnums.SNI_SUCCESS; } /// <summary> /// Send a packet /// </summary> /// <param name="handle">SNI handle</param> /// <param name="packet">SNI packet</param> /// <param name="sync">true if synchronous, false if asynchronous</param> /// <returns>SNI error status</returns> public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync) { SNIPacket clonedPacket = packet.Clone(); uint result; if (sync) { result = handle.Send(clonedPacket); clonedPacket.Dispose(); } else { result = handle.SendAsync(clonedPacket, true); } return result; } /// <summary> /// Create a SNI connection handle /// </summary> /// <param name="callbackObject">Asynchronous I/O callback object</param> /// <param name="fullServerName">Full server name from connection string</param> /// <param name="ignoreSniOpenTimeout">Ignore open timeout</param> /// <param name="timerExpire">Timer expiration</param> /// <param name="instanceName">Instance name</param> /// <param name="spnBuffer">SPN</param> /// <param name="flushCache">Flush packet cache</param> /// <param name="async">Asynchronous connection</param> /// <param name="parallel">Attempt parallel connects</param> /// <returns>SNI handle</returns> public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity) { instanceName = new byte[1]; bool errorWithLocalDBProcessing; string localDBDataSource = GetLocalDBDataSource(fullServerName, out errorWithLocalDBProcessing); if (errorWithLocalDBProcessing) { return null; } // If a localDB Data source is available, we need to use it. fullServerName = localDBDataSource ?? fullServerName; DataSource details = DataSource.ParseServerName(fullServerName); if (details == null) { return null; } SNIHandle sniHandle = null; switch (details.ConnectionProtocol) { case DataSource.Protocol.Admin: case DataSource.Protocol.None: // default to using tcp if no protocol is provided case DataSource.Protocol.TCP: sniHandle = CreateTcpHandle(details, timerExpire, callbackObject, parallel); break; case DataSource.Protocol.NP: sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel); break; default: Debug.Fail($"Unexpected connection protocol: {details.ConnectionProtocol}"); break; } if (isIntegratedSecurity) { try { spnBuffer = GetSqlServerSPN(details); } catch (Exception e) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e); } } return sniHandle; } private static byte[] GetSqlServerSPN(DataSource dataSource) { Debug.Assert(!string.IsNullOrWhiteSpace(dataSource.ServerName)); string hostName = dataSource.ServerName; string postfix = null; if (dataSource.Port != -1) { postfix = dataSource.Port.ToString(); } else if (!string.IsNullOrWhiteSpace(dataSource.InstanceName)) { postfix = dataSource.InstanceName; } // For handling tcp:<hostname> format else if (dataSource.ConnectionProtocol == DataSource.Protocol.TCP) { postfix = DefaultSqlServerPort.ToString(); } return GetSqlServerSPN(hostName, postfix); } private static byte[] GetSqlServerSPN(string hostNameOrAddress, string portOrInstanceName) { Debug.Assert(!string.IsNullOrWhiteSpace(hostNameOrAddress)); IPHostEntry hostEntry = null; string fullyQualifiedDomainName; try { hostEntry = Dns.GetHostEntry(hostNameOrAddress); } catch (SocketException) { // A SocketException can occur while resolving the hostname. // We will fallback on using hostname from the connection string in the finally block } finally { // If the DNS lookup failed, then resort to using the user provided hostname to construct the SPN. fullyQualifiedDomainName = hostEntry?.HostName ?? hostNameOrAddress; } string serverSpn = SqlServerSpnHeader + "/" + fullyQualifiedDomainName; if (!string.IsNullOrWhiteSpace(portOrInstanceName)) { serverSpn += ":" + portOrInstanceName; } return Encoding.UTF8.GetBytes(serverSpn); } /// <summary> /// Creates an SNITCPHandle object /// </summary> /// <param name="fullServerName">Server string. May contain a comma delimited port number.</param> /// <param name="timerExpire">Timer expiration</param> /// <param name="callbackObject">Asynchronous I/O callback object</param> /// <param name="parallel">Should MultiSubnetFailover be used</param> /// <returns>SNITCPHandle</returns> private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel) { // TCP Format: // tcp:<host name>\<instance name> // tcp:<host name>,<TCP/IP port number> string hostName = details.ServerName; if (string.IsNullOrWhiteSpace(hostName)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty); return null; } int port = -1; bool isAdminConnection = details.ConnectionProtocol == DataSource.Protocol.Admin; if (details.IsSsrpRequired) { try { port = isAdminConnection ? SSRP.GetDacPortByInstanceName(hostName, details.InstanceName) : SSRP.GetPortByInstanceName(hostName, details.InstanceName); } catch (SocketException se) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, se); return null; } } else if (details.Port != -1) { port = details.Port; } else { port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort; } return new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel); } /// <summary> /// Creates an SNINpHandle object /// </summary> /// <param name="fullServerName">Server string representing a UNC pipe path.</param> /// <param name="timerExpire">Timer expiration</param> /// <param name="callbackObject">Asynchronous I/O callback object</param> /// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param> /// <returns>SNINpHandle</returns> private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel) { if (parallel) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty); return null; } return new SNINpHandle(details.PipeHostName, details.PipeName, timerExpire, callbackObject); } /// <summary> /// Read packet asynchronously /// </summary> /// <param name="handle">SNI handle</param> /// <param name="packet">Packet</param> /// <returns>SNI error status</returns> public uint ReadAsync(SNIHandle handle, out SNIPacket packet) { packet = null; return handle.ReceiveAsync(ref packet); } /// <summary> /// Set packet data /// </summary> /// <param name="packet">SNI packet</param> /// <param name="data">Data</param> /// <param name="length">Length</param> public void PacketSetData(SNIPacket packet, byte[] data, int length) { packet.SetData(data, length); } /// <summary> /// Release packet /// </summary> /// <param name="packet">SNI packet</param> public void PacketRelease(SNIPacket packet) { packet.Release(); } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public uint CheckConnection(SNIHandle handle) { return handle.CheckConnection(); } /// <summary> /// Get last SNI error on this thread /// </summary> /// <returns></returns> public SNIError GetLastError() { return SNILoadHandle.SingletonInstance.LastError; } /// <summary> /// Gets the Local db Named pipe data source if the input is a localDB server. /// </summary> /// <param name="fullServerName">The data source</param> /// <param name="error">Set true when an error occurred while getting LocalDB up</param> /// <returns></returns> private string GetLocalDBDataSource(string fullServerName, out bool error) { string localDBConnectionString = null; bool isBadLocalDBDataSource; string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource); if (isBadLocalDBDataSource) { error = true; return null; } else if (!string.IsNullOrEmpty(localDBInstance)) { // We have successfully received a localDBInstance which is valid. Debug.Assert(!string.IsNullOrWhiteSpace(localDBInstance), "Local DB Instance name cannot be empty."); localDBConnectionString = LocalDB.GetLocalDBConnectionString(localDBInstance); if (fullServerName == null) { // The Last error is set in LocalDB.GetLocalDBConnectionString. We don't need to set Last here. error = true; return null; } } error = false; return localDBConnectionString; } } internal class DataSource { private const char CommaSeparator = ','; private const char BackSlashSeparator = '\\'; private const string DefaultHostName = "localhost"; private const string DefaultSqlServerInstanceName = "mssqlserver"; private const string PipeBeginning = @"\\"; private const string PipeToken = "pipe"; private const string LocalDbHost = "(localdb)"; private const string NamedPipeInstanceNameHeader = "mssql$"; private const string DefaultPipeName = "sql\\query"; internal enum Protocol { TCP, NP, None, Admin }; internal Protocol ConnectionProtocol = Protocol.None; /// <summary> /// Provides the HostName of the server to connect to for TCP protocol. /// This information is also used for finding the SPN of SqlServer /// </summary> internal string ServerName { get; private set; } /// <summary> /// Provides the port on which the TCP connection should be made if one was specified in Data Source /// </summary> internal int Port { get; private set; } = -1; /// <summary> /// Provides the inferred Instance Name from Server Data Source /// </summary> public string InstanceName { get; internal set; } /// <summary> /// Provides the pipe name in case of Named Pipes /// </summary> public string PipeName { get; internal set; } /// <summary> /// Provides the HostName to connect to in case of Named pipes Data Source /// </summary> public string PipeHostName { get; internal set; } private string _workingDataSource; private string _dataSourceAfterTrimmingProtocol; internal bool IsBadDataSource { get; private set; } = false; internal bool IsSsrpRequired { get; private set; } = false; private DataSource(string dataSource) { // Remove all whitespaces from the datasource and all operations will happen on lower case. _workingDataSource = dataSource.Trim().ToLowerInvariant(); int firstIndexOfColon = _workingDataSource.IndexOf(':'); PopulateProtocol(); _dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && ConnectionProtocol != DataSource.Protocol.None ? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource; // Pipe paths only allow back slashes #if netcoreapp if (_dataSourceAfterTrimmingProtocol.Contains('/')) // string.Contains(char) is .NetCore2.1+ specific #else if (_dataSourceAfterTrimmingProtocol.Contains("/")) #endif { if (ConnectionProtocol == DataSource.Protocol.None) ReportSNIError(SNIProviders.INVALID_PROV); else if (ConnectionProtocol == DataSource.Protocol.NP) ReportSNIError(SNIProviders.NP_PROV); else if (ConnectionProtocol == DataSource.Protocol.TCP) ReportSNIError(SNIProviders.TCP_PROV); } } private void PopulateProtocol() { string[] splitByColon = _workingDataSource.Split(':'); if (splitByColon.Length <= 1) { ConnectionProtocol = DataSource.Protocol.None; } else { // We trim before switching because " tcp : server , 1433 " is a valid data source switch (splitByColon[0].Trim()) { case TdsEnums.TCP: ConnectionProtocol = DataSource.Protocol.TCP; break; case TdsEnums.NP: ConnectionProtocol = DataSource.Protocol.NP; break; case TdsEnums.ADMIN: ConnectionProtocol = DataSource.Protocol.Admin; break; default: // None of the supported protocols were found. This may be a IPv6 address ConnectionProtocol = DataSource.Protocol.None; break; } } } public static string GetLocalDBInstance(string dataSource, out bool error) { string instanceName = null; string workingDataSource = dataSource.ToLowerInvariant(); string[] tokensByBackSlash = workingDataSource.Split(BackSlashSeparator); error = false; // All LocalDb endpoints are of the format host\instancename where host is always (LocalDb) (case-insensitive) if (tokensByBackSlash.Length == 2 && LocalDbHost.Equals(tokensByBackSlash[0].TrimStart())) { if (!string.IsNullOrWhiteSpace(tokensByBackSlash[1])) { instanceName = tokensByBackSlash[1].Trim(); } else { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, string.Empty); error = true; return null; } } return instanceName; } public static DataSource ParseServerName(string dataSource) { DataSource details = new DataSource(dataSource); if (details.IsBadDataSource) { return null; } if (details.InferNamedPipesInformation()) { return details; } if (details.IsBadDataSource) { return null; } if (details.InferConnectionDetails()) { return details; } return null; } private void InferLocalServerName() { // If Server name is empty or localhost, then use "localhost" if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName)) { ServerName = ConnectionProtocol == DataSource.Protocol.Admin ? Environment.MachineName : DefaultHostName; } } private bool InferConnectionDetails() { string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator, ','); ServerName = tokensByCommaAndSlash[0].Trim(); int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(','); int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(BackSlashSeparator); // Check the parameters. The parameters are Comma separated in the Data Source. The parameter we really care about is the port // If Comma exists, the try to get the port number if (commaIndex > -1) { string parameter = backSlashIndex > -1 ? ((commaIndex > backSlashIndex) ? tokensByCommaAndSlash[2].Trim() : tokensByCommaAndSlash[1].Trim()) : tokensByCommaAndSlash[1].Trim(); // Bad Data Source like "server, " if (string.IsNullOrEmpty(parameter)) { ReportSNIError(SNIProviders.INVALID_PROV); return false; } // For Tcp and Only Tcp are parameters allowed. if (ConnectionProtocol == DataSource.Protocol.None) { ConnectionProtocol = DataSource.Protocol.TCP; } else if (ConnectionProtocol != DataSource.Protocol.TCP) { // Parameter has been specified for non-TCP protocol. This is not allowed. ReportSNIError(SNIProviders.INVALID_PROV); return false; } int port; if (!int.TryParse(parameter, out port)) { ReportSNIError(SNIProviders.TCP_PROV); return false; } // If the user explicitly specified a invalid port in the connection string. if (port < 1) { ReportSNIError(SNIProviders.TCP_PROV); return false; } Port = port; } // Instance Name Handling. Only if we found a '\' and we did not find a port in the Data Source else if (backSlashIndex > -1) { // This means that there will not be any part separated by comma. InstanceName = tokensByCommaAndSlash[1].Trim(); if (string.IsNullOrWhiteSpace(InstanceName)) { ReportSNIError(SNIProviders.INVALID_PROV); return false; } if (DefaultSqlServerInstanceName.Equals(InstanceName)) { ReportSNIError(SNIProviders.INVALID_PROV); return false; } IsSsrpRequired = true; } InferLocalServerName(); return true; } private void ReportSNIError(SNIProviders provider) { SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, string.Empty); IsBadDataSource = true; } private bool InferNamedPipesInformation() { // If we have a datasource beginning with a pipe or we have already determined that the protocol is Named Pipe if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || ConnectionProtocol == Protocol.NP) { // If the data source is "np:servername" if (!_dataSourceAfterTrimmingProtocol.Contains(BackSlashSeparator)) // string.Contains(char) is .NetCore2.1+ specific. Else uses Linq (perf warning) { PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol; InferLocalServerName(); PipeName = SNINpHandle.DefaultPipePath; return true; } try { string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator); // The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5] // It would at least have 6 parts. // Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query if (tokensByBackSlash.Length < 6) { ReportSNIError(SNIProviders.NP_PROV); return false; } string host = tokensByBackSlash[2]; if (string.IsNullOrEmpty(host)) { ReportSNIError(SNIProviders.NP_PROV); return false; } //Check if the "pipe" keyword is the first part of path if (!PipeToken.Equals(tokensByBackSlash[3])) { ReportSNIError(SNIProviders.NP_PROV); return false; } if (tokensByBackSlash[4].StartsWith(NamedPipeInstanceNameHeader)) { InstanceName = tokensByBackSlash[4].Substring(NamedPipeInstanceNameHeader.Length); } StringBuilder pipeNameBuilder = new StringBuilder(); for (int i = 4; i < tokensByBackSlash.Length - 1; i++) { pipeNameBuilder.Append(tokensByBackSlash[i]); pipeNameBuilder.Append(Path.DirectorySeparatorChar); } // Append the last part without a "/" pipeNameBuilder.Append(tokensByBackSlash[tokensByBackSlash.Length - 1]); PipeName = pipeNameBuilder.ToString(); if (string.IsNullOrWhiteSpace(InstanceName) && !DefaultPipeName.Equals(PipeName)) { InstanceName = PipeToken + PipeName; } ServerName = IsLocalHost(host) ? Environment.MachineName : host; // Pipe hostname is the hostname after leading \\ which should be passed down as is to open Named Pipe. // For Named Pipes the ServerName makes sense for SPN creation only. PipeHostName = host; } catch (UriFormatException) { ReportSNIError(SNIProviders.NP_PROV); return false; } // DataSource is something like "\\pipename" if (ConnectionProtocol == DataSource.Protocol.None) { ConnectionProtocol = DataSource.Protocol.NP; } else if (ConnectionProtocol != DataSource.Protocol.NP) { // In case the path began with a "\\" and protocol was not Named Pipes ReportSNIError(SNIProviders.NP_PROV); return false; } return true; } return false; } private static bool IsLocalHost(string serverName) => ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName); } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Text; namespace Moq { internal static class Extensions { public static bool CanCreateInstance(this Type type) { return type.IsValueType || type.GetConstructor(Type.EmptyTypes) != null; } public static bool CanRead(this PropertyInfo property, out MethodInfo getter) { if (property.CanRead) { // The given `PropertyInfo` should be able to provide a getter: getter = property.GetGetMethod(nonPublic: true); Debug.Assert(getter != null); return true; } else { // The given `PropertyInfo` cannot provide a getter... but there may still be one in a base class' // corresponding `PropertyInfo`! We need to find that base `PropertyInfo`, and because `PropertyInfo` // does not have `.GetBaseDefinition()`, we'll find it via the setter's `.GetBaseDefinition()`. // (We may assume that there's a setter because properties/indexers must have at least one accessor.) Debug.Assert(property.CanWrite); var setter = property.GetSetMethod(nonPublic: true); Debug.Assert(setter != null); var baseSetter = setter.GetBaseDefinition(); if (baseSetter != setter) { var baseProperty = baseSetter .DeclaringType .GetMember(property.Name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Cast<PropertyInfo>() .First(p => p.GetSetMethod(nonPublic: true) == baseSetter); return baseProperty.CanRead(out getter); } } getter = null; return false; } public static bool CanWrite(this PropertyInfo property, out MethodInfo setter) { if (property.CanWrite) { // The given `PropertyInfo` should be able to provide a setter: setter = property.GetSetMethod(nonPublic: true); Debug.Assert(setter != null); return true; } else { // The given `PropertyInfo` cannot provide a setter... but there may still be one in a base class' // corresponding `PropertyInfo`! We need to find that base `PropertyInfo`, and because `PropertyInfo` // does not have `.GetBaseDefinition()`, we'll find it via the getter's `.GetBaseDefinition()`. // (We may assume that there's a getter because properties/indexers must have at least one accessor.) Debug.Assert(property.CanRead); var getter = property.GetGetMethod(nonPublic: true); Debug.Assert(getter != null); var baseGetter = getter.GetBaseDefinition(); if (baseGetter != getter) { var baseProperty = baseGetter .DeclaringType .GetMember(property.Name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Cast<PropertyInfo>() .First(p => p.GetGetMethod(nonPublic: true) == baseGetter); return baseProperty.CanWrite(out setter); } } setter = null; return false; } /// <summary> /// Gets the default value for the specified type. This is the Reflection counterpart of C#'s <see langword="default"/> operator. /// </summary> public static object GetDefaultValue(this Type type) { return type.IsValueType ? Activator.CreateInstance(type) : null; } /// <summary> /// Gets the least-derived <see cref="MethodInfo"/> in the given type that provides /// the implementation for the given <paramref name="method"/>. /// </summary> public static MethodInfo GetImplementingMethod(this MethodInfo method, Type proxyType) { Debug.Assert(method != null); Debug.Assert(proxyType != null); Debug.Assert(proxyType.IsClass); if (method.IsGenericMethod) { method = method.GetGenericMethodDefinition(); } var declaringType = method.DeclaringType; if (declaringType.IsInterface) { Debug.Assert(declaringType.IsAssignableFrom(proxyType)); var map = proxyType.GetInterfaceMap(method.DeclaringType); var index = Array.IndexOf(map.InterfaceMethods, method); Debug.Assert(index >= 0); return map.TargetMethods[index].GetBaseDefinition(); } else if (declaringType.IsDelegateType()) { return proxyType.GetMethod("Invoke"); } else { Debug.Assert(declaringType.IsAssignableFrom(proxyType)); return method.GetBaseDefinition(); } } public static object InvokePreserveStack(this Delegate del, IReadOnlyList<object> args = null) { try { return del.DynamicInvoke((args as object[]) ?? args?.ToArray()); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } public static bool IsExtensionMethod(this MethodInfo method) { return method.IsStatic && method.IsDefined(typeof(ExtensionAttribute)); } public static bool IsGetAccessor(this MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("get_", StringComparison.Ordinal); } public static bool IsSetAccessor(this MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("set_", StringComparison.Ordinal); } public static bool IsIndexerAccessor(this MethodInfo method) { var parameterCount = method.GetParameters().Length; return (method.IsGetAccessor() && parameterCount > 0) || (method.IsSetAccessor() && parameterCount > 1); } public static bool IsPropertyAccessor(this MethodInfo method) { var parameterCount = method.GetParameters().Length; return (method.IsGetAccessor() && parameterCount == 0) || (method.IsSetAccessor() && parameterCount == 1); } // NOTE: The following two methods used to first check whether `method.IsSpecialName` was set // as a quick guard against non-event accessor methods. This was removed in commit 44070a90 // to "increase compatibility with F# and COM". More specifically: // // 1. COM does not really have events. Some COM interop assemblies define events, but do not // mark those with the IL `specialname` flag. See: // - https://code.google.com/archive/p/moq/issues/226 // - the `Microsoft.Office.Interop.Word.ApplicationEvents4_Event` interface in Office PIA // // 2. F# does not mark abstract events' accessors with the IL `specialname` flag. See: // - https://github.com/Microsoft/visualfsharp/issues/5834 // - https://code.google.com/archive/p/moq/issues/238 // - the unit tests in `FSharpCompatibilityFixture` public static bool IsEventAddAccessor(this MethodInfo method) { return method.Name.StartsWith("add_", StringComparison.Ordinal); } public static bool IsEventRemoveAccessor(this MethodInfo method) { return method.Name.StartsWith("remove_", StringComparison.Ordinal); } /// <summary> /// Gets whether the given <paramref name="type"/> is a delegate type. /// </summary> public static bool IsDelegateType(this Type type) { Debug.Assert(type != null); return type.BaseType == typeof(MulticastDelegate); } public static bool IsMockable(this Type type) { return !type.IsSealed || type.IsDelegateType(); } public static bool IsTypeMatcher(this Type type) { return Attribute.IsDefined(type, typeof(TypeMatcherAttribute)); } public static bool IsTypeMatcher(this Type type, out Type typeMatcherType) { if (type.IsTypeMatcher()) { var attr = (TypeMatcherAttribute)Attribute.GetCustomAttribute(type, typeof(TypeMatcherAttribute)); typeMatcherType = attr.Type ?? type; Guard.ImplementsTypeMatcherProtocol(typeMatcherType); return true; } else { typeMatcherType = null; return false; } } public static bool ImplementsTypeMatcherProtocol(this Type type) { return typeof(ITypeMatcher).IsAssignableFrom(type) && type.CanCreateInstance(); } public static bool CanOverride(this MethodBase method) { return method.IsVirtual && !method.IsFinal && !method.IsPrivate; } public static bool CanOverrideGet(this PropertyInfo property) { return property.CanRead(out var getter) && getter.CanOverride(); } public static bool CanOverrideSet(this PropertyInfo property) { return property.CanWrite(out var setter) && setter.CanOverride(); } public static IEnumerable<MethodInfo> GetMethods(this Type type, string name) { return type.GetMember(name).OfType<MethodInfo>(); } public static bool CompareTo<TTypes, TOtherTypes>(this TTypes types, TOtherTypes otherTypes, bool exact, bool considerTypeMatchers) where TTypes : IReadOnlyList<Type> where TOtherTypes : IReadOnlyList<Type> { var count = otherTypes.Count; if (types.Count != count) { return false; } for (int i = 0; i < count; ++i) { if (considerTypeMatchers && types[i].IsTypeMatcher(out var typeMatcherType)) { Debug.Assert(typeMatcherType.ImplementsTypeMatcherProtocol()); var typeMatcher = (ITypeMatcher)Activator.CreateInstance(typeMatcherType); if (typeMatcher.Matches(otherTypes[i]) == false) { return false; } } else if (exact) { if (types[i] != otherTypes[i]) { return false; } } else { if (types[i].IsAssignableFrom(otherTypes[i]) == false) { return false; } } } return true; } public static string GetParameterTypeList(this MethodInfo method) { return new StringBuilder().AppendCommaSeparated(method.GetParameters(), StringBuilderExtensions.AppendParameterType).ToString(); } public static ParameterTypes GetParameterTypes(this MethodInfo method) { return new ParameterTypes(method.GetParameters()); } public static bool CompareParameterTypesTo<TOtherTypes>(this Delegate function, TOtherTypes otherTypes) where TOtherTypes : IReadOnlyList<Type> { var method = function.GetMethodInfo(); if (method.GetParameterTypes().CompareTo(otherTypes, exact: false, considerTypeMatchers: false)) { // the backing method for the literal delegate is compatible, DynamicInvoke(...) will succeed return true; } // it's possible for the .Method property (backing method for a delegate) to have // differing parameter types than the actual delegate signature. This occurs in C# when // an instance delegate invocation is created for an extension method (bundled with a receiver) // or at times for DLR code generation paths because the CLR is optimized for instance methods. var invokeMethod = GetInvokeMethodFromUntypedDelegateCallback(function); if (invokeMethod != null && invokeMethod.GetParameterTypes().CompareTo(otherTypes, exact: false, considerTypeMatchers: false)) { // the Invoke(...) method is compatible instead. DynamicInvoke(...) will succeed. return true; } // Neither the literal backing field of the delegate was compatible // nor the delegate invoke signature. return false; } private static MethodInfo GetInvokeMethodFromUntypedDelegateCallback(Delegate callback) { // Section 8.9.3 of 4th Ed ECMA 335 CLI spec requires delegates to have an 'Invoke' method. // However, there is not a requirement for 'public', or for it to be unambiguous. try { return callback.GetType().GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } catch (AmbiguousMatchException) { return null; } } public static Setup TryFind(this IEnumerable<Setup> setups, InvocationShape expectation) { return setups.FirstOrDefault(setup => setup.Expectation.Equals(expectation)); } public static Setup TryFind(this IEnumerable<Setup> setups, Invocation invocation) { return setups.FirstOrDefault(setup => setup.Matches(invocation)); } } }
// 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.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InvertIf { // [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InvertIf)] internal partial class InvertIfCodeRefactoringProvider : CodeRefactoringProvider { private static readonly Dictionary<SyntaxKind, Tuple<SyntaxKind, SyntaxKind>> s_binaryMap = new Dictionary<SyntaxKind, Tuple<SyntaxKind, SyntaxKind>>(SyntaxFacts.EqualityComparer) { { SyntaxKind.EqualsExpression, Tuple.Create(SyntaxKind.NotEqualsExpression, SyntaxKind.ExclamationEqualsToken) }, { SyntaxKind.NotEqualsExpression, Tuple.Create(SyntaxKind.EqualsExpression, SyntaxKind.EqualsEqualsToken) }, { SyntaxKind.LessThanExpression, Tuple.Create(SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.GreaterThanEqualsToken) }, { SyntaxKind.LessThanOrEqualExpression, Tuple.Create(SyntaxKind.GreaterThanExpression, SyntaxKind.GreaterThanToken) }, { SyntaxKind.GreaterThanExpression, Tuple.Create(SyntaxKind.LessThanOrEqualExpression, SyntaxKind.LessThanEqualsToken) }, { SyntaxKind.GreaterThanOrEqualExpression, Tuple.Create(SyntaxKind.LessThanExpression, SyntaxKind.LessThanToken) }, }; public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; var textSpan = context.Span; var cancellationToken = context.CancellationToken; if (!textSpan.IsEmpty) { return; } if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var ifStatement = root.FindToken(textSpan.Start).GetAncestor<IfStatementSyntax>(); if (ifStatement == null || ifStatement.Else == null) { return; } if (!ifStatement.IfKeyword.Span.IntersectsWith(textSpan.Start)) { return; } if (ifStatement.OverlapsHiddenPosition(cancellationToken)) { return; } context.RegisterRefactoring( new MyCodeAction( CSharpFeaturesResources.InvertIfStatement, (c) => InvertIfAsync(document, ifStatement, c))); } private async Task<Document> InvertIfAsync(Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var ifNode = ifStatement; // In the case that the else clause is actually an else if clause, place the if // statement to be moved in a new block in order to make sure that the else // statement matches the right if statement after the edit. var newIfNodeStatement = ifNode.Else.Statement.Kind() == SyntaxKind.IfStatement ? SyntaxFactory.Block(ifNode.Else.Statement) : ifNode.Else.Statement; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var invertedIf = ifNode.WithCondition(Negate(ifNode.Condition, semanticModel, cancellationToken)) .WithStatement(newIfNodeStatement) .WithElse(ifNode.Else.WithStatement(ifNode.Statement)) .WithAdditionalAnnotations(Formatter.Annotation); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var result = root.ReplaceNode(ifNode, invertedIf); return document.WithSyntaxRoot(result); } private bool IsComparisonOfZeroAndSomethingNeverLessThanZero(BinaryExpressionSyntax binaryExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { var canSimplify = false; if (binaryExpression.Kind() == SyntaxKind.GreaterThanExpression && binaryExpression.Right.Kind() == SyntaxKind.NumericLiteralExpression) { canSimplify = CanSimplifyToLengthEqualsZeroExpression( binaryExpression.Left, (LiteralExpressionSyntax)binaryExpression.Right, semanticModel, cancellationToken); } else if (binaryExpression.Kind() == SyntaxKind.LessThanExpression && binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression) { canSimplify = CanSimplifyToLengthEqualsZeroExpression( binaryExpression.Right, (LiteralExpressionSyntax)binaryExpression.Left, semanticModel, cancellationToken); } else if (binaryExpression.Kind() == SyntaxKind.EqualsExpression && binaryExpression.Right.Kind() == SyntaxKind.NumericLiteralExpression) { canSimplify = CanSimplifyToLengthEqualsZeroExpression( binaryExpression.Left, (LiteralExpressionSyntax)binaryExpression.Right, semanticModel, cancellationToken); } else if (binaryExpression.Kind() == SyntaxKind.EqualsExpression && binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression) { canSimplify = CanSimplifyToLengthEqualsZeroExpression( binaryExpression.Right, (LiteralExpressionSyntax)binaryExpression.Left, semanticModel, cancellationToken); } return canSimplify; } private bool CanSimplifyToLengthEqualsZeroExpression( ExpressionSyntax variableExpression, LiteralExpressionSyntax numericLiteralExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { var numericValue = semanticModel.GetConstantValue(numericLiteralExpression, cancellationToken); if (numericValue.HasValue && numericValue.Value is int && (int)numericValue.Value == 0) { var symbol = semanticModel.GetSymbolInfo(variableExpression, cancellationToken).Symbol; if (symbol != null && (symbol.Name == "Length" || symbol.Name == "LongLength")) { var containingType = symbol.ContainingType; if (containingType != null && (containingType.SpecialType == SpecialType.System_Array || containingType.SpecialType == SpecialType.System_String)) { return true; } } var typeInfo = semanticModel.GetTypeInfo(variableExpression, cancellationToken); if (typeInfo.Type != null) { switch (typeInfo.Type.SpecialType) { case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return true; } } } return false; } private bool TryNegateBinaryComparisonExpression( ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken, out ExpressionSyntax result) { Tuple<SyntaxKind, SyntaxKind> tuple; if (s_binaryMap.TryGetValue(expression.Kind(), out tuple)) { var binaryExpression = (BinaryExpressionSyntax)expression; var expressionType = tuple.Item1; var operatorType = tuple.Item2; // Special case negating Length > 0 to Length == 0 and 0 < Length to 0 == Length // for arrays and strings. We can do this because we know that Length cannot be // less than 0. Additionally, if we find Length == 0 or 0 == Length, we'll invert // it to Length > 0 or 0 < Length, respectively. if (IsComparisonOfZeroAndSomethingNeverLessThanZero(binaryExpression, semanticModel, cancellationToken)) { operatorType = binaryExpression.OperatorToken.Kind() == SyntaxKind.EqualsEqualsToken ? binaryExpression.Right is LiteralExpressionSyntax ? SyntaxKind.GreaterThanToken : SyntaxKind.LessThanToken : SyntaxKind.EqualsEqualsToken; expressionType = binaryExpression.Kind() == SyntaxKind.EqualsExpression ? binaryExpression.Right is LiteralExpressionSyntax ? SyntaxKind.GreaterThanExpression : SyntaxKind.LessThanExpression : SyntaxKind.EqualsExpression; } result = SyntaxFactory.BinaryExpression( expressionType, binaryExpression.Left, SyntaxFactory.Token( binaryExpression.OperatorToken.LeadingTrivia, operatorType, binaryExpression.OperatorToken.TrailingTrivia), binaryExpression.Right); return true; } result = null; return false; } private ExpressionSyntax Negate(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { ExpressionSyntax result; if (TryNegateBinaryComparisonExpression(expression, semanticModel, cancellationToken, out result)) { return result; } switch (expression.Kind()) { case SyntaxKind.ParenthesizedExpression: { var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; return parenthesizedExpression .WithExpression(Negate(parenthesizedExpression.Expression, semanticModel, cancellationToken)) .WithAdditionalAnnotations(Simplifier.Annotation); } case SyntaxKind.LogicalNotExpression: { var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression; var notToken = logicalNotExpression.OperatorToken; var nextToken = logicalNotExpression.Operand.GetFirstToken( includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); var existingTrivia = SyntaxFactory.TriviaList( notToken.LeadingTrivia.Concat( notToken.TrailingTrivia.Concat( nextToken.LeadingTrivia))); var updatedNextToken = nextToken.WithLeadingTrivia(existingTrivia); return logicalNotExpression.Operand.ReplaceToken( nextToken, updatedNextToken); } case SyntaxKind.LogicalOrExpression: { var binaryExpression = (BinaryExpressionSyntax)expression; result = SyntaxFactory.BinaryExpression( SyntaxKind.LogicalAndExpression, Negate(binaryExpression.Left, semanticModel, cancellationToken), SyntaxFactory.Token( binaryExpression.OperatorToken.LeadingTrivia, SyntaxKind.AmpersandAmpersandToken, binaryExpression.OperatorToken.TrailingTrivia), Negate(binaryExpression.Right, semanticModel, cancellationToken)); return result .Parenthesize() .WithLeadingTrivia(binaryExpression.GetLeadingTrivia()) .WithTrailingTrivia(binaryExpression.GetTrailingTrivia()); } case SyntaxKind.LogicalAndExpression: { var binaryExpression = (BinaryExpressionSyntax)expression; result = SyntaxFactory.BinaryExpression( SyntaxKind.LogicalOrExpression, Negate(binaryExpression.Left, semanticModel, cancellationToken), SyntaxFactory.Token( binaryExpression.OperatorToken.LeadingTrivia, SyntaxKind.BarBarToken, binaryExpression.OperatorToken.TrailingTrivia), Negate(binaryExpression.Right, semanticModel, cancellationToken)); return result .Parenthesize() .WithLeadingTrivia(binaryExpression.GetLeadingTrivia()) .WithTrailingTrivia(binaryExpression.GetTrailingTrivia()); } case SyntaxKind.TrueLiteralExpression: { var literalExpression = (LiteralExpressionSyntax)expression; return SyntaxFactory.LiteralExpression( SyntaxKind.FalseLiteralExpression, SyntaxFactory.Token( literalExpression.Token.LeadingTrivia, SyntaxKind.FalseKeyword, literalExpression.Token.TrailingTrivia)); } case SyntaxKind.FalseLiteralExpression: { var literalExpression = (LiteralExpressionSyntax)expression; return SyntaxFactory.LiteralExpression( SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token( literalExpression.Token.LeadingTrivia, SyntaxKind.TrueKeyword, literalExpression.Token.TrailingTrivia)); } } // Anything else we can just negate by adding a ! in front of the parenthesized expression. // Unnecessary parentheses will get removed by the simplification service. return SyntaxFactory.PrefixUnaryExpression( SyntaxKind.LogicalNotExpression, expression.Parenthesize()); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument) { } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Prediction API Version v1.4 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/prediction/docs/developer-guide'>Prediction API</a> * <tr><th>API Version<td>v1.4 * <tr><th>API Rev<td>20160304 (428) * <tr><th>API Docs * <td><a href='https://developers.google.com/prediction/docs/developer-guide'> * https://developers.google.com/prediction/docs/developer-guide</a> * <tr><th>Discovery Name<td>prediction * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Prediction API can be found at * <a href='https://developers.google.com/prediction/docs/developer-guide'>https://developers.google.com/prediction/docs/developer-guide</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Prediction.v1_4 { /// <summary>The Prediction Service.</summary> public class PredictionService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1.4"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PredictionService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PredictionService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { hostedmodels = new HostedmodelsResource(this); trainedmodels = new TrainedmodelsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "prediction"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/prediction/v1.4/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "prediction/v1.4/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Prediction API.</summary> public class Scope { /// <summary>Manage your data and permissions in Google Cloud Storage</summary> public static string DevstorageFullControl = "https://www.googleapis.com/auth/devstorage.full_control"; /// <summary>View your data in Google Cloud Storage</summary> public static string DevstorageReadOnly = "https://www.googleapis.com/auth/devstorage.read_only"; /// <summary>Manage your data in Google Cloud Storage</summary> public static string DevstorageReadWrite = "https://www.googleapis.com/auth/devstorage.read_write"; /// <summary>Manage your data in the Google Prediction API</summary> public static string Prediction = "https://www.googleapis.com/auth/prediction"; } private readonly HostedmodelsResource hostedmodels; /// <summary>Gets the Hostedmodels resource.</summary> public virtual HostedmodelsResource Hostedmodels { get { return hostedmodels; } } private readonly TrainedmodelsResource trainedmodels; /// <summary>Gets the Trainedmodels resource.</summary> public virtual TrainedmodelsResource Trainedmodels { get { return trainedmodels; } } } ///<summary>A base abstract class for Prediction requests.</summary> public abstract class PredictionBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PredictionBaseServiceRequest instance.</summary> protected PredictionBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Prediction parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "hostedmodels" collection of methods.</summary> public class HostedmodelsResource { private const string Resource = "hostedmodels"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public HostedmodelsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Submit input and request an output against a hosted model.</summary> /// <param name="body">The body of the request.</param> /// <param name="hostedModelName">The name of a hosted model.</param> public virtual PredictRequest Predict(Google.Apis.Prediction.v1_4.Data.Input body, string hostedModelName) { return new PredictRequest(service, body, hostedModelName); } /// <summary>Submit input and request an output against a hosted model.</summary> public class PredictRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_4.Data.Output> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_4.Data.Input body, string hostedModelName) : base(service) { HostedModelName = hostedModelName; Body = body; InitParameters(); } /// <summary>The name of a hosted model.</summary> [Google.Apis.Util.RequestParameterAttribute("hostedModelName", Google.Apis.Util.RequestParameterType.Path)] public virtual string HostedModelName { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_4.Data.Input Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "predict"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "hostedmodels/{hostedModelName}/predict"; } } /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "hostedModelName", new Google.Apis.Discovery.Parameter { Name = "hostedModelName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "trainedmodels" collection of methods.</summary> public class TrainedmodelsResource { private const string Resource = "trainedmodels"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TrainedmodelsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Delete a trained model.</summary> /// <param name="id">The unique name for the predictive model.</param> public virtual DeleteRequest Delete(string id) { return new DeleteRequest(service, id); } /// <summary>Delete a trained model.</summary> public class DeleteRequest : PredictionBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string id) : base(service) { Id = id; InitParameters(); } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "trainedmodels/{id}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Check training status of your model.</summary> /// <param name="id">The unique name for the predictive model.</param> public virtual GetRequest Get(string id) { return new GetRequest(service, id); } /// <summary>Check training status of your model.</summary> public class GetRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_4.Data.Training> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string id) : base(service) { Id = id; InitParameters(); } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "trainedmodels/{id}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Begin training your model.</summary> /// <param name="body">The body of the request.</param> public virtual InsertRequest Insert(Google.Apis.Prediction.v1_4.Data.Training body) { return new InsertRequest(service, body); } /// <summary>Begin training your model.</summary> public class InsertRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_4.Data.Training> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_4.Data.Training body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_4.Data.Training Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "trainedmodels"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Submit model id and request a prediction</summary> /// <param name="body">The body of the request.</param> /// <param name="id">The unique name for the predictive model.</param> public virtual PredictRequest Predict(Google.Apis.Prediction.v1_4.Data.Input body, string id) { return new PredictRequest(service, body, id); } /// <summary>Submit model id and request a prediction</summary> public class PredictRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_4.Data.Output> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_4.Data.Input body, string id) : base(service) { Id = id; Body = body; InitParameters(); } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_4.Data.Input Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "predict"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "trainedmodels/{id}/predict"; } } /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Add new data to a trained model.</summary> /// <param name="body">The body of the request.</param> /// <param name="id">The unique name for the predictive model.</param> public virtual UpdateRequest Update(Google.Apis.Prediction.v1_4.Data.Update body, string id) { return new UpdateRequest(service, body, id); } /// <summary>Add new data to a trained model.</summary> public class UpdateRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_4.Data.Training> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_4.Data.Update body, string id) : base(service) { Id = id; Body = body; InitParameters(); } /// <summary>The unique name for the predictive model.</summary> [Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)] public virtual string Id { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_4.Data.Update Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "trainedmodels/{id}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "id", new Google.Apis.Discovery.Parameter { Name = "id", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Prediction.v1_4.Data { public class Input : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input to the model for a prediction</summary> [Newtonsoft.Json.JsonPropertyAttribute("input")] public virtual Input.InputData InputValue { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Input to the model for a prediction</summary> public class InputData { /// <summary>A list of input features, these can be strings or doubles.</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } } } public class Output : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The most likely class label [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputLabel")] public virtual string OutputLabel { get; set; } /// <summary>A list of class labels with their estimated probabilities [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputMulti")] public virtual System.Collections.Generic.IList<Output.OutputMultiData> OutputMulti { get; set; } /// <summary>The estimated regression value [Regression models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputValue")] public virtual System.Nullable<double> OutputValue { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class OutputMultiData { /// <summary>The class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("label")] public virtual string Label { get; set; } /// <summary>The probability of the class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<double> Score { get; set; } } } public class Training : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Data Analysis.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dataAnalysis")] public virtual Training.DataAnalysisData DataAnalysis { get; set; } /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Model metadata.</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelInfo")] public virtual Training.ModelInfoData ModelInfo { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>Google storage location of the training data file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storageDataLocation")] public virtual string StorageDataLocation { get; set; } /// <summary>Google storage location of the preprocessing pmml file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storagePMMLLocation")] public virtual string StoragePMMLLocation { get; set; } /// <summary>Google storage location of the pmml model file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("storagePMMLModelLocation")] public virtual string StoragePMMLModelLocation { get; set; } /// <summary>The current status of the training job. This can be one of following: RUNNING; DONE; ERROR; ERROR: /// TRAINING JOB NOT FOUND</summary> [Newtonsoft.Json.JsonPropertyAttribute("trainingStatus")] public virtual string TrainingStatus { get; set; } /// <summary>A class weighting function, which allows the importance weights for class labels to be specified /// [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("utility")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,System.Nullable<double>>> Utility { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Data Analysis.</summary> public class DataAnalysisData { [Newtonsoft.Json.JsonPropertyAttribute("warnings")] public virtual System.Collections.Generic.IList<string> Warnings { get; set; } } /// <summary>Model metadata.</summary> public class ModelInfoData { /// <summary>Estimated accuracy of model taking utility weights into account [Categorical models /// only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("classWeightedAccuracy")] public virtual System.Nullable<double> ClassWeightedAccuracy { get; set; } /// <summary>A number between 0.0 and 1.0, where 1.0 is 100% accurate. This is an estimate, based on the /// amount and quality of the training data, of the estimated prediction accuracy. You can use this is a /// guide to decide whether the results are accurate enough for your needs. This estimate will be more /// reliable if your real input data is similar to your training data [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("classificationAccuracy")] public virtual System.Nullable<double> ClassificationAccuracy { get; set; } /// <summary>An output confusion matrix. This shows an estimate for how this model will do in predictions. /// This is first indexed by the true class label. For each true class label, this provides a pair /// {predicted_label, count}, where count is the estimated number of times the model will predict the /// predicted label given the true label. Will not output if more then 100 classes [Categorical models /// only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("confusionMatrix")] public virtual System.Collections.Generic.IDictionary<string,System.Collections.Generic.IDictionary<string,System.Nullable<double>>> ConfusionMatrix { get; set; } /// <summary>A list of the confusion matrix row totals</summary> [Newtonsoft.Json.JsonPropertyAttribute("confusionMatrixRowTotals")] public virtual System.Collections.Generic.IDictionary<string,System.Nullable<double>> ConfusionMatrixRowTotals { get; set; } /// <summary>An estimated mean squared error. The can be used to measure the quality of the predicted model /// [Regression models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("meanSquaredError")] public virtual System.Nullable<double> MeanSquaredError { get; set; } /// <summary>Type of predictive model (CLASSIFICATION or REGRESSION)</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelType")] public virtual string ModelType { get; set; } /// <summary>Number of valid data instances used in the trained model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberInstances")] public virtual System.Nullable<long> NumberInstances { get; set; } /// <summary>Number of class labels in the trained model [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberLabels")] public virtual System.Nullable<long> NumberLabels { get; set; } } } public class Update : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The input features for this instance</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } /// <summary>The class label of this instance</summary> [Newtonsoft.Json.JsonPropertyAttribute("label")] public virtual string Label { get; set; } /// <summary>The generic output value - could be regression value or class label</summary> [Newtonsoft.Json.JsonPropertyAttribute("output")] public virtual string Output { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Docuverse.Identicon { /// <summary> /// Code borrowed from http://identicon.codeplex.com/ /// </summary> public class IdenticonRenderer { // Each "patch" in an Identicon is a polygon created from a list of vertices on a 5 by 5 grid. // Vertices are numbered from 0 to 24, starting from top-left corner of // the grid, moving left to right and top to bottom. private const int MaxSize = 128; private const int MinSize = 16; private const int PatchCells = 4; private const int PatchGrids = PatchCells + 1; private const byte PatchInverted = 2; private const byte PatchSymmetric = 1; private static readonly int[] CenterPatchTypes = new[] {0, 4, 8, 15}; private static readonly byte[] Patch0 = new byte[] {0, 4, 24, 20, 0}; private static readonly byte[] Patch1 = new byte[] {0, 4, 20, 0}; private static readonly byte[] Patch10 = new byte[] {0, 2, 12, 10, 0}; private static readonly byte[] Patch11 = new byte[] {10, 14, 22, 10}; private static readonly byte[] Patch12 = new byte[] {20, 12, 24, 20}; private static readonly byte[] Patch13 = new byte[] {10, 2, 12, 10}; private static readonly byte[] Patch14 = new byte[] {0, 2, 10, 0}; private static readonly byte[] Patch2 = new byte[] {2, 24, 20, 2}; private static readonly byte[] Patch3 = new byte[] {2, 10, 14, 22, 2}; private static readonly byte[] Patch4 = new byte[] {2, 14, 22, 10, 2}; private static readonly byte[] Patch5 = new byte[] {0, 14, 24, 22, 0}; private static readonly byte[] Patch6 = new byte[] {2, 24, 22, 13, 11, 22, 20, 2}; private static readonly byte[] Patch7 = new byte[] {0, 14, 22, 0}; private static readonly byte[] Patch8 = new byte[] {6, 8, 18, 16, 6}; private static readonly byte[] Patch9 = new byte[] {4, 20, 10, 12, 2, 4}; private static readonly byte[] PatchFlags = new byte[] { PatchSymmetric, 0, 0, 0, PatchSymmetric, 0, 0, 0, PatchSymmetric, 0, 0, 0, 0, 0, 0, (PatchSymmetric + PatchInverted) }; private static readonly byte[][] PatchTypes = new[] { Patch0, Patch1, Patch2, Patch3, Patch4, Patch5, Patch6, Patch7, Patch8, Patch9, Patch10, Patch11, Patch12, Patch13, Patch14, Patch0 }; private int _patchOffset; // used to center patch shape at origin because shape rotation works correctly. private GraphicsPath[] _patchShapes; /// <summary> /// The size in pixels at which each patch will be rendered interally before they /// are scaled down to the requested identicon size. Default size is 20 pixels /// which means, for 9-block identicon, a 60x60 image will be rendered and /// scaled down. /// </summary> public int PatchSize { get; set; } private IEnumerable<GraphicsPath> CalculatePatchShapes() { _patchOffset = PatchSize / 2; // used to center patch shape at origin. int scale = PatchSize / PatchCells; foreach(var patchVertices in PatchTypes) { var patch = new GraphicsPath(); foreach(int vertex in patchVertices) { int xVertex = (vertex % PatchGrids * scale) - _patchOffset; int yVertex = (vertex / PatchGrids * scale) - _patchOffset; AddPointToGraphicsPath(patch, xVertex, yVertex); } yield return patch; } } /// <summary> /// Adds the X and Y coordinates to the current graphics path. /// </summary> /// <param name="path"> The current Graphics path</param> /// <param name="x">The x coordinate to be added</param> /// <param name="y">The y coordinate to be added</param> private static void AddPointToGraphicsPath(GraphicsPath path, int x, int y) { // increment by one. var points = new PointF[path.PointCount + 1]; var pointTypes = new byte[path.PointCount + 1]; if(path.PointCount == 0) { points[0] = new PointF(x, y); var newPath = new GraphicsPath(points, new[] {(byte)PathPointType.Start}); path.AddPath(newPath, false); } else { path.PathPoints.CopyTo(points, 0); points[path.PointCount] = new Point(x, y); path.PathTypes.CopyTo(pointTypes, 0); pointTypes[path.PointCount] = (byte)PathPointType.Line; var tempGraphics = new GraphicsPath(points, pointTypes); path.Reset(); path.AddPath(tempGraphics, false); } } /// <summary> /// Returns rendered identicon bitmap for a given identicon code. /// </summary> /// <param name="code">Identicon code</param> /// <param name="size">desired image size</param> public Bitmap Render(int code, int size) { // enforce size limits size = Math.Min(size, MaxSize); size = Math.Max(size, MinSize); // set patch size appropriately to avoid scaling artifacts if(size <= 24) { PatchSize = 16; } else if(size <= 40) { PatchSize = 20; } else if(size <= 64) { PatchSize = 32; } else if(size <= 128) { PatchSize = 48; } _patchShapes = CalculatePatchShapes().ToArray(); // decode the code into parts: // bit 0-1: middle patch type int centerType = CenterPatchTypes[code & 0x3]; // bit 2: middle invert bool centerInvert = ((code >> 2) & 0x1) != 0; // bit 3-6: corner patch type int cornerType = (code >> 3) & 0x0f; // bit 7: corner invert bool cornerInvert = ((code >> 7) & 0x1) != 0; // bit 8-9: corner turns int cornerTurn = (code >> 8) & 0x3; // bit 10-13: side patch type int sideType = (code >> 10) & 0x0f; // bit 14: side invert bool sideInvert = ((code >> 14) & 0x1) != 0; // bit 15: corner turns int sideTurn = (code >> 15) & 0x3; // bit 16-20: blue color component int blue = (code >> 16) & 0x01f; // bit 21-26: green color component int green = (code >> 21) & 0x01f; // bit 27-31: red color component int red = (code >> 27) & 0x01f; // color components are used at top of the range for color difference // use white background for now. TODO: support transparency. Color foreColor = Color.FromArgb(red << 3, green << 3, blue << 3); Color backColor = Color.White; // outline shapes with a noticeable color (complementary will do) if // shape color and background color are too similar (measured by color // distance). Color strokeColor = Color.Empty; if(ColorDistance(ref foreColor, ref backColor) < 32f) { strokeColor = ComplementaryColor(ref foreColor); } // render at larger source size (to be scaled down later) int sourceSize = PatchSize * 3; using(var sourceImage = new Bitmap(sourceSize, sourceSize, PixelFormat.Format32bppRgb)) { using(Graphics graphics = Graphics.FromImage(sourceImage)) { // center patch DrawPatch(graphics, PatchSize, PatchSize, centerType, 0, centerInvert, ref foreColor, ref backColor, ref strokeColor); // side patch (top) DrawPatch(graphics, PatchSize, 0, sideType, sideTurn++, sideInvert, ref foreColor, ref backColor, ref strokeColor); // side patch (right) DrawPatch(graphics, PatchSize * 2, PatchSize, sideType, sideTurn++, sideInvert, ref foreColor, ref backColor, ref strokeColor); // side patch (bottom) DrawPatch(graphics, PatchSize, PatchSize * 2, sideType, sideTurn++, sideInvert, ref foreColor, ref backColor, ref strokeColor); // side patch (left) DrawPatch(graphics, 0, PatchSize, sideType, sideTurn, sideInvert, ref foreColor, ref backColor, ref strokeColor); // corner patch (top left) DrawPatch(graphics, 0, 0, cornerType, cornerTurn++, cornerInvert, ref foreColor, ref backColor, ref strokeColor); // corner patch (top right) DrawPatch(graphics, PatchSize * 2, 0, cornerType, cornerTurn++, cornerInvert, ref foreColor, ref backColor, ref strokeColor); // corner patch (bottom right) DrawPatch(graphics, PatchSize * 2, PatchSize * 2, cornerType, cornerTurn++, cornerInvert, ref foreColor, ref backColor, ref strokeColor); // corner patch (bottom left) DrawPatch(graphics, 0, PatchSize * 2, cornerType, cornerTurn, cornerInvert, ref foreColor, ref backColor, ref strokeColor); } // scale source image to target size with bicubic smoothing return ScaleImage(size, sourceImage); } } private static Bitmap ScaleImage(int size, Image sourceImage) { var bitmap = new Bitmap(size, size, PixelFormat.Format32bppRgb); using(Graphics g = Graphics.FromImage(bitmap)) { var fudge = (int)(size * 0.016); // this is necessary to prevent scaling artifacts at larger sizes g.DrawImage(sourceImage, 0, 0, size + fudge, size + fudge); } return bitmap; } private void DrawPatch(Graphics g, int x, int y, int patch, int turn, bool invert, ref Color fore, ref Color back, ref Color stroke) { patch %= PatchTypes.Length; turn %= 4; if((PatchFlags[patch] & PatchInverted) != 0) { invert = !invert; } // paint the background g.FillRegion(new SolidBrush(invert ? fore : back), new Region(new Rectangle(x, y, PatchSize, PatchSize))); // offset and rotate coordinate space by patch position (x, y) and // 'turn' before rendering patch shape Matrix m = g.Transform; g.TranslateTransform((x + _patchOffset), (y + _patchOffset)); g.RotateTransform(turn * 90); // if stroke color was specified, apply stroke // stroke color should be specified if fore color is too close to the back color. if(!stroke.IsEmpty) { g.DrawPath(new Pen(stroke), _patchShapes[patch]); } // render rotated patch using fore color (back color if inverted) g.FillPath(new SolidBrush(invert ? back : fore), _patchShapes[patch]); // restore previous rotation g.Transform = m; } /// <summary>Returns distance between two colors</summary> private static float ColorDistance(ref Color c1, ref Color c2) { float dx = c1.R - c2.R; float dy = c1.G - c2.G; float dz = c1.B - c2.B; return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz); } /// <summary>Returns complementary color</summary> private static Color ComplementaryColor(ref Color c) { return Color.FromArgb(c.ToArgb() ^ 0x00FFFFFF); } } }
using log4net; /* * Copyright (c) Contributors * 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 OpenSim 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 Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Scripting; using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Scripting.JsonStore { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "JsonStoreScriptModule")] public class JsonStoreScriptModule : INonSharedRegionModule { // ----------------------------------------------------------------- /// <summary> /// Convert a list of values that are path components to a single string path /// </summary> // ----------------------------------------------------------------- protected static Regex m_ArrayPattern = new Regex("^([0-9]+|\\+)$"); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IScriptModuleComms m_comms; private IConfig m_config = null; private bool m_enabled = false; private Scene m_scene = null; private Dictionary<UUID, HashSet<UUID>> m_scriptStores = new Dictionary<UUID, HashSet<UUID>>(); private IJsonStoreModule m_store; #region Region Module interface // ----------------------------------------------------------------- /// <summary> /// Name of this shared module is it's class name /// </summary> // ----------------------------------------------------------------- public string Name { get { return this.GetType().Name; } } /// ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public Type ReplaceableInterface { get { return null; } } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void AddRegion(Scene scene) { scene.EventManager.OnScriptReset += HandleScriptReset; scene.EventManager.OnRemoveScript += HandleScriptReset; } // ----------------------------------------------------------------- /// <summary> /// Nothing to do on close /// </summary> // ----------------------------------------------------------------- public void Close() { } // ----------------------------------------------------------------- /// <summary> /// Initialise this shared module /// </summary> /// <param name="scene">this region is getting initialised</param> /// <param name="source">nini config, we are not using this</param> // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { try { if ((m_config = config.Configs["JsonStore"]) == null) { // There is no configuration, the module is disabled // m_log.InfoFormat("[JsonStoreScripts] no configuration info"); return; } m_enabled = m_config.GetBoolean("Enabled", m_enabled); } catch (Exception e) { m_log.ErrorFormat("[JsonStoreScripts]: initialization error: {0}", e.Message); return; } if (m_enabled) m_log.DebugFormat("[JsonStoreScripts]: module is enabled"); } // ----------------------------------------------------------------- /// <summary> /// everything is loaded, perform post load configuration /// </summary> // ----------------------------------------------------------------- public void PostInitialise() { } // ----------------------------------------------------------------- /// <summary> /// Called when all modules have been added for a region. This is /// where we hook up events /// </summary> // ----------------------------------------------------------------- public void RegionLoaded(Scene scene) { if (m_enabled) { m_scene = scene; m_comms = m_scene.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) { m_log.ErrorFormat("[JsonStoreScripts]: ScriptModuleComms interface not defined"); m_enabled = false; return; } m_store = m_scene.RequestModuleInterface<IJsonStoreModule>(); if (m_store == null) { m_log.ErrorFormat("[JsonStoreScripts]: JsonModule interface not defined"); m_enabled = false; return; } try { m_comms.RegisterScriptInvocations(this); m_comms.RegisterConstants(this); } catch (Exception e) { // See http://opensimulator.org/mantis/view.php?id=5971 for more information m_log.WarnFormat("[JsonStoreScripts]: script method registration failed; {0}", e.Message); m_enabled = false; } } } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void RemoveRegion(Scene scene) { scene.EventManager.OnScriptReset -= HandleScriptReset; scene.EventManager.OnRemoveScript -= HandleScriptReset; // need to remove all references to the scene in the subscription // list to enable full garbage collection of the scene object } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- private void HandleScriptReset(uint localID, UUID itemID) { HashSet<UUID> stores; lock (m_scriptStores) { if (!m_scriptStores.TryGetValue(itemID, out stores)) return; m_scriptStores.Remove(itemID); } foreach (UUID id in stores) m_store.DestroyStore(id); } #endregion Region Module interface #region ScriptConstantsInterface [ScriptConstant] public static readonly int JSON_NODETYPE_ARRAY = (int)JsonStoreNodeType.Array; [ScriptConstant] public static readonly int JSON_NODETYPE_OBJECT = (int)JsonStoreNodeType.Object; [ScriptConstant] public static readonly int JSON_NODETYPE_UNDEF = (int)JsonStoreNodeType.Undefined; [ScriptConstant] public static readonly int JSON_NODETYPE_VALUE = (int)JsonStoreNodeType.Value; [ScriptConstant] public static readonly int JSON_VALUETYPE_BOOLEAN = (int)JsonStoreValueType.Boolean; [ScriptConstant] public static readonly int JSON_VALUETYPE_FLOAT = (int)JsonStoreValueType.Float; [ScriptConstant] public static readonly int JSON_VALUETYPE_INTEGER = (int)JsonStoreValueType.Integer; [ScriptConstant] public static readonly int JSON_VALUETYPE_STRING = (int)JsonStoreValueType.String; [ScriptConstant] public static readonly int JSON_VALUETYPE_UNDEF = (int)JsonStoreValueType.Undefined; #endregion ScriptConstantsInterface #region ScriptInvocationInteface // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonAttachObjectStore(UUID hostID, UUID scriptID) { UUID uuid = UUID.Zero; if (!m_store.AttachObjectStore(hostID)) GenerateRuntimeError("Failed to create Json store"); return hostID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonCreateStore(UUID hostID, UUID scriptID, string value) { UUID uuid = UUID.Zero; if (!m_store.CreateStore(value, ref uuid)) GenerateRuntimeError("Failed to create Json store"); lock (m_scriptStores) { if (!m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID] = new HashSet<UUID>(); m_scriptStores[scriptID].Add(uuid); } return uuid; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonDestroyStore(UUID hostID, UUID scriptID, UUID storeID) { lock (m_scriptStores) { if (m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID].Remove(storeID); } return m_store.DestroyStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetArrayLength(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.GetArrayLength(storeID, path); } [ScriptInvocation] public string JsonGetJson(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID, path, true, out value); return value; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetNodeType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetNodeType(storeID, path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonGetValue(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID, path, false, out value); return value; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetValueType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetValueType(storeID, path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonList2Path(UUID hostID, UUID scriptID, object[] pathlist) { string ipath = ConvertList2Path(pathlist); string opath; if (JsonStore.CanonicalPathExpression(ipath, out opath)) return opath; // This won't parse if passed to the other routines as opposed to // returning an empty string which is a valid path and would overwrite // the entire store return "**INVALID**"; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID reqID = UUID.Random(); Util.FireAndForget(o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier)); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonReadValue(scriptID, reqID, storeID, path, false); }); return reqID; } [ScriptInvocation] public UUID JsonReadValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonReadValue(scriptID, reqID, storeID, path, true); }); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonRemoveValue(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.RemoveValue(storeID, path) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonRezAtRoot(UUID hostID, UUID scriptID, string item, Vector3 pos, Vector3 vel, Quaternion rot, string param) { UUID reqID = UUID.Random(); Util.FireAndForget(o => DoJsonRezObject(hostID, scriptID, reqID, item, pos, vel, rot, param)); return reqID; } [ScriptInvocation] public int JsonSetJson(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID, path, value, true) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonSetValue(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID, path, value, false) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonTakeValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonTakeValue(scriptID, reqID, storeID, path, false); }); return reqID; } [ScriptInvocation] public UUID JsonTakeValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonTakeValue(scriptID, reqID, storeID, path, true); }); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonTestStore(UUID hostID, UUID scriptID, UUID storeID) { return m_store.TestStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonWriteNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string name) { UUID reqID = UUID.Random(); Util.FireAndForget(delegate(object o) { DoJsonWriteNotecard(reqID, hostID, scriptID, storeID, path, name); }); return reqID; } #endregion ScriptInvocationInteface // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void DispatchValue(UUID scriptID, UUID reqID, string value) { m_comms.DispatchReply(scriptID, 1, value, reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void GenerateRuntimeError(string msg) { m_log.InfoFormat("[JsonStore] runtime error: {0}", msg); throw new Exception("JsonStore Runtime Error: " + msg); } private string ConvertList2Path(object[] pathlist) { string path = ""; for (int i = 0; i < pathlist.Length; i++) { string token = ""; if (pathlist[i] is string) { token = pathlist[i].ToString(); // Check to see if this is a bare number which would not be a valid // identifier otherwise if (m_ArrayPattern.IsMatch(token)) token = '[' + token + ']'; } else if (pathlist[i] is int) { token = "[" + pathlist[i].ToString() + "]"; } else { token = "." + pathlist[i].ToString() + "."; } path += token + "."; } return path; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadNotecard( UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID assetID; if (!UUID.TryParse(notecardIdentifier, out assetID)) { SceneObjectPart part = m_scene.GetSceneObjectPart(hostID); assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard); } AssetBase a = m_scene.AssetService.Get(assetID.ToString()); if (a == null) GenerateRuntimeError(String.Format("Unable to find notecard asset {0}", assetID)); if (a.Type != (sbyte)AssetType.Notecard) GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID)); m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}", storeID); try { string jsondata = SLUtil.ParseNotecardToString(Encoding.UTF8.GetString(a.Data)); int result = m_store.SetValue(storeID, path, jsondata, true) ? 1 : 0; m_comms.DispatchReply(scriptID, result, "", reqID.ToString()); return; } catch (Exception e) { m_log.WarnFormat("[JsonStoreScripts]: Json parsing failed; {0}", e.Message); } GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID)); m_comms.DispatchReply(scriptID, 0, "", reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.ReadValue(storeID, path, useJson, delegate(string value) { DispatchValue(scriptID, reqID, value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}", e.ToString()); } DispatchValue(scriptID, reqID, String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param) { if (Double.IsNaN(rot.X) || Double.IsNaN(rot.Y) || Double.IsNaN(rot.Z) || Double.IsNaN(rot.W)) { GenerateRuntimeError("Invalid rez rotation"); return; } SceneObjectGroup host = m_scene.GetSceneObjectGroup(hostID); if (host == null) { GenerateRuntimeError(String.Format("Unable to find rezzing host '{0}'", hostID)); return; } // hpos = host.RootPart.GetWorldPosition() // float dist = (float)llVecDist(hpos, pos); // if (dist > m_ScriptDistanceFactor * 10.0f) // return; TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name); if (item == null) { GenerateRuntimeError(String.Format("Unable to find object to rez '{0}'", name)); return; } if (item.InvType != (int)InventoryType.Object) { GenerateRuntimeError("Can't create requested object; object is missing from database"); return; } List<SceneObjectGroup> objlist; List<Vector3> veclist; bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist); if (!success) { GenerateRuntimeError("Failed to create object"); return; } int totalPrims = 0; foreach (SceneObjectGroup group in objlist) totalPrims += group.PrimCount; if (!m_scene.Permissions.CanRezObject(totalPrims, item.OwnerID, pos)) { GenerateRuntimeError("Not allowed to create the object"); return; } if (!m_scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) host.RootPart.Inventory.RemoveInventoryItem(item.ItemID); } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup group = objlist[i]; Vector3 curpos = pos + veclist[i]; if (group.IsAttachment == false && group.RootPart.Shape.State != 0) { group.RootPart.AttachedPos = group.AbsolutePosition; group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } group.FromPartID = host.RootPart.UUID; m_scene.AddNewSceneObject(group, true, curpos, rot, vel); UUID storeID = group.UUID; if (!m_store.CreateStore(param, ref storeID)) { GenerateRuntimeError("Unable to create jsonstore for new object"); continue; } // We can only call this after adding the scene object, since the scene object references the scene // to find out if scripts should be activated at all. group.RootPart.SetDieAtEdge(true); group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3); group.ResumeScripts(); group.ScheduleGroupForFullUpdate(); // send the reply back to the host object, use the integer param to indicate the number // of remaining objects m_comms.DispatchReply(scriptID, objlist.Count - i - 1, group.RootPart.UUID.ToString(), reqID.ToString()); } } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.TakeValue(storeID, path, useJson, delegate(string value) { DispatchValue(scriptID, reqID, value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}", e.ToString()); } DispatchValue(scriptID, reqID, String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name) { string data; if (!m_store.GetValue(storeID, path, true, out data)) { m_comms.DispatchReply(scriptID, 0, UUID.Zero.ToString(), reqID.ToString()); return; } SceneObjectPart host = m_scene.GetSceneObjectPart(hostID); // Create new asset UUID assetID = UUID.Random(); AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString()); asset.Description = "Json store"; int textLength = data.Length; data = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + textLength.ToString() + "\n" + data + "}\n"; asset.Data = Util.UTF8.GetBytes(data); m_scene.AssetService.Store(asset); // Create Task Entry TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ResetIDs(host.UUID); taskItem.ParentID = host.UUID; taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch(); taskItem.Name = asset.Name; taskItem.Description = asset.Description; taskItem.Type = (int)AssetType.Notecard; taskItem.InvType = (int)InventoryType.Notecard; taskItem.OwnerID = host.OwnerID; taskItem.CreatorID = host.OwnerID; taskItem.BasePermissions = (uint)PermissionMask.All; taskItem.CurrentPermissions = (uint)PermissionMask.All; taskItem.EveryonePermissions = 0; taskItem.NextPermissions = (uint)PermissionMask.All; taskItem.GroupID = host.GroupID; taskItem.GroupPermissions = 0; taskItem.Flags = 0; taskItem.PermsGranter = UUID.Zero; taskItem.PermsMask = 0; taskItem.AssetID = asset.FullID; host.Inventory.AddInventoryItem(taskItem, false); m_comms.DispatchReply(scriptID, 1, assetID.ToString(), reqID.ToString()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.IO; namespace ProGauges { public partial class SmallLinearGauge : UserControl, ISupportInitialize { private PrivateFontCollection m_pfc = new PrivateFontCollection(); private Color m_BackGroundColor = Color.FromArgb(24, 24, 24); private bool m_bIsInitializing; private Rectangle rcentre; private int m_NumberOfDecimals = 0; public int NumberOfDecimals { get { return m_NumberOfDecimals; } set { m_NumberOfDecimals = value; } } private float m_MaxPeakHoldValue = float.MinValue; private bool m_ShowRanges = true; private System.Timers.Timer peakholdtimer = new System.Timers.Timer(); [Browsable(true), Category("SmallLinearGauge"), Description("Toggles ranges display on/off"), DefaultValue(typeof(bool), "true")] public bool ShowRanges { get { return m_ShowRanges; } set { if (m_ShowRanges != value) { m_ShowRanges = value; base.Invalidate(); } } } private bool m_ShowValue = true; [Browsable(true), Category("SmallLinearGauge"), Description("Toggles value display on/off"), DefaultValue(typeof(bool), "true")] public bool ShowValue { get { return m_ShowValue; } set { if (m_ShowValue != value) { m_ShowValue = value; base.Invalidate(); } } } private bool m_ShowValueInPercentage = false; [Browsable(true), Category("SmallLinearGauge"), Description("Toggles value display from actual values to percentage"), DefaultValue(typeof(bool), "false")] public bool ShowValueInPercentage { get { return m_ShowValueInPercentage; } set { if (m_ShowValueInPercentage != value) { m_ShowValueInPercentage = value; base.Invalidate(); } } } private string m_gaugeText = "Linear gauge"; [Browsable(true), Category("SmallLinearGauge"), Description("Sets the text for the gauge"), DefaultValue(typeof(bool), "Linear gauge")] public string GaugeText { get { return m_gaugeText; } set { if (m_gaugeText != value) { m_gaugeText = value; base.Invalidate(); } } } private string m_gaugeUnits = "units"; [Browsable(true), Category("SmallLinearGauge"), Description("Sets the units for the gauge"), DefaultValue(typeof(bool), "units")] public string GaugeUnits { get { return m_gaugeUnits; } set { if (m_gaugeUnits != value) { m_gaugeUnits = value; base.Invalidate(); } } } [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge background color"), DefaultValue(typeof(Color), "System.Drawing.Color.Black")] public Color BackGroundColor { get { return m_BackGroundColor; } set { m_BackGroundColor = value; base.Invalidate(); } } private Color m_BevelLineColor = Color.Gray; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge bevel color"), DefaultValue(typeof(Color), "System.Drawing.Color.Gray")] public Color BevelLineColor { get { return m_BevelLineColor; } set { m_BevelLineColor = value; base.Invalidate(); } } private int m_peakholdOpaque = 0; private float m_value = 0; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge value"), DefaultValue(typeof(float), "0")] public float Value { get { return m_value; } set { if (m_value != value) { m_value = value; base.Invalidate(); } if (m_value > m_MaxPeakHoldValue) { m_MaxPeakHoldValue = m_value; m_peakholdOpaque = 255; } } } private float m_recommendedValue = 25; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge recommended value"), DefaultValue(typeof(float), "25")] public float RecommendedValue { get { return m_recommendedValue; } set { if (m_recommendedValue != value) { m_recommendedValue = value; base.Invalidate(); } } } private int m_recommendedPercentage = 10; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge recommended percentage"), DefaultValue(typeof(int), "10")] public int RecommendedPercentage { get { return m_recommendedPercentage; } set { if (m_recommendedPercentage != value) { m_recommendedPercentage = value; base.Invalidate(); } } } private float m_thresholdValue = 90; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge threshold value"), DefaultValue(typeof(float), "90")] public float ThresholdValue { get { return m_thresholdValue; } set { if (m_thresholdValue != value) { m_thresholdValue = value; base.Invalidate(); } } } private float m_maxValue = 100; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge maximum scale value"), DefaultValue(typeof(float), "100")] public float MaxValue { get { return m_maxValue; } set { if (m_maxValue != value) { m_maxValue = value; base.Invalidate(); } } } private float m_minValue = 0; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge minimum scale value"), DefaultValue(typeof(float), "0")] public float MinValue { get { return m_minValue; } set { if (m_minValue != value) { m_minValue = value; base.Invalidate(); } } } private void LoadFont() { Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("ProGauges.Eurostile.ttf"); if (fontStream != null) { byte[] fontdata = new byte[fontStream.Length]; fontStream.Read(fontdata, 0, (int)fontStream.Length); fontStream.Close(); unsafe { fixed (byte* pFontData = fontdata) { m_pfc.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length); } } } else { throw new Exception("Font could not be found"); } } public SmallLinearGauge() { InitializeComponent(); base.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); base.SetStyle(ControlStyles.SupportsTransparentBackColor, true); peakholdtimer.Interval = 50; peakholdtimer.Elapsed += new System.Timers.ElapsedEventHandler(peakholdtimer_Elapsed); peakholdtimer.Start(); GetCenterRectangle(); try { LoadFont(); System.Drawing.Font fn; foreach (FontFamily ff in m_pfc.Families) { this.Font = fn = new Font(ff, 10, FontStyle.Bold); } } catch (Exception E) { Console.WriteLine(E.Message); } } void peakholdtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (m_peakholdOpaque > 0) m_peakholdOpaque--; else { m_MaxPeakHoldValue = float.MinValue; } } void ISupportInitialize.BeginInit() { this.m_bIsInitializing = true; } void ISupportInitialize.EndInit() { this.m_bIsInitializing = false; base.Invalidate(); } protected override void OnPaintBackground(PaintEventArgs pevent) { if (!this.IsDisposed) { base.OnPaintBackground(pevent); } } protected override void OnSizeChanged(EventArgs e) { if (!this.IsDisposed) { base.OnSizeChanged(e); } } protected override void OnPaint(PaintEventArgs e) { if (!this.IsDisposed) { Graphics g = e.Graphics; //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.AntiAlias; this.DrawBackground(g); /*if ((base.ClientRectangle.Height >= 85) && (base.ClientRectangle.Width >= 85)) { this.DrawNumbers(g); this.DrawText(g); }*/ this.DrawScale(g); //this.DrawRanges(g); this.DrawHighlight(g); } //g.Dispose(); } private bool m_bShowHighlight = true; [Browsable(true), Category("SmallLinearGauge"), Description("Switches highlighting of the gauge on and off"), DefaultValue(typeof(bool), "true")] public bool ShowHighlight { get { return m_bShowHighlight; } set { if (m_bShowHighlight != value) { m_bShowHighlight = value; base.Invalidate(); } } } private byte m_nHighlightOpaqueEnd = 30; [DefaultValue(50), Browsable(true), Category("SmallLinearGauge"), Description("Set the opaque value of the highlight")] public byte HighlightOpaqueEnd { get { return this.m_nHighlightOpaqueEnd; } set { if (value > 100) { throw new ArgumentException("This value should be between 0 and 50"); } if (this.m_nHighlightOpaqueEnd != value) { this.m_nHighlightOpaqueEnd = value; //if (!this.m_bIsInitializing) //{ base.Invalidate(); //} } } } private byte m_nHighlightOpaqueStart = 100; [DefaultValue(100), Browsable(true), Category("SmallLinearGauge"), Description("Set the opaque start value of the highlight")] public byte HighlightOpaqueStart { get { return this.m_nHighlightOpaqueStart; } set { if (value > 255) { throw new ArgumentException("This value should be between 0 and 50"); } if (this.m_nHighlightOpaqueStart != value) { this.m_nHighlightOpaqueStart = value; //if (!this.m_bIsInitializing) //{ base.Invalidate(); //} } } } private void DrawHighlight(Graphics g) { if (this.m_bShowHighlight) { Rectangle clientRectangle = base.ClientRectangle; clientRectangle.Height = clientRectangle.Height >> 1; clientRectangle.Inflate(-2, -2); Color color = Color.FromArgb(this.m_nHighlightOpaqueStart, 0xff, 0xff, 0xff); Color color2 = Color.FromArgb(this.m_nHighlightOpaqueEnd, 0xff, 0xff, 0xff); this.DrawRoundRect(g, clientRectangle, /*((this.m_nCornerRadius - 1) > 1) ? ((float)(this.m_nCornerRadius - 1)) :*/ ((float)1), color, color2, Color.Empty, 0, true, false); } else { /*Rectangle clientRectangle = base.ClientRectangle; clientRectangle.Height = clientRectangle.Height >> 1; clientRectangle.Inflate(-2, -2); Color color = Color.FromArgb(100, 0xff, 0xff, 0xff); Color color2 = Color.FromArgb(this.m_nHighlightOpaque, 0xff, 0xff, 0xff); Brush backGroundBrush = new SolidBrush(Color.FromArgb(120, Color.Silver)); g.FillEllipse(backGroundBrush, clientRectangle);*/ } } private void DrawRoundRect(Graphics g, Rectangle rect, float radius, Color col1, Color col2, Color colBorder, int nBorderWidth, bool bGradient, bool bDrawBorder) { GraphicsPath path = new GraphicsPath(); float width = radius + radius; RectangleF ef = new RectangleF(0f, 0f, width, width); Brush brush = null; ef.X = rect.Left; ef.Y = rect.Top; path.AddArc(ef, 180f, 90f); ef.X = (rect.Right - 1) - width; path.AddArc(ef, 270f, 90f); ef.Y = (rect.Bottom - 1) - width; path.AddArc(ef, 0f, 90f); ef.X = rect.Left; path.AddArc(ef, 90f, 90f); path.CloseFigure(); if (bGradient) { brush = new LinearGradientBrush(rect, col1, col2, 90f, false); } else { brush = new SolidBrush(col1); } //g.SmoothingMode = SmoothingMode.AntiAlias; g.FillPath(brush, path); if (/*bDrawBorder*/ true) { Pen pen = new Pen(colBorder); pen.Width = nBorderWidth; g.DrawPath(pen, path); pen.Dispose(); } g.SmoothingMode = SmoothingMode.None; brush.Dispose(); path.Dispose(); } private Color m_recommendedRangeColor = Color.LawnGreen; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge recommended range color"), DefaultValue(typeof(Color), "System.Drawing.Color.LawnGreen")] public Color RecommendedRangeColor { get { return m_recommendedRangeColor; } set { if (m_recommendedRangeColor != value) { m_recommendedRangeColor = value; base.Invalidate(); } } } private Color m_thresholdColor = Color.Firebrick; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge recommended range color"), DefaultValue(typeof(Color), "System.Drawing.Color.Firebrick")] public Color ThresholdColor { get { return m_thresholdColor; } set { if (m_thresholdColor != value) { m_thresholdColor = value; base.Invalidate(); } } } private Color m_startColor = Color.GreenYellow; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge start color"), DefaultValue(typeof(Color), "System.Drawing.Color.GreenYellow")] public Color StartColor { get { return m_startColor; } set { if (m_startColor != value) { m_startColor = value; base.Invalidate(); } } } private Color m_endColor = Color.OrangeRed; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge end color"), DefaultValue(typeof(Color), "System.Drawing.Color.OrangeRed")] public Color EndColor { get { return m_endColor; } set { if (m_endColor != value) { m_endColor = value; base.Invalidate(); } } } private int m_alphaForGaugeColors = 180; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge alpha value for the gauge colored bar"), DefaultValue(typeof(int), "180")] public int AlphaForGaugeColors { get { return (m_alphaForGaugeColors * 100) / 255; } set { int realvalue = value * 255 / 100; if (m_alphaForGaugeColors != realvalue) { m_alphaForGaugeColors = realvalue; base.Invalidate(); } } } /// <summary> /// Draws the recommended and threshold ranges on the gauge /// </summary> /// <param name="g"></param> private void DrawRanges(Graphics g) { if (m_ShowRanges) { // draw recommended range Pen p = new Pen(Color.FromArgb(m_alphaForGaugeColors, m_BevelLineColor)); float range = m_maxValue - m_minValue; Rectangle scalerect = new Rectangle(rcentre.X, rcentre.Y + rcentre.Height + 1, rcentre.Width, 6); //scalerect.Inflate(-1, -1); if (m_recommendedValue >= m_minValue && m_recommendedValue < m_maxValue) { // calculate range based on percentage // percentage = percentage of entire scale! System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(scalerect, m_BackGroundColor, m_recommendedRangeColor, System.Drawing.Drawing2D.LinearGradientMode.Vertical); float centerpercentage = (m_recommendedValue - m_minValue) / range; float recommendedstartpercentage = centerpercentage; recommendedstartpercentage -= (float)m_recommendedPercentage / 200; float recommendedendpercentage = centerpercentage; recommendedendpercentage += (float)m_recommendedPercentage / 200; float startx = scalerect.Width * recommendedstartpercentage; float endx = scalerect.Width * recommendedendpercentage; float centerx = scalerect.Width * centerpercentage; Rectangle startfillrect = new Rectangle(scalerect.X + (int)startx, scalerect.Y, (int)centerx - (int)startx, scalerect.Height); Rectangle startcolorrect = startfillrect; startcolorrect.Inflate(1, 0); System.Drawing.Drawing2D.LinearGradientBrush gb1 = new System.Drawing.Drawing2D.LinearGradientBrush(startcolorrect, Color.Transparent, m_recommendedRangeColor, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); g.FillRectangle(gb1, startfillrect); Rectangle endfillrect = new Rectangle(scalerect.X + (int)centerx, scalerect.Y, (int)endx - (int)centerx, scalerect.Height); Rectangle endcolorrect = endfillrect; endcolorrect.Inflate(1, 0); System.Drawing.Drawing2D.LinearGradientBrush gb2 = new System.Drawing.Drawing2D.LinearGradientBrush(endcolorrect, m_recommendedRangeColor, Color.Transparent, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); g.FillRectangle(gb2, endfillrect); g.DrawRectangle(p, startfillrect.X, startfillrect.Y, startfillrect.Width + endfillrect.Width, startfillrect.Height); gb.Dispose(); gb1.Dispose(); gb2.Dispose(); } // draw threshold if (m_thresholdValue >= m_minValue && m_thresholdValue < m_maxValue) { // percentage float percentage = (m_thresholdValue - m_minValue) / range; if (percentage > 1) percentage = 1; if (percentage < 0) percentage = 0; float startx = scalerect.Width * percentage; Rectangle fillrect = new Rectangle(scalerect.X + (int)startx, scalerect.Y, scalerect.Width - (int)startx, scalerect.Height); Rectangle fillcolorrect = fillrect; fillcolorrect.Inflate(1, 0); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(fillcolorrect, Color.Transparent, m_thresholdColor, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); g.FillRectangle(gb, fillrect); // nog een rectangle erom heen? g.DrawRectangle(p, fillrect); gb.Dispose(); } p.Dispose(); } } /// <summary> /// Draws the actual scale on the gauge /// </summary> /// <param name="g"></param> private void DrawScale(Graphics g) { Rectangle scalerect = rcentre; scalerect.Inflate(-2, -2); Color realstart = Color.FromArgb(m_alphaForGaugeColors, m_startColor); Color realend = Color.FromArgb(m_alphaForGaugeColors, m_endColor); scalerect = new Rectangle(scalerect.X + 1, scalerect.Y + 1, scalerect.Width, scalerect.Height); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(rcentre, realstart, realend, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); // percentage calulation float range = m_maxValue - m_minValue; float percentage = (m_value - m_minValue) / range; //float percentage = (m_value) / (m_maxValue - m_minValue); if (percentage > 1) percentage = 1; float width = scalerect.Width * percentage; Rectangle fillrect = new Rectangle(scalerect.X - 1, scalerect.Y - 1, (int)width, scalerect.Height + 1); g.FillRectangle(gb, fillrect); // draw peak & hold? if (m_MaxPeakHoldValue > float.MinValue && m_peakholdOpaque > 0) { Color peakholdcolor = Color.FromArgb(m_peakholdOpaque, Color.Red); percentage = (m_MaxPeakHoldValue - m_minValue) / range; if (percentage > 1) percentage = 1; width = scalerect.Width * percentage; g.DrawLine(new Pen(peakholdcolor, 3), new Point(scalerect.X - 1 + (int)width, scalerect.Y - 1), new Point(scalerect.X - 1 + (int)width, scalerect.Y + scalerect.Height)); } gb.Dispose(); } private int m_numberOfDivisions = 5; [Browsable(true), Category("SmallLinearGauge"), Description("Sets number of divisions that should be drawn"), DefaultValue(typeof(int), "5")] public int NumberOfDivisions { get { return m_numberOfDivisions; } set { if (m_numberOfDivisions != value) { m_numberOfDivisions = value; base.Invalidate(); } } } private Color m_TickColor = Color.Gray; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge tick color"), DefaultValue(typeof(Color), "System.Drawing.Color.Gray")] public Color TickColor { get { return m_TickColor; } set { if (m_TickColor != value) { m_TickColor = value; base.Invalidate(); } } } private int m_subTickCount = 4; [Browsable(true), Category("SmallLinearGauge"), Description("Sets number of sub divisions that should be drawn"), DefaultValue(typeof(int), "4")] public int SubTickCount { get { return m_subTickCount; } set { if (m_subTickCount != value) { m_subTickCount = value; base.Invalidate(); } } } private Color m_TextColor = Color.Silver; [Browsable(true), Category("SmallLinearGauge"), Description("Set the gauge text color"), DefaultValue(typeof(Color), "System.Drawing.Color.Silver")] public Color TextColor { get { return m_TextColor; } set { if (m_TextColor != value) { m_TextColor = value; base.Invalidate(); } } } /// <summary> /// Draws the numbers above the center retangle /// </summary> /// <param name="g"></param> private void DrawNumbers(Graphics g) { int y_offset = rcentre.Y - 20; int x_offset = rcentre.X; for (int t = 0; t < m_numberOfDivisions + 1; t++) { int tickWidth = rcentre.Width / (m_numberOfDivisions); int xPos = x_offset + t * tickWidth; float fval = m_minValue + (t * ((m_maxValue - m_minValue) / m_numberOfDivisions)); string outstr = fval.ToString("F" + m_NumberOfDecimals.ToString()); // string outstr = fval.ToString("F0"); if (fval < 10 && fval > -10 && fval != 0) outstr = fval.ToString("F1"); if (fval < 1 && fval > -1 && fval != 0) outstr = fval.ToString("F2"); SizeF textSize = g.MeasureString(outstr, this.Font); Pen p = new Pen(Color.FromArgb(80, m_TickColor)); g.DrawRectangle(p, new Rectangle(xPos, rcentre.Y + 1, 3, rcentre.Height - 2)); // subticks SolidBrush sb = new SolidBrush(Color.FromArgb(80, m_TickColor)); if (t < m_numberOfDivisions) { for (int subt = 0; subt < m_subTickCount; subt++) { int subTickWidth = tickWidth / (m_subTickCount + 1); int xPosSub = xPos + (subt + 1) * subTickWidth; g.FillEllipse(sb, xPosSub, rcentre.Y + (rcentre.Height / 2), 3, 3); } } xPos -= (int)textSize.Width / 2; SolidBrush sbtxt = new SolidBrush(m_TextColor); g.DrawString(outstr, this.Font, sbtxt, new PointF((float)xPos, (float)y_offset)); p.Dispose(); sb.Dispose(); sbtxt.Dispose(); } } /// <summary> /// Draws the text under the center retangle /// </summary> /// <param name="g"></param> private void DrawText(Graphics g) { string text2display = m_gaugeText; if (m_ShowValue) { if (m_ShowValueInPercentage) { // add percentage to text float range = m_maxValue - m_minValue; float percentage = (m_value - m_minValue) / range; percentage *= 100; // and percentage sign text2display += " " + percentage.ToString("F0") + " %"; } else { // add value to text //string strval = m_value.ToString("F0"); string strval = m_value.ToString("F" + m_NumberOfDecimals.ToString()); if (m_value > -10 && m_value < 10 && m_value != 0) strval = m_value.ToString("F1"); if (m_value > -1 && m_value < 1 && m_value != 0) strval = m_value.ToString("F2"); text2display += " " + strval; // and units text2display += " " + m_gaugeUnits; } } SizeF textsize = g.MeasureString(text2display, this.Font); SolidBrush sbtxt = new SolidBrush(m_TextColor); int xPos = this.ClientRectangle.X + (this.ClientRectangle.Width / 2) - ((int)textsize.Width / 2); g.DrawString(text2display, this.Font, sbtxt, new PointF((float)xPos, rcentre.Y + rcentre.Height + 10)); sbtxt.Dispose(); } /// <summary> /// Draws the background image for that gauge /// </summary> /// <param name="g"></param> private void DrawBackground(Graphics g) { SolidBrush b = new SolidBrush(m_BackGroundColor); //SolidBrush bt = new SolidBrush(Color.Transparent); DrawRoundRect(g, this.ClientRectangle, 3, m_BackGroundColor, Color.Gray, Color.Green, 1, true, true); //g.FillRectangle(b, this.ClientRectangle); RectangleF r = this.ClientRectangle; r.Inflate(-3, -3); Pen p = new Pen(m_BevelLineColor, 2); g.DrawRectangle(p, new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height)); //g.DrawRectangle(Pens.DimGray, rcentre); b.Dispose(); p.Dispose(); } private void GetCenterRectangle() { //rcentre = new Rectangle(this.ClientRectangle.X + this.ClientRectangle.Width / 8, this.ClientRectangle.Y + (this.ClientRectangle.Height * 3) / 8, (this.ClientRectangle.Width * 6) / 8, (this.ClientRectangle.Height * 2) / 8); rcentre = new Rectangle(this.ClientRectangle.X , this.ClientRectangle.Y , (this.ClientRectangle.Width ), (this.ClientRectangle.Height )); } private void LinearGauge_Resize(object sender, EventArgs e) { GetCenterRectangle(); base.Invalidate(); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Media; using CocosSharp; using CocosDenshion; using System.Diagnostics; namespace tests { public class CocosDenshionTest : CCLayer { static readonly string EFFECT_FILE = "Sounds/effect1"; static readonly string MUSIC_FILE = "Sounds/background"; int soundId; class Button : CCNode { CCNode child; public event TriggeredHandler Triggered; // A delegate type for hooking up button triggered events public delegate void TriggeredHandler(object sender,EventArgs e); private Button() { AttachListener(); } public Button(CCSprite sprite) : this() { child = sprite; AddChild(sprite); } public Button(string text) : this() { child = new CCLabel(text, "fonts/arial", 16, CCLabelFormat.SpriteFont); AddChild(child); } void AttachListener() { // Register Touch Event var listener = new CCEventListenerTouchOneByOne(); listener.IsSwallowTouches = true; listener.OnTouchBegan = OnTouchBegan; listener.OnTouchEnded = OnTouchEnded; listener.OnTouchCancelled = OnTouchCancelled; AddEventListener(listener, this); } bool touchHits(CCTouch touch) { var location = touch.Location; var area = child.BoundingBox; return area.ContainsPoint(child.WorldToParentspace(location)); } bool OnTouchBegan(CCTouch touch, CCEvent touchEvent) { bool hits = touchHits(touch); if (hits) scaleButtonTo(0.9f); return hits; } void OnTouchEnded(CCTouch touch, CCEvent touchEvent) { bool hits = touchHits(touch); if (hits && Triggered != null) Triggered(this, EventArgs.Empty); scaleButtonTo(1); } void OnTouchCancelled(CCTouch touch, CCEvent touchEvent) { scaleButtonTo(1); } void scaleButtonTo(float scale) { var action = new CCScaleTo(0.1f, scale); action.Tag = 900; StopAction(900); RunAction(action); } } class AudioSlider : CCNode { CCControlSlider slider; CCLabel lblMinValue, lblMaxValue; Direction direction; public enum Direction { Vertical, Horizontal } public AudioSlider(Direction direction = Direction.Horizontal) { slider = new CCControlSlider("extensions/sliderTrack.png", "extensions/sliderProgress.png", "extensions/sliderThumb.png"); slider.Scale = 0.5f; this.direction = direction; if (direction == Direction.Vertical) slider.Rotation = -90.0f; AddChild(slider); ContentSize = slider.ScaledContentSize; } public float Value { get { return slider.Value; } set { SetValue(slider.MinimumValue, slider.MaximumValue, value); } } public void SetValue(float minValue, float maxValue, float value) { slider.MinimumValue = minValue; slider.MaximumValue = maxValue; slider.Value = value; var valueText = string.Format("{0,2:f2}", minValue); if (lblMinValue == null) { lblMinValue = new CCLabel(valueText, "fonts/arial", 8, CCLabelFormat.SpriteFont) { AnchorPoint = CCPoint.AnchorMiddleLeft }; AddChild(lblMinValue); if (direction == Direction.Vertical) lblMinValue.Position = new CCPoint(0, slider.ScaledContentSize.Height); else lblMinValue.Position = new CCPoint(0, slider.ScaledContentSize.Height * 1.5f); } else lblMinValue.Text = valueText; valueText = string.Format("{0,2:f2}", maxValue); if (lblMaxValue == null) { lblMaxValue = new CCLabel(valueText, "fonts/arial", 8, CCLabelFormat.SpriteFont) { AnchorPoint = CCPoint.AnchorMiddleRight }; AddChild(lblMaxValue); if (direction == Direction.Vertical) { lblMaxValue.Position = new CCPoint(slider.ScaledContentSize.Height * 1.75f, slider.ScaledContentSize.Width); AnchorPoint = CCPoint.AnchorMiddleLeft; } else lblMaxValue.Position = new CCPoint(slider.ScaledContentSize.Width, slider.ScaledContentSize.Height * 1.5f); } else lblMaxValue.Text = valueText; } } float MusicVolume { get; set; } float EffectsVolume { get; set; } #region Constructors public CocosDenshionTest() { MusicVolume = 1; EffectsVolume = 1; Schedule( (dt) => { var musicVolume = sliderMusicVolume.Value; if ((float)Math.Abs(musicVolume - MusicVolume) > 0.001) { MusicVolume = musicVolume; CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume = musicVolume; } var effectsVolume = sliderEffectsVolume.Value; if ((float)Math.Abs(effectsVolume - EffectsVolume) > 0.001) { EffectsVolume = effectsVolume; CCSimpleAudioEngine.SharedEngine.EffectsVolume = effectsVolume; } } ); // preload background music and effect CCSimpleAudioEngine.SharedEngine.PreloadBackgroundMusic(MUSIC_FILE); CCSimpleAudioEngine.SharedEngine.PreloadEffect(EFFECT_FILE); // set default volume CCSimpleAudioEngine.SharedEngine.EffectsVolume = 0.5f; CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume = 0.5f; } #endregion Constructors #region Setup content public override void OnEnter() { base.OnEnter(); AddButtons(); AddSliders(); } void AddButtons() { var audio = CCSimpleAudioEngine.SharedEngine; var lblMusic = new CCLabel("Control Music", "fonts/arial", 24, CCLabelFormat.SpriteFont); AddChildAt(lblMusic, 0.25f, 0.9f); var btnPlay = new Button("play"); btnPlay.Triggered += (sender, e) => { audio.BackgroundMusicVolume = sliderMusicVolume.Value; audio.PlayBackgroundMusic(MUSIC_FILE, true); }; AddChildAt(btnPlay, 0.1f, 0.75f); var btnStop = new Button("stop"); btnStop.Triggered += (sender, e) => { audio.StopBackgroundMusic(); }; AddChildAt(btnStop, 0.25f, 0.75f); var btnRewindMusic = new Button("rewind"); btnRewindMusic.Triggered += (sender, e) => { audio.RewindBackgroundMusic(); }; AddChildAt(btnRewindMusic, 0.4f, 0.75f); var btnPause = new Button("pause"); btnPause.Triggered += (sender, e) => { audio.PauseBackgroundMusic(); }; AddChildAt(btnPause, 0.1f, 0.65f); var btnResumeMusic = new Button("resume"); btnResumeMusic.Triggered += (sender, e) => { audio.ResumeBackgroundMusic(); }; AddChildAt(btnResumeMusic, 0.25f, 0.65f); var btnIsPlayingMusic = new Button("is playing"); btnIsPlayingMusic.Triggered += (sender, e) => { if (audio.BackgroundMusicPlaying) CCLog.Log("background music is playing"); else CCLog.Log("background music is not playing"); }; AddChildAt(btnIsPlayingMusic, 0.4f, 0.65f); var lblSound = new CCLabel("Control Effects", "fonts/arial", 24, CCLabelFormat.SpriteFont); AddChildAt(lblSound, 0.75f, 0.9f); var btnPlayEffect = new Button("play"); btnPlayEffect.Triggered += (sender, e) => { var pitch = sliderPitch.Value; var pan = sliderPan.Value; var gain = sliderGain.Value; soundId = audio.PlayEffect(EFFECT_FILE, false);//, pitch, pan, gain); }; AddChildAt(btnPlayEffect, 0.6f, 0.8f); var btnPlayEffectInLoop = new Button("play in loop"); btnPlayEffectInLoop.Triggered += (sender, e) => { var pitch = sliderPitch.Value; var pan = sliderPan.Value; var gain = sliderGain.Value; soundId = audio.PlayEffect(EFFECT_FILE, true);//, pitch, pan, gain); }; AddChildAt(btnPlayEffectInLoop, 0.75f, 0.8f); var btnStopEffect = new Button("stop"); btnStopEffect.Triggered += (sender, e) => { audio.StopEffect(soundId); }; AddChildAt(btnStopEffect, 0.9f, 0.8f); var btnUnloadEffect = new Button("unload"); btnUnloadEffect.Triggered += (sender, e) => { audio.UnloadEffect(EFFECT_FILE); }; AddChildAt(btnUnloadEffect, 0.6f, 0.7f); var btnPauseEffect = new Button("pause"); btnPauseEffect.Triggered += (sender, e) => { audio.PauseEffect(soundId); }; AddChildAt(btnPauseEffect, 0.75f, 0.7f); var btnResumeEffect = new Button("resume"); btnResumeEffect.Triggered += (sender, e) => { audio.ResumeEffect(soundId); }; AddChildAt(btnResumeEffect, 0.9f, 0.7f); var btnPauseAll = new Button("pause all"); btnPauseAll.Triggered += (sender, e) => { audio.PauseAllEffects(); }; AddChildAt(btnPauseAll, 0.6f, 0.6f); var btnResumeAll = new Button("resume all"); btnResumeAll.Triggered += (sender, e) => { audio.ResumeAllEffects(); }; AddChildAt(btnResumeAll, 0.75f, 0.6f); var btnStopAll = new Button("stop all"); btnStopAll.Triggered += (sender, e) => { audio.StopAllEffects(); }; AddChildAt(btnStopAll, 0.9f, 0.6f); } AudioSlider sliderPitch, sliderMusicVolume, sliderEffectsVolume, sliderPan, sliderGain; void AddSliders() { // var lblPitch = new CCLabel("Pitch", "fonts/arial", 14, CCLabelFormat.SpriteFont); // AddChildAt(lblPitch, 0.67f, 0.4f); // sliderPitch = new AudioSlider(AudioSlider.Direction.Horizontal); sliderPitch.SetValue(0.5f, 2, 1); // AddChildAt(sliderPitch, 0.72f, 0.39f); // var lblPan = new CCLabel("Pan", "fonts/arial", 14, CCLabelFormat.SpriteFont); // AddChildAt(lblPan, 0.67f, 0.3f); sliderPan = new AudioSlider(); sliderPan.SetValue(-1, 1, 0); // AddChildAt(sliderPan, 0.72f, 0.29f); // // var lblGain = new CCLabel("Gain", "fonts/arial", 14, CCLabelFormat.SpriteFont); // AddChildAt(lblGain, 0.67f, 0.2f); sliderGain = new AudioSlider(); sliderGain.SetValue(0, 1, 1); // AddChildAt(sliderGain, 0.72f, 0.19f); var lblEffectsVolume = new CCLabel("Effects Volume", "fonts/arial", 14, CCLabelFormat.SpriteFont); AddChildAt(lblEffectsVolume, 0.62f, 0.5f); sliderEffectsVolume = new AudioSlider(); sliderEffectsVolume.SetValue(0, 1, CCSimpleAudioEngine.SharedEngine.EffectsVolume); AddChildAt(sliderEffectsVolume, 0.71f, 0.49f); var lblMusicVolume = new CCLabel("Music Volume", "fonts/arial", 14, CCLabelFormat.SpriteFont); AddChildAt(lblMusicVolume, 0.12f, 0.5f); sliderMusicVolume = new AudioSlider(); sliderMusicVolume.SetValue(0, 1, CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume); AddChildAt(sliderMusicVolume, 0.21f, 0.49f); } void AddChildAt(CCNode node, float percentageX, float percentageY) { var size = VisibleBoundsWorldspace.Size; node.PositionX = percentageX * size.Width; node.PositionY = percentageY * size.Height; AddChild(node); } #endregion Setup content public override void OnExit() { base.OnExit(); CCSimpleAudioEngine.SharedEngine.End(); } } public class CocosDenshionTestScene : TestScene { public override void runThisTest() { CCLayer layer = new CocosDenshionTest(); AddChild(layer); Director.ReplaceScene(this); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the ThreeDSensorCalibration profile message. /// </summary> public class ThreeDSensorCalibrationMesg : Mesg { #region Fields static class CalibrationFactorSubfield { public static ushort AccelCalFactor = 0; public static ushort GyroCalFactor = 1; public static ushort Subfields = 2; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } #endregion #region Constructors public ThreeDSensorCalibrationMesg() : base(Profile.mesgs[Profile.ThreeDSensorCalibrationIndex]) { } public ThreeDSensorCalibrationMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s /// Comment: Whole second part of the timestamp</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s /// Comment: Whole second part of the timestamp</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SensorType field /// Comment: Indicates which sensor the calibration is for</summary> /// <returns>Returns nullable SensorType enum representing the SensorType field</returns> public SensorType? GetSensorType() { object obj = GetFieldValue(0, 0, Fit.SubfieldIndexMainField); SensorType? value = obj == null ? (SensorType?)null : (SensorType)obj; return value; } /// <summary> /// Set SensorType field /// Comment: Indicates which sensor the calibration is for</summary> /// <param name="sensorType_">Nullable field value to be set</param> public void SetSensorType(SensorType? sensorType_) { SetFieldValue(0, 0, sensorType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CalibrationFactor field /// Comment: Calibration factor used to convert from raw ADC value to degrees, g, etc.</summary> /// <returns>Returns nullable uint representing the CalibrationFactor field</returns> public uint? GetCalibrationFactor() { return (uint?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CalibrationFactor field /// Comment: Calibration factor used to convert from raw ADC value to degrees, g, etc.</summary> /// <param name="calibrationFactor_">Nullable field value to be set</param> public void SetCalibrationFactor(uint? calibrationFactor_) { SetFieldValue(1, 0, calibrationFactor_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the AccelCalFactor subfield /// Units: g /// Comment: Accelerometer calibration factor</summary> /// <returns>Nullable uint representing the AccelCalFactor subfield</returns> public uint? GetAccelCalFactor() { return (uint?)GetFieldValue(1, 0, CalibrationFactorSubfield.AccelCalFactor); } /// <summary> /// /// Set AccelCalFactor subfield /// Units: g /// Comment: Accelerometer calibration factor</summary> /// <param name="accelCalFactor">Subfield value to be set</param> public void SetAccelCalFactor(uint? accelCalFactor) { SetFieldValue(1, 0, accelCalFactor, CalibrationFactorSubfield.AccelCalFactor); } /// <summary> /// Retrieves the GyroCalFactor subfield /// Units: deg/s /// Comment: Gyro calibration factor</summary> /// <returns>Nullable uint representing the GyroCalFactor subfield</returns> public uint? GetGyroCalFactor() { return (uint?)GetFieldValue(1, 0, CalibrationFactorSubfield.GyroCalFactor); } /// <summary> /// /// Set GyroCalFactor subfield /// Units: deg/s /// Comment: Gyro calibration factor</summary> /// <param name="gyroCalFactor">Subfield value to be set</param> public void SetGyroCalFactor(uint? gyroCalFactor) { SetFieldValue(1, 0, gyroCalFactor, CalibrationFactorSubfield.GyroCalFactor); } ///<summary> /// Retrieves the CalibrationDivisor field /// Units: counts /// Comment: Calibration factor divisor</summary> /// <returns>Returns nullable uint representing the CalibrationDivisor field</returns> public uint? GetCalibrationDivisor() { return (uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CalibrationDivisor field /// Units: counts /// Comment: Calibration factor divisor</summary> /// <param name="calibrationDivisor_">Nullable field value to be set</param> public void SetCalibrationDivisor(uint? calibrationDivisor_) { SetFieldValue(2, 0, calibrationDivisor_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LevelShift field /// Comment: Level shift value used to shift the ADC value back into range</summary> /// <returns>Returns nullable uint representing the LevelShift field</returns> public uint? GetLevelShift() { return (uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LevelShift field /// Comment: Level shift value used to shift the ADC value back into range</summary> /// <param name="levelShift_">Nullable field value to be set</param> public void SetLevelShift(uint? levelShift_) { SetFieldValue(3, 0, levelShift_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field OffsetCal</returns> public int GetNumOffsetCal() { return GetNumFieldValues(4, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the OffsetCal field /// Comment: Internal calibration factors, one for each: xy, yx, zx</summary> /// <param name="index">0 based index of OffsetCal element to retrieve</param> /// <returns>Returns nullable int representing the OffsetCal field</returns> public int? GetOffsetCal(int index) { return (int?)GetFieldValue(4, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set OffsetCal field /// Comment: Internal calibration factors, one for each: xy, yx, zx</summary> /// <param name="index">0 based index of offset_cal</param> /// <param name="offsetCal_">Nullable field value to be set</param> public void SetOffsetCal(int index, int? offsetCal_) { SetFieldValue(4, index, offsetCal_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field OrientationMatrix</returns> public int GetNumOrientationMatrix() { return GetNumFieldValues(5, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the OrientationMatrix field /// Comment: 3 x 3 rotation matrix (row major)</summary> /// <param name="index">0 based index of OrientationMatrix element to retrieve</param> /// <returns>Returns nullable float representing the OrientationMatrix field</returns> public float? GetOrientationMatrix(int index) { return (float?)GetFieldValue(5, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set OrientationMatrix field /// Comment: 3 x 3 rotation matrix (row major)</summary> /// <param name="index">0 based index of orientation_matrix</param> /// <param name="orientationMatrix_">Nullable field value to be set</param> public void SetOrientationMatrix(int index, float? orientationMatrix_) { SetFieldValue(5, index, orientationMatrix_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Azure; using Management; using Rest; using 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> /// VirtualMachineExtensionsOperations operations. /// </summary> internal partial class VirtualMachineExtensionsOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineExtensionsOperations { /// <summary> /// Initializes a new instance of the VirtualMachineExtensionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal VirtualMachineExtensionsOperations(ComputeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// The operation to create or update the extension. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be create or /// updated. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='extensionParameters'> /// Parameters supplied to the Create Virtual Machine Extension operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualMachineExtension>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, string vmExtensionName, VirtualMachineExtension extensionParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<VirtualMachineExtension> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// The operation to delete the extension. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be deleted. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, string vmExtensionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<OperationStatusResponse> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// The operation to get the extension. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine containing the extension. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VirtualMachineExtension>> GetWithHttpMessagesAsync(string resourceGroupName, string vmName, string vmExtensionName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vmName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vmName"); } if (vmExtensionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vmExtensionName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vmName", vmName); tracingParameters.Add("vmExtensionName", vmExtensionName); tracingParameters.Add("expand", expand); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vmName}", System.Uri.EscapeDataString(vmName)); _url = _url.Replace("{vmExtensionName}", System.Uri.EscapeDataString(vmExtensionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualMachineExtension>(); _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<VirtualMachineExtension>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// The operation to create or update the extension. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be create or /// updated. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='extensionParameters'> /// Parameters supplied to the Create Virtual Machine Extension operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VirtualMachineExtension>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, string vmExtensionName, VirtualMachineExtension extensionParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vmName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vmName"); } if (vmExtensionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vmExtensionName"); } if (extensionParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "extensionParameters"); } if (extensionParameters != null) { extensionParameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vmName", vmName); tracingParameters.Add("vmExtensionName", vmExtensionName); tracingParameters.Add("extensionParameters", extensionParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vmName}", System.Uri.EscapeDataString(vmName)); _url = _url.Replace("{vmExtensionName}", System.Uri.EscapeDataString(vmExtensionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(extensionParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(extensionParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualMachineExtension>(); _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<VirtualMachineExtension>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineExtension>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// The operation to delete the extension. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be deleted. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, string vmExtensionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vmName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vmName"); } if (vmExtensionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vmExtensionName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vmName", vmName); tracingParameters.Add("vmExtensionName", vmExtensionName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vmName}", System.Uri.EscapeDataString(vmName)); _url = _url.Replace("{vmExtensionName}", System.Uri.EscapeDataString(vmExtensionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationStatusResponse>(); _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<OperationStatusResponse>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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; } } }
/* * 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.Globalization; using System.Linq; using QuantConnect.Data; using QuantConnect.Orders; using QuantConnect.Securities; using QuantConnect.Util; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Provides a regression baseline focused on updating orders /// </summary> /// <meta name="tag" content="regression test" /> public class UpdateOrderRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private int LastMonth = -1; private Security Security; private int Quantity = 100; private const int DeltaQuantity = 10; private const decimal StopPercentage = 0.025m; private const decimal StopPercentageDelta = 0.005m; private const decimal LimitPercentage = 0.025m; private const decimal LimitPercentageDelta = 0.005m; private const string symbol = "SPY"; private const SecurityType SecType = SecurityType.Equity; private readonly CircularQueue<OrderType> _orderTypesQueue = new CircularQueue<OrderType>(Enum.GetValues(typeof(OrderType)) .OfType<OrderType>() .Where (x => x != OrderType.OptionExercise && x != OrderType.LimitIfTouched)); private readonly List<OrderTicket> _tickets = new List<OrderTicket>(); /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 01, 01); //Set Start Date SetEndDate(2015, 01, 01); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddSecurity(SecType, symbol, Resolution.Daily); Security = Securities[symbol]; _orderTypesQueue.CircleCompleted += (sender, args) => { // flip our signs when we've gone through all the order types Quantity *= -1; }; } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!data.Bars.ContainsKey(symbol)) return; // each month make an action if (Time.Month != LastMonth) { // we'll submit the next type of order from the queue var orderType = _orderTypesQueue.Dequeue(); //Log(""); Log($"\r\n--------------MONTH: {Time.ToStringInvariant("MMMM")}:: {orderType}\r\n"); //Log(""); LastMonth = Time.Month; Log("ORDER TYPE:: " + orderType); var isLong = Quantity > 0; var stopPrice = isLong ? (1 + StopPercentage)*data.Bars[symbol].High : (1 - StopPercentage)*data.Bars[symbol].Low; var limitPrice = isLong ? (1 - LimitPercentage)*stopPrice : (1 + LimitPercentage)*stopPrice; if (orderType == OrderType.Limit) { limitPrice = !isLong ? (1 + LimitPercentage) * data.Bars[symbol].High : (1 - LimitPercentage) * data.Bars[symbol].Low; } var request = new SubmitOrderRequest(orderType, SecType, symbol, Quantity, stopPrice, limitPrice, UtcTime, ((int)orderType).ToString(CultureInfo.InvariantCulture)); var ticket = Transactions.AddOrder(request); _tickets.Add(ticket); } else if (_tickets.Count > 0) { var ticket = _tickets.Last(); if (Time.Day > 8 && Time.Day < 14) { if (ticket.UpdateRequests.Count == 0 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Update(new UpdateOrderFields { Quantity = ticket.Quantity + Math.Sign(Quantity)*DeltaQuantity, Tag = "Change quantity: " + Time.Day }); Log("UPDATE1:: " + ticket.UpdateRequests.Last()); } } else if (Time.Day > 13 && Time.Day < 20) { if (ticket.UpdateRequests.Count == 1 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Update(new UpdateOrderFields { LimitPrice = Security.Price*(1 - Math.Sign(ticket.Quantity)*LimitPercentageDelta), StopPrice = Security.Price*(1 + Math.Sign(ticket.Quantity)*StopPercentageDelta), Tag = "Change prices: " + Time.Day }); Log("UPDATE2:: " + ticket.UpdateRequests.Last()); } } else { if (ticket.UpdateRequests.Count == 2 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Cancel(Time.Day + " and is still open!"); Log("CANCELLED:: " + ticket.CancelRequest); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { // if the order time isn't equal to the algo time, then the modified time on the order should be updated var order = Transactions.GetOrderById(orderEvent.OrderId); var ticket = Transactions.GetOrderTicket(orderEvent.OrderId); if (order.Status == OrderStatus.Canceled && order.CanceledTime != orderEvent.UtcTime) { throw new Exception("Expected canceled order CanceledTime to equal canceled order event time."); } // fills update LastFillTime if ((order.Status == OrderStatus.Filled || order.Status == OrderStatus.PartiallyFilled) && order.LastFillTime != orderEvent.UtcTime) { throw new Exception("Expected filled order LastFillTime to equal fill order event time."); } // check the ticket to see if the update was successfully processed if (ticket.UpdateRequests.Any(ur => ur.Response?.IsSuccess == true) && order.CreatedTime != UtcTime && order.LastUpdateTime == null) { throw new Exception("Expected updated order LastUpdateTime to equal submitted update order event time"); } if (orderEvent.Status == OrderStatus.Filled) { Log("FILLED:: " + Transactions.GetOrderById(orderEvent.OrderId) + " FILL PRICE:: " + orderEvent.FillPrice.SmartRounding()); } else { Log(orderEvent.ToString()); Log("TICKET:: " + ticket); } } private new void Log(string msg) { if (LiveMode) Debug(msg); else base.Log(msg); } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "21"}, {"Average Win", "0%"}, {"Average Loss", "-1.51%"}, {"Compounding Annual Return", "-7.319%"}, {"Drawdown", "15.000%"}, {"Expectancy", "-1"}, {"Net Profit", "-14.102%"}, {"Sharpe Ratio", "-1.09"}, {"Probabilistic Sharpe Ratio", "0.026%"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.015"}, {"Beta", "-0.417"}, {"Annual Standard Deviation", "0.046"}, {"Annual Variance", "0.002"}, {"Information Ratio", "-1.525"}, {"Tracking Error", "0.135"}, {"Treynor Ratio", "0.12"}, {"Total Fees", "$21.00"}, {"Estimated Strategy Capacity", "$3000000000.00"}, {"Lowest Capacity Asset", "SPY R735QTJ8XC9X"}, {"Fitness Score", "0.001"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-2.096"}, {"Return Over Maximum Drawdown", "-0.489"}, {"Portfolio Turnover", "0.006"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "308c3da05b4bd6f294158736c998ef36"} }; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// Circuit data for an agent. Connection information shared between /// regions that accept UDP connections from a client /// </summary> public class AgentCircuitData { /// <summary> /// Avatar Unique Agent Identifier /// </summary> public UUID AgentID; /// <summary> /// Avatar's Appearance /// </summary> public AvatarAppearance Appearance; /// <summary> /// Agent's root inventory folder /// </summary> public UUID BaseFolder; /// <summary> /// Base Caps path for user /// </summary> public string CapsPath = String.Empty; /// <summary> /// Seed caps for neighbor regions that the user can see into /// </summary> public Dictionary<ulong, string> ChildrenCapSeeds; /// <summary> /// Root agent, or Child agent /// </summary> public bool child; /// <summary> /// Number given to the client when they log-in that they provide /// as credentials to the UDP server /// </summary> public uint circuitcode; /// <summary> /// How this agent got here /// </summary> public uint teleportFlags; /// <summary> /// Agent's account first name /// </summary> public string firstname; public UUID InventoryFolder; /// <summary> /// Agent's account last name /// </summary> public string lastname; /// <summary> /// Random Unique GUID for this session. Client gets this at login and it's /// only supposed to be disclosed over secure channels /// </summary> public UUID SecureSessionID; /// <summary> /// Non secure Session ID /// </summary> public UUID SessionID; /// <summary> /// Hypergrid service token; generated by the user domain, consumed by the receiving grid. /// There is one such unique token for each grid visited. /// </summary> public string ServiceSessionID = string.Empty; /// <summary> /// Viewer's version string /// </summary> public string Viewer; /// <summary> /// Position the Agent's Avatar starts in the region /// </summary> public Vector3 startpos; public Dictionary<string, object> ServiceURLs; public AgentCircuitData() { } /// <summary> /// Create AgentCircuitData from a Serializable AgentCircuitData /// </summary> /// <param name="cAgent"></param> public AgentCircuitData(sAgentCircuitData cAgent) { AgentID = new UUID(cAgent.AgentID); SessionID = new UUID(cAgent.SessionID); SecureSessionID = new UUID(cAgent.SecureSessionID); startpos = new Vector3(cAgent.startposx, cAgent.startposy, cAgent.startposz); firstname = cAgent.firstname; lastname = cAgent.lastname; circuitcode = cAgent.circuitcode; child = cAgent.child; InventoryFolder = new UUID(cAgent.InventoryFolder); BaseFolder = new UUID(cAgent.BaseFolder); CapsPath = cAgent.CapsPath; ChildrenCapSeeds = cAgent.ChildrenCapSeeds; Viewer = cAgent.Viewer; } /// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) args["children_seeds"] = childrenSeeds; } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); args["viewer"] = OSD.FromString(Viewer); if (Appearance != null) { //System.Console.WriteLine("XXX Before packing Wearables"); if ((Appearance.Wearables != null) && (Appearance.Wearables.Length > 0)) { OSDArray wears = new OSDArray(Appearance.Wearables.Length * 2); foreach (AvatarWearable awear in Appearance.Wearables) { wears.Add(OSD.FromUUID(awear.ItemID)); wears.Add(OSD.FromUUID(awear.AssetID)); //System.Console.WriteLine("XXX ItemID=" + awear.ItemID + " assetID=" + awear.AssetID); } args["wearables"] = wears; } //System.Console.WriteLine("XXX Before packing Attachments"); Dictionary<int, UUID[]> attachments = Appearance.GetAttachmentDictionary(); if ((attachments != null) && (attachments.Count > 0)) { OSDArray attachs = new OSDArray(attachments.Count); foreach (KeyValuePair<int, UUID[]> kvp in attachments) { AttachmentData adata = new AttachmentData(kvp.Key, kvp.Value[0], kvp.Value[1]); attachs.Add(adata.PackUpdateMessage()); //System.Console.WriteLine("XXX att.pt=" + kvp.Key + "; itemID=" + kvp.Value[0] + "; assetID=" + kvp.Value[1]); } args["attachments"] = attachs; } } if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } return args; } /// <summary> /// Unpack agent circuit data map into an AgentCiruitData object /// </summary> /// <param name="args"></param> public void UnpackAgentCircuitData(OSDMap args) { if (args["agent_id"] != null) AgentID = args["agent_id"].AsUUID(); if (args["base_folder"] != null) BaseFolder = args["base_folder"].AsUUID(); if (args["caps_path"] != null) CapsPath = args["caps_path"].AsString(); if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array)) { OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]); ChildrenCapSeeds = new Dictionary<ulong, string>(); foreach (OSD o in childrenSeeds) { if (o.Type == OSDType.Map) { ulong handle = 0; string seed = ""; OSDMap pair = (OSDMap)o; if (pair["handle"] != null) if (!UInt64.TryParse(pair["handle"].AsString(), out handle)) continue; if (pair["seed"] != null) seed = pair["seed"].AsString(); if (!ChildrenCapSeeds.ContainsKey(handle)) ChildrenCapSeeds.Add(handle, seed); } } } else ChildrenCapSeeds = new Dictionary<ulong, string>(); if (args["child"] != null) child = args["child"].AsBoolean(); if (args["circuit_code"] != null) UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode); if (args["first_name"] != null) firstname = args["first_name"].AsString(); if (args["last_name"] != null) lastname = args["last_name"].AsString(); if (args["inventory_folder"] != null) InventoryFolder = args["inventory_folder"].AsUUID(); if (args["secure_session_id"] != null) SecureSessionID = args["secure_session_id"].AsUUID(); if (args["session_id"] != null) SessionID = args["session_id"].AsUUID(); if (args["service_session_id"] != null) ServiceSessionID = args["service_session_id"].AsString(); if (args["viewer"] != null) Viewer = args["viewer"].AsString(); if (args["start_pos"] != null) Vector3.TryParse(args["start_pos"].AsString(), out startpos); Appearance = new AvatarAppearance(AgentID); if (args["appearance_serial"] != null) Appearance.Serial = args["appearance_serial"].AsInteger(); if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array) { OSDArray wears = (OSDArray)(args["wearables"]); for (int i = 0; i < wears.Count / 2; i++) { Appearance.Wearables[i].ItemID = wears[i*2].AsUUID(); Appearance.Wearables[i].AssetID = wears[(i*2)+1].AsUUID(); } } if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array) { OSDArray attachs = (OSDArray)(args["attachments"]); AttachmentData[] attachments = new AttachmentData[attachs.Count]; int i = 0; foreach (OSD o in attachs) { if (o.Type == OSDType.Map) { attachments[i++] = new AttachmentData((OSDMap)o); } } Appearance.SetAttachments(attachments); } ServiceURLs = new Dictionary<string, object>(); if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) { OSDArray urls = (OSDArray)(args["service_urls"]); for (int i = 0; i < urls.Count / 2; i++) { ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString(); //System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString()); } } } } /// <summary> /// Serializable Agent Circuit Data /// </summary> [Serializable] public class sAgentCircuitData { public Guid AgentID; public Guid BaseFolder; public string CapsPath = String.Empty; public Dictionary<ulong, string> ChildrenCapSeeds; public bool child; public uint circuitcode; public string firstname; public Guid InventoryFolder; public string lastname; public Guid SecureSessionID; public Guid SessionID; public float startposx; public float startposy; public float startposz; public string Viewer; public sAgentCircuitData() { } public sAgentCircuitData(AgentCircuitData cAgent) { AgentID = cAgent.AgentID.Guid; SessionID = cAgent.SessionID.Guid; SecureSessionID = cAgent.SecureSessionID.Guid; startposx = cAgent.startpos.X; startposy = cAgent.startpos.Y; startposz = cAgent.startpos.Z; firstname = cAgent.firstname; lastname = cAgent.lastname; circuitcode = cAgent.circuitcode; child = cAgent.child; InventoryFolder = cAgent.InventoryFolder.Guid; BaseFolder = cAgent.BaseFolder.Guid; CapsPath = cAgent.CapsPath; ChildrenCapSeeds = cAgent.ChildrenCapSeeds; Viewer = cAgent.Viewer; } } }
/* * VBCodeCompiler.cs - Implementation of the * System.CodeDom.Compiler.VBCodeCompiler class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.CodeDom.Compiler { #if CONFIG_CODEDOM using System.IO; using System.Reflection; using System.Globalization; internal class VBCodeCompiler : CodeCompiler { // List of reserved words in VB. private static readonly String[] reservedWords = { "addhandler", "addressof", "alias", "and", "andalso", "ansi", "as", "assembly", "auto", "boolean", "byref", "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate", "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "cshort", "csng", "cstr", "ctype", "date", "decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double", "each", "else", "elseif", "end", "enum", "erase", "error", "event", "exit", "false", "finally", "for", "friend", "function", "get", "gettype", "gosub", "goto", "handles", "if", "implements", "imports", "in", "inherits", "integer", "interface", "is", "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit", "mustoverride", "mybase", "myclass", "namespace", "new", "next", "not", "nothing", "notinheritable", "notoverridable", "object", "on", "option", "optional", "or", "orelse", "overloads", "overridable", "overrides", "paramarray", "preserve", "private", "property", "protected", "public", "raiseevent", "readonly", "redim", "removehandler", "resume", "return", "select", "set", "shadows", "shared", "short", "single", "static", "step", "stop", "string", "structure", "sub", "synclock", "then", "throw", "to", "true", "try", "typeof", "unicode", "until", "variant", "when", "while", "with", "withevents", "writeonly", "xor" }; // Constructor. public VBCodeCompiler() {} // Get the name of the compiler. protected override String CompilerName { get { // Use the Portable.NET VB compiler. String cscc = Environment.GetEnvironmentVariable("CSCC"); if(cscc != null) { return cscc; } else { return "cscc"; } } } // Get the file extension to use for source files. protected override String FileExtension { get { return ".vb"; } } // Convert compiler parameters into compiler arguments. protected override String CmdArgsFromParameters (CompilerParameters options) { return CSharpCodeCompiler.CmdArgsFromParameters(options, "vb"); } // Process an output line from the compiler. protected override void ProcessCompilerOutputLine (CompilerResults results, String line) { CompilerError error = ProcessCompilerOutputLine(line); if(error != null) { results.Errors.Add(error); } } // Get the token for "null". protected override String NullToken { get { return "Nothing"; } } // Determine if a string is a reserved word. private static bool IsReservedWord(String value) { if(value != null) { value = value.ToLower(CultureInfo.InvariantCulture); return (Array.IndexOf(reservedWords, value) != -1); } else { return false; } } // Create an escaped identifier if "value" is a language keyword. protected override String CreateEscapedIdentifier(String value) { if(IsReservedWord(value)) { return "[" + value + "]"; } else { return value; } } // Create a valid identifier if "value" is a language keyword. protected override String CreateValidIdentifier(String value) { if(IsReservedWord(value)) { return "_" + value; } else { return value; } } // Normalize a type name to its keyword form. private String NormalizeTypeName(String type) { int index1, index2; String baseName; String suffixes; // Bail out if the type is null. if(type == null) { return null; } // Split the type into base and suffix parts. index1 = type.IndexOf('*'); index2 = type.IndexOf('['); if(index1 > index2 && index2 != -1) { index1 = index2; } if(index1 != -1) { baseName = type.Substring(0, index1); suffixes = type.Substring(index1); suffixes = suffixes.Replace('[', '('); suffixes = suffixes.Replace(']', ')'); } else { baseName = type; suffixes = null; } // Convert the base name. switch(baseName) { case "System.Boolean": baseName = "Boolean"; break; case "System.Char": baseName = "Char"; break; case "System.Byte": baseName = "Byte"; break; case "System.Int16": baseName = "Short"; break; case "System.Int32": baseName = "Integer"; break; case "System.Int64": baseName = "Long"; break; case "System.Single": baseName = "Single"; break; case "System.Double": baseName = "Double"; break; case "System.Decimal": baseName = "Decimal"; break; case "System.String": baseName = "String"; break; case "System.DateTime": baseName = "Date"; break; case "System.Object": baseName = "Object"; break; default: break; } // Return the new type to the caller. return baseName + suffixes; } // Generate various expression categories. protected override void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression e) { OutputIdentifier(e.ParameterName); } protected override void GenerateArrayCreateExpression (CodeArrayCreateExpression e) { Output.Write("New "); if(e.Initializers.Count == 0) { Output.Write(NormalizeTypeName(e.CreateType.BaseType)); Output.Write("("); if(e.SizeExpression != null) { GenerateExpression(e.SizeExpression); } else { Output.Write(e.Size); } Output.Write(")"); } else { OutputType(e.CreateType); if(e.CreateType.ArrayRank == 0) { Output.Write("()"); } Output.WriteLine(" {"); Indent += 1; OutputExpressionList(e.Initializers, true); Indent -= 1; Output.Write("}"); } } protected override void GenerateArrayIndexerExpression (CodeArrayIndexerExpression e) { GenerateExpression(e.TargetObject); Output.Write("("); OutputExpressionList(e.Indices); Output.Write(")"); } protected override void GenerateBaseReferenceExpression (CodeBaseReferenceExpression e) { Output.Write("MyBase"); } protected override void GenerateCastExpression (CodeCastExpression e) { Output.Write("CType("); GenerateExpression(e.Expression); Output.Write(", "); OutputType(e.TargetType); Output.Write(")"); } protected override void GenerateDelegateCreateExpression (CodeDelegateCreateExpression e) { Output.Write("New "); OutputType(e.DelegateType); Output.Write("("); if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.MethodName); Output.Write(")"); } protected override void GenerateDelegateInvokeExpression (CodeDelegateInvokeExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); } Output.Write("("); OutputExpressionList(e.Parameters); Output.Write(")"); } protected override void GenerateEventReferenceExpression (CodeEventReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.EventName); } protected override void GenerateFieldReferenceExpression (CodeFieldReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.FieldName); } protected override void GenerateIndexerExpression (CodeIndexerExpression e) { GenerateExpression(e.TargetObject); Output.Write("("); OutputExpressionList(e.Indices); Output.Write(")"); } protected override void GenerateMethodInvokeExpression (CodeMethodInvokeExpression e) { GenerateMethodReferenceExpression(e.Method); Output.Write("("); OutputExpressionList(e.Parameters); Output.Write(")"); } protected override void GenerateMethodReferenceExpression (CodeMethodReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.MethodName); } protected override void GenerateObjectCreateExpression (CodeObjectCreateExpression e) { Output.Write("New "); OutputType(e.CreateType); Output.Write("("); OutputExpressionList(e.Parameters); Output.Write(")"); } protected override void GeneratePropertyReferenceExpression (CodePropertyReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.PropertyName); } protected override void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression e) { Output.Write("value"); } protected override void GenerateSnippetExpression (CodeSnippetExpression e) { Output.Write(e.Value); } protected override void GenerateThisReferenceExpression (CodeThisReferenceExpression e) { Output.Write("Me"); } protected override void GenerateVariableReferenceExpression (CodeVariableReferenceExpression e) { OutputIdentifier(e.VariableName); } // Generate various statement categories. protected override void GenerateAssignStatement (CodeAssignStatement e) { GenerateExpression(e.Left); Output.Write(" = "); GenerateExpression(e.Right); Output.WriteLine(); } protected override void GenerateAttachEventStatement (CodeAttachEventStatement e) { Output.Write("AddHandler "); GenerateExpression(e.Event); Output.Write(", "); GenerateExpression(e.Listener); Output.WriteLine(); } protected override void GenerateConditionStatement (CodeConditionStatement e) { Output.Write("If "); GenerateExpression(e.Condition); Output.WriteLine(" Then"); ++Indent; GenerateStatements(e.TrueStatements); --Indent; CodeStatementCollection stmts = e.FalseStatements; if(stmts.Count > 0 || Options.ElseOnClosing) { Output.WriteLine("Else"); ++Indent; GenerateStatements(stmts); --Indent; } Output.WriteLine("End If"); } protected override void GenerateExpressionStatement (CodeExpressionStatement e) { GenerateExpression(e.Expression); Output.WriteLine(); } protected override void GenerateGotoStatement (CodeGotoStatement e) { Output.Write("Goto "); Output.Write(e.Label); Output.WriteLine(); } protected override void GenerateIterationStatement (CodeIterationStatement e) { if(e.InitStatement != null) { GenerateStatement(e.InitStatement); } Output.Write("While "); if(e.TestExpression != null) { GenerateExpression(e.TestExpression); } else { Output.Write("True"); } Output.WriteLine(); ++Indent; GenerateStatements(e.Statements); if(e.IncrementStatement != null) { GenerateStatement(e.IncrementStatement); } --Indent; Output.WriteLine("End While"); } protected override void GenerateLabeledStatement (CodeLabeledStatement e) { Indent -= 1; Output.Write(e.Label); Output.WriteLine(":"); Indent += 1; GenerateStatement(e.Statement); } protected override void GenerateMethodReturnStatement (CodeMethodReturnStatement e) { CodeExpression expr = e.Expression; if(expr == null) { Output.WriteLine("Return"); } else { Output.Write("Return "); GenerateExpression(expr); Output.WriteLine(); } } protected override void GenerateRemoveEventStatement (CodeRemoveEventStatement e) { Output.Write("RemoveHandler "); GenerateExpression(e.Event); Output.Write(", "); GenerateExpression(e.Listener); Output.WriteLine(); } protected override void GenerateThrowExceptionStatement (CodeThrowExceptionStatement e) { CodeExpression expr = e.ToThrow; if(expr == null) { Output.WriteLine("Throw"); } else { Output.Write("Throw "); GenerateExpression(expr); Output.WriteLine(); } } protected override void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement e) { Output.WriteLine("Try"); ++Indent; GenerateStatements(e.TryStatements); --Indent; CodeCatchClauseCollection clauses = e.CatchClauses; if(clauses.Count > 0) { foreach(CodeCatchClause clause in clauses) { if(clause.CatchExceptionType != null) { Output.Write("Catch "); OutputIdentifier(clause.LocalName); Output.Write(" As "); OutputType(clause.CatchExceptionType); Output.WriteLine(); } else { Output.WriteLine("Catch"); } ++Indent; GenerateStatements(clause.Statements); --Indent; } } CodeStatementCollection fin = e.FinallyStatements; if(fin.Count > 0) { Output.WriteLine("Finally"); ++Indent; GenerateStatements(fin); --Indent; } Output.WriteLine("End Try"); } protected override void GenerateVariableDeclarationStatement (CodeVariableDeclarationStatement e) { Output.Write("Dim "); OutputTypeNamePair(e.Type, e.Name); if(e.InitExpression != null) { Output.Write(" = "); GenerateExpression(e.InitExpression); } Output.WriteLine(); } // Generate various declaration categories. protected override void GenerateAttributeDeclarationsStart (CodeAttributeDeclarationCollection attributes) { Output.Write("<"); } protected override void GenerateAttributeDeclarationsEnd (CodeAttributeDeclarationCollection attributes) { Output.Write(">"); } protected override void GenerateConstructor (CodeConstructor e, CodeTypeDeclaration c) { // Bail out if not a class or struct. if(!IsCurrentClass && !IsCurrentStruct) { return; } // Output the attributes and constructor signature. OutputAttributeDeclarations(e.CustomAttributes); OutputMemberAccessModifier(e.Attributes); Output.Write("Sub New "); Output.Write("("); OutputParameters(e.Parameters); Output.WriteLine(")"); // Output the body of the constructor. ++Indent; GenerateStatements(e.Statements); --Indent; Output.WriteLine("End Sub"); } protected override void GenerateEntryPointMethod (CodeEntryPointMethod e, CodeTypeDeclaration c) { Output.WriteLine("Public Shared Sub Main()"); ++Indent; GenerateStatements(e.Statements); --Indent; Output.WriteLine("End Sub"); } protected override void GenerateEvent (CodeMemberEvent e, CodeTypeDeclaration c) { // Bail out if not a class, struct, or interface. if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface) { return; } // Output the event definition. OutputAttributeDeclarations(e.CustomAttributes); if(e.PrivateImplementationType == null) { OutputMemberAccessModifier(e.Attributes); OutputMemberScopeModifier(e.Attributes); Output.Write("Event "); OutputTypeNamePair(e.Type, e.Name); } else { Output.Write("Event "); OutputTypeNamePair(e.Type, e.Name); Output.Write(" Implements "); OutputType(e.PrivateImplementationType); } Output.WriteLine(); } protected override void GenerateField(CodeMemberField e) { // Bail out if not a class, struct, or enum. if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentEnum) { return; } // Generate information about the field. if(!IsCurrentEnum) { OutputAttributeDeclarations(e.CustomAttributes); OutputMemberAccessModifier(e.Attributes); OutputFieldScopeModifier(e.Attributes); OutputTypeNamePair(e.Type, e.Name); if(e.InitExpression != null) { Output.Write(" = "); GenerateExpression(e.InitExpression); } Output.WriteLine(); } else { OutputAttributeDeclarations(e.CustomAttributes); OutputIdentifier(e.Name); if(e.InitExpression != null) { Output.Write(" = "); GenerateExpression(e.InitExpression); } Output.WriteLine(); } } protected override void GenerateMethod (CodeMemberMethod e, CodeTypeDeclaration c) { // Bail out if not a class, struct, or interface. if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface) { return; } // Output the attributes and method signature. OutputAttributeDeclarations(e.CustomAttributes); if(!IsCurrentInterface) { if(e.PrivateImplementationType == null) { OutputMemberAccessModifier(e.Attributes); OutputMemberScopeModifier(e.Attributes); } } else if((e.Attributes & MemberAttributes.VTableMask) == MemberAttributes.New) { Output.Write("Shadows "); } if(e.ReturnType != null) { Output.Write("Function "); } else { Output.Write("Sub "); } Output.Write(" "); OutputIdentifier(e.Name); Output.Write("("); OutputParameters(e.Parameters); Output.Write(")"); if(e.ReturnType != null) { Output.Write(" As "); OutputType(e.ReturnType); } Output.WriteLine(); if(e.PrivateImplementationType != null && !IsCurrentInterface) { Output.Write("Implements "); Output.Write(e.PrivateImplementationType.BaseType); Output.WriteLine(); } // Output the body of the method. if(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract) { // Nothing to do here. } else { ++Indent; GenerateStatements(e.Statements); --Indent; if(e.ReturnType != null) { Output.WriteLine("End Function"); } else { Output.WriteLine("End Sub"); } } } protected override void GenerateProperty (CodeMemberProperty e, CodeTypeDeclaration c) { // Bail out if not a class, struct, or interface. if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface) { return; } // Output the attributes and property signature. OutputAttributeDeclarations(e.CustomAttributes); if(!IsCurrentInterface) { if(e.PrivateImplementationType == null) { OutputMemberAccessModifier(e.Attributes); OutputMemberScopeModifier(e.Attributes); } } else if((e.Attributes & MemberAttributes.VTableMask) == MemberAttributes.New) { Output.Write("Shadows "); } Output.Write("Property "); OutputIdentifier(e.Name); if(e.Parameters.Count != 0) { Output.Write("("); OutputParameters(e.Parameters); Output.Write(")"); } Output.Write(" As "); OutputType(e.Type); if(e.PrivateImplementationType != null && !IsCurrentInterface) { Output.Write(" Implements "); Output.Write(e.PrivateImplementationType.BaseType); } Output.WriteLine(); // Output the body of the property. ++Indent; if(e.HasGet) { if(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract) { Output.WriteLine("Get"); } else { Output.WriteLine("Get"); ++Indent; GenerateStatements(e.GetStatements); --Indent; Output.WriteLine("End Get"); } } if(e.HasSet) { if(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract) { Output.WriteLine("Set"); } else { Output.WriteLine("Set"); ++Indent; GenerateStatements(e.SetStatements); --Indent; Output.WriteLine("End Set"); } } ++Indent; Output.WriteLine("End Property"); } protected override void GenerateNamespaceStart(CodeNamespace e) { Output.Write("Namespace "); OutputIdentifier(e.Name); Output.WriteLine(); } protected override void GenerateNamespaceEnd(CodeNamespace e) { Output.WriteLine("End Namespace"); } protected override void GenerateNamespaceImport(CodeNamespaceImport e) { Output.Write("Imports "); OutputIdentifier(e.Namespace); Output.WriteLine(); } protected override void GenerateSnippetMember (CodeSnippetTypeMember e) { Output.Write(e.Text); } protected override void GenerateTypeConstructor (CodeTypeConstructor e) { Output.WriteLine("Shared Sub New "); ++Indent; GenerateStatements(e.Statements); --Indent; Output.WriteLine("End Sub"); } protected override void GenerateTypeStart(CodeTypeDeclaration e) { OutputAttributeDeclarations(e.CustomAttributes); if(!IsCurrentDelegate) { OutputTypeAttributes (e.TypeAttributes, IsCurrentStruct, IsCurrentEnum); OutputIdentifier(e.Name); Output.WriteLine(); Indent += 2; String sep = " Inherits "; bool needeol = false; foreach(CodeTypeReference type in e.BaseTypes) { Output.Write(sep); OutputType(type); if(sep == " Inherits ") { Output.WriteLine(); sep = "Implements "; } else { sep = ", "; needeol = true; } } if(needeol) { Output.WriteLine(); } --Indent; } else { switch(e.TypeAttributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedPrivate: Output.Write("Private "); break; case TypeAttributes.Public: case TypeAttributes.NestedPublic: Output.Write("Public "); break; } Output.Write("Delegate "); CodeTypeDelegate d = (CodeTypeDelegate)e; if(d.ReturnType != null) { Output.Write("Function "); OutputType(d.ReturnType); } else { Output.Write("Sub "); } OutputIdentifier(d.Name); Output.Write("("); OutputParameters(d.Parameters); Output.Write(")"); if(d.ReturnType != null) { Output.Write(" As "); OutputType(d.ReturnType); Output.WriteLine(); Output.WriteLine("End Function"); } else { Output.WriteLine(); Output.WriteLine("End Sub"); } } } protected override void GenerateTypeEnd(CodeTypeDeclaration e) { if(IsCurrentClass) { --Indent; Output.WriteLine("End Class"); } else if(IsCurrentStruct) { --Indent; Output.WriteLine("End Structure"); } else if(IsCurrentInterface) { --Indent; Output.WriteLine("End Interface"); } else if(IsCurrentEnum) { --Indent; Output.WriteLine("End Enum"); } } // Generate various misc categories. protected override void GenerateComment(CodeComment e) { String text = e.Text; if(text == null) { return; } int posn = 0; int end, next; while(posn < text.Length) { end = posn; next = end; while(end < text.Length) { if(text[end] == '\r') { if((end + 1) < text.Length && text[end + 1] == '\n') { next = end + 1; } break; } else if(text[end] == '\n' || text[end] == '\u2028' || text[end] == '\u2029') { break; } ++end; next = end; } Output.Write("'"); Output.WriteLine(text.Substring(posn, end - posn)); posn = next + 1; } } protected override void GenerateLinePragmaStart(CodeLinePragma e) { Output.WriteLine(); Output.Write("#ExternalSource(\""); Output.Write(e.FileName); Output.Write(","); Output.Write(e.LineNumber); Output.WriteLine(")"); } protected override void GenerateLinePragmaEnd(CodeLinePragma e) { Output.WriteLine(); Output.WriteLine("#End ExternalSource"); } protected override String GetTypeOutput(CodeTypeReference value) { String baseType; if(value.ArrayElementType != null) { baseType = GetTypeOutput(value.ArrayElementType); } else { baseType = value.BaseType; } baseType = NormalizeTypeName(baseType); int rank = value.ArrayRank; if(rank > 0) { baseType += "("; while(rank > 1) { baseType += ","; --rank; } baseType += ")"; } return baseType; } // Determine if "value" is a valid identifier. protected override bool IsValidIdentifier(String value) { if(value == null || value.Length == 0) { return false; } switch(value[value.Length - 1]) { case '%': case '&': case '@': case '!': case '#': case '$': { // Strip the type suffix character from the identifier. value = value.Substring(0, value.Length - 1); if(value.Length == 0) { return false; } } break; default: break; } if(Array.IndexOf(reservedWords, value.ToLower (CultureInfo.InvariantCulture)) != -1) { return false; } else { return IsValidLanguageIndependentIdentifier(value); } } // Generate a direction expression. protected override void GenerateDirectionExpression (CodeDirectionExpression e) { if(e.Direction == FieldDirection.Out || e.Direction == FieldDirection.Ref) { Output.Write("AddressOf "); } GenerateExpression(e.Expression); } // Output a field direction value. protected override void OutputDirection(FieldDirection dir) { if(dir == FieldDirection.Out) { Output.Write("ByRef "); } else if(dir == FieldDirection.Ref) { Output.Write("ByRef "); } else { Output.Write("ByVal "); } } // Output a field scope modifier. protected override void OutputFieldScopeModifier (MemberAttributes attributes) { if((attributes & MemberAttributes.VTableMask) == MemberAttributes.New) { Output.Write("Shadows "); } if((attributes & MemberAttributes.ScopeMask) == MemberAttributes.Static) { Output.Write("Shared "); } else if((attributes & MemberAttributes.ScopeMask) == MemberAttributes.Const) { Output.Write("Const "); } } // Output a member access modifier. protected override void OutputMemberAccessModifier (MemberAttributes attributes) { String access; switch(attributes & MemberAttributes.AccessMask) { case MemberAttributes.Assembly: case MemberAttributes.FamilyAndAssembly: access = "Friend "; break; case MemberAttributes.Family: access = "Protected "; break; case MemberAttributes.FamilyOrAssembly: access = "Protected Friend "; break; case MemberAttributes.Private: access = "Private "; break; case MemberAttributes.Public: access = "Public "; break; default: return; } Output.Write(access); } // Output a member scope modifier. protected override void OutputMemberScopeModifier (MemberAttributes attributes) { if((attributes & MemberAttributes.VTableMask) == MemberAttributes.New) { Output.Write("Shadows "); } switch(attributes & MemberAttributes.ScopeMask) { case MemberAttributes.Abstract: Output.Write("MustOverride "); break;; case MemberAttributes.Final: break;; case MemberAttributes.Static: Output.Write("Shared "); break;; case MemberAttributes.Override: Output.Write("Overrides "); break;; default: { if((attributes & MemberAttributes.AccessMask) == MemberAttributes.Public || (attributes & MemberAttributes.AccessMask) == MemberAttributes.Family) { Output.Write("Overridable "); } } break; } } // Output a binary operator. protected override void OutputOperator(CodeBinaryOperatorType op) { String oper; switch(op) { case CodeBinaryOperatorType.Add: oper = "+"; break; case CodeBinaryOperatorType.Subtract: oper = "-"; break; case CodeBinaryOperatorType.Multiply: oper = "*"; break; case CodeBinaryOperatorType.Divide: oper = "/"; break; case CodeBinaryOperatorType.Modulus: oper = "Mod"; break; case CodeBinaryOperatorType.Assign: oper = "="; break; case CodeBinaryOperatorType.IdentityInequality: oper = "<>"; break; case CodeBinaryOperatorType.IdentityEquality: oper = "=="; break; case CodeBinaryOperatorType.ValueEquality: oper = "="; break; case CodeBinaryOperatorType.BitwiseOr: oper = "Or"; break; case CodeBinaryOperatorType.BitwiseAnd: oper = "And"; break; case CodeBinaryOperatorType.BooleanOr: oper = "OrElse"; break; case CodeBinaryOperatorType.BooleanAnd: oper = "AndAlso"; break; case CodeBinaryOperatorType.LessThan: oper = "<"; break; case CodeBinaryOperatorType.LessThanOrEqual: oper = "<="; break; case CodeBinaryOperatorType.GreaterThan: oper = ">"; break; case CodeBinaryOperatorType.GreaterThanOrEqual: oper = ">="; break; default: return; } Output.Write(oper); } // Output a type. protected override void OutputType(CodeTypeReference typeRef) { Output.Write(GetTypeOutput(typeRef)); } // Output the attributes for a type. protected override void OutputTypeAttributes (TypeAttributes attributes, bool isStruct, bool isEnum) { switch(attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedPrivate: Output.Write("Private "); break; case TypeAttributes.Public: case TypeAttributes.NestedPublic: Output.Write("Public "); break; } if(isStruct) { Output.Write("Structure "); } else if(isEnum) { Output.Write("Enum "); } else { if((attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) { Output.Write("Interface "); } else { if((attributes & TypeAttributes.Sealed) != 0) { Output.Write("NotInheritable "); } if((attributes & TypeAttributes.Abstract) != 0) { Output.Write("MustInherit "); } Output.Write("Class "); } } } // Output a type name pair. protected override void OutputTypeNamePair (CodeTypeReference typeRef, String name) { OutputIdentifier(name); Output.Write(" As "); OutputType(typeRef); } // Quote a snippet string. protected override String QuoteSnippetString(String value) { return "\"" + value.Replace("\"", "\"\"") + "\""; } // Determine if this code generator supports a particular // set of generator options. protected override bool Supports(GeneratorSupport supports) { return ((supports & (GeneratorSupport)0x001FFFFF) == supports); } }; // class VBCodeCompiler #endif // CONFIG_CODEDOM }; // namespace System.CodeDom.Compiler
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.Diagnostics; using System.Text; /// <summary> /// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> internal struct XsdDuration { private int _years; private int _months; private int _days; private int _hours; private int _minutes; private int _seconds; private uint _nanoseconds; // High bit is used to indicate whether duration is negative private const uint NegativeBit = 0x80000000; private enum Parts { HasNone = 0, HasYears = 1, HasMonths = 2, HasDays = 4, HasHours = 8, HasMinutes = 16, HasSeconds = 32, } public enum DurationType { Duration, YearMonthDuration, DayTimeDuration, }; /// <summary> /// Construct an XsdDuration from component parts. /// </summary> public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) { if (years < 0) throw new ArgumentOutOfRangeException(nameof(years)); if (months < 0) throw new ArgumentOutOfRangeException(nameof(months)); if (days < 0) throw new ArgumentOutOfRangeException(nameof(days)); if (hours < 0) throw new ArgumentOutOfRangeException(nameof(hours)); if (minutes < 0) throw new ArgumentOutOfRangeException(nameof(minutes)); if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException(nameof(nanoseconds)); _years = years; _months = months; _days = days; _hours = hours; _minutes = minutes; _seconds = seconds; _nanoseconds = (uint)nanoseconds; if (isNegative) _nanoseconds |= NegativeBit; } /// <summary> /// Construct an XsdDuration from a TimeSpan value. /// </summary> public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration) { } /// <summary> /// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or /// an xdt:yearMonthDuration. /// </summary> public XsdDuration(TimeSpan timeSpan, DurationType durationType) { long ticks = timeSpan.Ticks; ulong ticksPos; bool isNegative; if (ticks < 0) { // Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case isNegative = true; ticksPos = unchecked((ulong)-ticks); } else { isNegative = false; ticksPos = (ulong)ticks; } if (durationType == DurationType.YearMonthDuration) { int years = (int)(ticksPos / ((ulong)TimeSpan.TicksPerDay * 365)); int months = (int)((ticksPos % ((ulong)TimeSpan.TicksPerDay * 365)) / ((ulong)TimeSpan.TicksPerDay * 30)); if (months == 12) { // If remaining days >= 360 and < 365, then round off to year years++; months = 0; } this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0); } else { Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration); // Tick count is expressed in 100 nanosecond intervals _nanoseconds = (uint)(ticksPos % 10000000) * 100; if (isNegative) _nanoseconds |= NegativeBit; _years = 0; _months = 0; _days = (int)(ticksPos / (ulong)TimeSpan.TicksPerDay); _hours = (int)((ticksPos / (ulong)TimeSpan.TicksPerHour) % 24); _minutes = (int)((ticksPos / (ulong)TimeSpan.TicksPerMinute) % 60); _seconds = (int)((ticksPos / (ulong)TimeSpan.TicksPerSecond) % 60); } } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s) : this(s, DurationType.Duration) { } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s, DurationType durationType) { XsdDuration result; Exception exception = TryParse(s, durationType, out result); if (exception != null) { throw exception; } _years = result.Years; _months = result.Months; _days = result.Days; _hours = result.Hours; _minutes = result.Minutes; _seconds = result.Seconds; _nanoseconds = (uint)result.Nanoseconds; if (result.IsNegative) { _nanoseconds |= NegativeBit; } return; } /// <summary> /// Return true if this duration is negative. /// </summary> public bool IsNegative { get { return (_nanoseconds & NegativeBit) != 0; } } /// <summary> /// Return number of years in this duration (stored in 31 bits). /// </summary> public int Years { get { return _years; } } /// <summary> /// Return number of months in this duration (stored in 31 bits). /// </summary> public int Months { get { return _months; } } /// <summary> /// Return number of days in this duration (stored in 31 bits). /// </summary> public int Days { get { return _days; } } /// <summary> /// Return number of hours in this duration (stored in 31 bits). /// </summary> public int Hours { get { return _hours; } } /// <summary> /// Return number of minutes in this duration (stored in 31 bits). /// </summary> public int Minutes { get { return _minutes; } } /// <summary> /// Return number of seconds in this duration (stored in 31 bits). /// </summary> public int Seconds { get { return _seconds; } } /// <summary> /// Return number of nanoseconds in this duration. /// </summary> public int Nanoseconds { get { return (int)(_nanoseconds & ~NegativeBit); } } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan() { return ToTimeSpan(DurationType.Duration); } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan(DurationType durationType) { TimeSpan result; Exception exception = TryToTimeSpan(durationType, out result); if (exception != null) { throw exception; } return result; } internal Exception TryToTimeSpan(out TimeSpan result) { return TryToTimeSpan(DurationType.Duration, out result); } internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result) { Exception exception = null; ulong ticks = 0; // Throw error if result cannot fit into a long try { checked { // Discard year and month parts if constructing TimeSpan for DayTimeDuration if (durationType != DurationType.DayTimeDuration) { ticks += ((ulong)_years + (ulong)_months / 12) * 365; ticks += ((ulong)_months % 12) * 30; } // Discard day and time parts if constructing TimeSpan for YearMonthDuration if (durationType != DurationType.YearMonthDuration) { ticks += (ulong)_days; ticks *= 24; ticks += (ulong)_hours; ticks *= 60; ticks += (ulong)_minutes; ticks *= 60; ticks += (ulong)_seconds; // Tick count interval is in 100 nanosecond intervals (7 digits) ticks *= (ulong)TimeSpan.TicksPerSecond; ticks += (ulong)Nanoseconds / 100; } else { // Multiply YearMonth duration by number of ticks per day ticks *= (ulong)TimeSpan.TicksPerDay; } if (IsNegative) { // Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow if (ticks == (ulong)Int64.MaxValue + 1) { result = new TimeSpan(Int64.MinValue); } else { result = new TimeSpan(-((long)ticks)); } } else { result = new TimeSpan((long)ticks); } return null; } } catch (OverflowException) { result = TimeSpan.MinValue; exception = new OverflowException(SR.Format(SR.XmlConvert_Overflow, durationType, "TimeSpan")); } return exception; } /// <summary> /// Return the string representation of this Xsd duration. /// </summary> public override string ToString() { return ToString(DurationType.Duration); } /// <summary> /// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or /// xdt:yearMonthDuration rules. /// </summary> internal string ToString(DurationType durationType) { StringBuilder sb = new StringBuilder(20); int nanoseconds, digit, zeroIdx, len; if (IsNegative) sb.Append('-'); sb.Append('P'); if (durationType != DurationType.DayTimeDuration) { if (_years != 0) { sb.Append(XmlConvert.ToString(_years)); sb.Append('Y'); } if (_months != 0) { sb.Append(XmlConvert.ToString(_months)); sb.Append('M'); } } if (durationType != DurationType.YearMonthDuration) { if (_days != 0) { sb.Append(XmlConvert.ToString(_days)); sb.Append('D'); } if (_hours != 0 || _minutes != 0 || _seconds != 0 || Nanoseconds != 0) { sb.Append('T'); if (_hours != 0) { sb.Append(XmlConvert.ToString(_hours)); sb.Append('H'); } if (_minutes != 0) { sb.Append(XmlConvert.ToString(_minutes)); sb.Append('M'); } nanoseconds = Nanoseconds; if (_seconds != 0 || nanoseconds != 0) { sb.Append(XmlConvert.ToString(_seconds)); if (nanoseconds != 0) { sb.Append('.'); len = sb.Length; sb.Length += 9; zeroIdx = sb.Length - 1; for (int idx = zeroIdx; idx >= len; idx--) { digit = nanoseconds % 10; sb[idx] = (char)(digit + '0'); if (zeroIdx == idx && digit == 0) zeroIdx--; nanoseconds /= 10; } sb.Length = zeroIdx + 1; } sb.Append('S'); } } // Zero is represented as "PT0S" if (sb[sb.Length - 1] == 'P') sb.Append("T0S"); } else { // Zero is represented as "T0M" if (sb[sb.Length - 1] == 'P') sb.Append("0M"); } return sb.ToString(); } internal static Exception TryParse(string s, out XsdDuration result) { return TryParse(s, DurationType.Duration, out result); } internal static Exception TryParse(string s, DurationType durationType, out XsdDuration result) { string errorCode; int length; int value, pos, numDigits; Parts parts = Parts.HasNone; result = new XsdDuration(); s = s.Trim(); length = s.Length; pos = 0; numDigits = 0; if (pos >= length) goto InvalidFormat; if (s[pos] == '-') { pos++; result._nanoseconds = NegativeBit; } else { result._nanoseconds = 0; } if (pos >= length) goto InvalidFormat; if (s[pos++] != 'P') goto InvalidFormat; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'Y') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasYears; result._years = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMonths; result._months = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'D') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasDays; result._days = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'T') { if (numDigits != 0) goto InvalidFormat; pos++; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'H') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasHours; result._hours = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMinutes; result._minutes = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == '.') { pos++; parts |= Parts.HasSeconds; result._seconds = value; errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits); if (errorCode != null) goto Error; if (numDigits == 0) { //If there are no digits after the decimal point, assume 0 value = 0; } // Normalize to nanosecond intervals for (; numDigits > 9; numDigits--) value /= 10; for (; numDigits < 9; numDigits++) value *= 10; result._nanoseconds |= (uint)value; if (pos >= length) goto InvalidFormat; if (s[pos] != 'S') goto InvalidFormat; if (++pos == length) goto Done; } else if (s[pos] == 'S') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasSeconds; result._seconds = value; if (++pos == length) goto Done; } } // Duration cannot end with digits if (numDigits != 0) goto InvalidFormat; // No further characters are allowed if (pos != length) goto InvalidFormat; Done: // At least one part must be defined if (parts == Parts.HasNone) goto InvalidFormat; if (durationType == DurationType.DayTimeDuration) { if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0) goto InvalidFormat; } else if (durationType == DurationType.YearMonthDuration) { if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0) goto InvalidFormat; } return null; InvalidFormat: return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, durationType)); Error: return new OverflowException(SR.Format(SR.XmlConvert_Overflow, s, durationType)); } /// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is /// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in /// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32: /// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits) /// 2. If eatDigits is false, an overflow exception is thrown private static string TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits) { int offsetStart = offset; int offsetEnd = s.Length; int digit; result = 0; numDigits = 0; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { digit = s[offset] - '0'; if (result > (Int32.MaxValue - digit) / 10) { if (!eatDigits) { return SR.XmlConvert_Overflow; } // Skip past any remaining digits numDigits = offset - offsetStart; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { offset++; } return null; } result = result * 10 + digit; offset++; } numDigits = offset - offsetStart; return null; } } }
// 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.PetstoreV2AllSync { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for SwaggerPetstoreV2. /// </summary> public static partial class SwaggerPetstoreV2Extensions { /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Pet> AddPetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null) { return operations.AddPetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdatePetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null) { return operations.UpdatePetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<IList<Pet>> FindPetsByStatusWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> status, Dictionary<string, List<string>> customHeaders = null) { return operations.FindPetsByStatusWithHttpMessagesAsync(status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<IList<Pet>> FindPetsByTagsWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> tags, Dictionary<string, List<string>> customHeaders = null) { return operations.FindPetsByTagsWithHttpMessagesAsync(tags, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Pet> GetPetByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Dictionary<string, List<string>> customHeaders = null) { return operations.GetPetByIdWithHttpMessagesAsync(petId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, fileContent, fileName, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdatePetWithFormWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null) { return operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "") { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeletePetWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null) { return operations.DeletePetWithHttpMessagesAsync(petId, apiKey, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<IDictionary<string, int?>> GetInventoryWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null) { return operations.GetInventoryWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Order> PlaceOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, Order body, Dictionary<string, List<string>> customHeaders = null) { return operations.PlaceOrderWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Order> GetOrderByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null) { return operations.GetOrderByIdWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeleteOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null) { return operations.DeleteOrderWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstoreV2 operations, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse CreateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, User body, Dictionary<string, List<string>> customHeaders = null) { return operations.CreateUserWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse CreateUsersWithArrayInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null) { return operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse CreateUsersWithListInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null) { return operations.CreateUsersWithListInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<string,LoginUserHeaders> LoginUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, string password, Dictionary<string, List<string>> customHeaders = null) { return operations.LoginUserWithHttpMessagesAsync(username, password, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstoreV2 operations) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse LogoutUserWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null) { return operations.LogoutUserWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<User> GetUserByNameWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null) { return operations.GetUserByNameWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, User body, Dictionary<string, List<string>> customHeaders = null) { return operations.UpdateUserWithHttpMessagesAsync(username, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeleteUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null) { return operations.DeleteUserWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
using System; using Orchard.Taxonomies.Models; using Orchard.Taxonomies.Services; using LETS.Models; using Orchard; using Orchard.ContentManagement; using Orchard.ContentManagement.MetaData; using Orchard.Core.Common.Models; using Orchard.Core.Contents.Extensions; using Orchard.Core.Title.Models; using Orchard.Data.Migration; using Orchard.Indexing; using Orchard.Security; using Orchard.Settings; namespace LETS { public class Migrations : DataMigrationImpl { private readonly ITaxonomyService _taxonomyService; private readonly IOrchardServices _orchardServices; private readonly ISiteService _siteService; private readonly IMembershipService _membershipService; public Migrations(ITaxonomyService taxonomyService, IOrchardServices orchardServices, ISiteService siteService, IMembershipService membershipService) { _taxonomyService = taxonomyService; _orchardServices = orchardServices; _siteService = siteService; _membershipService = membershipService; } public int Create() { // LETS settings SchemaBuilder.CreateTable("LETSSettingsPartRecord", table => table .ContentPartRecord() .Column<int>("IdRoleMember") .Column<int>("IdTaxonomyNotices") .Column<string>("CurrencyUnit") .Column<int>("MaximumNoticeAgeDays") .Column<int>( "OldestRecordableTransactionDays") .Column<int>("DefaultTurnoverDays") .Column<bool>("UseDemurrage") .Column<int>("DemurrageTimeIntervalDays") .Column<string>("DemurrageSteps") .Column<int>("IdDemurrageRecipient") .Column<string>("IdMailChimpList") .Column<string>("MemberLinksZone") .Column<string>("MemberLinksPosition") .Column<string>("MemberNoticesZone") .Column<string>("MemberNoticesPosition") .Column<DateTime>("DemurrageStartDate")); // Notice type SchemaBuilder.CreateTable("NoticeTypePartRecord", table => table .Column<int>("RequiredCount") .Column<int>("SortOrder") .ContentPartRecord()); ContentDefinitionManager.AlterPartDefinition("NoticeTypePart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("Notice Type", type => type .Named("NoticeType") .WithPart("NoticeTypePart") .WithPart("TitlePart") .WithPart("CommonPart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'slug'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .Creatable() .Indexed()); // Member SchemaBuilder.CreateTable("MemberPartRecord", table => table .ContentPartRecord() .Column<string>("FirstName", c => c.WithLength(50)) .Column<string>("LastName", c => c.WithLength(50)) .Column<string>("Telephone") .Column<int>("OpeningBalance")); ContentDefinitionManager.AlterPartDefinition("MemberPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("User", type => type .WithPart("MemberPart") .Indexed()); // Locality SchemaBuilder.CreateTable("LocalityPartRecord", table => table .Column<string>("Postcode") .ContentPartRecord()); ContentDefinitionManager.AlterPartDefinition("LocalityPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("Locality", type => type .WithPart("LocalityPart") .WithPart("TitlePart") .WithPart("CommonPart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'slug'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .Creatable() .Indexed()); // Address SchemaBuilder.CreateTable("AddressPartRecord", table => table .ContentPartRecord().Column<int>("LocalityPartRecord_Id") .Column<string>("StreetAddress") .Column<string>("LatLong")); ContentDefinitionManager.AlterPartDefinition("AddressPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("User", type => type .WithPart("AddressPart")); // Category var categoryTaxonomy = _taxonomyService.GetTaxonomyByName("Category"); if (categoryTaxonomy == null) { categoryTaxonomy = _orchardServices.ContentManager.Create<TaxonomyPart>("Taxonomy", VersionOptions.Draft); categoryTaxonomy.Name = "Category"; categoryTaxonomy.As<TitlePart>().Title = "Category"; categoryTaxonomy.As<CommonPart>().Owner = _membershipService.GetUser(_siteService.GetSiteSettings().SuperUser); _orchardServices.ContentManager.Publish(categoryTaxonomy.ContentItem); //_orchardServices.ContentManager.Flush(); _siteService.GetSiteSettings().As<LETSSettingsPart>().IdTaxonomyNotices = categoryTaxonomy.Id; } // Notice SchemaBuilder.CreateTable("NoticePartRecord", table => table .ContentPartRecord() .Column<int>("NoticeTypePartRecord_Id") .Column<int>("Price")); ContentDefinitionManager.AlterPartDefinition("NoticePart", part => part .WithField("PaymentTerms", field => field .OfType("EnumerationField") .WithSetting( "EnumerationFieldSettings.Options", string.Join(Environment.NewLine, new[] { "free", "negotiable", "plus $costs" })) .WithSetting( "EnumerationFieldSettings.ListMode", "Checkbox")) .WithField("Per", field => field .OfType("EnumerationField") .WithSetting( "EnumerationFieldSettings.Options", string.Join(Environment.NewLine, new[] { "each", "per hour", "per head" })) .WithSetting( "EnumerationFieldSettings.ListMode", "Radiobutton")) .WithField("Description", field => field .OfType("TextField") .WithSetting( "TextFieldSettings.Flavor", "Textarea") .WithSetting("TextFieldSettings.Hint", "Don't add your contact details here. They will be added automatically.") ) //.WithField("Photos", field => field // .OfType("AgileUploaderField") // .WithSetting( // "AgileUploaderFieldSettings.MaxWidth", "870") // .WithSetting( // "AgileUploaderFieldSettings.MaxHeight", "600") // .WithSetting( // "AgileUploaderFieldSettings.Hint", "Upload your photos here, they will be resized automatically before upload") // .WithSetting( // "AgileUploaderFieldSettings.MediaFolder", "{user-id}/{content-type}") //) .WithField("Category", field => field .OfType("TaxonomyField") .WithSetting("TaxonomyFieldSettings.Taxonomy", "Category") .WithSetting("TaxonomyFieldSettings.LeavesOnly", "true") .WithSetting("TaxonomyFieldSettings.SingleChoice", "true") .WithSetting("FieldIndexing.Included", "true")) .Attachable()); ContentDefinitionManager.AlterTypeDefinition("Notice", type => type .WithPart("NoticePart") .WithPart("TitlePart") .WithPart("CommonPart") .WithPart("ArchiveLaterPart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Category then Slug', Pattern: '{Content.NoticeCategory}/{Content.Slug}', Description: 'Category slug then notice slug'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .Creatable() .Indexed()); SchemaBuilder.CreateTable("TransactionPartRecord", table => table .ContentPartRecord() .Column<DateTime>("TransactionDate") .Column<string>("Description") .Column<int>("NoticePartRecord_Id") .Column<int>("SellerMemberPartRecord_Id") .Column<int>("BuyerMemberPartRecord_Id") .Column<int>("Value") .Column<int>("CreditValue") .Column<string>("TransactionType")); ContentDefinitionManager.AlterPartDefinition("TransactionPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("Transaction", type => type .WithPart("TransactionPart") .WithPart("CommonPart") .WithPart("IdentityPart") .Indexed()); SchemaBuilder.CreateTable("CreditUsageRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<int>("IdTransactionEarnt", c => c.NotNull()) .Column<string>("TransactionType", c => c.NotNull()) .Column<int>("Value", c => c.NotNull()) .Column<DateTime>("RecordedDate") .Column<int>("IdTransactionSpent", c => c.NotNull())); SchemaBuilder.CreateForeignKey("CreditUsage_TransactionEarnt", "CreditUsageRecord", new[] { "IdTransactionEarnt" }, "TransactionPartRecord", new[] { "Id" }); //SchemaBuilder.CreateForeignKey("CreditUsage_TransactionSpent", "CreditUsageRecord", new[] { "IdTransactionSpent" }, // "TransactionPartRecord", new[] { "Id" }); SchemaBuilder.CreateTable("MemberAdminPartRecord", table => table .ContentPartRecord() .Column<int>("OpeningBalance") .Column<DateTime>("JoinDate") .Column<string>("MemberType")); ContentDefinitionManager.AlterPartDefinition("MemberAdminPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("User", type => type .WithPart("MemberAdminPart") .Indexed()); SchemaBuilder.CreateTable("MemberLinksPartRecord", table => table .ContentPartRecord() .Column<string>("Website") .Column<string>("Facebook") .Column<string>("Twitter") .Column<string>("LinkedIn") .Column<string>("Tumblr") .Column<string>("Flickr") .Column<string>("Pinterest") .Column<string>("GooglePlus") .Column<string>("Goodreads") .Column<string>("Skype")); ContentDefinitionManager.AlterPartDefinition("MemberLinksPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("User", type => type .WithPart("MemberLinksPart") .Indexed()); ContentDefinitionManager.AlterTypeDefinition("AuthNavigationWidget", type => type .WithPart("AuthNavigationWidgetPart") .WithPart("WidgetPart") .WithPart("CommonPart") .WithSetting("Stereotype", "Widget")); SchemaBuilder.CreateTable("MemberAccessOnlyPartRecord", table => table .ContentPartRecord()); ContentDefinitionManager.AlterTypeDefinition("Member Only Page", type => type .Named("MemberOnlyPage") .WithPart("MemberAccessOnlyPart") .WithPart("TitlePart") .WithPart("PublishLaterPart") .WithPart("BodyPart") .WithPart("TagsPart") .WithPart("LocalizationPart") .WithPart("CommonPart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'my-page'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .Creatable() .Draftable() .Indexed()); SchemaBuilder.CreateTable("MembersMapPartRecord", table => table .Column<double>("Latitude") .Column<double>("Longitude") .Column<string>("ApiKey") .Column<int>("MapWidth") .Column<int>("MapHeight") .Column<int>("ZoomLevel") .ContentPartRecord()); ContentDefinitionManager.AlterPartDefinition("MembersMapPart", part => part .Attachable()); ContentDefinitionManager.AlterTypeDefinition("MembersMapWidget", cfg => cfg .WithPart("MembersMapPart") .WithPart("WidgetPart") .WithPart("CommonPart") .WithSetting("Stereotype", "Widget")); ContentDefinitionManager.AlterTypeDefinition("StatsWidget", type => type .WithPart("StatsWidgetPart") .WithPart("WidgetPart") .WithPart("CommonPart") .WithSetting("Stereotype", "Widget")); SchemaBuilder.CreateTable("TransactionRecordSimulation", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<int>("IdTransaction") .Column<DateTime>("TransactionDate") .Column<string>("Description") .Column<int>("SellerMemberPartRecord_Id") .Column<int>("BuyerMemberPartRecord_Id") .Column<int>("Value") .Column<int>("CreditValue") .Column<string>("TransactionType")); SchemaBuilder.CreateTable("CreditUsageRecordSimulation", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<int>("IdTransactionEarnt", c => c.NotNull()) .Column<string>("TransactionType", c => c.NotNull()) .Column<int>("Value", c => c.NotNull()) .Column<DateTime>("RecordedDate") .Column<int>("IdTransactionSpent") .Column<int>("IdCreditUsage")); SchemaBuilder.ExecuteSql("CREATE FUNCTION LETS_CalculateMemberBalance (@Id int) RETURNS int AS BEGIN " + "DECLARE @Balance int DECLARE @Credits int DECLARE @Debits int " + "SET @Credits = (SELECT COALESCE(SUM(Value), 0) FROM LETS_TransactionPartRecord t " + "join Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id WHERE SellerMemberPartRecord_Id = @Id and v.Published = 1) " + "SET @Debits = (SELECT COALESCE(SUM(Value), 0) FROM LETS_TransactionPartRecord t join Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id " + "WHERE BuyerMemberPartRecord_Id = @Id and v.Published = 1) " + "SET @Balance = @Credits - @Debits RETURN @Balance END"); SchemaBuilder.ExecuteSql("CREATE FUNCTION LETS_CalculateMemberTurnover (@Id int, @Days int) RETURNS int AS BEGIN " + "DECLARE @Turnover int " + "SET @Turnover = (SELECT COALESCE(SUM(Value), 0) FROM LETS_TransactionPartRecord t join Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id " + "WHERE (SellerMemberPartRecord_Id = @Id or BuyerMemberPartRecord_Id = @Id) and v.Published = 1 AND t.TransactionType = 'Trade' AND DATEDIFF(DAY, t.TransactionDate, GETDATE()) <= @Days) " + "RETURN @Turnover END"); SchemaBuilder.ExecuteSql("CREATE FUNCTION LETS_CalculateTotalTurnover (@Days int) RETURNS int AS BEGIN " + "DECLARE @Turnover int " + "SET @Turnover = (SELECT COALESCE(SUM(Value), 0) FROM LETS_TransactionPartRecord t join Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id " + "where v.Published = 1 AND t.TransactionType = 'Trade' AND DATEDIFF(DAY, t.TransactionDate, GETDATE()) <= @Days) " + "RETURN @Turnover END"); SchemaBuilder.ExecuteSql("CREATE FUNCTION LETS_GetOldestCreditValueTransaction (@idMember int) RETURNS int AS BEGIN RETURN " + "(SELECT top 1 t.Id FROM LETS_TransactionPartRecord t join LETS_MemberPartRecord m on m.Id = t.SellerMemberPartRecord_Id " + "join Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id where v.Published = '1' and t.CreditValue > 0 and m.Id = @idMember " + "order by t.TransactionDate) END "); SchemaBuilder.ExecuteSql("CREATE FUNCTION LETS_CustomMaxDateFunction (@v1 DATETIME, @v2 DATETIME) RETURNS TABLE AS " + "RETURN SELECT MAX(v) MaxDate FROM (VALUES(@v1),(@v2))dates(v);"); SchemaBuilder.ExecuteSql("CREATE PROCEDURE LETS_GetMemberTransactions @idMember int, @pageSize int, @pageNumber int AS BEGIN " + "CREATE TABLE #memberTransactions (Id int, TransactionDate datetime, Value int, CreditValue int, IdTradingPartner int, Description nvarchar(255), TransactionType nvarchar(255))" + "INSERT INTO #memberTransactions " + "SELECT t.Id, TransactionDate, Value, CreditValue, BuyerMemberPartRecord_Id as 'IdTradingPartner', Description, TransactionType " + "FROM LETS_TransactionPartRecord t JOIN Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id " + "WHERE SellerMemberPartRecord_Id = @idMember AND v.Published = 1 " + "UNION ALL " + "SELECT t.Id, TransactionDate, -Value, CreditValue, SellerMemberPartRecord_Id as 'IdTradingPartner', Description, TransactionType " + "FROM LETS_TransactionPartRecord t JOIN Orchard_Framework_ContentItemVersionRecord v on v.ContentItemRecord_id = t.Id " + "WHERE BuyerMemberPartRecord_Id = @idMember AND v.Published = 1 " + "CREATE TABLE #sortedMemberTransactions (SequenceId int, Id int, TransactionDate datetime, IdTradingPartner int, Description nvarchar(255), Value int, CreditValue int, TransactionType nvarchar(255))" + "INSERT INTO #sortedMemberTransactions " + "SELECT ROW_NUMBER() OVER (ORDER BY Transactiondate, mt.Id) AS SequenceId, mt.Id, TransactionDate, IdTradingPartner, Description, Value, CreditValue, TransactionType " + "FROM #memberTransactions mt DROP TABLE #memberTransactions " + "SELECT ma.Id, TransactionDate, IdTradingPartner, m.FirstName + ' ' + m.LastName as 'TradingPartner', UserName , Description, Value, CreditValue, TransactionType , " + "Value + COALESCE ((SELECT SUM(Value) FROM #sortedMemberTransactions mt WHERE mt.SequenceId < ma.SequenceId),0) AS RunningBalance " + "FROM #sortedMemberTransactions ma JOIN LETS_MemberPartRecord m ON ma.IdTradingPartner = m.Id " + "JOIN Orchard_Users_UserPartRecord u on m.Id = u.Id ORDER BY SequenceId DESC " + "OFFSET (@pageNumber - 1) * @pageSize ROWS FETCH NEXT @pageSize ROWS ONLY DROP TABLE #sortedMemberTransactions " + "END"); return 1; } public int UpdateFrom1() { return 32; } public int UpdateFrom32() { SchemaBuilder.CreateTable("DailyStatsRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<DateTime>("DateCollected") .Column<int>("TotalTurnover") .Column<int>("MemberCount") ); SchemaBuilder.CreateTable("NoticeStatsRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<DateTime>("DateCollected") .Column<int>("IdNoticeType") .Column<int>("NoticeCount") ); return 33; } public int UpdateFrom33() { ContentDefinitionManager.AlterPartDefinition("BannerWidgetPart", part => part .WithField("BackgroundImage", field => field .OfType("MediaLibraryPickerField") .WithSetting("MediaLibraryPickerFieldSettings.Required", "true")) .Attachable()); ContentDefinitionManager.AlterTypeDefinition("BannerWidget", type => type .WithPart("BannerWidgetPart") .WithPart("WidgetPart") .WithPart("CommonPart") .WithPart("BodyPart") .WithSetting("Stereotype", "Widget")); return 36; } public int UpdateFrom36() { SchemaBuilder.AlterTable("MemberLinksPartRecord", t => t.AddColumn<string>("Instagram")); return 38; } public int UpdateFrom38() { ContentDefinitionManager.AlterPartDefinition("NoticePart", part => part .WithField("Photos", field => field .OfType("DropzoneField") .WithSetting( "DropzoneFieldSettings.MaxWidth", "870") .WithSetting( "DropzoneFieldSettings.MaxHeight", "600") .WithSetting( "DropzoneFieldSettings.Hint", "Upload your photos here, they will be resized automatically before upload") .WithSetting( "DropzoneFieldSettings.MediaFolder", "{user-id}/{content-type}") )); return 39; } } }
//----------------------------------------------------------------------------- // // <copyright file="ResourcePart.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // ResourcePart is an implementation of the abstract PackagePart class. It contains an override for GetStreamCore. // // History: // 10/04/2004: [....]: Initial creation. // //----------------------------------------------------------------------------- using System; using System.IO.Packaging; using System.Windows; using System.Windows.Resources; using System.IO; using System.Resources; using System.Globalization; using System.Security; using MS.Internal.Resources; using MS.Internal; //In order to avoid generating warnings about unknown message numbers and //unknown pragmas when compiling your C# source code with the actual C# compiler, //you need to disable warnings 1634 and 1691. (Presharp Documentation) #pragma warning disable 1634, 1691 namespace MS.Internal.AppModel { /// <summary> /// ResourcePart is an implementation of the abstract PackagePart class. It contains an override for GetStreamCore. /// </summary> internal class ResourcePart : System.IO.Packaging.PackagePart { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ #region Public Constructors /// <SecurityNote> /// Critical - because _rmWrapper, which is being set, is marked SecurityCriticalDataForSet. /// </SecurityNote> [SecurityCritical] public ResourcePart(Package container, Uri uri, string name, ResourceManagerWrapper rmWrapper) : base(container, uri) { if (rmWrapper == null) { throw new ArgumentNullException("rmWrapper"); } _rmWrapper.Value = rmWrapper; _name = name; } #endregion //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <SecurityNote> /// Critical - because creating a BamlStream is critical as it stores the assembly /// passed in to it the _assembly field, and this field is used by the /// BamlRecordReader to allow legitimate internal types in Partial Trust. /// Safe - because the _rmWrapper from which the assembly is obtained is SecurityCriticalDataForSet, /// and setting that when a ResourcePart is constructed is treated as safe by /// ResourceContainer.GetPartCore(). The _rmWrapper is trated as safe as it guarantees /// that any stream created by it is always from the assembly that it also holds on to. /// So to the BamlRecordReader, this Assembly that it uses is always guaranteed to be /// the one from which the baml stream that it reads, was created from. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override Stream GetStreamCore(FileMode mode, FileAccess access) { Stream stream = null; stream = EnsureResourceLocationSet(); // in order to find the resource we might have to open a stream. // rather than waste the stream it is returned here and we can use it. if (stream == null) { // Start looking for resources using the current ui culture. // The resource manager will fall back to invariant culture automatically. stream = _rmWrapper.Value.GetStream(_name); if (stream == null) { throw new IOException(SR.Get(SRID.UnableToLocateResource, _name)); } } // // If this is a Baml stream, it will return BamlStream object, which contains // both raw stream and the host assembly. // ContentType curContent = new ContentType(ContentType); if (MimeTypeMapper.BamlMime.AreTypeAndSubTypeEqual(curContent)) { BamlStream bamlStream = new BamlStream(stream, _rmWrapper.Value.Assembly); stream = bamlStream; } return stream; } protected override string GetContentTypeCore() { EnsureResourceLocationSet(); return MS.Internal.MimeTypeMapper.GetMimeTypeFromUri(new Uri(_name,UriKind.RelativeOrAbsolute)).ToString(); } #endregion //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private Stream EnsureResourceLocationSet() { Stream stream = null; lock (_globalLock) { // only need to do this once if (_ensureResourceIsCalled) { return null; } _ensureResourceIsCalled = true; try { // We do not allow the use of .baml in any Avalon public APIs. This is the code pass needed to go through for loading baml file. // Throw here we will catch all those cases. if (String.Compare(Path.GetExtension(_name), ResourceContainer.BamlExt, StringComparison.OrdinalIgnoreCase) == 0) { throw new IOException(SR.Get(SRID.UnableToLocateResource, _name)); } if (String.Compare(Path.GetExtension(_name), ResourceContainer.XamlExt, StringComparison.OrdinalIgnoreCase) == 0) { // try baml extension first since it's our most common senario. string newName = Path.ChangeExtension(_name, ResourceContainer.BamlExt); // Get resource from resource manager wrapper. stream = _rmWrapper.Value.GetStream(newName); if (stream != null) { // Remember that we have .baml for next time GetStreamCore is called. _name = newName; return stream; } } } #pragma warning disable 6502 // PRESharp - Catch statements should not have empty bodies catch (System.Resources.MissingManifestResourceException) { // When the main assembly doesn't contain any resource (all the resources must come from satellite assembly) // then above GetStream( ) just throws exception. We should catch this exception here and let the code continue // to try with the original file name. // If the main assembly does contain resource, but the resource with above _name does't exist, the above GetStream( ) // just returns null without exception. } #pragma warning restore 6502 } // Do not attempt to load the original file name here. If the .baml does not exist or if this resource not // .xaml or .baml then we will follow the normal code path to attempt to load the stream using the original name. return null; } #endregion //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members private SecurityCriticalDataForSet<ResourceManagerWrapper> _rmWrapper; private bool _ensureResourceIsCalled = false; private string _name; private Object _globalLock = new Object(); #endregion Private Members } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Compiler { internal interface ILocalCache { LocalBuilder GetLocal(Type type); void FreeLocal(LocalBuilder local); } /// <summary> /// LambdaCompiler is responsible for compiling individual lambda (LambdaExpression). The complete tree may /// contain multiple lambdas, the Compiler class is responsible for compiling the whole tree, individual /// lambdas are then compiled by the LambdaCompiler. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal sealed partial class LambdaCompiler : ILocalCache { private delegate void WriteBack(LambdaCompiler compiler); // Information on the entire lambda tree currently being compiled private readonly AnalyzedTree _tree; private readonly ILGenerator _ilg; #if FEATURE_COMPILE_TO_METHODBUILDER // The TypeBuilder backing this method, if any private readonly TypeBuilder _typeBuilder; #endif private readonly MethodInfo _method; // Currently active LabelTargets and their mapping to IL labels private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda); // Mapping of labels used for "long" jumps (jumping out and into blocks) private readonly Dictionary<LabelTarget, LabelInfo> _labelInfo = new Dictionary<LabelTarget, LabelInfo>(); // The currently active variable scope private CompilerScope _scope; // The lambda we are compiling private readonly LambdaExpression _lambda; // True if the method's first argument is of type Closure private readonly bool _hasClosureArgument; // Runtime constants bound to the delegate private readonly BoundConstants _boundConstants; // Free list of locals, so we reuse them rather than creating new ones private readonly KeyedStack<Type, LocalBuilder> _freeLocals = new KeyedStack<Type, LocalBuilder>(); /// <summary> /// Creates a lambda compiler that will compile to a dynamic method /// </summary> private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda) { Type[] parameterTypes = GetParameterTypes(lambda, typeof(Closure)); var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes, true); _tree = tree; _lambda = lambda; _method = method; // In a Win8 immersive process user code is not allowed to access non-W8P framework APIs through // reflection or RefEmit. Framework code, however, is given an exemption. // This is to make sure that user code cannot access non-W8P framework APIs via ExpressionTree. // TODO: This API is not available, is there an alternative way to achieve the same. // method.ProfileAPICheck = true; _ilg = method.GetILGenerator(); _hasClosureArgument = true; // These are populated by AnalyzeTree/VariableBinder _scope = tree.Scopes[lambda]; _boundConstants = tree.Constants[lambda]; InitializeMethod(); } #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Creates a lambda compiler that will compile into the provided MethodBuilder /// </summary> private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda, MethodBuilder method) { var scope = tree.Scopes[lambda]; var hasClosureArgument = scope.NeedsClosure; Type[] paramTypes = GetParameterTypes(lambda, hasClosureArgument ? typeof(Closure) : null); method.SetReturnType(lambda.ReturnType); method.SetParameters(paramTypes); var parameters = lambda.Parameters; // parameters are index from 1, with closure argument we need to skip the first arg int startIndex = hasClosureArgument ? 2 : 1; for (int i = 0, n = parameters.Count; i < n; i++) { method.DefineParameter(i + startIndex, ParameterAttributes.None, parameters[i].Name); } _tree = tree; _lambda = lambda; _typeBuilder = (TypeBuilder)method.DeclaringType; _method = method; _hasClosureArgument = hasClosureArgument; _ilg = method.GetILGenerator(); // These are populated by AnalyzeTree/VariableBinder _scope = scope; _boundConstants = tree.Constants[lambda]; InitializeMethod(); } #endif /// <summary> /// Creates a lambda compiler for an inlined lambda /// </summary> private LambdaCompiler( LambdaCompiler parent, LambdaExpression lambda, InvocationExpression invocation) { _tree = parent._tree; _lambda = lambda; _method = parent._method; _ilg = parent._ilg; _hasClosureArgument = parent._hasClosureArgument; #if FEATURE_COMPILE_TO_METHODBUILDER _typeBuilder = parent._typeBuilder; #endif // inlined scopes are associated with invocation, not with the lambda _scope = _tree.Scopes[invocation]; _boundConstants = parent._boundConstants; } private void InitializeMethod() { // See if we can find a return label, so we can emit better IL AddReturnLabel(_lambda); _boundConstants.EmitCacheConstants(this); } internal ILGenerator IL => _ilg; internal IParameterProvider Parameters => _lambda; #if FEATURE_COMPILE_TO_METHODBUILDER internal bool CanEmitBoundConstants => _method is DynamicMethod; #endif #region Compiler entry points /// <summary> /// Compiler entry point /// </summary> /// <param name="lambda">LambdaExpression to compile.</param> /// <returns>The compiled delegate.</returns> internal static Delegate Compile(LambdaExpression lambda) { // 1. Bind lambda AnalyzedTree tree = AnalyzeLambda(ref lambda); // 2. Create lambda compiler LambdaCompiler c = new LambdaCompiler(tree, lambda); // 3. Emit c.EmitLambdaBody(); // 4. Return the delegate. return c.CreateDelegate(); } #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Mutates the MethodBuilder parameter, filling in IL, parameters, /// and return type. /// /// (probably shouldn't be modifying parameters/return type...) /// </summary> internal static void Compile(LambdaExpression lambda, MethodBuilder method) { // 1. Bind lambda AnalyzedTree tree = AnalyzeLambda(ref lambda); // 2. Create lambda compiler LambdaCompiler c = new LambdaCompiler(tree, lambda, method); // 3. Emit c.EmitLambdaBody(); } #endif #endregion private static AnalyzedTree AnalyzeLambda(ref LambdaExpression lambda) { // Spill the stack for any exception handling blocks or other // constructs which require entering with an empty stack lambda = StackSpiller.AnalyzeLambda(lambda); // Bind any variable references in this lambda return VariableBinder.Bind(lambda); } public LocalBuilder GetLocal(Type type) => _freeLocals.TryPop(type) ?? _ilg.DeclareLocal(type); public void FreeLocal(LocalBuilder local) { Debug.Assert(local != null); _freeLocals.Push(local.LocalType, local); } /// <summary> /// Gets the argument slot corresponding to the parameter at the given /// index. Assumes that the method takes a certain number of prefix /// arguments, followed by the real parameters stored in Parameters /// </summary> internal int GetLambdaArgument(int index) { return index + (_hasClosureArgument ? 1 : 0) + (_method.IsStatic ? 0 : 1); } /// <summary> /// Returns the index-th argument. This method provides access to the actual arguments /// defined on the lambda itself, and excludes the possible 0-th closure argument. /// </summary> internal void EmitLambdaArgument(int index) { _ilg.EmitLoadArg(GetLambdaArgument(index)); } internal void EmitClosureArgument() { Debug.Assert(_hasClosureArgument, "must have a Closure argument"); Debug.Assert(_method.IsStatic, "must be a static method"); _ilg.EmitLoadArg(0); } private Delegate CreateDelegate() { Debug.Assert(_method is DynamicMethod); return _method.CreateDelegate(_lambda.Type, new Closure(_boundConstants.ToArray(), null)); } #if FEATURE_COMPILE_TO_METHODBUILDER private FieldBuilder CreateStaticField(string name, Type type) { // We are emitting into someone else's type. We don't want name // conflicts, so choose a long name that is unlikely to conflict. // Naming scheme chosen here is similar to what the C# compiler // uses. return _typeBuilder.DefineField("<ExpressionCompilerImplementationDetails>{" + System.Threading.Interlocked.Increment(ref s_counter) + "}" + name, type, FieldAttributes.Static | FieldAttributes.Private); } #endif /// <summary> /// Creates an uninitialized field suitable for private implementation details /// Works with DynamicMethods or TypeBuilders. /// </summary> private MemberExpression CreateLazyInitializedField<T>(string name) { #if FEATURE_COMPILE_TO_METHODBUILDER if (_method is DynamicMethod) #else Debug.Assert(_method is DynamicMethod); #endif { return Expression.Field(Expression.Constant(new StrongBox<T>(default(T))), "Value"); } #if FEATURE_COMPILE_TO_METHODBUILDER else { return Expression.Field(null, CreateStaticField(name, typeof(T))); } #endif } } }
// 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.Diagnostics; namespace Microsoft.CSharp.RuntimeBinder.Errors { internal static class ErrorFacts { public static string GetMessage(ErrorCode code) { string codeStr; switch (code) { case ErrorCode.ERR_BadBinaryOps: codeStr = SR.BadBinaryOps; break; case ErrorCode.ERR_IntDivByZero: codeStr = SR.IntDivByZero; break; case ErrorCode.ERR_BadIndexLHS: codeStr = SR.BadIndexLHS; break; case ErrorCode.ERR_BadIndexCount: codeStr = SR.BadIndexCount; break; case ErrorCode.ERR_BadUnaryOp: codeStr = SR.BadUnaryOp; break; case ErrorCode.ERR_NoImplicitConv: codeStr = SR.NoImplicitConv; break; case ErrorCode.ERR_NoExplicitConv: codeStr = SR.NoExplicitConv; break; case ErrorCode.ERR_ConstOutOfRange: codeStr = SR.ConstOutOfRange; break; case ErrorCode.ERR_AmbigBinaryOps: codeStr = SR.AmbigBinaryOps; break; case ErrorCode.ERR_AmbigUnaryOp: codeStr = SR.AmbigUnaryOp; break; case ErrorCode.ERR_ValueCantBeNull: codeStr = SR.ValueCantBeNull; break; case ErrorCode.ERR_WrongNestedThis: codeStr = SR.WrongNestedThis; break; case ErrorCode.ERR_NoSuchMember: codeStr = SR.NoSuchMember; break; case ErrorCode.ERR_ObjectRequired: codeStr = SR.ObjectRequired; break; case ErrorCode.ERR_AmbigCall: codeStr = SR.AmbigCall; break; case ErrorCode.ERR_BadAccess: codeStr = SR.BadAccess; break; case ErrorCode.ERR_MethDelegateMismatch: codeStr = SR.MethDelegateMismatch; break; case ErrorCode.ERR_AssgLvalueExpected: codeStr = SR.AssgLvalueExpected; break; case ErrorCode.ERR_NoConstructors: codeStr = SR.NoConstructors; break; case ErrorCode.ERR_BadDelegateConstructor: codeStr = SR.BadDelegateConstructor; break; case ErrorCode.ERR_PropertyLacksGet: codeStr = SR.PropertyLacksGet; break; case ErrorCode.ERR_ObjectProhibited: codeStr = SR.ObjectProhibited; break; case ErrorCode.ERR_AssgReadonly: codeStr = SR.AssgReadonly; break; case ErrorCode.ERR_RefReadonly: codeStr = SR.RefReadonly; break; case ErrorCode.ERR_AssgReadonlyStatic: codeStr = SR.AssgReadonlyStatic; break; case ErrorCode.ERR_RefReadonlyStatic: codeStr = SR.RefReadonlyStatic; break; case ErrorCode.ERR_AssgReadonlyProp: codeStr = SR.AssgReadonlyProp; break; case ErrorCode.ERR_AbstractBaseCall: codeStr = SR.AbstractBaseCall; break; case ErrorCode.ERR_RefProperty: codeStr = SR.RefProperty; break; case ErrorCode.ERR_ManagedAddr: codeStr = SR.ManagedAddr; break; case ErrorCode.ERR_FixedNotNeeded: codeStr = SR.FixedNotNeeded; break; case ErrorCode.ERR_UnsafeNeeded: codeStr = SR.UnsafeNeeded; break; case ErrorCode.ERR_BadBoolOp: codeStr = SR.BadBoolOp; break; case ErrorCode.ERR_MustHaveOpTF: codeStr = SR.MustHaveOpTF; break; case ErrorCode.ERR_CheckedOverflow: codeStr = SR.CheckedOverflow; break; case ErrorCode.ERR_ConstOutOfRangeChecked: codeStr = SR.ConstOutOfRangeChecked; break; case ErrorCode.ERR_AmbigMember: codeStr = SR.AmbigMember; break; case ErrorCode.ERR_SizeofUnsafe: codeStr = SR.SizeofUnsafe; break; case ErrorCode.ERR_FieldInitRefNonstatic: codeStr = SR.FieldInitRefNonstatic; break; case ErrorCode.ERR_CallingFinalizeDepracated: codeStr = SR.CallingFinalizeDepracated; break; case ErrorCode.ERR_CallingBaseFinalizeDeprecated: codeStr = SR.CallingBaseFinalizeDeprecated; break; case ErrorCode.ERR_BadCastInFixed: codeStr = SR.BadCastInFixed; break; case ErrorCode.ERR_NoImplicitConvCast: codeStr = SR.NoImplicitConvCast; break; case ErrorCode.ERR_InaccessibleGetter: codeStr = SR.InaccessibleGetter; break; case ErrorCode.ERR_InaccessibleSetter: codeStr = SR.InaccessibleSetter; break; case ErrorCode.ERR_BadArity: codeStr = SR.BadArity; break; case ErrorCode.ERR_BadTypeArgument: codeStr = SR.BadTypeArgument; break; case ErrorCode.ERR_TypeArgsNotAllowed: codeStr = SR.TypeArgsNotAllowed; break; case ErrorCode.ERR_HasNoTypeVars: codeStr = SR.HasNoTypeVars; break; case ErrorCode.ERR_NewConstraintNotSatisfied: codeStr = SR.NewConstraintNotSatisfied; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedRefType: codeStr = SR.GenericConstraintNotSatisfiedRefType; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum: codeStr = SR.GenericConstraintNotSatisfiedNullableEnum; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface: codeStr = SR.GenericConstraintNotSatisfiedNullableInterface; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar: codeStr = SR.GenericConstraintNotSatisfiedTyVar; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedValType: codeStr = SR.GenericConstraintNotSatisfiedValType; break; case ErrorCode.ERR_TypeVarCantBeNull: codeStr = SR.TypeVarCantBeNull; break; case ErrorCode.ERR_BadRetType: codeStr = SR.BadRetType; break; case ErrorCode.ERR_CantInferMethTypeArgs: codeStr = SR.CantInferMethTypeArgs; break; case ErrorCode.ERR_MethGrpToNonDel: codeStr = SR.MethGrpToNonDel; break; case ErrorCode.ERR_RefConstraintNotSatisfied: codeStr = SR.RefConstraintNotSatisfied; break; case ErrorCode.ERR_ValConstraintNotSatisfied: codeStr = SR.ValConstraintNotSatisfied; break; case ErrorCode.ERR_CircularConstraint: codeStr = SR.CircularConstraint; break; case ErrorCode.ERR_BaseConstraintConflict: codeStr = SR.BaseConstraintConflict; break; case ErrorCode.ERR_ConWithValCon: codeStr = SR.ConWithValCon; break; case ErrorCode.ERR_AmbigUDConv: codeStr = SR.AmbigUDConv; break; case ErrorCode.ERR_PredefinedTypeNotFound: codeStr = SR.PredefinedTypeNotFound; break; case ErrorCode.ERR_PredefinedTypeBadType: codeStr = SR.PredefinedTypeBadType; break; case ErrorCode.ERR_BindToBogus: codeStr = SR.BindToBogus; break; case ErrorCode.ERR_CantCallSpecialMethod: codeStr = SR.CantCallSpecialMethod; break; case ErrorCode.ERR_BogusType: codeStr = SR.BogusType; break; case ErrorCode.ERR_MissingPredefinedMember: codeStr = SR.MissingPredefinedMember; break; case ErrorCode.ERR_LiteralDoubleCast: codeStr = SR.LiteralDoubleCast; break; case ErrorCode.ERR_UnifyingInterfaceInstantiations: codeStr = SR.UnifyingInterfaceInstantiations; break; case ErrorCode.ERR_ConvertToStaticClass: codeStr = SR.ConvertToStaticClass; break; case ErrorCode.ERR_GenericArgIsStaticClass: codeStr = SR.GenericArgIsStaticClass; break; case ErrorCode.ERR_PartialMethodToDelegate: codeStr = SR.PartialMethodToDelegate; break; case ErrorCode.ERR_IncrementLvalueExpected: codeStr = SR.IncrementLvalueExpected; break; case ErrorCode.ERR_NoSuchMemberOrExtension: codeStr = SR.NoSuchMemberOrExtension; break; case ErrorCode.ERR_ValueTypeExtDelegate: codeStr = SR.ValueTypeExtDelegate; break; case ErrorCode.ERR_BadArgCount: codeStr = SR.BadArgCount; break; case ErrorCode.ERR_BadArgTypes: codeStr = SR.BadArgTypes; break; case ErrorCode.ERR_BadArgType: codeStr = SR.BadArgType; break; case ErrorCode.ERR_RefLvalueExpected: codeStr = SR.RefLvalueExpected; break; case ErrorCode.ERR_BadProtectedAccess: codeStr = SR.BadProtectedAccess; break; case ErrorCode.ERR_BindToBogusProp2: codeStr = SR.BindToBogusProp2; break; case ErrorCode.ERR_BindToBogusProp1: codeStr = SR.BindToBogusProp1; break; case ErrorCode.ERR_BadDelArgCount: codeStr = SR.BadDelArgCount; break; case ErrorCode.ERR_BadDelArgTypes: codeStr = SR.BadDelArgTypes; break; case ErrorCode.ERR_AssgReadonlyLocal: codeStr = SR.AssgReadonlyLocal; break; case ErrorCode.ERR_RefReadonlyLocal: codeStr = SR.RefReadonlyLocal; break; case ErrorCode.ERR_ReturnNotLValue: codeStr = SR.ReturnNotLValue; break; case ErrorCode.ERR_BadArgExtraRef: codeStr = SR.BadArgExtraRef; break; case ErrorCode.ERR_BadArgRef: codeStr = SR.BadArgRef; break; case ErrorCode.ERR_AssgReadonly2: codeStr = SR.AssgReadonly2; break; case ErrorCode.ERR_RefReadonly2: codeStr = SR.RefReadonly2; break; case ErrorCode.ERR_AssgReadonlyStatic2: codeStr = SR.AssgReadonlyStatic2; break; case ErrorCode.ERR_RefReadonlyStatic2: codeStr = SR.RefReadonlyStatic2; break; case ErrorCode.ERR_AssgReadonlyLocalCause: codeStr = SR.AssgReadonlyLocalCause; break; case ErrorCode.ERR_RefReadonlyLocalCause: codeStr = SR.RefReadonlyLocalCause; break; case ErrorCode.ERR_ThisStructNotInAnonMeth: codeStr = SR.ThisStructNotInAnonMeth; break; case ErrorCode.ERR_DelegateOnNullable: codeStr = SR.DelegateOnNullable; break; case ErrorCode.ERR_BadCtorArgCount: codeStr = SR.BadCtorArgCount; break; case ErrorCode.ERR_BadExtensionArgTypes: codeStr = SR.BadExtensionArgTypes; break; case ErrorCode.ERR_BadInstanceArgType: codeStr = SR.BadInstanceArgType; break; case ErrorCode.ERR_BadArgTypesForCollectionAdd: codeStr = SR.BadArgTypesForCollectionAdd; break; case ErrorCode.ERR_InitializerAddHasParamModifiers: codeStr = SR.InitializerAddHasParamModifiers; break; case ErrorCode.ERR_NonInvocableMemberCalled: codeStr = SR.NonInvocableMemberCalled; break; case ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument: codeStr = SR.NamedArgumentSpecificationBeforeFixedArgument; break; case ErrorCode.ERR_BadNamedArgument: codeStr = SR.BadNamedArgument; break; case ErrorCode.ERR_BadNamedArgumentForDelegateInvoke: codeStr = SR.BadNamedArgumentForDelegateInvoke; break; case ErrorCode.ERR_DuplicateNamedArgument: codeStr = SR.DuplicateNamedArgument; break; case ErrorCode.ERR_NamedArgumentUsedInPositional: codeStr = SR.NamedArgumentUsedInPositional; break; default: // means missing resources match the code entry Debug.Assert(false, "Missing resources for the error " + code.ToString()); codeStr = null; break; } return codeStr; } public static string GetMessage(MessageID id) { return id.ToString(); } } }
// ---------------------------------------------------------------------------------- // // 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.Common.Authentication; using Microsoft.Azure.Commands.ScenarioTest.Mocks; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Microsoft.WindowsAzure.Management.Storage; using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.ServiceManagemenet.Common.Models; using Xunit.Abstractions; using RestTestFramework = Microsoft.Rest.ClientRuntime.Azure.TestFramework; namespace Microsoft.Azure.Commands.ScenarioTest.SqlTests { using Graph.RBAC; using Common.Authentication.Abstractions; using ResourceManager.Common; using System.IO; public class SqlTestsBase : RMTestBase { protected SqlEvnSetupHelper helper; private const string TenantIdKey = "TenantId"; private const string DomainKey = "Domain"; public string UserDomain { get; private set; } protected SqlTestsBase(ITestOutputHelper output) { helper = new SqlEvnSetupHelper(); XunitTracingInterceptor tracer = new XunitTracingInterceptor(output); XunitTracingInterceptor.AddToContext(tracer); helper.TracingInterceptor = tracer; } protected virtual void SetupManagementClients(RestTestFramework.MockContext context) { var sqlClient = GetSqlClient(context); var sqlLegacyClient = GetLegacySqlClient(); var resourcesClient = GetResourcesClient(); var newResourcesClient = GetResourcesClient(context); helper.SetupSomeOfManagementClients(sqlClient, sqlLegacyClient, resourcesClient, newResourcesClient); } protected void RunPowerShellTest(params string[] scripts) { TestExecutionHelpers.SetUpSessionAndProfile(); var callingClassType = TestUtilities.GetCallingClass(2); var mockName = TestUtilities.GetCurrentMethodName(2); Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("Microsoft.Resources", null); d.Add("Microsoft.Features", null); d.Add("Microsoft.Authorization", null); var providersToIgnore = new Dictionary<string, string>(); providersToIgnore.Add("Microsoft.Azure.Graph.RBAC.Version1_6.GraphRbacManagementClient", "1.42-previewInternal"); providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01"); HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore); HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords"); // Enable undo functionality as well as mock recording using (RestTestFramework.MockContext context = RestTestFramework.MockContext.Start(callingClassType, mockName)) { SetupManagementClients(context); helper.SetupEnvironment(); helper.SetupModules(AzureModule.AzureResourceManager, "ScenarioTests\\Common.ps1", "ScenarioTests\\" + this.GetType().Name + ".ps1", helper.RMProfileModule, helper.RMResourceModule, helper.RMStorageDataPlaneModule, helper.GetRMModulePath(@"AzureRM.Insights.psd1"), helper.GetRMModulePath(@"AzureRM.Sql.psd1"), "AzureRM.Storage.ps1", "AzureRM.Resources.ps1"); helper.RunPowerShellTest(scripts); } } protected Management.Sql.SqlManagementClient GetSqlClient(RestTestFramework.MockContext context) { Management.Sql.SqlManagementClient client = context.GetServiceClient<Management.Sql.SqlManagementClient>( RestTestFramework.TestEnvironmentFactory.GetTestEnvironment()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationRetryTimeout = 0; } return client; } protected Management.Sql.LegacySdk.SqlManagementClient GetLegacySqlClient() { Management.Sql.LegacySdk.SqlManagementClient client = TestBase.GetServiceClient<Management.Sql.LegacySdk.SqlManagementClient>( new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected StorageManagementClient GetStorageClient() { StorageManagementClient client = TestBase.GetServiceClient<StorageManagementClient>(new RDFETestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected ResourceManagementClient GetResourcesClient() { ResourceManagementClient client = TestBase.GetServiceClient<ResourceManagementClient>(new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected Management.Internal.Resources.ResourceManagementClient GetResourcesClient(RestTestFramework.MockContext context) { Management.Internal.Resources.ResourceManagementClient client = context.GetServiceClient<Management.Internal.Resources.ResourceManagementClient>(RestTestFramework.TestEnvironmentFactory.GetTestEnvironment()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationRetryTimeout = 0; } return client; } protected AuthorizationManagementClient GetAuthorizationManagementClient() { AuthorizationManagementClient client = TestBase.GetServiceClient<AuthorizationManagementClient>(new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected GraphRbacManagementClient GetGraphClient(RestTestFramework.MockContext context) { var environment = RestTestFramework.TestEnvironmentFactory.GetTestEnvironment(); string tenantId = null; if (HttpMockServer.Mode == HttpRecorderMode.Record) { tenantId = environment.Tenant; UserDomain = environment.UserName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries).Last(); HttpMockServer.Variables[TenantIdKey] = tenantId; HttpMockServer.Variables[DomainKey] = UserDomain; } else if (HttpMockServer.Mode == HttpRecorderMode.Playback) { if (HttpMockServer.Variables.ContainsKey(TenantIdKey)) { tenantId = HttpMockServer.Variables[TenantIdKey]; AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant.Id = tenantId; } if (HttpMockServer.Variables.ContainsKey(DomainKey)) { UserDomain = HttpMockServer.Variables[DomainKey]; AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant.Directory = UserDomain; } } var client = context.GetGraphServiceClient<GraphRbacManagementClient>(environment); client.TenantID = tenantId; return client; } protected Management.Storage.StorageManagementClient GetStorageV2Client() { var client = TestBase.GetServiceClient<Management.Storage.StorageManagementClient>(new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } } }
using System; using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// UnderwriterSummary /// </summary> public sealed partial class UnderwriterSummary : DirtyExtensibleObject, IIdentifiable { private DirtyValue<string?>? _appraisal; private DirtyValue<DateTime?>? _appraisalCompletedDate; private DirtyValue<DateTime?>? _appraisalExpiredDate; private DirtyValue<DateTime?>? _appraisalOrderedDate; private DirtyValue<StringEnumValue<UnderwriterSummaryAppraisalType>>? _appraisalType; private DirtyValue<DateTime?>? _approvalExpiredDate; private DirtyValue<string?>? _approvedBy; private DirtyValue<DateTime?>? _approvedDate; private DirtyValue<string?>? _ausNumber; private DirtyValue<DateTime?>? _ausRunDate; private DirtyValue<string?>? _ausSource; private DirtyValue<bool?>? _benefitRequiredIndicator; private DirtyValue<DateTime?>? _clearToCloseDate; private DirtyValue<string?>? _concerns; private DirtyValue<string?>? _conditions; private DirtyValue<DateTime?>? _counterOfferDate; private DirtyValue<StringEnumValue<CounterOfferStatus>>? _counterOfferStatus; private DirtyValue<string?>? _credit; private DirtyValue<DateTime?>? _creditApprovalDate; private DirtyValue<string?>? _deniedBy; private DirtyValue<DateTime?>? _deniedDate; private DirtyValue<DateTime?>? _differentApprovalExpiredDate; private DirtyValue<string?>? _differentApprovedBy; private DirtyValue<DateTime?>? _differentApprovedDate; private DirtyValue<string?>? _exceptions; private DirtyValue<string?>? _exceptionSignOffBy; private DirtyValue<DateTime?>? _exceptionSignOffDate; private DirtyValue<string?>? _id; private DirtyValue<bool?>? _isAgencyManually; private DirtyValue<bool?>? _isAgencyWaiver; private DirtyValue<bool?>? _isAgencyWithAgreement; private DirtyValue<decimal?>? _maxRate; private DirtyValue<DateTime?>? _miOrderedDate; private DirtyValue<DateTime?>? _miReceivedDate; private DirtyValue<decimal?>? _modifiedLoanAmount; private DirtyValue<decimal?>? _modifiedLoanRate; private DirtyValue<int?>? _modifiedLoanTerm; private DirtyValue<decimal?>? _modifiedLtv; private DirtyValue<decimal?>? _modifiedMonthlyPayment; private DirtyValue<string?>? _originalAppraiser; private DirtyValue<decimal?>? _originalAppraisersValue; private DirtyValue<DateTime?>? _resubmittedDate; private DirtyValue<string?>? _reviewAppraiser; private DirtyValue<DateTime?>? _reviewCompletedDate; private DirtyValue<DateTime?>? _reviewRequestedDate; private DirtyValue<StringEnumValue<ReviewType>>? _reviewType; private DirtyValue<decimal?>? _reviewValue; private DirtyValue<DateTime?>? _sentToDate; private DirtyValue<string?>? _signOffBy; private DirtyValue<DateTime?>? _signOffDate; private DirtyValue<string?>? _strengths; private DirtyValue<DateTime?>? _submittedDate; private DirtyValue<string?>? _supervisoryAppraiserLicenseNumber; private DirtyValue<string?>? _suspendedBy; private DirtyValue<DateTime?>? _suspendedDate; private DirtyValue<string?>? _suspendedReasons; /// <summary> /// Underwriting Appraisal Comments [2322] /// </summary> public string? Appraisal { get => _appraisal; set => SetField(ref _appraisal, value); } /// <summary> /// Underwriting Appraisal Completed Date [2353] /// </summary> public DateTime? AppraisalCompletedDate { get => _appraisalCompletedDate; set => SetField(ref _appraisalCompletedDate, value); } /// <summary> /// Underwriting Appraisal Expired Date [2354] /// </summary> public DateTime? AppraisalExpiredDate { get => _appraisalExpiredDate; set => SetField(ref _appraisalExpiredDate, value); } /// <summary> /// Underwriting Appraisal Ordered Date [2352] /// </summary> public DateTime? AppraisalOrderedDate { get => _appraisalOrderedDate; set => SetField(ref _appraisalOrderedDate, value); } /// <summary> /// Underwriting Appraisal Type [2356] /// </summary> public StringEnumValue<UnderwriterSummaryAppraisalType> AppraisalType { get => _appraisalType; set => SetField(ref _appraisalType, value); } /// <summary> /// Underwriting Approval Expired Date [2302] /// </summary> public DateTime? ApprovalExpiredDate { get => _approvalExpiredDate; set => SetField(ref _approvalExpiredDate, value); } /// <summary> /// Underwriting Approved By [2984] /// </summary> public string? ApprovedBy { get => _approvedBy; set => SetField(ref _approvedBy, value); } /// <summary> /// Underwriting Approval Date [2301] /// </summary> public DateTime? ApprovedDate { get => _approvedDate; set => SetField(ref _approvedDate, value); } /// <summary> /// Underwriting AUS Number [2316] /// </summary> public string? AusNumber { get => _ausNumber; set => SetField(ref _ausNumber, value); } /// <summary> /// Underwriting AUS Run [2313] /// </summary> public DateTime? AusRunDate { get => _ausRunDate; set => SetField(ref _ausRunDate, value); } /// <summary> /// Underwriting AUS Source [2312] /// </summary> public string? AusSource { get => _ausSource; set => SetField(ref _ausSource, value); } /// <summary> /// Underwriting Net Tangible Benefit Required [2983] /// </summary> public bool? BenefitRequiredIndicator { get => _benefitRequiredIndicator; set => SetField(ref _benefitRequiredIndicator, value); } /// <summary> /// Underwriting Clear to Close Date [2305] /// </summary> public DateTime? ClearToCloseDate { get => _clearToCloseDate; set => SetField(ref _clearToCloseDate, value); } /// <summary> /// Underwriting Concerns [2320] /// </summary> public string? Concerns { get => _concerns; set => SetField(ref _concerns, value); } /// <summary> /// Underwriting Appraisal Conditions [2362] /// </summary> public string? Conditions { get => _conditions; set => SetField(ref _conditions, value); } /// <summary> /// Underwriting Counter Offer Date [4457] /// </summary> public DateTime? CounterOfferDate { get => _counterOfferDate; set => SetField(ref _counterOfferDate, value); } /// <summary> /// Underwriting Counteroffer Status [4458] /// </summary> public StringEnumValue<CounterOfferStatus> CounterOfferStatus { get => _counterOfferStatus; set => SetField(ref _counterOfferStatus, value); } /// <summary> /// Underwriting Credit Comments [2321] /// </summary> public string? Credit { get => _credit; set => SetField(ref _credit, value); } /// <summary> /// Underwriting Credit Approval Date [2300] /// </summary> public DateTime? CreditApprovalDate { get => _creditApprovalDate; set => SetField(ref _creditApprovalDate, value); } /// <summary> /// Underwriting Denied By [2986] /// </summary> public string? DeniedBy { get => _deniedBy; set => SetField(ref _deniedBy, value); } /// <summary> /// Underwriting Denied Date [2987] /// </summary> public DateTime? DeniedDate { get => _deniedDate; set => SetField(ref _deniedDate, value); } /// <summary> /// Underwriting Different Approval Expired Date [2990] /// </summary> public DateTime? DifferentApprovalExpiredDate { get => _differentApprovalExpiredDate; set => SetField(ref _differentApprovalExpiredDate, value); } /// <summary> /// Underwriting Different Approved By [2988] /// </summary> public string? DifferentApprovedBy { get => _differentApprovedBy; set => SetField(ref _differentApprovedBy, value); } /// <summary> /// Underwriting Different Approved Date [2989] /// </summary> public DateTime? DifferentApprovedDate { get => _differentApprovedDate; set => SetField(ref _differentApprovedDate, value); } /// <summary> /// Underwriting Exceptions Comments [2323] /// </summary> public string? Exceptions { get => _exceptions; set => SetField(ref _exceptions, value); } /// <summary> /// Underwriting Exception Sign Off By [2318] /// </summary> public string? ExceptionSignOffBy { get => _exceptionSignOffBy; set => SetField(ref _exceptionSignOffBy, value); } /// <summary> /// Underwriting Exception Sign Off Date [2317] /// </summary> public DateTime? ExceptionSignOffDate { get => _exceptionSignOffDate; set => SetField(ref _exceptionSignOffDate, value); } /// <summary> /// UnderwriterSummary Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Manually Underwritten according to Agency/GSE Guidelines [3880] /// </summary> public bool? IsAgencyManually { get => _isAgencyManually; set => SetField(ref _isAgencyManually, value); } /// <summary> /// Received Waiver for Agency/GSE Guidelines [3879] /// </summary> public bool? IsAgencyWaiver { get => _isAgencyWaiver; set => SetField(ref _isAgencyWaiver, value); } /// <summary> /// Underwritten According to Contractual Agreement with Agency/GSE [3878] /// </summary> public bool? IsAgencyWithAgreement { get => _isAgencyWithAgreement; set => SetField(ref _isAgencyWithAgreement, value); } /// <summary> /// Underwriting Max Rate [2310] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_4)] public decimal? MaxRate { get => _maxRate; set => SetField(ref _maxRate, value); } /// <summary> /// Underwriting MI Ordered Date [2308] /// </summary> public DateTime? MiOrderedDate { get => _miOrderedDate; set => SetField(ref _miOrderedDate, value); } /// <summary> /// Underwriting MI Received Date [2309] /// </summary> public DateTime? MiReceivedDate { get => _miReceivedDate; set => SetField(ref _miReceivedDate, value); } /// <summary> /// Underwriting Modified Terms Loan Amount [2991] /// </summary> public decimal? ModifiedLoanAmount { get => _modifiedLoanAmount; set => SetField(ref _modifiedLoanAmount, value); } /// <summary> /// Underwriting Modified Terms Interest Rate [2992] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? ModifiedLoanRate { get => _modifiedLoanRate; set => SetField(ref _modifiedLoanRate, value); } /// <summary> /// Underwriting Modified Terms Loan Term [2993] /// </summary> public int? ModifiedLoanTerm { get => _modifiedLoanTerm; set => SetField(ref _modifiedLoanTerm, value); } /// <summary> /// Underwriting Modified Terms Loan to Value [2995] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)] public decimal? ModifiedLtv { get => _modifiedLtv; set => SetField(ref _modifiedLtv, value); } /// <summary> /// Underwriting Modified Terms Principal and Interest [2994] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ModifiedMonthlyPayment { get => _modifiedMonthlyPayment; set => SetField(ref _modifiedMonthlyPayment, value); } /// <summary> /// Underwriting Original Appraiser [2351] /// </summary> public string? OriginalAppraiser { get => _originalAppraiser; set => SetField(ref _originalAppraiser, value); } /// <summary> /// Underwriting Original Appraisers Value [2355] /// </summary> public decimal? OriginalAppraisersValue { get => _originalAppraisersValue; set => SetField(ref _originalAppraisersValue, value); } /// <summary> /// Underwriting Resubmitted Date [2299] /// </summary> public DateTime? ResubmittedDate { get => _resubmittedDate; set => SetField(ref _resubmittedDate, value); } /// <summary> /// Underwriting Review Appraiser [2357] /// </summary> public string? ReviewAppraiser { get => _reviewAppraiser; set => SetField(ref _reviewAppraiser, value); } /// <summary> /// Underwriting Appraisal Review Completed Date [2360] /// </summary> public DateTime? ReviewCompletedDate { get => _reviewCompletedDate; set => SetField(ref _reviewCompletedDate, value); } /// <summary> /// Underwriting Appraisal Review Requested Date [2359] /// </summary> public DateTime? ReviewRequestedDate { get => _reviewRequestedDate; set => SetField(ref _reviewRequestedDate, value); } /// <summary> /// Underwriting Appraisal Review Type [2358] /// </summary> public StringEnumValue<ReviewType> ReviewType { get => _reviewType; set => SetField(ref _reviewType, value); } /// <summary> /// Underwriting Appraisal Review Value [2361] /// </summary> public decimal? ReviewValue { get => _reviewValue; set => SetField(ref _reviewValue, value); } /// <summary> /// Underwriting Date Sent to [2981] /// </summary> public DateTime? SentToDate { get => _sentToDate; set => SetField(ref _sentToDate, value); } /// <summary> /// Underwriting AUS Sign Off By [2315] /// </summary> public string? SignOffBy { get => _signOffBy; set => SetField(ref _signOffBy, value); } /// <summary> /// UnderwriterSummary SignOffDate [2304] /// </summary> public DateTime? SignOffDate { get => _signOffDate; set => SetField(ref _signOffDate, value); } /// <summary> /// Underwriting Strengths [2319] /// </summary> public string? Strengths { get => _strengths; set => SetField(ref _strengths, value); } /// <summary> /// Underwriting Submitted Date [2298] /// </summary> public DateTime? SubmittedDate { get => _submittedDate; set => SetField(ref _submittedDate, value); } /// <summary> /// Supervisory Appraisal Co License # [3243] /// </summary> public string? SupervisoryAppraiserLicenseNumber { get => _supervisoryAppraiserLicenseNumber; set => SetField(ref _supervisoryAppraiserLicenseNumber, value); } /// <summary> /// Underwriting Suspended By [2985] /// </summary> public string? SuspendedBy { get => _suspendedBy; set => SetField(ref _suspendedBy, value); } /// <summary> /// Underwriting Suspended Date [2303] /// </summary> public DateTime? SuspendedDate { get => _suspendedDate; set => SetField(ref _suspendedDate, value); } /// <summary> /// Underwriting Suspended Reasons [2311] /// </summary> public string? SuspendedReasons { get => _suspendedReasons; set => SetField(ref _suspendedReasons, value); } } }
// 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.Data.Common; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents a globally unique identifier to be stored in /// or retrieved from a database. /// </summary> [Serializable] [XmlSchemaProvider("GetXsdType")] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SqlGuid : INullable, IComparable, IXmlSerializable { private const int SizeOfGuid = 16; // Comparison orders. private static readonly int[] s_rgiGuidOrder = new int[16] {10, 11, 12, 13, 14, 15, 8, 9, 6, 7, 4, 5, 0, 1, 2, 3}; // NOTE: If any instance fields change, update SqlTypeWorkarounds type in System.Data.SqlClient. private byte[] m_value; // the SqlGuid is null if m_value is null // constructor // construct a SqlGuid.Null private SqlGuid(bool fNull) { m_value = null; } public SqlGuid(byte[] value) { if (value == null || value.Length != SizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); m_value = new byte[SizeOfGuid]; value.CopyTo(m_value, 0); } internal SqlGuid(byte[] value, bool ignored) { if (value == null || value.Length != SizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); m_value = value; } public SqlGuid(string s) { m_value = (new Guid(s)).ToByteArray(); } public SqlGuid(Guid g) { m_value = g.ToByteArray(); } public SqlGuid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) : this(new Guid(a, b, c, d, e, f, g, h, i, j, k)) { } // INullable public bool IsNull { get { return (m_value == null); } } // property: Value public Guid Value { get { if (IsNull) throw new SqlNullValueException(); else return new Guid(m_value); } } // Implicit conversion from Guid to SqlGuid public static implicit operator SqlGuid(Guid x) { return new SqlGuid(x); } // Explicit conversion from SqlGuid to Guid. Throw exception if x is Null. public static explicit operator Guid(SqlGuid x) { return x.Value; } public byte[] ToByteArray() { byte[] ret = new byte[SizeOfGuid]; m_value.CopyTo(ret, 0); return ret; } public override string ToString() { if (IsNull) return SQLResource.NullString; Guid g = new Guid(m_value); return g.ToString(); } public static SqlGuid Parse(string s) { if (s == SQLResource.NullString) return SqlGuid.Null; else return new SqlGuid(s); } // Comparison operators private static EComparison Compare(SqlGuid x, SqlGuid y) { //Swap to the correct order to be compared for (int i = 0; i < SizeOfGuid; i++) { byte b1, b2; b1 = x.m_value[s_rgiGuidOrder[i]]; b2 = y.m_value[s_rgiGuidOrder[i]]; if (b1 != b2) return (b1 < b2) ? EComparison.LT : EComparison.GT; } return EComparison.EQ; } // Implicit conversions // Explicit conversions // Explicit conversion from SqlString to SqlGuid public static explicit operator SqlGuid(SqlString x) { return x.IsNull ? Null : new SqlGuid(x.Value); } // Explicit conversion from SqlBinary to SqlGuid public static explicit operator SqlGuid(SqlBinary x) { return x.IsNull ? Null : new SqlGuid(x.Value); } // Overloading comparison operators public static SqlBoolean operator ==(SqlGuid x, SqlGuid y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.EQ); } public static SqlBoolean operator !=(SqlGuid x, SqlGuid y) { return !(x == y); } public static SqlBoolean operator <(SqlGuid x, SqlGuid y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.LT); } public static SqlBoolean operator >(SqlGuid x, SqlGuid y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.GT); } public static SqlBoolean operator <=(SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmp = Compare(x, y); return new SqlBoolean(cmp == EComparison.LT || cmp == EComparison.EQ); } public static SqlBoolean operator >=(SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmp = Compare(x, y); return new SqlBoolean(cmp == EComparison.GT || cmp == EComparison.EQ); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator == public static SqlBoolean Equals(SqlGuid x, SqlGuid y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlGuid x, SqlGuid y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlGuid x, SqlGuid y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlGuid x, SqlGuid y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlGuid x, SqlGuid y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlGuid x, SqlGuid y) { return (x >= y); } // Alternative method for conversions. public SqlString ToSqlString() { return (SqlString)this; } public SqlBinary ToSqlBinary() { return (SqlBinary)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlGuid) { SqlGuid i = (SqlGuid)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlGuid)); } public int CompareTo(SqlGuid value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlGuid)) { return false; } SqlGuid i = (SqlGuid)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); m_value = null; } else { m_value = new Guid(reader.ReadElementString()).ToByteArray(); } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(new Guid(m_value))); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("string", XmlSchema.Namespace); } public static readonly SqlGuid Null = new SqlGuid(true); } // SqlGuid } // namespace System.Data.SqlTypes
#region Copyright /*Copyright (C) 2015 Wosad 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. */ #endregion using System; using System.Collections.Generic; using System.Windows.Controls; using Dynamo.Controls; using Dynamo.Models; using Dynamo.Wpf; using ProtoCore.AST.AssociativeAST; using Wosad.Common.CalculationLogger; using Wosad.Dynamo.Common; using Wosad.Loads.ASCE7.Entities; using System.Xml; using Dynamo.Nodes; using Dynamo.Graph; using Dynamo.Graph.Nodes; namespace Wosad.Steel.AISC10.Flexure { /// <summary> ///Section group selection for flexure /// </summary> [NodeName("Flexural section group selection")] [NodeCategory("Wosad.Steel.AISC10.Flexure")] [NodeDescription("Section group selection for flexure")] [IsDesignScriptCompatible] public class FlexuralSectionGroupSelection : UiNodeBase { public FlexuralSectionGroupSelection() { //OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)")); OutPortData.Add(new PortData("SteelShapeGroupFlexure", "Type of steel shape for flexural calculations")); RegisterAllPorts(); //PropertyChanged += NodePropertyChanged; SetDefaultParameters(); } private void SetDefaultParameters() { ReportEntry = ""; SteelShapeType = "IShape"; SymmetryType = "DoublySymmetric"; IsMajorAxisShapeIOrChannel = true; IsDoublySymmetric = true; IsSinglySymmetric = false; BendingAxis = "Major"; SteelShapeGroupFlexure = "F2"; } /// <summary> /// Gets the type of this class, to be used in base class for reflection /// </summary> protected override Type GetModelType() { return GetType(); } #region properties #region InputProperties #endregion #region OutputProperties #region SteelShapeGroupFlexureProperty /// <summary> /// SteelShapeGroupFlexure property /// </summary> /// <value>Type of steel shape for flexural calculations</value> public string _SteelShapeGroupFlexure; public string SteelShapeGroupFlexure { get { return _SteelShapeGroupFlexure; } set { _SteelShapeGroupFlexure = value; RaisePropertyChanged("SteelShapeGroupFlexure"); OnNodeModified(true); } } #endregion #region ReportEntryProperty /// <summary> /// log property /// </summary> /// <value>Calculation entries that can be converted into a report.</value> public string reportEntry; public string ReportEntry { get { return reportEntry; } set { reportEntry = value; RaisePropertyChanged("ReportEntry"); OnNodeModified(true); } } #endregion #endregion #endregion #region Display parameters private void UpdateValuesAndView() { switch (SteelShapeType) { case "IShape": SteelShapeGroupFlexure = "F2"; IsMajorAxisShapeIOrChannel = true; IsIShapeOrChannel = true; break; case "Channel": SteelShapeGroupFlexure = "F2"; IsMajorAxisShapeIOrChannel = true; IsIShapeOrChannel = true; break; case "Angle": SteelShapeGroupFlexure = "F10"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; case "Tee": SteelShapeGroupFlexure = "F9"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; case "DoubleAngle": SteelShapeGroupFlexure = "F9"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; case "RectangularHSS": SteelShapeGroupFlexure = "F7"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; case "CircularHSS": SteelShapeGroupFlexure = "F8"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; case "SolidRectangle": SteelShapeGroupFlexure = "F11"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; case "SolidCircle": SteelShapeGroupFlexure = "F11"; IsMajorAxisShapeIOrChannel = false; IsIShapeOrChannel = false; break; default: SteelShapeGroupFlexure = "F2"; IsMajorAxisShapeIOrChannel = true; IsIShapeOrChannel = true; break; } if (IsMajorAxisShapeIOrChannel == false) { IsDoublySymmetric = false; IsSinglySymmetric = false; } else { if (BendingAxis == "Minor") { IsMajorAxisShapeIOrChannel = false; IsDoublySymmetric = false; IsSinglySymmetric = false; SteelShapeGroupFlexure = "F6"; } else { if (SymmetryType == "DoublySymmetric") { IsDoublySymmetric = true; IsSinglySymmetric = false; } else { SteelShapeGroupFlexure = "F4"; //default value IsDoublySymmetric = false; IsSinglySymmetric = true; } } } } private string _SteelShapeType; public string SteelShapeType { get { return _SteelShapeType; } set { _SteelShapeType = value; RaisePropertyChanged("SteelShapeType"); UpdateValuesAndView(); } } #region I-Shapes and Channels #region IsShapeIOrChannel Property private bool _IsMajorAxisShapeIOrChannel; public bool IsMajorAxisShapeIOrChannel { get { return _IsMajorAxisShapeIOrChannel; } set { _IsMajorAxisShapeIOrChannel = value; RaisePropertyChanged("IsMajorAxisShapeIOrChannel"); } } #endregion #region IsDoublySymmetric Property private bool _IsDoublySymmetric; public bool IsDoublySymmetric { get { return _IsDoublySymmetric; } set { _IsDoublySymmetric = value; RaisePropertyChanged("IsDoublySymmetric"); } } #endregion #region IsSinglySymmetric Property private bool _IsSinglySymmetric; public bool IsSinglySymmetric { get { return _IsSinglySymmetric; } set { _IsSinglySymmetric = value; RaisePropertyChanged("IsSinglySymmetric"); } } #endregion #region IsIShapeOrChannel Property private bool _IsIShapeOrChannel; public bool IsIShapeOrChannel { get { return _IsIShapeOrChannel; } set { _IsIShapeOrChannel = value; RaisePropertyChanged("IsIShapeOrChannel"); } } #endregion #region SymmetryType Property private string _SymmetryType; public string SymmetryType { get { return _SymmetryType; } set { _SymmetryType = value; RaisePropertyChanged("SymmetryType"); UpdateValuesAndView(); } } #endregion #region BendingAxis Property private string _BendingAxis; public string BendingAxis { get { return _BendingAxis; } set { _BendingAxis = value; RaisePropertyChanged("BendingAxis"); UpdateValuesAndView(); } } #endregion #endregion #endregion #region Serialization /// <summary> ///Saves property values to be retained when opening the node /// </summary> protected override void SerializeCore(XmlElement nodeElement, SaveContext context) { base.SerializeCore(nodeElement, context); nodeElement.SetAttribute("SteelShapeGroupFlexure", SteelShapeGroupFlexure); } /// <summary> ///Retrieved property values when opening the node /// </summary> protected override void DeserializeCore(XmlElement nodeElement, SaveContext context) { base.DeserializeCore(nodeElement, context); var attrib = nodeElement.Attributes["SteelShapeGroupFlexure"]; if (attrib == null) return; SteelShapeGroupFlexure = attrib.Value; } #endregion /// <summary> ///Customization of WPF view in Dynamo UI /// </summary> public class FlexuralSectionGroupSelectionViewCustomization : UiNodeBaseViewCustomization, INodeViewCustomization<FlexuralSectionGroupSelection> { public void CustomizeView(FlexuralSectionGroupSelection model, NodeView nodeView) { base.CustomizeView(model, nodeView); SteelShapeGroupFlexureView control = new SteelShapeGroupFlexureView(); control.DataContext = model; nodeView.inputGrid.Children.Add(control); base.CustomizeView(model, nodeView); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.SS.Util { using System; using System.Text; using System.Collections; public class AreaReference { /** The Char (!) that Separates sheet names from cell references */ private const char SHEET_NAME_DELIMITER = '!'; /** The Char (:) that Separates the two cell references in a multi-cell area reference */ private const char CELL_DELIMITER = ':'; /** The Char (') used to quote sheet names when they contain special Chars */ private const char SPECIAL_NAME_DELIMITER = '\''; private static SpreadsheetVersion DEFAULT_SPREADSHEET_VERSION = SpreadsheetVersion.EXCEL97; private CellReference _firstCell; private CellReference _lastCell; private bool _isSingleCell; private SpreadsheetVersion _version; // never null [Obsolete("deprecated POI 3.13 beta 1. Prefer supplying a version.")] public AreaReference(String reference) : this(reference, DEFAULT_SPREADSHEET_VERSION) { } /** * Create an area ref from a string representation. Sheet names containing special Chars should be * delimited and escaped as per normal syntax rules for formulas.<br/> * The area reference must be contiguous (i.e. represent a single rectangle, not a Union of rectangles) */ public AreaReference(String reference, SpreadsheetVersion version) { _version = (null != version) ? version : DEFAULT_SPREADSHEET_VERSION; if (!IsContiguous(reference)) { throw new ArgumentException( "References passed to the AreaReference must be contiguous, " + "use generateContiguous(ref) if you have non-contiguous references"); } String[] parts = SeparateAreaRefs(reference); String part0 = parts[0]; if (parts.Length == 1) { // TODO - probably shouldn't initialize area ref when text is really a cell ref // Need to fix some named range stuff to get rid of this _firstCell = new CellReference(part0); _lastCell = _firstCell; _isSingleCell = true; return; } if (parts.Length != 2) { throw new ArgumentException("Bad area ref '" + reference + "'"); } String part1 = parts[1]; if (IsPlainColumn(part0)) { if (!IsPlainColumn(part1)) { throw new Exception("Bad area ref '" + reference + "'"); } // Special handling for whole-column references // Represented internally as x$1 to x$65536 // which is the maximum range of rows bool firstIsAbs = CellReference.IsPartAbsolute(part0); bool lastIsAbs = CellReference.IsPartAbsolute(part1); int col0 = CellReference.ConvertColStringToIndex(part0); int col1 = CellReference.ConvertColStringToIndex(part1); _firstCell = new CellReference(0, col0, true, firstIsAbs); _lastCell = new CellReference(0xFFFF, col1, true, lastIsAbs); _isSingleCell = false; // TODO - whole row refs } else { _firstCell = new CellReference(part0); _lastCell = new CellReference(part1); _isSingleCell = part0.Equals(part1); } } private static bool IsPlainColumn(String refPart) { for (int i = refPart.Length - 1; i >= 0; i--) { int ch = refPart[i]; if (ch == '$' && i == 0) { continue; } if (ch < 'A' || ch > 'Z') { return false; } } return true; } public static AreaReference GetWholeRow(SpreadsheetVersion version, String start, String end) { if (null == version) { version = DEFAULT_SPREADSHEET_VERSION; } return new AreaReference("$A" + start + ":$" + version.LastColumnName + end, version); } public static AreaReference GetWholeColumn(SpreadsheetVersion version, String start, String end) { if (null == version) { version = DEFAULT_SPREADSHEET_VERSION; } return new AreaReference(start + "$1:" + end + "$" + version.MaxRows, version); } /** * Creates an area ref from a pair of Cell References. */ public AreaReference(CellReference topLeft, CellReference botRight) { _version = DEFAULT_SPREADSHEET_VERSION; bool swapRows = topLeft.Row > botRight.Row; bool swapCols = topLeft.Col > botRight.Col; if (swapRows || swapCols) { int firstRow; int lastRow; int firstColumn; int lastColumn; bool firstRowAbs; bool lastRowAbs; bool firstColAbs; bool lastColAbs; if (swapRows) { firstRow = botRight.Row; firstRowAbs = botRight.IsRowAbsolute; lastRow = topLeft.Row; lastRowAbs = topLeft.IsRowAbsolute; } else { firstRow = topLeft.Row; firstRowAbs = topLeft.IsRowAbsolute; lastRow = botRight.Row; lastRowAbs = botRight.IsRowAbsolute; } if (swapCols) { firstColumn = botRight.Col; firstColAbs = botRight.IsColAbsolute; lastColumn = topLeft.Col; lastColAbs = topLeft.IsColAbsolute; } else { firstColumn = topLeft.Col; firstColAbs = topLeft.IsColAbsolute; lastColumn = botRight.Col; lastColAbs = botRight.IsColAbsolute; } _firstCell = new CellReference(firstRow, firstColumn, firstRowAbs, firstColAbs); _lastCell = new CellReference(lastRow, lastColumn, lastRowAbs, lastColAbs); } else { _firstCell = topLeft; _lastCell = botRight; } _isSingleCell = false; } /** * is the reference for a contiguous (i.e. * Unbroken) area, or is it made up of * several different parts? * (If it Is, you will need to call * .... */ public static bool IsContiguous(String reference) { // If there's a sheet name, strip it off int sheetRefEnd = reference.IndexOf('!'); if (sheetRefEnd != -1) { reference = reference.Substring(sheetRefEnd); } // Check for the , as a sign of non-coniguous if (reference.IndexOf(',') == -1) { return true; } return false; } /** * is the reference for a whole-column reference, * such as C:C or D:G ? */ public static bool IsWholeColumnReference(SpreadsheetVersion version, CellReference topLeft, CellReference botRight) { if (null == version) { version = SpreadsheetVersion.EXCEL97; // how the code used to behave. } // These are represented as something like // C$1:C$65535 or D$1:F$0 // i.e. absolute from 1st row to 0th one if (topLeft.Row == 0 && topLeft.IsRowAbsolute && (botRight.Row == version.LastRowIndex) && botRight.IsRowAbsolute) { return true; } return false; } public bool IsWholeColumnReference() { return IsWholeColumnReference(_version, _firstCell, _lastCell); } /** * Takes a non-contiguous area reference, and * returns an array of contiguous area references. */ public static AreaReference[] GenerateContiguous(String reference) { ArrayList refs = new ArrayList(); String st = reference; string[] token = st.Split(','); foreach (string t in token) { refs.Add( new AreaReference(t) ); } return (AreaReference[])refs.ToArray(typeof(AreaReference)); } /** * @return <c>false</c> if this area reference involves more than one cell */ public bool IsSingleCell { get { return _isSingleCell; } } /** * @return the first cell reference which defines this area. Usually this cell is in the upper * left corner of the area (but this is not a requirement). */ public CellReference FirstCell { get { return _firstCell; } } /** * Note - if this area reference refers to a single cell, the return value of this method will * be identical to that of <c>GetFirstCell()</c> * @return the second cell reference which defines this area. For multi-cell areas, this is * cell diagonally opposite the 'first cell'. Usually this cell is in the lower right corner * of the area (but this is not a requirement). */ public CellReference LastCell { get{return _lastCell;} } /** * Returns a reference to every cell covered by this area */ public CellReference[] GetAllReferencedCells() { // Special case for single cell reference if (_isSingleCell) { return new CellReference[] { _firstCell, }; } // Interpolate between the two int minRow = Math.Min(_firstCell.Row, _lastCell.Row); int maxRow = Math.Max(_firstCell.Row, _lastCell.Row); int minCol = Math.Min(_firstCell.Col, _lastCell.Col); int maxCol = Math.Max(_firstCell.Col, _lastCell.Col); String sheetName = _firstCell.SheetName; ArrayList refs = new ArrayList(); for (int row = minRow; row <= maxRow; row++) { for (int col = minCol; col <= maxCol; col++) { CellReference ref1 = new CellReference(sheetName, row, col, _firstCell.IsRowAbsolute, _firstCell.IsColAbsolute); refs.Add(ref1); } } return (CellReference[])refs.ToArray(typeof(CellReference)); } /** * Example return values: * <table border="0" cellpAdding="1" cellspacing="0" summary="Example return values"> * <tr><th align='left'>Result</th><th align='left'>Comment</th></tr> * <tr><td>A1:A1</td><td>Single cell area reference without sheet</td></tr> * <tr><td>A1:$C$1</td><td>Multi-cell area reference without sheet</td></tr> * <tr><td>Sheet1!A$1:B4</td><td>Standard sheet name</td></tr> * <tr><td>'O''Brien''s Sales'!B5:C6' </td><td>Sheet name with special Chars</td></tr> * </table> * @return the text representation of this area reference as it would appear in a formula. */ public String FormatAsString() { // Special handling for whole-column references if (IsWholeColumnReference()) { return CellReference.ConvertNumToColString(_firstCell.Col) + ":" + CellReference.ConvertNumToColString(_lastCell.Col); } StringBuilder sb = new StringBuilder(32); sb.Append(_firstCell.FormatAsString()); if (!_isSingleCell) { sb.Append(CELL_DELIMITER); if (_lastCell.SheetName == null) { sb.Append(_lastCell.FormatAsString()); } else { // don't want to include the sheet name twice _lastCell.AppendCellReference(sb); } } return sb.ToString(); } public override String ToString() { StringBuilder sb = new StringBuilder(64); sb.Append(this.GetType().Name).Append(" ["); sb.Append(FormatAsString()); sb.Append("]"); return sb.ToString(); } /** * Separates Area refs in two parts and returns them as Separate elements in a String array, * each qualified with the sheet name (if present) * * @return array with one or two elements. never <c>null</c> */ private static String[] SeparateAreaRefs(String reference) { // TODO - refactor cell reference parsing logic to one place. // Current known incarnations: // FormulaParser.Name // CellReference.SeparateRefParts() // AreaReference.SeparateAreaRefs() (here) // SheetNameFormatter.format() (inverse) int len = reference.Length; int delimiterPos = -1; bool insideDelimitedName = false; for (int i = 0; i < len; i++) { switch (reference[i]) { case CELL_DELIMITER: if (!insideDelimitedName) { if (delimiterPos >= 0) { throw new ArgumentException("More than one cell delimiter '" + CELL_DELIMITER + "' appears in area reference '" + reference + "'"); } delimiterPos = i; } continue; case SPECIAL_NAME_DELIMITER: break; default: continue; } if (!insideDelimitedName) { insideDelimitedName = true; continue; } if (i >= len - 1) { // reference ends with the delimited name. // Assume names like: "Sheet1!'A1'" are never legal. throw new ArgumentException("Area reference '" + reference + "' ends with special name delimiter '" + SPECIAL_NAME_DELIMITER + "'"); } if (reference[i + 1] == SPECIAL_NAME_DELIMITER) { // two consecutive quotes is the escape sequence for a single one i++; // skip this and keep parsing the special name } else { // this is the end of the delimited name insideDelimitedName = false; } } if (delimiterPos < 0) { return new String[] { reference, }; } String partA = reference.Substring(0, delimiterPos); String partB = reference.Substring(delimiterPos + 1); if (partB.IndexOf(SHEET_NAME_DELIMITER) >= 0) { // TODO - are references like "Sheet1!A1:Sheet1:B2" ever valid? // FormulaParser has code to handle that. throw new Exception("Unexpected " + SHEET_NAME_DELIMITER + " in second cell reference of '" + reference + "'"); } int plingPos = partA.LastIndexOf(SHEET_NAME_DELIMITER); if (plingPos < 0) { return new String[] { partA, partB, }; } String sheetName = partA.Substring(0, plingPos + 1); // +1 to include delimiter return new String[] { partA, sheetName + partB, }; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/rpc/ota_base_supply_svc.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.RPC { /// <summary>Holder for reflection information generated from supply/rpc/ota_base_supply_svc.proto</summary> public static partial class OtaBaseSupplySvcReflection { #region Descriptor /// <summary>File descriptor for supply/rpc/ota_base_supply_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OtaBaseSupplySvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiRzdXBwbHkvcnBjL290YV9iYXNlX3N1cHBseV9zdmMucHJvdG8SFmhvbG1z", "LnR5cGVzLnN1cHBseS5ycGMaKnByaW1pdGl2ZS9wYl9pbmNsdXNpdmVfb3Bz", "ZGF0ZV9yYW5nZS5wcm90bxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJv", "dG8aH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJvdG8aK3N1cHBseS9y", "b29tX3R5cGVzL3Jvb21fdHlwZV9pbmRpY2F0b3IucHJvdG8aNWJvb2tpbmcv", "Y2hhbm5lbHMvb3RhX2NoYW5uZWxfcHJvdmlkZXJfaW5kaWNhdG9yLnByb3Rv", "GiFwcmltaXRpdmUvZml4ZWRfcG9pbnRfcmF0aW8ucHJvdG8iXQoXT3RhU3Vw", "cGx5RGV0YWlsc1JlcXVlc3QSQgoKZGF0ZV9yYW5nZRgBIAEoCzIuLmhvbG1z", "LnR5cGVzLnByaW1pdGl2ZS5QYkluY2x1c2l2ZU9wc2RhdGVSYW5nZSKFAwoY", "Q2hhbm5lbEFsbG9jYXRpb25QcmljaW5nEkMKCXJvb21fdHlwZRgBIAEoCzIw", "LmhvbG1zLnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLlJvb21UeXBlSW5kaWNh", "dG9yEjAKBGRhdGUYAiABKAsyIi5ob2xtcy50eXBlcy5wcmltaXRpdmUuUGJM", "b2NhbERhdGUSPAoNb2ZmZXJlZF9wcmljZRgDIAEoCzIlLmhvbG1zLnR5cGVz", "LnByaW1pdGl2ZS5Nb25ldGFyeUFtb3VudBIRCglhdmFpbGFibGUYBCABKAUS", "TwoMb3RhX3Byb3ZpZGVyGAUgASgLMjkuaG9sbXMudHlwZXMuYm9va2luZy5j", "aGFubmVscy5PVEFDaGFubmVsUHJvdmlkZXJJbmRpY2F0b3ISFAoMaXNfU3Rv", "cF9zZWxsGAYgASgIEjoKCnByaWNlX3JhdGUYByABKAsyJi5ob2xtcy50eXBl", "cy5wcmltaXRpdmUuRml4ZWRQb2ludFJhdGlvIp4BCg9DaGFubmVsU3RvcFNl", "bGwSQwoJcm9vbV90eXBlGAEgASgLMjAuaG9sbXMudHlwZXMuc3VwcGx5LnJv", "b21fdHlwZXMuUm9vbVR5cGVJbmRpY2F0b3ISMAoEZGF0ZRgCIAEoCzIiLmhv", "bG1zLnR5cGVzLnByaW1pdGl2ZS5QYkxvY2FsRGF0ZRIUCgxpc19TdG9wX3Nl", "bGwYAyABKAgidgoeQ2hhbm5lbEFsbG9jYXRpb25VcGRhdGVSZXF1ZXN0ElQK", "GmNoYW5uZWxfYWxsb2NhdGlvbl9wcmljaW5nGAEgAygLMjAuaG9sbXMudHlw", "ZXMuc3VwcGx5LnJwYy5DaGFubmVsQWxsb2NhdGlvblByaWNpbmciYgocQ2hh", "bm5lbFN0b3BTZWxsVXBkYXRlUmVxdWVzdBJCChFjaGFubmVsX3N0b3Bfc2Vs", "bBgBIAMoCzInLmhvbG1zLnR5cGVzLnN1cHBseS5ycGMuQ2hhbm5lbFN0b3BT", "ZWxsIn8KH0NoYW5uZWxBbGxvY2F0aW9uVXBkYXRlUmVzcG9uc2USRQoGUmVz", "dWx0GAEgASgOMjUuaG9sbXMudHlwZXMuc3VwcGx5LnJwYy5DaGFubmVsQWxs", "b2NhdGlvblVwZGF0ZVJlc3VsdBIVCg1FcnJvck1lc3NhZ2VzGAIgAygJInAK", "GE90YVN1cHBseURldGFpbHNSZXNwb25zZRJUChpjaGFubmVsX2FsbG9jYXRp", "b25fcHJpY2luZxgBIAMoCzIwLmhvbG1zLnR5cGVzLnN1cHBseS5ycGMuQ2hh", "bm5lbEFsbG9jYXRpb25QcmljaW5nKoQBCh1DaGFubmVsQWxsb2NhdGlvblVw", "ZGF0ZVJlc3VsdBIRCg1VUERBVEVfRkFJTEVEEAASFwoTREJfVVBEQVRFX0NS", "X0ZBSUxFRBABEiAKHENSX1VQREFURV9TWU5DX1NUQVRVU19GQUlMRUQQAhIV", "ChFVUERBVEVfU1VDQ0VTU0ZVTBADMowFChBPdGFCYXNlU3VwcGx5U3ZjEnAK", "C0FsbEZvckRhdGVzEi8uaG9sbXMudHlwZXMuc3VwcGx5LnJwYy5PdGFTdXBw", "bHlEZXRhaWxzUmVxdWVzdBowLmhvbG1zLnR5cGVzLnN1cHBseS5ycGMuT3Rh", "U3VwcGx5RGV0YWlsc1Jlc3BvbnNlEocBChRJbnNlcnRPclVwZGF0ZVN1cHBs", "eRI2LmhvbG1zLnR5cGVzLnN1cHBseS5ycGMuQ2hhbm5lbEFsbG9jYXRpb25V", "cGRhdGVSZXF1ZXN0GjcuaG9sbXMudHlwZXMuc3VwcGx5LnJwYy5DaGFubmVs", "QWxsb2NhdGlvblVwZGF0ZVJlc3BvbnNlEn8KDlVwZGF0ZVN0b3BTZWxsEjQu", "aG9sbXMudHlwZXMuc3VwcGx5LnJwYy5DaGFubmVsU3RvcFNlbGxVcGRhdGVS", "ZXF1ZXN0GjcuaG9sbXMudHlwZXMuc3VwcGx5LnJwYy5DaGFubmVsQWxsb2Nh", "dGlvblVwZGF0ZVJlc3BvbnNlEn4KC1VwZGF0ZVByaWNlEjYuaG9sbXMudHlw", "ZXMuc3VwcGx5LnJwYy5DaGFubmVsQWxsb2NhdGlvblVwZGF0ZVJlcXVlc3Qa", "Ny5ob2xtcy50eXBlcy5zdXBwbHkucnBjLkNoYW5uZWxBbGxvY2F0aW9uVXBk", "YXRlUmVzcG9uc2USewoPU3luY0NoYW5uZWxSdXNoEi8uaG9sbXMudHlwZXMu", "c3VwcGx5LnJwYy5PdGFTdXBwbHlEZXRhaWxzUmVxdWVzdBo3LmhvbG1zLnR5", "cGVzLnN1cHBseS5ycGMuQ2hhbm5lbEFsbG9jYXRpb25VcGRhdGVSZXNwb25z", "ZUIlWgpzdXBwbHkvcnBjqgIWSE9MTVMuVHlwZXMuU3VwcGx5LlJQQ2IGcHJv", "dG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Channels.OtaChannelProviderIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.FixedPointRatioReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResult), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest), global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsRequest.Parser, new[]{ "DateRange" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing), global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing.Parser, new[]{ "RoomType", "Date", "OfferedPrice", "Available", "OtaProvider", "IsStopSell", "PriceRate" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.ChannelStopSell), global::HOLMS.Types.Supply.RPC.ChannelStopSell.Parser, new[]{ "RoomType", "Date", "IsStopSell" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest), global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateRequest.Parser, new[]{ "ChannelAllocationPricing" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest), global::HOLMS.Types.Supply.RPC.ChannelStopSellUpdateRequest.Parser, new[]{ "ChannelStopSell" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse), global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResponse.Parser, new[]{ "Result", "ErrorMessages" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse), global::HOLMS.Types.Supply.RPC.OtaSupplyDetailsResponse.Parser, new[]{ "ChannelAllocationPricing" }, null, null, null) })); } #endregion } #region Enums public enum ChannelAllocationUpdateResult { [pbr::OriginalName("UPDATE_FAILED")] UpdateFailed = 0, [pbr::OriginalName("DB_UPDATE_CR_FAILED")] DbUpdateCrFailed = 1, [pbr::OriginalName("CR_UPDATE_SYNC_STATUS_FAILED")] CrUpdateSyncStatusFailed = 2, [pbr::OriginalName("UPDATE_SUCCESSFUL")] UpdateSuccessful = 3, } #endregion #region Messages public sealed partial class OtaSupplyDetailsRequest : pb::IMessage<OtaSupplyDetailsRequest> { private static readonly pb::MessageParser<OtaSupplyDetailsRequest> _parser = new pb::MessageParser<OtaSupplyDetailsRequest>(() => new OtaSupplyDetailsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OtaSupplyDetailsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OtaSupplyDetailsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OtaSupplyDetailsRequest(OtaSupplyDetailsRequest other) : this() { DateRange = other.dateRange_ != null ? other.DateRange.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OtaSupplyDetailsRequest Clone() { return new OtaSupplyDetailsRequest(this); } /// <summary>Field number for the "date_range" field.</summary> public const int DateRangeFieldNumber = 1; private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRange_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRange { get { return dateRange_; } set { dateRange_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OtaSupplyDetailsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OtaSupplyDetailsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(DateRange, other.DateRange)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (dateRange_ != null) hash ^= DateRange.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 (dateRange_ != null) { output.WriteRawTag(10); output.WriteMessage(DateRange); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (dateRange_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRange); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OtaSupplyDetailsRequest other) { if (other == null) { return; } if (other.dateRange_ != null) { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } DateRange.MergeFrom(other.DateRange); } } [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 (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } input.ReadMessage(dateRange_); break; } } } } } public sealed partial class ChannelAllocationPricing : pb::IMessage<ChannelAllocationPricing> { private static readonly pb::MessageParser<ChannelAllocationPricing> _parser = new pb::MessageParser<ChannelAllocationPricing>(() => new ChannelAllocationPricing()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChannelAllocationPricing> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationPricing() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationPricing(ChannelAllocationPricing other) : this() { RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; Date = other.date_ != null ? other.Date.Clone() : null; OfferedPrice = other.offeredPrice_ != null ? other.OfferedPrice.Clone() : null; available_ = other.available_; OtaProvider = other.otaProvider_ != null ? other.OtaProvider.Clone() : null; isStopSell_ = other.isStopSell_; PriceRate = other.priceRate_ != null ? other.PriceRate.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationPricing Clone() { return new ChannelAllocationPricing(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 "offered_price" field.</summary> public const int OfferedPriceFieldNumber = 3; private global::HOLMS.Types.Primitive.MonetaryAmount offeredPrice_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount OfferedPrice { get { return offeredPrice_; } set { offeredPrice_ = value; } } /// <summary>Field number for the "available" field.</summary> public const int AvailableFieldNumber = 4; private int available_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Available { get { return available_; } set { available_ = value; } } /// <summary>Field number for the "ota_provider" field.</summary> public const int OtaProviderFieldNumber = 5; private global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator otaProvider_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator OtaProvider { get { return otaProvider_; } set { otaProvider_ = value; } } /// <summary>Field number for the "is_Stop_sell" field.</summary> public const int IsStopSellFieldNumber = 6; private bool isStopSell_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IsStopSell { get { return isStopSell_; } set { isStopSell_ = value; } } /// <summary>Field number for the "price_rate" field.</summary> public const int PriceRateFieldNumber = 7; private global::HOLMS.Types.Primitive.FixedPointRatio priceRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.FixedPointRatio PriceRate { get { return priceRate_; } set { priceRate_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChannelAllocationPricing); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChannelAllocationPricing 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 (!object.Equals(OfferedPrice, other.OfferedPrice)) return false; if (Available != other.Available) return false; if (!object.Equals(OtaProvider, other.OtaProvider)) return false; if (IsStopSell != other.IsStopSell) return false; if (!object.Equals(PriceRate, other.PriceRate)) 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 (offeredPrice_ != null) hash ^= OfferedPrice.GetHashCode(); if (Available != 0) hash ^= Available.GetHashCode(); if (otaProvider_ != null) hash ^= OtaProvider.GetHashCode(); if (IsStopSell != false) hash ^= IsStopSell.GetHashCode(); if (priceRate_ != null) hash ^= PriceRate.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 (offeredPrice_ != null) { output.WriteRawTag(26); output.WriteMessage(OfferedPrice); } if (Available != 0) { output.WriteRawTag(32); output.WriteInt32(Available); } if (otaProvider_ != null) { output.WriteRawTag(42); output.WriteMessage(OtaProvider); } if (IsStopSell != false) { output.WriteRawTag(48); output.WriteBool(IsStopSell); } if (priceRate_ != null) { output.WriteRawTag(58); output.WriteMessage(PriceRate); } } [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 (offeredPrice_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OfferedPrice); } if (Available != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Available); } if (otaProvider_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OtaProvider); } if (IsStopSell != false) { size += 1 + 1; } if (priceRate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PriceRate); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChannelAllocationPricing 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.offeredPrice_ != null) { if (offeredPrice_ == null) { offeredPrice_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } OfferedPrice.MergeFrom(other.OfferedPrice); } if (other.Available != 0) { Available = other.Available; } if (other.otaProvider_ != null) { if (otaProvider_ == null) { otaProvider_ = new global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator(); } OtaProvider.MergeFrom(other.OtaProvider); } if (other.IsStopSell != false) { IsStopSell = other.IsStopSell; } if (other.priceRate_ != null) { if (priceRate_ == null) { priceRate_ = new global::HOLMS.Types.Primitive.FixedPointRatio(); } PriceRate.MergeFrom(other.PriceRate); } } [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 26: { if (offeredPrice_ == null) { offeredPrice_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(offeredPrice_); break; } case 32: { Available = input.ReadInt32(); break; } case 42: { if (otaProvider_ == null) { otaProvider_ = new global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator(); } input.ReadMessage(otaProvider_); break; } case 48: { IsStopSell = input.ReadBool(); break; } case 58: { if (priceRate_ == null) { priceRate_ = new global::HOLMS.Types.Primitive.FixedPointRatio(); } input.ReadMessage(priceRate_); break; } } } } } public sealed partial class ChannelStopSell : pb::IMessage<ChannelStopSell> { private static readonly pb::MessageParser<ChannelStopSell> _parser = new pb::MessageParser<ChannelStopSell>(() => new ChannelStopSell()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChannelStopSell> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelStopSell() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelStopSell(ChannelStopSell other) : this() { RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; Date = other.date_ != null ? other.Date.Clone() : null; isStopSell_ = other.isStopSell_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelStopSell Clone() { return new ChannelStopSell(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 "is_Stop_sell" field.</summary> public const int IsStopSellFieldNumber = 3; private bool isStopSell_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IsStopSell { get { return isStopSell_; } set { isStopSell_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChannelStopSell); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChannelStopSell 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 (IsStopSell != other.IsStopSell) 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 (IsStopSell != false) hash ^= IsStopSell.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 (IsStopSell != false) { output.WriteRawTag(24); output.WriteBool(IsStopSell); } } [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 (IsStopSell != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChannelStopSell 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.IsStopSell != false) { IsStopSell = other.IsStopSell; } } [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: { IsStopSell = input.ReadBool(); break; } } } } } public sealed partial class ChannelAllocationUpdateRequest : pb::IMessage<ChannelAllocationUpdateRequest> { private static readonly pb::MessageParser<ChannelAllocationUpdateRequest> _parser = new pb::MessageParser<ChannelAllocationUpdateRequest>(() => new ChannelAllocationUpdateRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChannelAllocationUpdateRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationUpdateRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationUpdateRequest(ChannelAllocationUpdateRequest other) : this() { channelAllocationPricing_ = other.channelAllocationPricing_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationUpdateRequest Clone() { return new ChannelAllocationUpdateRequest(this); } /// <summary>Field number for the "channel_allocation_pricing" field.</summary> public const int ChannelAllocationPricingFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing> _repeated_channelAllocationPricing_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing> channelAllocationPricing_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing> ChannelAllocationPricing { get { return channelAllocationPricing_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChannelAllocationUpdateRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChannelAllocationUpdateRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!channelAllocationPricing_.Equals(other.channelAllocationPricing_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= channelAllocationPricing_.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) { channelAllocationPricing_.WriteTo(output, _repeated_channelAllocationPricing_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += channelAllocationPricing_.CalculateSize(_repeated_channelAllocationPricing_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChannelAllocationUpdateRequest other) { if (other == null) { return; } channelAllocationPricing_.Add(other.channelAllocationPricing_); } [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: { channelAllocationPricing_.AddEntriesFrom(input, _repeated_channelAllocationPricing_codec); break; } } } } } public sealed partial class ChannelStopSellUpdateRequest : pb::IMessage<ChannelStopSellUpdateRequest> { private static readonly pb::MessageParser<ChannelStopSellUpdateRequest> _parser = new pb::MessageParser<ChannelStopSellUpdateRequest>(() => new ChannelStopSellUpdateRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChannelStopSellUpdateRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelStopSellUpdateRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelStopSellUpdateRequest(ChannelStopSellUpdateRequest other) : this() { channelStopSell_ = other.channelStopSell_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelStopSellUpdateRequest Clone() { return new ChannelStopSellUpdateRequest(this); } /// <summary>Field number for the "channel_stop_sell" field.</summary> public const int ChannelStopSellFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RPC.ChannelStopSell> _repeated_channelStopSell_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RPC.ChannelStopSell.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelStopSell> channelStopSell_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelStopSell>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelStopSell> ChannelStopSell { get { return channelStopSell_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChannelStopSellUpdateRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChannelStopSellUpdateRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!channelStopSell_.Equals(other.channelStopSell_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= channelStopSell_.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) { channelStopSell_.WriteTo(output, _repeated_channelStopSell_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += channelStopSell_.CalculateSize(_repeated_channelStopSell_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChannelStopSellUpdateRequest other) { if (other == null) { return; } channelStopSell_.Add(other.channelStopSell_); } [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: { channelStopSell_.AddEntriesFrom(input, _repeated_channelStopSell_codec); break; } } } } } public sealed partial class ChannelAllocationUpdateResponse : pb::IMessage<ChannelAllocationUpdateResponse> { private static readonly pb::MessageParser<ChannelAllocationUpdateResponse> _parser = new pb::MessageParser<ChannelAllocationUpdateResponse>(() => new ChannelAllocationUpdateResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChannelAllocationUpdateResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationUpdateResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationUpdateResponse(ChannelAllocationUpdateResponse other) : this() { result_ = other.result_; errorMessages_ = other.errorMessages_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChannelAllocationUpdateResponse Clone() { return new ChannelAllocationUpdateResponse(this); } /// <summary>Field number for the "Result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResult Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "ErrorMessages" field.</summary> public const int ErrorMessagesFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_errorMessages_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> errorMessages_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> ErrorMessages { get { return errorMessages_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChannelAllocationUpdateResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChannelAllocationUpdateResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if(!errorMessages_.Equals(other.errorMessages_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); hash ^= errorMessages_.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 (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } errorMessages_.WriteTo(output, _repeated_errorMessages_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } size += errorMessages_.CalculateSize(_repeated_errorMessages_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChannelAllocationUpdateResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } errorMessages_.Add(other.errorMessages_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Supply.RPC.ChannelAllocationUpdateResult) input.ReadEnum(); break; } case 18: { errorMessages_.AddEntriesFrom(input, _repeated_errorMessages_codec); break; } } } } } public sealed partial class OtaSupplyDetailsResponse : pb::IMessage<OtaSupplyDetailsResponse> { private static readonly pb::MessageParser<OtaSupplyDetailsResponse> _parser = new pb::MessageParser<OtaSupplyDetailsResponse>(() => new OtaSupplyDetailsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OtaSupplyDetailsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.OtaBaseSupplySvcReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OtaSupplyDetailsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OtaSupplyDetailsResponse(OtaSupplyDetailsResponse other) : this() { channelAllocationPricing_ = other.channelAllocationPricing_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OtaSupplyDetailsResponse Clone() { return new OtaSupplyDetailsResponse(this); } /// <summary>Field number for the "channel_allocation_pricing" field.</summary> public const int ChannelAllocationPricingFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing> _repeated_channelAllocationPricing_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing> channelAllocationPricing_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Supply.RPC.ChannelAllocationPricing> ChannelAllocationPricing { get { return channelAllocationPricing_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OtaSupplyDetailsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OtaSupplyDetailsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!channelAllocationPricing_.Equals(other.channelAllocationPricing_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= channelAllocationPricing_.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) { channelAllocationPricing_.WriteTo(output, _repeated_channelAllocationPricing_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += channelAllocationPricing_.CalculateSize(_repeated_channelAllocationPricing_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OtaSupplyDetailsResponse other) { if (other == null) { return; } channelAllocationPricing_.Add(other.channelAllocationPricing_); } [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: { channelAllocationPricing_.AddEntriesFrom(input, _repeated_channelAllocationPricing_codec); break; } } } } } #endregion } #endregion Designer generated code
/* 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.Linq; using System.Reflection; using System.Threading; using System.Web.UI.WebControls; using Adxstudio.Xrm; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Events; using Adxstudio.Xrm.Notes; using Adxstudio.Xrm.Web.Mvc.Html; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Portal; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Web; using Microsoft.Xrm.Sdk; using Site.Pages; namespace Site.Areas.Events.Pages { public partial class Event : PortalPage { protected const string EventRegistrationIdQueryStringParameterName = "id"; private readonly Lazy<IPortalContext> _portal = new Lazy<IPortalContext>(() => PortalCrmConfigurationManager.CreatePortalContext(), LazyThreadSafetyMode.None); protected bool CanRegister { get; private set; } protected bool IsRegistered { get; private set; } protected IEventOccurrence RequestEventOccurrence { get; private set; } protected bool RequiresRegistration { get; private set; } protected bool RegistrationRequiresPayment { get; private set; } protected enum EventStatusCode { Started = 1, Completed = 756150000 } protected void Page_Load(object sender, EventArgs args) { var @event = _portal.Value.Entity; if (@event == null || @event.LogicalName != "adx_event") { return; } var dataAdapter = new EventDataAdapter(@event, new PortalContextDataAdapterDependencies(_portal.Value, PortalName)); var now = DateTime.UtcNow; var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90)); var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90)); var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray(); IEventOccurrence requestOccurrence; RequestEventOccurrence = dataAdapter.TryMatchRequestEventOccurrence(Request, occurrences, out requestOccurrence) ? requestOccurrence : occurrences.Length == 1 ? occurrences.Single() : null; var user = _portal.Value.User; CanRegister = Request.IsAuthenticated && user != null && RequestEventOccurrence != null && RequestEventOccurrence.Start >= now && RequestEventOccurrence.EventSchedule != null && RequestEventOccurrence.Event != null; RequiresRegistration = @event.GetAttributeValue<bool?>("adx_requiresregistration").GetValueOrDefault() && RequestEventOccurrence != null && RequestEventOccurrence.Start >= now; RegistrationRequiresPayment = _portal.Value.ServiceContext.CreateQuery("adx_eventproduct") .Where(ep => ep.GetAttributeValue<EntityReference>("adx_event") == @event.ToEntityReference()) .ToList() .Any(); if (CanRegister) { var registration = _portal.Value.ServiceContext.CreateQuery("adx_eventregistration") .FirstOrDefault(e => e.GetAttributeValue<EntityReference>("adx_attendeeid") == user.ToEntityReference() && e.GetAttributeValue<EntityReference>("adx_eventscheduleid") == RequestEventOccurrence.EventSchedule.ToEntityReference() && e.GetAttributeValue<OptionSetValue>("statuscode") != null && e.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)EventStatusCode.Completed); if (registration != null) { IsRegistered = true; Unregister.CommandArgument = registration.Id.ToString(); } } OtherOccurrences.DataSource = occurrences .Where(e => e.Start >= now) .Where(e => RequestEventOccurrence == null || !(e.EventSchedule.Id == RequestEventOccurrence.EventSchedule.Id && e.Start == RequestEventOccurrence.Start)); OtherOccurrences.DataBind(); var sessionEvent = @event; Speakers.DataSource = sessionEvent.GetRelatedEntities(_portal.Value.ServiceContext, new Relationship("adx_eventspeaker_event")) .OrderBy(e => e.GetAttributeValue<string>("adx_name")); Speakers.DataBind(); } protected void Speakers_OnItemDataBound(object sender, ListViewItemEventArgs e) { var dataItem = e.Item as ListViewDataItem; if (dataItem == null || dataItem.DataItem == null) { return; } var speaker = dataItem.DataItem as Entity; if (speaker == null) { return; } var repeaterControl = (Repeater)e.Item.FindControl("SpeakerAnnotations"); if (repeaterControl == null) { return; } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var annotations = XrmContext.CreateQuery("annotation") .Where(a => a.GetAttributeValue<EntityReference>("objectid") == speaker.ToEntityReference() && a.GetAttributeValue<bool?>("isdocument").GetValueOrDefault(false)) .OrderBy(a => a.GetAttributeValue<DateTime>("createdon")) .Select(entity => dataAdapter.GetAnnotation(entity)); repeaterControl.DataSource = annotations; repeaterControl.DataBind(); } protected void Register_Click(object sender, EventArgs e) { var user = _portal.Value.User; if (!Request.IsAuthenticated || user == null || RequestEventOccurrence == null || RequestEventOccurrence.Event == null || RequestEventOccurrence.EventSchedule == null) { return; } var registration = new Entity("adx_eventregistration"); registration["adx_attendeeid"] = user.ToEntityReference(); registration["adx_eventid"] = RequestEventOccurrence.Event.ToEntityReference(); registration["adx_eventscheduleid"] = RequestEventOccurrence.EventSchedule.ToEntityReference(); registration["adx_registrationdate"] = DateTime.UtcNow; if (!RegistrationRequiresPayment) { registration["adx_registrationconfirmed"] = true; } _portal.Value.ServiceContext.AddObject(registration); _portal.Value.ServiceContext.SaveChanges(); if (!RegistrationRequiresPayment) { _portal.Value.ServiceContext.SetState(0, (int)EventStatusCode.Completed, registration); } var registrationUrl = RegistrationRequiresPayment ? GetRegistrationPaymentUrl(registration.Id) : GetRegistrationUrl(registration.Id); Response.Redirect(string.IsNullOrWhiteSpace(registrationUrl) ? Request.Url.PathAndQuery : registrationUrl); } protected string GetRegistrationUrl(Guid eventRegistrationId) { var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName); var website = portal.ServiceContext.CreateQuery("adx_website").FirstOrDefault(w => w.GetAttributeValue<Guid>("adx_websiteid") == portal.Website.Id); var page = portal.ServiceContext.GetPageBySiteMarkerName(website, "Event Registration"); if (page == null) { ADXTrace.Instance.TraceError(TraceCategory.Application, "Page could not be found for Site Marker named 'Event Registration'"); return null; } var url = portal.ServiceContext.GetUrl(page); if (string.IsNullOrWhiteSpace(url)) { ADXTrace.Instance.TraceError(TraceCategory.Application, "Url could not be determined for Site Marker named 'Event Registration'"); return null; } var urlBuilder = new UrlBuilder(url); urlBuilder.QueryString.Add(EventRegistrationIdQueryStringParameterName, eventRegistrationId.ToString()); return urlBuilder.PathWithQueryString; } protected string GetRegistrationPaymentUrl(Guid eventRegistrationId) { var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName); var website = portal.ServiceContext.CreateQuery("adx_website").FirstOrDefault(w => w.GetAttributeValue<Guid>("adx_websiteid") == portal.Website.Id); var page = portal.ServiceContext.GetPageBySiteMarkerName(website, "Event Registration - Payment Required"); if (page == null) { ADXTrace.Instance.TraceError(TraceCategory.Application, "Page could not be found for Site Marker named 'Event Registration - Payment Required'"); return null; } var url = portal.ServiceContext.GetUrl(page); if (string.IsNullOrWhiteSpace(url)) { ADXTrace.Instance.TraceError(TraceCategory.Application, "Url could not be determined for Site Marker named 'Event Registration - Payment Required'"); return null; } var urlBuilder = new UrlBuilder(url); urlBuilder.QueryString.Add(EventRegistrationIdQueryStringParameterName, eventRegistrationId.ToString()); return urlBuilder.PathWithQueryString; } protected void Unregister_Click(object sender, CommandEventArgs args) { var user = _portal.Value.User; if (!Request.IsAuthenticated || user == null || RequestEventOccurrence == null) { return; } Guid registrationId; if (!Guid.TryParse(args.CommandArgument.ToString(), out registrationId)) { return; } var registration = _portal.Value.ServiceContext.CreateQuery("adx_eventregistration") .FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_eventregistrationid") == registrationId && e.GetAttributeValue<EntityReference>("adx_attendeeid") == user.ToEntityReference()); if (registration != null) { _portal.Value.ServiceContext.DeleteObject(registration); _portal.Value.ServiceContext.SaveChanges(); } Response.Redirect(Request.Url.PathAndQuery); } } }
using System.Collections.Generic; using System.Linq; namespace UnityEngine.UI.Windows { public class WindowObjectElement : WindowObject { [Header("Sub Components")] public bool autoRegisterInRoot = true; public bool autoRegisterSubComponents = true; [SerializeField] [ReadOnly] protected List<WindowObjectElement> subComponents = new List<WindowObjectElement>(); private WindowObjectState currentState = WindowObjectState.NotInitialized; /// <summary> /// Gets the state of the component. /// </summary> /// <returns>The component state.</returns> public WindowObjectState GetComponentState() { return this.currentState; } public virtual void SetComponentState(WindowObjectState state) { this.currentState = state; if (this == null) return; var go = this.gameObject; if (this.currentState == WindowObjectState.Showing || this.currentState == WindowObjectState.Shown) { if (go != null) go.SetActive(true); } else if (this.currentState == WindowObjectState.Hidden || this.currentState == WindowObjectState.NotInitialized || this.currentState == WindowObjectState.Initializing) { if (go != null && this.NeedToInactive() == true) go.SetActive(false); } } public virtual bool NeedToInactive() { return true; } /// <summary> /// Gets the sub components. /// </summary> /// <returns>The sub components.</returns> public List<WindowObjectElement> GetSubComponents() { return this.subComponents; } internal virtual void Setup(WindowLayoutBase layoutRoot) { for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].Setup(layoutRoot); } internal override void Setup(WindowBase window) { base.Setup(window); for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].Setup(window); } /// <summary> /// Raises the init event. /// You can override this method but call it's base. /// </summary> public virtual void OnInit() { this.SetComponentState(WindowObjectState.Initializing); for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].OnInit(); //this.SetComponentState(WindowObjectState.Initialized); } /// <summary> /// Raises the deinit event. /// You can override this method but call it's base. /// </summary> public virtual void OnDeinit() { for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].OnDeinit(); this.SetComponentState(WindowObjectState.NotInitialized); } /// <summary> /// Raises the show end event. /// You can override this method but call it's base. /// </summary> public virtual void OnShowEnd() { for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].OnShowEnd(); this.SetComponentState(WindowObjectState.Shown); } /// <summary> /// Raises the hide end event. /// You can override this method but call it's base. /// </summary> public virtual void OnHideEnd() { for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].OnHideEnd(); this.SetComponentState(WindowObjectState.Hidden); } public virtual void OnShowBegin(System.Action callback, bool resetAnimation = true) { // At the top of the level - setup Shown state (may be must be declared in OnShowEnd method) if (this.GetComponentState() == WindowObjectState.Showing) { this.SetComponentState(WindowObjectState.Shown); } if (callback != null) callback(); } public virtual void OnHideBegin(System.Action callback, bool immediately = false) { // At the top of the level - setup Hidden state (may be must be declared in OnHideEnd method) if (this.GetComponentState() == WindowObjectState.Hiding) { this.SetComponentState(WindowObjectState.Hidden); } //this.SetComponentState(WindowObjectState.Hiding); if (callback != null) callback(); } /*public virtual void DeactivateComponents() { for (int i = 0; i < this.subComponents.Count; ++i) this.subComponents[i].DeactivateComponents(); if (this == null) return; this.gameObject.SetActive(false); }*/ /// <summary> /// Registers the sub component. /// If you want to instantiate a new component manualy but wants window events - register this component here. /// </summary> /// <param name="subComponent">Sub component.</param> public virtual void RegisterSubComponent(WindowObjectElement subComponent) { //Debug.Log("REGISTER: " + subComponent + " :: " + this.GetComponentState() + "/" + subComponent.GetComponentState()); switch (this.GetComponentState()) { case WindowObjectState.Hiding: if (subComponent.GetComponentState() == WindowObjectState.NotInitialized) { // after OnInit subComponent.OnInit(); } subComponent.SetComponentState(this.GetComponentState()); break; case WindowObjectState.Hidden: if (subComponent.GetComponentState() == WindowObjectState.NotInitialized) { // after OnInit subComponent.OnInit(); } subComponent.SetComponentState(this.GetComponentState()); break; case WindowObjectState.Initializing: case WindowObjectState.Initialized: if (subComponent.GetComponentState() == WindowObjectState.NotInitialized) { // after OnInit subComponent.OnInit(); } break; case WindowObjectState.Showing: // after OnShowBegin if (subComponent.GetComponentState() == WindowObjectState.NotInitialized) { subComponent.OnInit(); } subComponent.OnShowBegin(null); break; case WindowObjectState.Shown: // after OnShowEnd if (subComponent.GetComponentState() == WindowObjectState.NotInitialized) { subComponent.OnInit(); } subComponent.OnShowBegin(() => { subComponent.OnShowEnd(); }); break; } if (this.GetWindow() != null) { subComponent.Setup(this.GetWindow()); // subComponent.Setup(this.GetLayoutRoot()); } if (this.subComponents.Contains(subComponent) == false) this.subComponents.Add(subComponent); } /// <summary> /// Unregisters the sub component. /// </summary> /// <param name="subComponent">Sub component.</param> public void UnregisterSubComponent(WindowObjectElement subComponent, System.Action callback = null) { var sendCallback = true; //Debug.Log("UNREGISTER: " + subComponent + " :: " + this.GetComponentState() + "/" + subComponent.GetComponentState()); this.subComponents.Remove(subComponent); switch (this.GetComponentState()) { case WindowObjectState.Shown: // after OnShowEnd subComponent.OnHideBegin(() => { subComponent.OnHideEnd(); subComponent.OnDeinit(); if (callback != null) callback(); }); sendCallback = false; break; case WindowObjectState.Hiding: // after OnHideBegin subComponent.OnHideBegin(null); sendCallback = false; if (callback != null) callback(); break; case WindowObjectState.Hidden: // after OnHideEnd subComponent.OnHideBegin(() => { subComponent.OnHideEnd(); subComponent.OnDeinit(); if (callback != null) callback(); }); sendCallback = false; break; } if (sendCallback == true && callback != null) callback(); } #if UNITY_EDITOR /// <summary> /// Raises the validate event. Editor Only. /// </summary> public void OnValidate() { this.OnValidateEditor(); } /// <summary> /// Raises the validate editor event. /// You can override this method but call it's base. /// </summary> public virtual void OnValidateEditor() { this.Update_EDITOR(); } private void Update_EDITOR() { if (this.autoRegisterSubComponents == true) { var components = this.GetComponentsInChildren<WindowObjectElement>(true).ToList(); this.subComponents.Clear(); foreach (var component in components) { if (component == this) continue; var parents = component.GetComponentsInParent<WindowObjectElement>(true).ToList(); parents.Remove(component); if (parents.Count > 0 && parents[0] != this) continue; if (component.autoRegisterInRoot == false) continue; this.subComponents.Add(component); } } else { //this.subComponents.Clear(); } this.subComponents = this.subComponents.Where((c) => c != null).ToList(); } #endif } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * 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 NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Infoplus.Api; using Infoplus.Model; using Infoplus.Client; using System.Reflection; namespace Infoplus.Test { /// <summary> /// Class for testing Item /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class ItemTests { // TODO uncomment below to declare an instance variable for Item //private Item instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of Item //instance = new Item(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of Item /// </summary> [Test] public void ItemInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" Item //Assert.IsInstanceOfType<Item> (instance, "variable 'instance' is a Item"); } /// <summary> /// Test the property 'Id' /// </summary> [Test] public void IdTest() { // TODO unit test for the property 'Id' } /// <summary> /// Test the property 'AccountCodeId' /// </summary> [Test] public void AccountCodeIdTest() { // TODO unit test for the property 'AccountCodeId' } /// <summary> /// Test the property 'LowStockContactId' /// </summary> [Test] public void LowStockContactIdTest() { // TODO unit test for the property 'LowStockContactId' } /// <summary> /// Test the property 'LegacyLowLevelContactId' /// </summary> [Test] public void LegacyLowLevelContactIdTest() { // TODO unit test for the property 'LegacyLowLevelContactId' } /// <summary> /// Test the property 'LowStockCodeId' /// </summary> [Test] public void LowStockCodeIdTest() { // TODO unit test for the property 'LowStockCodeId' } /// <summary> /// Test the property 'MajorGroupId' /// </summary> [Test] public void MajorGroupIdTest() { // TODO unit test for the property 'MajorGroupId' } /// <summary> /// Test the property 'SubGroupId' /// </summary> [Test] public void SubGroupIdTest() { // TODO unit test for the property 'SubGroupId' } /// <summary> /// Test the property 'ProductCodeId' /// </summary> [Test] public void ProductCodeIdTest() { // TODO unit test for the property 'ProductCodeId' } /// <summary> /// Test the property 'SummaryCodeId' /// </summary> [Test] public void SummaryCodeIdTest() { // TODO unit test for the property 'SummaryCodeId' } /// <summary> /// Test the property 'BuyerId' /// </summary> [Test] public void BuyerIdTest() { // TODO unit test for the property 'BuyerId' } /// <summary> /// Test the property 'LobId' /// </summary> [Test] public void LobIdTest() { // TODO unit test for the property 'LobId' } /// <summary> /// Test the property 'Sku' /// </summary> [Test] public void SkuTest() { // TODO unit test for the property 'Sku' } /// <summary> /// Test the property 'VendorSKU' /// </summary> [Test] public void VendorSKUTest() { // TODO unit test for the property 'VendorSKU' } /// <summary> /// Test the property 'Upc' /// </summary> [Test] public void UpcTest() { // TODO unit test for the property 'Upc' } /// <summary> /// Test the property 'ItemDescription' /// </summary> [Test] public void ItemDescriptionTest() { // TODO unit test for the property 'ItemDescription' } /// <summary> /// Test the property 'PackingSlipDescription' /// </summary> [Test] public void PackingSlipDescriptionTest() { // TODO unit test for the property 'PackingSlipDescription' } /// <summary> /// Test the property 'AbsoluteMax' /// </summary> [Test] public void AbsoluteMaxTest() { // TODO unit test for the property 'AbsoluteMax' } /// <summary> /// Test the property 'AdditionalDescription' /// </summary> [Test] public void AdditionalDescriptionTest() { // TODO unit test for the property 'AdditionalDescription' } /// <summary> /// Test the property 'Backorder' /// </summary> [Test] public void BackorderTest() { // TODO unit test for the property 'Backorder' } /// <summary> /// Test the property 'ChargeCode' /// </summary> [Test] public void ChargeCodeTest() { // TODO unit test for the property 'ChargeCode' } /// <summary> /// Test the property 'CommodityCode' /// </summary> [Test] public void CommodityCodeTest() { // TODO unit test for the property 'CommodityCode' } /// <summary> /// Test the property 'CompCode' /// </summary> [Test] public void CompCodeTest() { // TODO unit test for the property 'CompCode' } /// <summary> /// Test the property 'CreateDate' /// </summary> [Test] public void CreateDateTest() { // TODO unit test for the property 'CreateDate' } /// <summary> /// Test the property 'CriticalAmount' /// </summary> [Test] public void CriticalAmountTest() { // TODO unit test for the property 'CriticalAmount' } /// <summary> /// Test the property 'OverallFixedReorderPoint' /// </summary> [Test] public void OverallFixedReorderPointTest() { // TODO unit test for the property 'OverallFixedReorderPoint' } /// <summary> /// Test the property 'OverallLeadTime' /// </summary> [Test] public void OverallLeadTimeTest() { // TODO unit test for the property 'OverallLeadTime' } /// <summary> /// Test the property 'ListPrice' /// </summary> [Test] public void ListPriceTest() { // TODO unit test for the property 'ListPrice' } /// <summary> /// Test the property 'LotControlFlag' /// </summary> [Test] public void LotControlFlagTest() { // TODO unit test for the property 'LotControlFlag' } /// <summary> /// Test the property 'MaxCycle' /// </summary> [Test] public void MaxCycleTest() { // TODO unit test for the property 'MaxCycle' } /// <summary> /// Test the property 'MaxInterim' /// </summary> [Test] public void MaxInterimTest() { // TODO unit test for the property 'MaxInterim' } /// <summary> /// Test the property 'NumericSortOrder' /// </summary> [Test] public void NumericSortOrderTest() { // TODO unit test for the property 'NumericSortOrder' } /// <summary> /// Test the property 'OutsideVendor' /// </summary> [Test] public void OutsideVendorTest() { // TODO unit test for the property 'OutsideVendor' } /// <summary> /// Test the property 'PickNo' /// </summary> [Test] public void PickNoTest() { // TODO unit test for the property 'PickNo' } /// <summary> /// Test the property 'PodOrderSuffix' /// </summary> [Test] public void PodOrderSuffixTest() { // TODO unit test for the property 'PodOrderSuffix' } /// <summary> /// Test the property 'PodRevDate' /// </summary> [Test] public void PodRevDateTest() { // TODO unit test for the property 'PodRevDate' } /// <summary> /// Test the property 'Status' /// </summary> [Test] public void StatusTest() { // TODO unit test for the property 'Status' } /// <summary> /// Test the property 'SeasonalItem' /// </summary> [Test] public void SeasonalItemTest() { // TODO unit test for the property 'SeasonalItem' } /// <summary> /// Test the property 'RequiresProductionLot' /// </summary> [Test] public void RequiresProductionLotTest() { // TODO unit test for the property 'RequiresProductionLot' } /// <summary> /// Test the property 'Sector' /// </summary> [Test] public void SectorTest() { // TODO unit test for the property 'Sector' } /// <summary> /// Test the property 'Secure' /// </summary> [Test] public void SecureTest() { // TODO unit test for the property 'Secure' } /// <summary> /// Test the property 'SerialCode' /// </summary> [Test] public void SerialCodeTest() { // TODO unit test for the property 'SerialCode' } /// <summary> /// Test the property 'UnitCode' /// </summary> [Test] public void UnitCodeTest() { // TODO unit test for the property 'UnitCode' } /// <summary> /// Test the property 'UnitsPerWrap' /// </summary> [Test] public void UnitsPerWrapTest() { // TODO unit test for the property 'UnitsPerWrap' } /// <summary> /// Test the property 'WeightPerWrap' /// </summary> [Test] public void WeightPerWrapTest() { // TODO unit test for the property 'WeightPerWrap' } /// <summary> /// Test the property 'VoidDate' /// </summary> [Test] public void VoidDateTest() { // TODO unit test for the property 'VoidDate' } /// <summary> /// Test the property 'WrapCode' /// </summary> [Test] public void WrapCodeTest() { // TODO unit test for the property 'WrapCode' } /// <summary> /// Test the property 'ExtrinsicText1' /// </summary> [Test] public void ExtrinsicText1Test() { // TODO unit test for the property 'ExtrinsicText1' } /// <summary> /// Test the property 'ExtrinsicText2' /// </summary> [Test] public void ExtrinsicText2Test() { // TODO unit test for the property 'ExtrinsicText2' } /// <summary> /// Test the property 'ExtrinsicText3' /// </summary> [Test] public void ExtrinsicText3Test() { // TODO unit test for the property 'ExtrinsicText3' } /// <summary> /// Test the property 'ExtrinsicNumber1' /// </summary> [Test] public void ExtrinsicNumber1Test() { // TODO unit test for the property 'ExtrinsicNumber1' } /// <summary> /// Test the property 'ExtrinsicNumber2' /// </summary> [Test] public void ExtrinsicNumber2Test() { // TODO unit test for the property 'ExtrinsicNumber2' } /// <summary> /// Test the property 'ExtrinsicDecimal1' /// </summary> [Test] public void ExtrinsicDecimal1Test() { // TODO unit test for the property 'ExtrinsicDecimal1' } /// <summary> /// Test the property 'ExtrinsicDecimal2' /// </summary> [Test] public void ExtrinsicDecimal2Test() { // TODO unit test for the property 'ExtrinsicDecimal2' } /// <summary> /// Test the property 'CasebreakEnabled' /// </summary> [Test] public void CasebreakEnabledTest() { // TODO unit test for the property 'CasebreakEnabled' } /// <summary> /// Test the property 'ModifyDate' /// </summary> [Test] public void ModifyDateTest() { // TODO unit test for the property 'ModifyDate' } /// <summary> /// Test the property 'ForwardLotMixingRule' /// </summary> [Test] public void ForwardLotMixingRuleTest() { // TODO unit test for the property 'ForwardLotMixingRule' } /// <summary> /// Test the property 'StorageLotMixingRule' /// </summary> [Test] public void StorageLotMixingRuleTest() { // TODO unit test for the property 'StorageLotMixingRule' } /// <summary> /// Test the property 'ForwardItemMixingRule' /// </summary> [Test] public void ForwardItemMixingRuleTest() { // TODO unit test for the property 'ForwardItemMixingRule' } /// <summary> /// Test the property 'StorageItemMixingRule' /// </summary> [Test] public void StorageItemMixingRuleTest() { // TODO unit test for the property 'StorageItemMixingRule' } /// <summary> /// Test the property 'AllocationRule' /// </summary> [Test] public void AllocationRuleTest() { // TODO unit test for the property 'AllocationRule' } /// <summary> /// Test the property 'Hazmat' /// </summary> [Test] public void HazmatTest() { // TODO unit test for the property 'Hazmat' } } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Drawing; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Threading; using MonoTouch.UIKit; using UIKit; using MonoTouch.Foundation; using Foundation; using Xamarin.Controls; using Xamarin.Utilities.iOS; #if __UNIFIED__ using CoreGraphics; #else using nint = global::System.Int32; using nfloat = global::System.Single; using CGRect = global::System.Drawing.RectangleF; #endif namespace Xamarin.Auth { internal class FormAuthenticatorController : UITableViewController { FormAuthenticator authenticator; ProgressLabel progress; CancellationTokenSource cancelSource; public FormAuthenticatorController (FormAuthenticator authenticator) : base (UITableViewStyle.Grouped) { this.authenticator = authenticator; Title = authenticator.Title; TableView.DataSource = new FormDataSource (this); TableView.Delegate = new FormDelegate (this); NavigationItem.LeftBarButtonItem = new UIBarButtonItem ( UIBarButtonSystemItem.Cancel, delegate { StopProgress (); authenticator.OnCancelled (); }); } void HandleSubmit () { if (progress == null) { progress = new ProgressLabel (NSBundle.MainBundle.LocalizedString ("Verifying", "Verifying status message when adding accounts")); NavigationItem.TitleView = progress; progress.StartAnimating (); } cancelSource = new CancellationTokenSource (); authenticator.SignInAsync (cancelSource.Token).ContinueWith (task => { StopProgress (); if (task.IsFaulted) { this.ShowError ("Error Signing In", task.Exception); } else { authenticator.OnSucceeded (task.Result); } }, TaskScheduler.FromCurrentSynchronizationContext ()); } void StopProgress () { if (progress != null) { progress.StopAnimating (); NavigationItem.TitleView = null; progress = null; } } class FormDelegate : UITableViewDelegate { FormAuthenticatorController controller; public FormDelegate (FormAuthenticatorController controller) { this.controller = controller; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { tableView.ResignFirstResponder (); if (indexPath.Section == 1) { tableView.DeselectRow (indexPath, true); ((FormDataSource)tableView.DataSource).ResignFirstResponder (); controller.HandleSubmit (); } else if (indexPath.Section == 2) { tableView.DeselectRow (indexPath, true); UIApplication.SharedApplication.OpenUrl ( new NSUrl (controller.authenticator.CreateAccountLink.AbsoluteUri)); } } } class FieldCell : UITableViewCell { public static readonly UIFont LabelFont = UIFont.BoldSystemFontOfSize (16); public static readonly UIFont FieldFont = UIFont.SystemFontOfSize (16); static readonly UIColor FieldColor = UIColor.FromRGB (56, 84, 135); public UITextField TextField { get; private set; } public FieldCell (FormAuthenticatorField field, nfloat fieldXPosition, Action handleReturn) : base (UITableViewCellStyle.Default, "Field") { SelectionStyle = UITableViewCellSelectionStyle.None; TextLabel.Text = field.Title; var hang = 3; var h = FieldFont.PointSize + hang; var cellSize = Frame.Size; TextField = new UITextField (new CGRect ( fieldXPosition, (cellSize.Height - h)/2, cellSize.Width - fieldXPosition - 12, h)) { Font = FieldFont, Placeholder = field.Placeholder, Text = field.Value, TextColor = FieldColor, AutoresizingMask = UIViewAutoresizing.FlexibleWidth, SecureTextEntry = (field.FieldType == FormAuthenticatorFieldType.Password), KeyboardType = (field.FieldType == FormAuthenticatorFieldType.Email) ? UIKeyboardType.EmailAddress : UIKeyboardType.Default, AutocorrectionType = (field.FieldType == FormAuthenticatorFieldType.PlainText) ? UITextAutocorrectionType.Yes : UITextAutocorrectionType.No, AutocapitalizationType = UITextAutocapitalizationType.None, ShouldReturn = delegate { handleReturn (); return false; }, }; TextField.EditingDidEnd += delegate { field.Value = TextField.Text; }; ContentView.AddSubview (TextField); } } class FormDataSource : UITableViewDataSource { FormAuthenticatorController controller; public FormDataSource (FormAuthenticatorController controller) { this.controller = controller; } public override nint NumberOfSections (UITableView tableView) { return 2 + (controller.authenticator.CreateAccountLink != null ? 1 : 0); } public override nint RowsInSection (UITableView tableView, nint section) { if (section == 0) { return controller.authenticator.Fields.Count; } else { return 1; } } FieldCell[] fieldCells = null; public void SelectNext () { for (var i = 0; i < controller.authenticator.Fields.Count; i++) { if (fieldCells[i].TextField.IsFirstResponder) { if (i + 1 < fieldCells.Length) { fieldCells[i+1].TextField.BecomeFirstResponder (); return; } else { fieldCells[i].TextField.ResignFirstResponder (); controller.HandleSubmit (); return; } } } } public void ResignFirstResponder () { foreach (var cell in fieldCells) { cell.TextField.ResignFirstResponder (); } } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { if (indexPath.Section == 0) { if (fieldCells == null) { var fieldXPosition = controller .authenticator .Fields .Select (f => f.Title.StringSize ( FieldCell.LabelFont).Width) .Max (); fieldXPosition += 36; fieldCells = controller .authenticator .Fields .Select (f => new FieldCell (f, fieldXPosition, SelectNext)) .ToArray (); } return fieldCells[indexPath.Row]; } else if (indexPath.Section == 1) { var cell = tableView.DequeueReusableCell ("SignIn"); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, "SignIn"); cell.TextLabel.TextAlignment = UITextAlignment.Center; } cell.TextLabel.Text = NSBundle.MainBundle.LocalizedString ("Sign In", "Sign In button title"); return cell; } else { var cell = tableView.DequeueReusableCell ("CreateAccount"); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, "CreateAccount"); cell.TextLabel.TextAlignment = UITextAlignment.Center; } cell.TextLabel.Text = NSBundle.MainBundle.LocalizedString ("Create Account", "Create Account button title"); return cell; } } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.TimeZones; using NodaTime.Utility; using System; using System.Collections.Generic; namespace NodaTime { /// <summary> /// Represents a time zone - a mapping between UTC and local time. A time zone maps UTC instants to local times /// - or, equivalently, to the offset from UTC at any particular instant. /// </summary> /// <remarks> /// <para> /// The mapping is unambiguous in the "UTC to local" direction, but /// the reverse is not true: when the offset changes, usually due to a Daylight Saving transition, /// the change either creates a gap (a period of local time which never occurs in the time zone) /// or an ambiguity (a period of local time which occurs twice in the time zone). Mapping back from /// local time to an instant requires consideration of how these problematic times will be handled. /// </para> /// <para> /// Noda Time provides various options when mapping local time to a specific instant: /// <list type="bullet"> /// <item> /// <description><see cref="AtStrictly"/> will throw an exception if the mapping from local time is either ambiguous /// or impossible, i.e. if there is anything other than one instant which maps to the given local time.</description> /// </item> /// <item> /// <description><see cref="AtLeniently"/> will never throw an exception due to ambiguous or skipped times, /// resolving to the earlier option of ambiguous matches, or to a value that's forward-shifted by the duration /// of the gap for skipped times.</description> /// </item> /// <item> /// <description><see cref="ResolveLocal(LocalDateTime, ZoneLocalMappingResolver)"/> will apply a <see cref="ZoneLocalMappingResolver"/> to the result of /// a mapping.</description> /// </item> /// <item> /// <description><see cref="MapLocal"/> will return a <see cref="ZoneLocalMapping"/> /// with complete information about whether the given local time occurs zero times, once or twice. This is the most /// fine-grained approach, which is the fiddliest to use but puts the caller in the most control.</description> /// </item> /// </list> /// </para> /// <para> /// Noda Time has two built-in sources of time zone data available: a copy of the /// <a href="https://www.iana.org/time-zones">tz database</a> (also known as the IANA Time Zone database, or zoneinfo /// or Olson database), and the ability to convert .NET's own <see cref="TimeZoneInfo"/> format into a "native" Noda /// Time zone. Which of these is most appropriate for you to use will very much depend on your exact needs. The /// zoneinfo database is widely used outside Windows, and has more historical data than the Windows-provided /// information, but if you need to interoperate with other Windows systems by specifying time zone IDs, you may /// wish to stick to the Windows time zones. /// </para> /// <para> /// To obtain a <see cref="DateTimeZone"/> for a given timezone ID, use one of the methods on /// <see cref="IDateTimeZoneProvider"/> (and see <see cref="DateTimeZoneProviders"/> for access to the built-in /// providers). The UTC timezone is also available via the <see cref="Utc"/> property on this class. /// </para> /// <para> /// To obtain a <see cref="DateTimeZone"/> representing the system default time zone, you can either call /// <see cref="IDateTimeZoneProvider.GetSystemDefault"/> on a provider to obtain the <see cref="DateTimeZone"/> that /// the provider considers matches the system default time zone, or you can construct a /// <see cref="BclDateTimeZone"/> via <see cref="BclDateTimeZone.ForSystemDefault"/>, which returns a /// <see cref="DateTimeZone"/> that wraps the system local <see cref="TimeZoneInfo"/>. The latter will always /// succeed, but has access only to that information available via the .NET time zone; the former may contain more /// complete data, but may (in uncommon cases) fail to find a matching <see cref="DateTimeZone"/>. /// Note that <c>BclDateTimeZone</c> may not be available in all versions of Noda Time 1.x and 2.x; see the class /// documentation for more details. /// </para> /// <para> /// Note that Noda Time does not require that <see cref="DateTimeZone"/> instances be singletons. /// Comparing two time zones for equality is not straightforward: if you care about whether two /// zones act the same way within a particular portion of time, use <see cref="ZoneEqualityComparer"/>. /// Additional guarantees are provided by <see cref="IDateTimeZoneProvider"/> and <see cref="ForOffset(Offset)"/>. /// </para> /// </remarks> /// <threadsafety> /// All time zone implementations within Noda Time are immutable and thread-safe. /// See the thread safety section of the user guide for more information. /// It is expected that third party implementations will be immutable and thread-safe as well: /// code within Noda Time assumes that it can hand out time zones to any thread without any concerns. If you /// implement a non-thread-safe time zone, you will need to use it extremely carefully. We'd recommend that you /// avoid this if possible. /// </threadsafety> [Immutable] public abstract class DateTimeZone : IZoneIntervalMapWithMinMax { /// <summary> /// The ID of the UTC (Coordinated Universal Time) time zone. This ID is always valid, whatever provider is /// used. If the provider has its own mapping for UTC, that will be returned by <see cref="DateTimeZoneCache.GetZoneOrNull" />, but otherwise /// the value of the <see cref="Utc"/> property will be returned. /// </summary> internal const string UtcId = "UTC"; /// <summary> /// Gets the UTC (Coordinated Universal Time) time zone. /// </summary> /// <remarks> /// This is a single instance which is not provider-specific; it is guaranteed to have the ID "UTC", and to /// compare equal to an instance returned by calling <see cref="ForOffset"/> with an offset of zero, but it may /// or may not compare equal to an instance returned by e.g. <c>DateTimeZoneProviders.Tzdb["UTC"]</c>. /// </remarks> /// <value>A UTC <see cref="NodaTime.DateTimeZone" />.</value> public static DateTimeZone Utc { get; } = new FixedDateTimeZone(Offset.Zero); private const int FixedZoneCacheGranularitySeconds = NodaConstants.SecondsPerMinute * 30; private const int FixedZoneCacheMinimumSeconds = -FixedZoneCacheGranularitySeconds * 12 * 2; // From UTC-12 private const int FixedZoneCacheSize = (12 + 15) * 2 + 1; // To UTC+15 inclusive private static readonly DateTimeZone[] FixedZoneCache = BuildFixedZoneCache(); /// <summary> /// Returns a fixed time zone with the given offset. /// </summary> /// <remarks> /// <para> /// The returned time zone will have an ID of "UTC" if the offset is zero, or "UTC+/-Offset" /// otherwise. In the former case, the returned instance will be equal to <see cref="Utc"/>. /// </para> /// <para> /// Note also that this method is not required to return the same <see cref="DateTimeZone"/> instance for /// successive requests for the same offset; however, all instances returned for a given offset will compare /// as equal. /// </para> /// </remarks> /// <param name="offset">The offset for the returned time zone</param> /// <returns>A fixed time zone with the given offset.</returns> public static DateTimeZone ForOffset(Offset offset) { int seconds = offset.Seconds; if (seconds % FixedZoneCacheGranularitySeconds != 0) { return new FixedDateTimeZone(offset); } int index = (seconds - FixedZoneCacheMinimumSeconds) / FixedZoneCacheGranularitySeconds; if (index < 0 || index >= FixedZoneCacheSize) { return new FixedDateTimeZone(offset); } return FixedZoneCache[index]; } /// <summary> /// Initializes a new instance of the <see cref="NodaTime.DateTimeZone" /> class. /// </summary> /// <param name="id">The unique id of this time zone.</param> /// <param name="isFixed">Set to <c>true</c> if this time zone has no transitions.</param> /// <param name="minOffset">Minimum offset applied within this zone</param> /// <param name="maxOffset">Maximum offset applied within this zone</param> protected DateTimeZone(string id, bool isFixed, Offset minOffset, Offset maxOffset) { this.Id = Preconditions.CheckNotNull(id, nameof(id)); this.IsFixed = isFixed; this.MinOffset = minOffset; this.MaxOffset = maxOffset; } /// <summary> /// Get the provider's ID for the time zone. /// </summary> /// <remarks> /// <para> /// This identifies the time zone within the current time zone provider; a different provider may /// provide a different time zone with the same ID, or may not provide a time zone with that ID at all. /// </para> /// </remarks> /// <value>The provider's ID for the time zone.</value> public string Id { get; } /// <summary> /// Indicates whether the time zone is fixed, i.e. contains no transitions. /// </summary> /// <remarks> /// This is used as an optimization. If the time zone has no transitions but returns <c>false</c> /// for this then the behavior will be correct but the system will have to do extra work. However /// if the time zone has transitions and this returns <c>true</c> then the transitions will never /// be examined. /// </remarks> /// <value>true if the time zone is fixed; false otherwise.</value> internal bool IsFixed { get; } /// <summary> /// Gets the least (most negative) offset within this time zone, over all time. /// </summary> /// <value>The least (most negative) offset within this time zone, over all time.</value> public Offset MinOffset { get; } /// <summary> /// Gets the greatest (most positive) offset within this time zone, over all time. /// </summary> /// <value>The greatest (most positive) offset within this time zone, over all time.</value> public Offset MaxOffset { get; } #region Core abstract/virtual methods /// <summary> /// Returns the offset from UTC, where a positive duration indicates that local time is /// later than UTC. In other words, local time = UTC + offset. /// </summary> /// <remarks> /// This is mostly a convenience method for calling <c>GetZoneInterval(instant).WallOffset</c>, /// although it can also be overridden for more efficiency. /// </remarks> /// <param name="instant">The instant for which to calculate the offset.</param> /// <returns> /// The offset from UTC at the specified instant. /// </returns> public virtual Offset GetUtcOffset(Instant instant) => GetZoneInterval(instant).WallOffset; /// <summary> /// Gets the zone interval for the given instant; the range of time around the instant in which the same Offset /// applies (with the same split between standard time and daylight saving time, and with the same offset). /// </summary> /// <remarks> /// This will always return a valid zone interval, as time zones cover the whole of time. /// </remarks> /// <param name="instant">The <see cref="NodaTime.Instant" /> to query.</param> /// <returns>The defined <see cref="NodaTime.TimeZones.ZoneInterval" />.</returns> /// <seealso cref="GetZoneIntervals(Interval)"/> public abstract ZoneInterval GetZoneInterval(Instant instant); /// <summary> /// Returns complete information about how the given <see cref="LocalDateTime" /> is mapped in this time zone. /// </summary> /// <remarks> /// <para> /// Mapping a local date/time to a time zone can give an unambiguous, ambiguous or impossible result, depending on /// time zone transitions. Use the return value of this method to handle these cases in an appropriate way for /// your use case. /// </para> /// <para> /// As an alternative, consider <see cref="ResolveLocal(LocalDateTime, ZoneLocalMappingResolver)"/>, which uses a caller-provided strategy to /// convert the <see cref="ZoneLocalMapping"/> returned here to a <see cref="ZonedDateTime"/>. /// </para> /// </remarks> /// <param name="localDateTime">The local date and time to map in this time zone.</param> /// <returns>A mapping of the given local date and time to zero, one or two zoned date/time values.</returns> public virtual ZoneLocalMapping MapLocal(LocalDateTime localDateTime) { LocalInstant localInstant = localDateTime.ToLocalInstant(); Instant firstGuess = localInstant.MinusZeroOffset(); ZoneInterval interval = GetZoneInterval(firstGuess); // Most of the time we'll go into here... the local instant and the instant // are close enough that we've found the right instant. if (interval.Contains(localInstant)) { ZoneInterval? earlier = GetEarlierMatchingInterval(interval, localInstant); if (earlier != null) { return new ZoneLocalMapping(this, localDateTime, earlier, interval, 2); } ZoneInterval? later = GetLaterMatchingInterval(interval, localInstant); if (later != null) { return new ZoneLocalMapping(this, localDateTime, interval, later, 2); } return new ZoneLocalMapping(this, localDateTime, interval, interval, 1); } else { // Our first guess was wrong. Either we need to change interval by one (either direction) // or we're in a gap. ZoneInterval? earlier = GetEarlierMatchingInterval(interval, localInstant); if (earlier != null) { return new ZoneLocalMapping(this, localDateTime, earlier, earlier, 1); } ZoneInterval? later = GetLaterMatchingInterval(interval, localInstant); if (later != null) { return new ZoneLocalMapping(this, localDateTime, later, later, 1); } return new ZoneLocalMapping(this, localDateTime, GetIntervalBeforeGap(localInstant), GetIntervalAfterGap(localInstant), 0); } } #endregion #region Conversion between local dates/times and ZonedDateTime /// <summary> /// Returns the earliest valid <see cref="ZonedDateTime"/> with the given local date. /// </summary> /// <remarks> /// If midnight exists unambiguously on the given date, it is returned. /// If the given date has an ambiguous start time (e.g. the clocks go back from 1am to midnight) /// then the earlier ZonedDateTime is returned. If the given date has no midnight (e.g. the clocks /// go forward from midnight to 1am) then the earliest valid value is returned; this will be the instant /// of the transition. /// </remarks> /// <param name="date">The local date to map in this time zone.</param> /// <exception cref="SkippedTimeException">The entire day was skipped due to a very large time zone transition. /// (This is extremely rare.)</exception> /// <returns>The <see cref="ZonedDateTime"/> representing the earliest time in the given date, in this time zone.</returns> public ZonedDateTime AtStartOfDay(LocalDate date) { LocalDateTime midnight = date.AtMidnight(); var mapping = MapLocal(midnight); switch (mapping.Count) { // Midnight doesn't exist. Maybe we just skip to 1am (or whatever), or maybe the whole day is missed. case 0: var interval = mapping.LateInterval; // Safe to use Start, as it can't extend to the start of time. var offsetDateTime = new OffsetDateTime(interval.Start, interval.WallOffset, date.Calendar); // It's possible that the entire day is skipped. For example, Samoa skipped December 30th 2011. // We know the two values are in the same calendar here, so we just need to check the YearMonthDay. if (offsetDateTime.YearMonthDay != date.YearMonthDay) { throw new SkippedTimeException(midnight, this); } return new ZonedDateTime(offsetDateTime, this); // Unambiguous or occurs twice, we can just use the offset from the earlier interval. case 1: case 2: return new ZonedDateTime(midnight.WithOffset(mapping.EarlyInterval.WallOffset), this); default: throw new InvalidOperationException("This won't happen."); } } /// <summary> /// Maps the given <see cref="LocalDateTime"/> to the corresponding <see cref="ZonedDateTime"/>, following /// the given <see cref="ZoneLocalMappingResolver"/> to handle ambiguity and skipped times. /// </summary> /// <remarks> /// <para> /// This is a convenience method for calling <see cref="MapLocal"/> and passing the result to the resolver. /// Common options for resolvers are provided in the static <see cref="Resolvers"/> class. /// </para> /// <para> /// See <see cref="AtStrictly"/> and <see cref="AtLeniently"/> for alternative ways to map a local time to a /// specific instant. /// </para> /// </remarks> /// <param name="localDateTime">The local date and time to map in this time zone.</param> /// <param name="resolver">The resolver to apply to the mapping.</param> /// <returns>The result of resolving the mapping.</returns> public ZonedDateTime ResolveLocal(LocalDateTime localDateTime, ZoneLocalMappingResolver resolver) { Preconditions.CheckNotNull(resolver, nameof(resolver)); return resolver(MapLocal(localDateTime)); } /// <summary> /// Maps the given <see cref="LocalDateTime"/> to the corresponding <see cref="ZonedDateTime"/>, if and only if /// that mapping is unambiguous in this time zone. Otherwise, <see cref="SkippedTimeException"/> or /// <see cref="AmbiguousTimeException"/> is thrown, depending on whether the mapping is ambiguous or the local /// date/time is skipped entirely. /// </summary> /// <remarks> /// See <see cref="AtLeniently"/> and <see cref="ResolveLocal(LocalDateTime, ZoneLocalMappingResolver)"/> for alternative ways to map a local time to a /// specific instant. /// </remarks> /// <param name="localDateTime">The local date and time to map into this time zone.</param> /// <exception cref="SkippedTimeException">The given local date/time is skipped in this time zone.</exception> /// <exception cref="AmbiguousTimeException">The given local date/time is ambiguous in this time zone.</exception> /// <returns>The unambiguous matching <see cref="ZonedDateTime"/> if it exists.</returns> public ZonedDateTime AtStrictly(LocalDateTime localDateTime) => ResolveLocal(localDateTime, Resolvers.StrictResolver); /// <summary> /// Maps the given <see cref="LocalDateTime"/> to the corresponding <see cref="ZonedDateTime"/> in a lenient /// manner: ambiguous values map to the earlier of the alternatives, and "skipped" values are shifted forward /// by the duration of the "gap". /// </summary> /// <remarks> /// See <see cref="AtStrictly"/> and <see cref="ResolveLocal(LocalDateTime, ZoneLocalMappingResolver)"/> for alternative ways to map a local time to a /// specific instant. /// <para>Note: The behavior of this method was changed in version 2.0 to fit the most commonly seen real-world /// usage pattern. Previous versions returned the later instance of ambiguous values, and returned the start of /// the zone interval after the gap for skipped value. The previous functionality can still be used if desired, /// by using <see cref="ResolveLocal(LocalDateTime, ZoneLocalMappingResolver)"/>, passing in a resolver /// created from <see cref="Resolvers.ReturnLater"/> and <see cref="Resolvers.ReturnStartOfIntervalAfter"/>.</para> /// </remarks> /// <param name="localDateTime">The local date/time to map.</param> /// <returns>The unambiguous mapping if there is one, the earlier result if the mapping is ambiguous, /// or the forward-shifted value if the given local date/time is skipped.</returns> public ZonedDateTime AtLeniently(LocalDateTime localDateTime) => ResolveLocal(localDateTime, Resolvers.LenientResolver); #endregion /// <summary> /// Returns the interval before this one, if it contains the given local instant, or null otherwise. /// </summary> private ZoneInterval? GetEarlierMatchingInterval(ZoneInterval interval, LocalInstant localInstant) { // Micro-optimization to avoid fetching interval.Start multiple times. Seems // to give a performance improvement on x86 at least... // If the zone interval extends to the start of time, the next check will definitely evaluate to false. Instant intervalStart = interval.RawStart; // This allows for a maxOffset of up to +1 day, and the "truncate towards beginning of time" // nature of the Days property. if (localInstant.DaysSinceEpoch <= intervalStart.DaysSinceEpoch + 1) { // We *could* do a more accurate check here based on the actual maxOffset, but it's probably // not worth it. ZoneInterval candidate = GetZoneInterval(intervalStart - Duration.Epsilon); if (candidate.Contains(localInstant)) { return candidate; } } return null; } /// <summary> /// Returns the next interval after this one, if it contains the given local instant, or null otherwise. /// </summary> private ZoneInterval? GetLaterMatchingInterval(ZoneInterval interval, LocalInstant localInstant) { // Micro-optimization to avoid fetching interval.End multiple times. Seems // to give a performance improvement on x86 at least... // If the zone interval extends to the end of time, the next check will // definitely evaluate to false. Instant intervalEnd = interval.RawEnd; // Crude but cheap first check to see whether there *might* be a later interval. // This allows for a minOffset of up to -1 day, and the "truncate towards beginning of time" // nature of the Days property. if (localInstant.DaysSinceEpoch >= intervalEnd.DaysSinceEpoch - 1) { // We *could* do a more accurate check here based on the actual maxOffset, but it's probably // not worth it. ZoneInterval candidate = GetZoneInterval(intervalEnd); if (candidate.Contains(localInstant)) { return candidate; } } return null; } private ZoneInterval GetIntervalBeforeGap(LocalInstant localInstant) { Instant guess = localInstant.MinusZeroOffset(); ZoneInterval guessInterval = GetZoneInterval(guess); // If the local interval occurs before the zone interval we're looking at starts, // we need to find the earlier one; otherwise this interval must come after the gap, and // it's therefore the one we want. if (localInstant.Minus(guessInterval.WallOffset) < guessInterval.RawStart) { return GetZoneInterval(guessInterval.Start - Duration.Epsilon); } else { return guessInterval; } } private ZoneInterval GetIntervalAfterGap(LocalInstant localInstant) { Instant guess = localInstant.MinusZeroOffset(); ZoneInterval guessInterval = GetZoneInterval(guess); // If the local interval occurs before the zone interval we're looking at starts, // it's the one we're looking for. Otherwise, we need to find the next interval. if (localInstant.Minus(guessInterval.WallOffset) < guessInterval.RawStart) { return guessInterval; } else { // Will definitely be valid - there can't be a gap after an infinite interval. return GetZoneInterval(guessInterval.End); } } #region Object overrides /// <summary> /// Returns the ID of this time zone. /// </summary> /// <returns> /// The ID of this time zone. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() => Id; #endregion /// <summary> /// Creates a fixed time zone for offsets -12 to +15 at every half hour, /// fixing the 0 offset as DateTimeZone.Utc. /// </summary> private static DateTimeZone[] BuildFixedZoneCache() { DateTimeZone[] ret = new DateTimeZone[FixedZoneCacheSize]; for (int i = 0; i < FixedZoneCacheSize; i++) { int offsetSeconds = i * FixedZoneCacheGranularitySeconds + FixedZoneCacheMinimumSeconds; ret[i] = new FixedDateTimeZone(Offset.FromSeconds(offsetSeconds)); } ret[-FixedZoneCacheMinimumSeconds / FixedZoneCacheGranularitySeconds] = Utc; return ret; } /// <summary> /// Returns all the zone intervals which occur for any instant in the interval [<paramref name="start"/>, <paramref name="end"/>). /// </summary> /// <remarks> /// <para>This method is simply a convenience method for calling <see cref="GetZoneIntervals(Interval)"/> without /// explicitly constructing the interval beforehand. /// </para> /// </remarks> /// <param name="start">Inclusive start point of the interval for which to retrieve zone intervals.</param> /// <param name="end">Exclusive end point of the interval for which to retrieve zone intervals.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="end"/> is earlier than <paramref name="start"/>.</exception> /// <returns>A sequence of zone intervals covering the given interval.</returns> /// <seealso cref="DateTimeZone.GetZoneInterval"/> public IEnumerable<ZoneInterval> GetZoneIntervals(Instant start, Instant end) => // The constructor performs all the validation we need. GetZoneIntervals(new Interval(start, end)); /// <summary> /// Returns all the zone intervals which occur for any instant in the given interval. /// </summary> /// <remarks> /// <para>The zone intervals are returned in chronological order. /// This method is equivalent to calling <see cref="DateTimeZone.GetZoneInterval"/> for every /// instant in the interval and then collapsing to a set of distinct zone intervals. /// The first and last zone intervals are likely to also cover instants outside the given interval; /// the zone intervals returned are not truncated to match the start and end points. /// </para> /// </remarks> /// <param name="interval">Interval to find zone intervals for. This is allowed to be unbounded (i.e. /// infinite in both directions).</param> /// <returns>A sequence of zone intervals covering the given interval.</returns> /// <seealso cref="DateTimeZone.GetZoneInterval"/> public IEnumerable<ZoneInterval> GetZoneIntervals(Interval interval) { var current = interval.HasStart ? interval.Start : Instant.MinValue; var end = interval.RawEnd; while (current < end) { var zoneInterval = GetZoneInterval(current); yield return zoneInterval; // If this is the end of time, this will just fail on the next comparison. current = zoneInterval.RawEnd; } } /// <summary> /// Returns the zone intervals within the given interval, potentially coalescing some of the /// original intervals according to options. /// </summary> /// <remarks> /// <para> /// This is equivalent to <see cref="GetZoneIntervals(Interval)"/>, but may coalesce some intervals. /// For example, if the <see cref="ZoneEqualityComparer.Options.OnlyMatchWallOffset"/> is specified, /// and two consecutive zone intervals have the same offset but different names, a single zone interval /// will be returned instead of two separate ones. When zone intervals are coalesced, all aspects of /// the first zone interval are used except its end instant, which is taken from the second zone interval. /// </para> /// <para> /// As the options are only used to determine which intervals to coalesce, the /// <see cref="ZoneEqualityComparer.Options.MatchStartAndEndTransitions"/> option does not affect /// the intervals returned. /// </para> /// </remarks> /// <param name="interval">Interval to find zone intervals for. This is allowed to be unbounded (i.e. /// infinite in both directions).</param> /// <param name="options"></param> /// <returns></returns> public IEnumerable<ZoneInterval> GetZoneIntervals(Interval interval, ZoneEqualityComparer.Options options) { if ((options & ~ZoneEqualityComparer.Options.StrictestMatch) != 0) { throw new ArgumentOutOfRangeException(nameof(options), $"The value {options} is not defined within ZoneEqualityComparer.Options"); } var zoneIntervalEqualityComparer = new ZoneEqualityComparer.ZoneIntervalEqualityComparer(options, interval); var originalIntervals = GetZoneIntervals(interval); return zoneIntervalEqualityComparer.CoalesceIntervals(originalIntervals); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //using System; //using System.Collections; //using System.Text; //namespace Lucene.Net.Analysis.Compound.Hyphenation //{ // /* // * <h2>Ternary Search Tree.</h2> // * // * <p> // * A ternary search tree is a hybrid between a binary tree and a digital search // * tree (trie). Keys are limited to strings. A data value of type char is stored // * in each leaf node. It can be used as an index (or pointer) to the data. // * Branches that only contain one key are compressed to one node by storing a // * pointer to the trailer substring of the key. This class is intended to serve // * as base class or helper class to implement Dictionary collections or the // * like. Ternary trees have some nice properties as the following: the tree can // * be traversed in sorted order, partial matches (wildcard) can be implemented, // * retrieval of all keys within a given distance from the target, etc. The // * storage requirements are higher than a binary tree but a lot less than a // * trie. Performance is comparable with a hash table, sometimes it outperforms a // * hash function (most of the time can determine a miss faster than a hash). // * </p> // * // * <p> // * The main purpose of this java port is to serve as a base for implementing // * TeX's hyphenation algorithm (see The TeXBook, appendix H). Each language // * requires from 5000 to 15000 hyphenation patterns which will be keys in this // * tree. The strings patterns are usually small (from 2 to 5 characters), but // * each char in the tree is stored in a node. Thus memory usage is the main // * concern. We will sacrifice 'elegance' to keep memory requirements to the // * minimum. Using java's char type as pointer (yes, I know pointer it is a // * forbidden word in java) we can keep the size of the node to be just 8 bytes // * (3 pointers and the data char). This gives room for about 65000 nodes. In my // * tests the english patterns took 7694 nodes and the german patterns 10055 // * nodes, so I think we are safe. // * </p> // * // * <p> // * All said, this is a map with strings as keys and char as value. Pretty // * limited!. It can be extended to a general map by using the string // * representation of an object and using the char value as an index to an array // * that contains the object values. // * </p> // * // * This class has been taken from the Apache FOP project (http://xmlgraphics.apache.org/fop/). They have been slightly modified. // */ // [Serializable] // public class TernaryTree : ICloneable // { // /* // * We use 4 arrays to represent a node. I guess I should have created a proper // * node class, but somehow Knuth's pascal code made me forget we now have a // * portable language with virtual memory management and automatic garbage // * collection! And now is kind of late, furthermore, if it ain't broken, don't // * fix it. // */ // /* // * Pointer to low branch and to rest of the key when it is stored directly in // * this node, we don't have unions in java! // */ // protected char[] lo; // /* // * Pointer to high branch. // */ // protected char[] hi; // /* // * Pointer to equal branch and to data when this node is a string terminator. // */ // protected char[] eq; // /* // * <P> // * The character stored in this node: splitchar. Two special values are // * reserved: // * </P> // * <ul> // * <li>0x0000 as string terminator</li> // * <li>0xFFFF to indicate that the branch starting at this node is compressed</li> // * </ul> // * <p> // * This shouldn't be a problem if we give the usual semantics to strings since // * 0xFFFF is guaranteed not to be an Unicode character. // * </p> // */ // protected char[] sc; // /* // * This vector holds the trailing of the keys when the branch is compressed. // */ // protected CharVector kv; // protected char root; // protected char freenode; // protected int length; // number of items in tree // protected static readonly int BLOCK_SIZE = 2048; // allocation size for arrays // private TernaryTree() // { // Init(); // } // protected void Init() // { // root = (char)0; // freenode = (char)1; // length = 0; // lo = new char[BLOCK_SIZE]; // hi = new char[BLOCK_SIZE]; // eq = new char[BLOCK_SIZE]; // sc = new char[BLOCK_SIZE]; // kv = new CharVector(); // } // /* // * Branches are initially compressed, needing one node per key plus the size // * of the string key. They are decompressed as needed when another key with // * same prefix is inserted. This saves a lot of space, specially for long // * keys. // */ // public void insert(String key, char val) // { // // make sure we have enough room in the arrays // int len = key.Length + 1; // maximum number of nodes that may be generated // if (freenode + len > eq.Length) // { // redimNodeArrays(eq.Length + BLOCK_SIZE); // } // char[] strkey = new char[len--]; // key.GetChars(0, len, strkey, 0); // strkey[len] = (char)0; // root = insert(root, strkey, 0, val); // } // public void insert(char[] key, int start, char val) // { // int len = strlen(key) + 1; // if (freenode + len > eq.Length) // { // redimNodeArrays(eq.Length + BLOCK_SIZE); // } // root = insert(root, key, start, val); // } // /* // * The actual insertion function, recursive version. // */ // private char insert(char p, char[] key, int start, char val) // { // int len = strlen(key, start); // if (p == 0) // { // // this means there is no branch, this node will start a new branch. // // Instead of doing that, we store the key somewhere else and create // // only one node with a pointer to the key // p = freenode++; // eq[p] = val; // holds data // length++; // hi[p] = (char)0; // if (len > 0) // { // sc[p] = (char)0xFFFF; // indicates branch is compressed // lo[p] = (char)kv.Alloc(len + 1); // use 'lo' to hold pointer to key // strcpy(kv.GetArray(), lo[p], key, start); // } // else // { // sc[p] = (char)0; // lo[p] = (char)0; // } // return p; // } // if (sc[p] == 0xFFFF) // { // // branch is compressed: need to decompress // // this will generate garbage in the external key array // // but we can do some garbage collection later // char pp = freenode++; // lo[pp] = lo[p]; // previous pointer to key // eq[pp] = eq[p]; // previous pointer to data // lo[p] = (char)0; // if (len > 0) // { // sc[p] = kv.Get(lo[pp]); // eq[p] = pp; // lo[pp]++; // if (kv.Get(lo[pp]) == 0) // { // // key completly decompressed leaving garbage in key array // lo[pp] = (char)0; // sc[pp] = (char)0; // hi[pp] = (char)0; // } // else // { // // we only got first char of key, rest is still there // sc[pp] = (char)0xFFFF; // } // } // else // { // // In this case we can save a node by swapping the new node // // with the compressed node // sc[pp] = (char)0xFFFF; // hi[p] = pp; // sc[p] = (char)0; // eq[p] = val; // length++; // return p; // } // } // char s = key[start]; // if (s < sc[p]) // { // lo[p] = insert(lo[p], key, start, val); // } // else if (s == sc[p]) // { // if (s != 0) // { // eq[p] = insert(eq[p], key, start + 1, val); // } // else // { // // key already in tree, overwrite data // eq[p] = val; // } // } // else // { // hi[p] = insert(hi[p], key, start, val); // } // return p; // } // /* // * Compares 2 null terminated char arrays // */ // public static int strcmp(char[] a, int startA, char[] b, int startB) // { // for (; a[startA] == b[startB]; startA++, startB++) // { // if (a[startA] == 0) // { // return 0; // } // } // return a[startA] - b[startB]; // } // /* // * Compares a string with null terminated char array // */ // public static int strcmp(String str, char[] a, int start) // { // int i, d, len = str.Length; // for (i = 0; i < len; i++) // { // d = (int)str[i] - a[start + i]; // if (d != 0) // { // return d; // } // if (a[start + i] == 0) // { // return d; // } // } // if (a[start + i] != 0) // { // return (int)-a[start + i]; // } // return 0; // } // public static void strcpy(char[] dst, int di, char[] src, int si) // { // while (src[si] != 0) // { // dst[di++] = src[si++]; // } // dst[di] = (char)0; // } // public static int strlen(char[] a, int start) // { // int len = 0; // for (int i = start; i < a.Length && a[i] != 0; i++) // { // len++; // } // return len; // } // public static int strlen(char[] a) // { // return strlen(a, 0); // } // public int find(String key) // { // int len = key.Length; // char[] strkey = new char[len + 1]; // key.GetChars(0, len, strkey, 0); // strkey[len] = (char)0; // return find(strkey, 0); // } // public int find(char[] key, int start) // { // int d; // char p = root; // int i = start; // char c; // while (p != 0) // { // if (sc[p] == 0xFFFF) // { // if (strcmp(key, i, kv.GetArray(), lo[p]) == 0) // { // return eq[p]; // } // else // { // return -1; // } // } // c = key[i]; // d = c - sc[p]; // if (d == 0) // { // if (c == 0) // { // return eq[p]; // } // i++; // p = eq[p]; // } // else if (d < 0) // { // p = lo[p]; // } // else // { // p = hi[p]; // } // } // return -1; // } // public bool knows(String key) // { // return (find(key) >= 0); // } // // redimension the arrays // private void redimNodeArrays(int newsize) // { // int len = newsize < lo.Length ? newsize : lo.Length; // char[] na = new char[newsize]; // Array.Copy(lo, 0, na, 0, len); // lo = na; // na = new char[newsize]; // Array.Copy(hi, 0, na, 0, len); // hi = na; // na = new char[newsize]; // Array.Copy(eq, 0, na, 0, len); // eq = na; // na = new char[newsize]; // Array.Copy(sc, 0, na, 0, len); // sc = na; // } // public int size() // { // return length; // } // public Object clone() // { // TernaryTree t = new TernaryTree(); // t.lo = (char[])this.lo.Clone(); // t.hi = (char[])this.hi.Clone(); // t.eq = (char[])this.eq.Clone(); // t.sc = (char[])this.sc.Clone(); // t.kv = (CharVector)this.kv.Clone(); // t.root = this.root; // t.freenode = this.freenode; // t.length = this.length; // return t; // } // /* // * Recursively insert the median first and then the median of the lower and // * upper halves, and so on in order to get a balanced tree. The array of keys // * is assumed to be sorted in ascending order. // */ // protected void insertBalanced(String[] k, char[] v, int offset, int n) // { // int m; // if (n < 1) // { // return; // } // m = n >> 1; // insert(k[m + offset], v[m + offset]); // insertBalanced(k, v, offset, m); // insertBalanced(k, v, offset + m + 1, n - m - 1); // } // /* // * Balance the tree for best search performance // */ // public void balance() // { // // System.out.print("Before root splitchar = "); // // System.out.println(sc[root]); // int i = 0, n = length; // String[] k = new String[n]; // char[] v = new char[n]; // Iterator iter = new Iterator(); // while (iter.HasMoreElements()) // { // v[i] = iter.getValue(); // k[i++] = (String)iter.nextElement(); // } // Init(); // insertBalanced(k, v, 0, n); // // With uniform letter distribution sc[root] should be around 'm' // // System.out.print("After root splitchar = "); // // System.out.println(sc[root]); // } // /* // * Each node stores a character (splitchar) which is part of some key(s). In a // * compressed branch (one that only contain a single string key) the trailer // * of the key which is not already in nodes is stored externally in the kv // * array. As items are inserted, key substrings decrease. Some substrings may // * completely disappear when the whole branch is totally decompressed. The // * tree is traversed to find the key substrings actually used. In addition, // * duplicate substrings are removed using a map (implemented with a // * TernaryTree!). // * // */ // public void trimToSize() // { // // first balance the tree for best performance // balance(); // // redimension the node arrays // redimNodeArrays(freenode); // // ok, compact kv array // CharVector kx = new CharVector(); // kx.Alloc(1); // TernaryTree map = new TernaryTree(); // compact(kx, map, root); // kv = kx; // kv.TrimToSize(); // } // private void compact(CharVector kx, TernaryTree map, char p) // { // int k; // if (p == 0) // { // return; // } // if (sc[p] == 0xFFFF) // { // k = map.find(kv.GetArray(), lo[p]); // if (k < 0) // { // k = kx.Alloc(strlen(kv.GetArray(), lo[p]) + 1); // strcpy(kx.GetArray(), k, kv.GetArray(), lo[p]); // map.insert(kx.GetArray(), k, (char)k); // } // lo[p] = (char)k; // } // else // { // compact(kx, map, lo[p]); // if (sc[p] != 0) // { // compact(kx, map, eq[p]); // } // compact(kx, map, hi[p]); // } // } // public IEnumerator keys() // { // return new Iterator(); // } // public class Iterator : IEnumerator // { // /* // * current node index // */ // int cur; // /* // * current key // */ // String curkey; // private class Item : ICloneable // { // char parent; // char child; // public Item() // { // parent = (char)0; // child = (char)0; // } // public Item(char p, char c) // { // parent = p; // child = c; // } // public Object Clone() // { // return new Item(parent, child); // } // } // /* // * Node stack // */ // Stack ns; // /* // * key stack implemented with a StringBuilder // */ // StringBuilder ks; // public Iterator() // { // cur = -1; // ns = new Stack(); // ks = new StringBuilder(); // rewind(); // } // public void rewind() // { // ns.Clear(); // ks.SetLength(0); // cur = root; // Run(); // } // public Object nextElement() // { // String res = curkey; // cur = up(); // Run(); // return res; // } // public char getValue() // { // if (cur >= 0) // { // return eq[cur]; // } // return 0; // } // public bool hasMoreElements() // { // return (cur != -1); // } // /* // * traverse upwards // */ // private int up() // { // Item i = new Item(); // int res = 0; // if (ns.Empty()) // { // return -1; // } // if (cur != 0 && sc[cur] == 0) // { // return lo[cur]; // } // bool climb = true; // while (climb) // { // i = (Item)ns.Pop(); // i.child++; // switch (i.child) // { // case 1: // if (sc[i.parent] != 0) // { // res = eq[i.parent]; // ns.Push(i.Clone()); // ks.Append(sc[i.parent]); // } // else // { // i.child++; // ns.Push(i.Clone()); // res = hi[i.parent]; // } // climb = false; // break; // case 2: // res = hi[i.parent]; // ns.Push(i.Clone()); // if (ks.Length() > 0) // { // ks.SetLength(ks.Length() - 1); // pop // } // climb = false; // break; // default: // if (ns.Clear()) // { // return -1; // } // climb = true; // break; // } // } // return res; // } // /* // * traverse the tree to find next key // */ // private int Run() // { // if (cur == -1) // { // return -1; // } // bool leaf = false; // while (true) // { // // first go down on low branch until leaf or compressed branch // while (cur != 0) // { // if (sc[cur] == 0xFFFF) // { // leaf = true; // break; // } // ns.Push(new Item((char)cur, '\u0000')); // if (sc[cur] == 0) // { // leaf = true; // break; // } // cur = lo[cur]; // } // if (leaf) // { // break; // } // // nothing found, go up one node and try again // cur = up(); // if (cur == -1) // { // return -1; // } // } // // The current node should be a data node and // // the key should be in the key stack (at least partially) // StringBuilder buf = new StringBuilder(ks.ToString()); // if (sc[cur] == 0xFFFF) // { // int p = lo[cur]; // while (kv.Get(p) != 0) // { // buf.Append(kv.Get(p++)); // } // } // curkey = buf.ToString(); // return 0; // } // } // public void PrintStats() // { // Console.WriteLine("Number of keys = " + length); // Console.WriteLine("Node count = " + freenode); // // System.out.println("Array length = " + Integer.toString(eq.length)); // Console.WriteLine("Key Array length = " + kv.Length()); // /* // * for(int i=0; i<kv.length(); i++) if ( kv.get(i) != 0 ) // * System.out.print(kv.get(i)); else System.out.println(""); // * System.out.println("Keys:"); for(Enumeration enum = keys(); // * enum.hasMoreElements(); ) System.out.println(enum.nextElement()); // */ // } // public static void Main(String[] args) // { // TernaryTree tt = new TernaryTree(); // tt.insert("Carlos", 'C'); // tt.insert("Car", 'r'); // tt.insert("palos", 'l'); // tt.insert("pa", 'p'); // tt.trimToSize(); // Console.WriteLine((char)tt.find("Car")); // Console.WriteLine((char)tt.find("Carlos")); // Console.WriteLine((char)tt.find("alto")); // tt.PrintStats(); // } // } //}
// 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. // Generated code. DO NOT EDIT! using Google.Api; using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Monitoring.V3 { /// <summary> /// Settings for a <see cref="GroupServiceClient"/>. /// </summary> public sealed partial class GroupServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="GroupServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="GroupServiceSettings"/>. /// </returns> public static GroupServiceSettings GetDefault() => new GroupServiceSettings(); /// <summary> /// Constructs a new <see cref="GroupServiceSettings"/> object with default settings. /// </summary> public GroupServiceSettings() { } private GroupServiceSettings(GroupServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListGroupsSettings = existing.ListGroupsSettings; GetGroupSettings = existing.GetGroupSettings; CreateGroupSettings = existing.CreateGroupSettings; UpdateGroupSettings = existing.UpdateGroupSettings; DeleteGroupSettings = existing.DeleteGroupSettings; ListGroupMembersSettings = existing.ListGroupMembersSettings; } /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="GroupServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="GroupServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="GroupServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="GroupServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="GroupServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="GroupServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="GroupServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="GroupServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupServiceClient.ListGroups</c> and <c>GroupServiceClient.ListGroupsAsync</c>. /// </summary> /// <remarks> /// The default <c>GroupServiceClient.ListGroups</c> and /// <c>GroupServiceClient.ListGroupsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListGroupsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupServiceClient.GetGroup</c> and <c>GroupServiceClient.GetGroupAsync</c>. /// </summary> /// <remarks> /// The default <c>GroupServiceClient.GetGroup</c> and /// <c>GroupServiceClient.GetGroupAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings GetGroupSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupServiceClient.CreateGroup</c> and <c>GroupServiceClient.CreateGroupAsync</c>. /// </summary> /// <remarks> /// The default <c>GroupServiceClient.CreateGroup</c> and /// <c>GroupServiceClient.CreateGroupAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings CreateGroupSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupServiceClient.UpdateGroup</c> and <c>GroupServiceClient.UpdateGroupAsync</c>. /// </summary> /// <remarks> /// The default <c>GroupServiceClient.UpdateGroup</c> and /// <c>GroupServiceClient.UpdateGroupAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings UpdateGroupSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupServiceClient.DeleteGroup</c> and <c>GroupServiceClient.DeleteGroupAsync</c>. /// </summary> /// <remarks> /// The default <c>GroupServiceClient.DeleteGroup</c> and /// <c>GroupServiceClient.DeleteGroupAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings DeleteGroupSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupServiceClient.ListGroupMembers</c> and <c>GroupServiceClient.ListGroupMembersAsync</c>. /// </summary> /// <remarks> /// The default <c>GroupServiceClient.ListGroupMembers</c> and /// <c>GroupServiceClient.ListGroupMembersAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListGroupMembersSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="GroupServiceSettings"/> object.</returns> public GroupServiceSettings Clone() => new GroupServiceSettings(this); } /// <summary> /// GroupService client wrapper, for convenient use. /// </summary> public abstract partial class GroupServiceClient { /// <summary> /// The default endpoint for the GroupService service, which is a host of "monitoring.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("monitoring.googleapis.com", 443); /// <summary> /// The default GroupService scopes. /// </summary> /// <remarks> /// The default GroupService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// <item><description>"https://www.googleapis.com/auth/monitoring"</description></item> /// <item><description>"https://www.googleapis.com/auth/monitoring.read"</description></item> /// <item><description>"https://www.googleapis.com/auth/monitoring.write"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/monitoring.read", "https://www.googleapis.com/auth/monitoring.write", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); /// <summary> /// Path template for a project resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// </list> /// </summary> public static PathTemplate ProjectTemplate { get; } = new PathTemplate("projects/{project}"); /// <summary> /// Creates a project resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <returns> /// The full project resource name. /// </returns> public static string FormatProjectName(string projectId) => ProjectTemplate.Expand(projectId); /// <summary> /// Path template for a group resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// <item><description>group</description></item> /// </list> /// </summary> public static PathTemplate GroupTemplate { get; } = new PathTemplate("projects/{project}/groups/{group}"); /// <summary> /// Creates a group resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <param name="groupId">The group ID.</param> /// <returns> /// The full group resource name. /// </returns> public static string FormatGroupName(string projectId, string groupId) => GroupTemplate.Expand(projectId, groupId); /// <summary> /// Path template for a metric_descriptor resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// <item><description>metricDescriptor</description></item> /// </list> /// </summary> public static PathTemplate MetricDescriptorTemplate { get; } = new PathTemplate("projects/{project}/metricDescriptors/{metric_descriptor=**}"); /// <summary> /// Creates a metric_descriptor resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <param name="metricDescriptorId">The metricDescriptor ID.</param> /// <returns> /// The full metric_descriptor resource name. /// </returns> public static string FormatMetricDescriptorName(string projectId, string metricDescriptorId) => MetricDescriptorTemplate.Expand(projectId, metricDescriptorId); /// <summary> /// Path template for a monitored_resource_descriptor resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// <item><description>monitoredResourceDescriptor</description></item> /// </list> /// </summary> public static PathTemplate MonitoredResourceDescriptorTemplate { get; } = new PathTemplate("projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}"); /// <summary> /// Creates a monitored_resource_descriptor resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <param name="monitoredResourceDescriptorId">The monitoredResourceDescriptor ID.</param> /// <returns> /// The full monitored_resource_descriptor resource name. /// </returns> public static string FormatMonitoredResourceDescriptorName(string projectId, string monitoredResourceDescriptorId) => MonitoredResourceDescriptorTemplate.Expand(projectId, monitoredResourceDescriptorId); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="GroupServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="GroupServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="GroupServiceClient"/>.</returns> public static async Task<GroupServiceClient> CreateAsync(ServiceEndpoint endpoint = null, GroupServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="GroupServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="GroupServiceSettings"/>.</param> /// <returns>The created <see cref="GroupServiceClient"/>.</returns> public static GroupServiceClient Create(ServiceEndpoint endpoint = null, GroupServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="GroupServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="GroupServiceSettings"/>.</param> /// <returns>The created <see cref="GroupServiceClient"/>.</returns> public static GroupServiceClient Create(Channel channel, GroupServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); GroupService.GroupServiceClient grpcClient = new GroupService.GroupServiceClient(channel); return new GroupServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, GroupServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, GroupServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, GroupServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, GroupServiceSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC GroupService client. /// </summary> public virtual GroupService.GroupServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Gets a single group. /// </summary> /// <param name="name"> /// The group to retrieve. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Group> GetGroupAsync( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a single group. /// </summary> /// <param name="name"> /// The group to retrieve. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Group> GetGroupAsync( string name, CancellationToken cancellationToken) => GetGroupAsync( name, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets a single group. /// </summary> /// <param name="name"> /// The group to retrieve. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Group GetGroup( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates a new group. /// </summary> /// <param name="name"> /// The project in which to create the group. The format is /// `"projects/{project_id_or_number}"`. /// </param> /// <param name="group"> /// A group definition. It is an error to define the `name` field because /// the system assigns the name. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Group> CreateGroupAsync( string name, Group group, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates a new group. /// </summary> /// <param name="name"> /// The project in which to create the group. The format is /// `"projects/{project_id_or_number}"`. /// </param> /// <param name="group"> /// A group definition. It is an error to define the `name` field because /// the system assigns the name. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Group> CreateGroupAsync( string name, Group group, CancellationToken cancellationToken) => CreateGroupAsync( name, group, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a new group. /// </summary> /// <param name="name"> /// The project in which to create the group. The format is /// `"projects/{project_id_or_number}"`. /// </param> /// <param name="group"> /// A group definition. It is an error to define the `name` field because /// the system assigns the name. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Group CreateGroup( string name, Group group, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="group"> /// The new definition of the group. All fields of the existing group, /// excepting `name`, are replaced with the corresponding fields of this group. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Group> UpdateGroupAsync( Group group, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="group"> /// The new definition of the group. All fields of the existing group, /// excepting `name`, are replaced with the corresponding fields of this group. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Group> UpdateGroupAsync( Group group, CancellationToken cancellationToken) => UpdateGroupAsync( group, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="group"> /// The new definition of the group. All fields of the existing group, /// excepting `name`, are replaced with the corresponding fields of this group. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Group UpdateGroup( Group group, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="name"> /// The group to delete. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteGroupAsync( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="name"> /// The group to delete. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteGroupAsync( string name, CancellationToken cancellationToken) => DeleteGroupAsync( name, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes an existing group. /// </summary> /// <param name="name"> /// The group to delete. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteGroup( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="name"> /// The group whose members are listed. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="MonitoredResource"/> resources. /// </returns> public virtual IPagedAsyncEnumerable<ListGroupMembersResponse, MonitoredResource> ListGroupMembersAsync( string name, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="name"> /// The group whose members are listed. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="MonitoredResource"/> resources. /// </returns> public virtual IPagedEnumerable<ListGroupMembersResponse, MonitoredResource> ListGroupMembers( string name, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// GroupService client wrapper implementation, for convenient use. /// </summary> public sealed partial class GroupServiceClientImpl : GroupServiceClient { private readonly ClientHelper _clientHelper; private readonly ApiCall<ListGroupsRequest, ListGroupsResponse> _callListGroups; private readonly ApiCall<GetGroupRequest, Group> _callGetGroup; private readonly ApiCall<CreateGroupRequest, Group> _callCreateGroup; private readonly ApiCall<UpdateGroupRequest, Group> _callUpdateGroup; private readonly ApiCall<DeleteGroupRequest, Empty> _callDeleteGroup; private readonly ApiCall<ListGroupMembersRequest, ListGroupMembersResponse> _callListGroupMembers; /// <summary> /// Constructs a client wrapper for the GroupService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="GroupServiceSettings"/> used within this client </param> public GroupServiceClientImpl(GroupService.GroupServiceClient grpcClient, GroupServiceSettings settings) { this.GrpcClient = grpcClient; GroupServiceSettings effectiveSettings = settings ?? GroupServiceSettings.GetDefault(); _clientHelper = new ClientHelper(effectiveSettings); _callListGroups = _clientHelper.BuildApiCall<ListGroupsRequest, ListGroupsResponse>( GrpcClient.ListGroupsAsync, GrpcClient.ListGroups, effectiveSettings.ListGroupsSettings); _callGetGroup = _clientHelper.BuildApiCall<GetGroupRequest, Group>( GrpcClient.GetGroupAsync, GrpcClient.GetGroup, effectiveSettings.GetGroupSettings); _callCreateGroup = _clientHelper.BuildApiCall<CreateGroupRequest, Group>( GrpcClient.CreateGroupAsync, GrpcClient.CreateGroup, effectiveSettings.CreateGroupSettings); _callUpdateGroup = _clientHelper.BuildApiCall<UpdateGroupRequest, Group>( GrpcClient.UpdateGroupAsync, GrpcClient.UpdateGroup, effectiveSettings.UpdateGroupSettings); _callDeleteGroup = _clientHelper.BuildApiCall<DeleteGroupRequest, Empty>( GrpcClient.DeleteGroupAsync, GrpcClient.DeleteGroup, effectiveSettings.DeleteGroupSettings); _callListGroupMembers = _clientHelper.BuildApiCall<ListGroupMembersRequest, ListGroupMembersResponse>( GrpcClient.ListGroupMembersAsync, GrpcClient.ListGroupMembers, effectiveSettings.ListGroupMembersSettings); } /// <summary> /// The underlying gRPC GroupService client. /// </summary> public override GroupService.GroupServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_ListGroupsRequest(ref ListGroupsRequest request, ref CallSettings settings); partial void Modify_GetGroupRequest(ref GetGroupRequest request, ref CallSettings settings); partial void Modify_CreateGroupRequest(ref CreateGroupRequest request, ref CallSettings settings); partial void Modify_UpdateGroupRequest(ref UpdateGroupRequest request, ref CallSettings settings); partial void Modify_DeleteGroupRequest(ref DeleteGroupRequest request, ref CallSettings settings); partial void Modify_ListGroupMembersRequest(ref ListGroupMembersRequest request, ref CallSettings settings); /// <summary> /// Gets a single group. /// </summary> /// <param name="name"> /// The group to retrieve. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<Group> GetGroupAsync( string name, CallSettings callSettings = null) { GetGroupRequest request = new GetGroupRequest { Name = name, }; Modify_GetGroupRequest(ref request, ref callSettings); return _callGetGroup.Async(request, callSettings); } /// <summary> /// Gets a single group. /// </summary> /// <param name="name"> /// The group to retrieve. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Group GetGroup( string name, CallSettings callSettings = null) { GetGroupRequest request = new GetGroupRequest { Name = name, }; Modify_GetGroupRequest(ref request, ref callSettings); return _callGetGroup.Sync(request, callSettings); } /// <summary> /// Creates a new group. /// </summary> /// <param name="name"> /// The project in which to create the group. The format is /// `"projects/{project_id_or_number}"`. /// </param> /// <param name="group"> /// A group definition. It is an error to define the `name` field because /// the system assigns the name. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<Group> CreateGroupAsync( string name, Group group, CallSettings callSettings = null) { CreateGroupRequest request = new CreateGroupRequest { Name = name, Group = group, }; Modify_CreateGroupRequest(ref request, ref callSettings); return _callCreateGroup.Async(request, callSettings); } /// <summary> /// Creates a new group. /// </summary> /// <param name="name"> /// The project in which to create the group. The format is /// `"projects/{project_id_or_number}"`. /// </param> /// <param name="group"> /// A group definition. It is an error to define the `name` field because /// the system assigns the name. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Group CreateGroup( string name, Group group, CallSettings callSettings = null) { CreateGroupRequest request = new CreateGroupRequest { Name = name, Group = group, }; Modify_CreateGroupRequest(ref request, ref callSettings); return _callCreateGroup.Sync(request, callSettings); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="group"> /// The new definition of the group. All fields of the existing group, /// excepting `name`, are replaced with the corresponding fields of this group. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<Group> UpdateGroupAsync( Group group, CallSettings callSettings = null) { UpdateGroupRequest request = new UpdateGroupRequest { Group = group, }; Modify_UpdateGroupRequest(ref request, ref callSettings); return _callUpdateGroup.Async(request, callSettings); } /// <summary> /// Updates an existing group. /// You can change any group attributes except `name`. /// </summary> /// <param name="group"> /// The new definition of the group. All fields of the existing group, /// excepting `name`, are replaced with the corresponding fields of this group. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Group UpdateGroup( Group group, CallSettings callSettings = null) { UpdateGroupRequest request = new UpdateGroupRequest { Group = group, }; Modify_UpdateGroupRequest(ref request, ref callSettings); return _callUpdateGroup.Sync(request, callSettings); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="name"> /// The group to delete. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task DeleteGroupAsync( string name, CallSettings callSettings = null) { DeleteGroupRequest request = new DeleteGroupRequest { Name = name, }; Modify_DeleteGroupRequest(ref request, ref callSettings); return _callDeleteGroup.Async(request, callSettings); } /// <summary> /// Deletes an existing group. /// </summary> /// <param name="name"> /// The group to delete. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void DeleteGroup( string name, CallSettings callSettings = null) { DeleteGroupRequest request = new DeleteGroupRequest { Name = name, }; Modify_DeleteGroupRequest(ref request, ref callSettings); _callDeleteGroup.Sync(request, callSettings); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="name"> /// The group whose members are listed. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="MonitoredResource"/> resources. /// </returns> public override IPagedAsyncEnumerable<ListGroupMembersResponse, MonitoredResource> ListGroupMembersAsync( string name, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { ListGroupMembersRequest request = new ListGroupMembersRequest { Name = name, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListGroupMembersRequest(ref request, ref callSettings); return new PagedAsyncEnumerable<ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>(_callListGroupMembers, request, callSettings); } /// <summary> /// Lists the monitored resources that are members of a group. /// </summary> /// <param name="name"> /// The group whose members are listed. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="MonitoredResource"/> resources. /// </returns> public override IPagedEnumerable<ListGroupMembersResponse, MonitoredResource> ListGroupMembers( string name, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { ListGroupMembersRequest request = new ListGroupMembersRequest { Name = name, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListGroupMembersRequest(ref request, ref callSettings); return new PagedEnumerable<ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>(_callListGroupMembers, request, callSettings); } } // Partial classes to enable page-streaming public partial class ListGroupMembersRequest : IPageRequest { } public partial class ListGroupMembersResponse : IPageResponse<MonitoredResource> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<MonitoredResource> GetEnumerator() => Members.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class ParameterNamesShouldMatchBaseDeclarationTests { [Fact] public async Task VerifyNoFalsePositivesAreReported() { await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod() { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod(string arg1, string arg2, __arglist) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod(string arg1, string arg2, params string[] arg3) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Sub TestMethod() End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3() As String) End Sub End Class"); } [Fact] public async Task VerifyOverrideWithWrongParameterNames() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2)")); await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2, __arglist)")); await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 106, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", GetBasicResultAt(8, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class", GetBasicResultAt(8, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 106, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VerifyInternalOverrideWithWrongParameterNames_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { internal abstract void TestMethod(string baseArg1, string baseArg2); } public class TestClass : BaseClass { internal override void TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"internal abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, __arglist); } internal class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, __arglist) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"internal class OuterClass { public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, params string[] arg3) { } } }"); await VerifyVB.VerifyAnalyzerAsync(@"Friend MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Friend Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Friend MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Friend Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Friend Class OuterClass Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class End Class"); } [Fact] public async Task VerifyInterfaceImplementationWithWrongParameterNames() { await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2)")); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)")); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 97, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String) End Interface Public Class TestClass Implements IBase Public Sub TestMethod(arg1 As String, arg2 As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 53, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 69, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3() As String) End Interface Public Class TestClass Implements IBase Public Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3() As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 53, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 69, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 96, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VerifyExplicitInterfaceImplementationWithWrongParameterNames_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2, __arglist) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2, params string[] arg3) { } }"); } [Fact] public async Task VerifyInterfaceImplementationWithDifferentMethodName() { await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String) End Interface Public Class TestClass Implements IBase Public Sub AnotherTestMethod(arg1 As String, arg2 As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 60, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 76, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Interface Public Class TestClass Implements IBase Public Sub AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 60, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 76, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 103, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact] public async Task VerifyThatInvalidOverrideIsNotReported() { await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public override void {|CS0115:TestMethod|}(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Overrides Sub {|BC30284:TestMethod|}(arg1 As String, arg2 As String) End Sub End Class"); } [Fact] public async Task VerifyOverrideWithInheritanceChain() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2); } public abstract class IntermediateBaseClass : BaseClass { } public class TestClass : IntermediateBaseClass { public override void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(12, 71, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(12, 84, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Public MustInherit Class IntermediateBaseClass Inherits BaseClass End Class Public Class TestClass Inherits IntermediateBaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", GetBasicResultAt(12, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(12, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)")); } [Fact] public async Task VerifyNewOverrideWithInheritance() { await VerifyCS.VerifyAnalyzerAsync(@"public class BaseClass { public void TestMethod(string baseArg1, string baseArg2) { } } public class TestClass : BaseClass { public new void TestMethod(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class BaseClass Public Sub TestMethod(baseArg1 As String, baseArg2 As String) End Sub End Class Public Class TestClass Inherits BaseClass Public Shadows Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); } [Fact] public async Task VerifyBaseClassNameHasPriority() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string arg1, string arg2); } public interface ITest { void TestMethod(string interfaceArg1, string interfaceArg2); } public class TestClass : BaseClass, ITest { public override void TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string arg1, string arg2); } public interface ITest { void TestMethod(string interfaceArg1, string interfaceArg2); } public class TestClass : BaseClass, ITest { public override void TestMethod(string interfaceArg1, string interfaceArg2) { } }", GetCSharpResultAt(13, 71, "void TestClass.TestMethod(string interfaceArg1, string interfaceArg2)", "interfaceArg1", "arg1", "void BaseClass.TestMethod(string arg1, string arg2)"), GetCSharpResultAt(13, 93, "void TestClass.TestMethod(string interfaceArg1, string interfaceArg2)", "interfaceArg2", "arg2", "void BaseClass.TestMethod(string arg1, string arg2)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(arg1 As String, arg2 As String) End Class Public Interface ITest Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) End Interface Public Class TestClass Inherits BaseClass Implements ITest Public Overrides Sub TestMethod(arg1 As String, arg2 As String) Implements ITest.TestMethod End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(arg1 As String, arg2 As String) End Class Public Interface ITest Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) End Interface Public Class TestClass Inherits BaseClass Implements ITest Public Overrides Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) Implements ITest.TestMethod End Sub End Class", GetBasicResultAt(13, 63, "Sub TestClass.TestMethod(interfaceArg1 As String, interfaceArg2 As String)", "interfaceArg1", "arg1", "Sub BaseClass.TestMethod(arg1 As String, arg2 As String)"), GetBasicResultAt(13, 88, "Sub TestClass.TestMethod(interfaceArg1 As String, interfaceArg2 As String)", "interfaceArg2", "arg2", "Sub BaseClass.TestMethod(arg1 As String, arg2 As String)")); } [Fact] public async Task VerifyMultipleClashingInterfacesWithFullMatch() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest1 { void TestMethod(string arg1, string arg2); } public interface ITest2 { void TestMethod(string otherArg1, string otherArg2); } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Interface ITest2 Sub TestMethod(otherArg1 As String, otherArg2 As String) End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest1.TestMethod, ITest2.TestMethod End Sub End Class"); } [Fact] public async Task VerifyMultipleClashingInterfacesWithPartialMatch() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest1 { void TestMethod(string arg1, string arg2, string arg3); } public interface ITest2 { void TestMethod(string otherArg1, string otherArg2, string otherArg3); } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2, string otherArg3) { } }", GetCSharpResultAt(13, 88, "void TestClass.TestMethod(string arg1, string arg2, string otherArg3)", "otherArg3", "arg3", "void ITest1.TestMethod(string arg1, string arg2, string arg3)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String, arg3 As String) End Interface Public Interface ITest2 Sub TestMethod(otherArg1 As String, otherArg2 As String, otherArg3 As String) End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String, otherArg3 As String) Implements ITest1.TestMethod, ITest2.TestMethod End Sub End Class", GetBasicResultAt(12, 85, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, otherArg3 As String)", "otherArg3", "arg3", "Sub ITest1.TestMethod(arg1 As String, arg2 As String, arg3 As String)")); } [Fact] public async Task VerifyIgnoresPropertiesWithTheSameName() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest1 { void TestMethod(string arg1, string arg2); } public interface ITest2 { int TestMethod { get; set; } } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2) { } int ITest2.TestMethod { get; set; } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Interface ITest2 Property TestMethod As Integer End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest1.TestMethod End Sub Private Property TestMethodFromITest2 As Integer Implements ITest2.TestMethod End Class"); } [Fact] public async Task VerifyHandlesMultipleBaseMethodsWithTheSameName() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest { void TestMethod(string arg1); void TestMethod(string arg1, string arg2); } public class TestClass : ITest { public void TestMethod(string arg1) { } public void TestMethod(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest Sub TestMethod(arg1 As String) Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Class TestClass Implements ITest Public Sub TestMethod(arg1 As String) Implements ITest.TestMethod End Sub Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest.TestMethod End Sub End Class"); } private static DiagnosticResult GetCSharpResultAt(int line, int column, string violatingMember, string violatingParameter, string baseParameter, string baseMember) => VerifyCS.Diagnostic() .WithLocation(line, column) .WithArguments(violatingMember, violatingParameter, baseParameter, baseMember); private static DiagnosticResult GetBasicResultAt(int line, int column, string violatingMember, string violatingParameter, string baseParameter, string baseMember) => VerifyVB.Diagnostic() .WithLocation(line, column) .WithArguments(violatingMember, violatingParameter, baseParameter, baseMember); } }
// // Copyright (c) 2012 Krueger Systems, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace SQLite { public partial class SQLiteAsyncConnection { SQLiteConnectionString _connectionString; SQLiteOpenFlags _openFlags; public SQLiteAsyncConnection(string databasePath, bool storeDateTimeAsTicks = false) : this(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) { } public SQLiteAsyncConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false) { _openFlags = openFlags; _connectionString = new SQLiteConnectionString(databasePath, storeDateTimeAsTicks); } SQLiteConnectionWithLock GetConnection () { return SQLiteConnectionPool.Shared.GetConnection (_connectionString, _openFlags); } public Task<CreateTablesResult> CreateTableAsync<T> () where T : new () { return CreateTablesAsync (typeof (T)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2> () where T : new () where T2 : new () { return CreateTablesAsync (typeof (T), typeof (T2)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> () where T : new () where T2 : new () where T3 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> () where T : new () where T2 : new () where T3 : new () where T4 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> () where T : new () where T2 : new () where T3 : new () where T4 : new () where T5 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); } public Task<CreateTablesResult> CreateTablesAsync (params Type[] types) { return Task.Factory.StartNew (() => { CreateTablesResult result = new CreateTablesResult (); var conn = GetConnection (); using (conn.Lock ()) { foreach (Type type in types) { int aResult = conn.CreateTable (type); result.Results[type] = aResult; } } return result; }); } public Task<int> DropTableAsync<T> () where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.DropTable<T> (); } }); } public Task<int> InsertAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Insert (item); } }); } public Task<int> UpdateAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Update (item); } }); } public Task<int> DeleteAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Delete (item); } }); } public Task<T> GetAsync<T>(object pk) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T>(pk); } }); } public Task<T> FindAsync<T> (object pk) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (pk); } }); } public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T> (predicate); } }); } public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (predicate); } }); } public Task<int> ExecuteAsync (string query, params object[] args) { return Task<int>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Execute (query, args); } }); } public Task<int> InsertAllAsync (IEnumerable items) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.InsertAll (items); } }); } public Task<int> UpdateAllAsync (IEnumerable items) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.UpdateAll (items); } }); } [Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")] public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action) { return Task.Factory.StartNew (() => { var conn = this.GetConnection (); using (conn.Lock ()) { conn.BeginTransaction (); try { action (this); conn.Commit (); } catch (Exception) { conn.Rollback (); throw; } } }); } public Task RunInTransactionAsync(Action<SQLiteConnection> action) { return Task.Factory.StartNew(() => { var conn = this.GetConnection(); using (conn.Lock()) { conn.BeginTransaction(); try { action(conn); conn.Commit(); } catch (Exception) { conn.Rollback(); throw; } } }); } public AsyncTableQuery<T> Table<T> () where T : new () { // // This isn't async as the underlying connection doesn't go out to the database // until the query is performed. The Async methods are on the query iteself. // var conn = GetConnection (); return new AsyncTableQuery<T> (conn.Table<T> ()); } public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args) { return Task<T>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { var command = conn.CreateCommand (sql, args); return command.ExecuteScalar<T> (); } }); } public Task<List<T>> QueryAsync<T> (string sql, params object[] args) where T : new () { return Task<List<T>>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Query<T> (sql, args); } }); } } // // TODO: Bind to AsyncConnection.GetConnection instead so that delayed // execution can still work after a Pool.Reset. // public class AsyncTableQuery<T> where T : new () { TableQuery<T> _innerQuery; public AsyncTableQuery (TableQuery<T> innerQuery) { _innerQuery = innerQuery; } public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr) { return new AsyncTableQuery<T> (_innerQuery.Where (predExpr)); } public AsyncTableQuery<T> Skip (int n) { return new AsyncTableQuery<T> (_innerQuery.Skip (n)); } public AsyncTableQuery<T> Take (int n) { return new AsyncTableQuery<T> (_innerQuery.Take (n)); } public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr)); } public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr)); } public Task<List<T>> ToListAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ToList (); } }); } public Task<int> CountAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.Count (); } }); } public Task<T> ElementAtAsync (int index) { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ElementAt (index); } }); } public Task<T> FirstAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.First (); } }); } public Task<T> FirstOrDefaultAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.FirstOrDefault (); } }); } } public class CreateTablesResult { public Dictionary<Type, int> Results { get; private set; } internal CreateTablesResult () { this.Results = new Dictionary<Type, int> (); } } class SQLiteConnectionPool { class Entry { public SQLiteConnectionString ConnectionString { get; private set; } public SQLiteConnectionWithLock Connection { get; private set; } public Entry (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) { ConnectionString = connectionString; Connection = new SQLiteConnectionWithLock (connectionString, openFlags); } public void OnApplicationSuspended () { Connection.Dispose (); Connection = null; } } readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> (); readonly object _entriesLock = new object (); static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool (); /// <summary> /// Gets the singleton instance of the connection tool. /// </summary> public static SQLiteConnectionPool Shared { get { return _shared; } } public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) { lock (_entriesLock) { Entry entry; string key = connectionString.ConnectionString; if (!_entries.TryGetValue (key, out entry)) { entry = new Entry (connectionString, openFlags); _entries[key] = entry; } return entry.Connection; } } /// <summary> /// Closes all connections managed by this pool. /// </summary> public void Reset () { lock (_entriesLock) { foreach (var entry in _entries.Values) { entry.OnApplicationSuspended (); } _entries.Clear (); } } /// <summary> /// Call this method when the application is suspended. /// </summary> /// <remarks>Behaviour here is to close any open connections.</remarks> public void ApplicationSuspended () { Reset (); } } class SQLiteConnectionWithLock : SQLiteConnection { readonly object _lockPoint = new object (); public SQLiteConnectionWithLock (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) : base (connectionString.DatabasePath, openFlags, connectionString.StoreDateTimeAsTicks) { } public IDisposable Lock () { return new LockWrapper (_lockPoint); } private class LockWrapper : IDisposable { object _lockPoint; public LockWrapper (object lockPoint) { _lockPoint = lockPoint; Monitor.Enter (_lockPoint); } public void Dispose () { Monitor.Exit (_lockPoint); } } } }
using System; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Cocos2D { public class CCMotionStreak : CCNodeRGBA, ICCTextureProtocol { protected bool m_bFastMode; protected bool m_bStartingPositionInitialized; private float m_fFadeDelta; private float m_fMinSeg; private float m_fStroke; private float[] m_pPointState; private CCPoint[] m_pPointVertexes; /** texture used for the motion streak */ private CCTexture2D m_pTexture; private CCV3F_C4B_T2F[] m_pVertices; private CCBlendFunc m_tBlendFunc; private CCPoint m_tPositionR; private int m_uMaxPoints; private int m_uNuPoints; private int m_uPreviousNuPoints; /** Pointers */ public CCMotionStreak() { m_tBlendFunc = CCBlendFunc.NonPremultiplied; } public override CCPoint Position { set { m_bStartingPositionInitialized = true; m_tPositionR = value; } } #region RGBA Protocol public override byte Opacity { get { return 0; } set { } } public override bool IsOpacityModifyRGB { get { return false; } set { } } #endregion #region ICCTextureProtocol Members public CCTexture2D Texture { get { return m_pTexture; } set { m_pTexture = value; } } public CCBlendFunc BlendFunc { set { m_tBlendFunc = value; } get { return (m_tBlendFunc); } } #endregion public bool FastMode { get { return m_bFastMode; } set { m_bFastMode = value; } } public bool StartingPositionInitialized { get { return m_bStartingPositionInitialized; } set { m_bStartingPositionInitialized = value; } } public static CCMotionStreak Create(float fade, float minSeg, float stroke, CCColor3B color, string path) { var pRet = new CCMotionStreak(); pRet.InitWithFade(fade, minSeg, stroke, color, path); return pRet; } public static CCMotionStreak Create(float fade, float minSeg, float stroke, CCColor3B color, CCTexture2D texture) { var pRet = new CCMotionStreak(); pRet.InitWithFade(fade, minSeg, stroke, color, texture); return pRet; } public bool InitWithFade(float fade, float minSeg, float stroke, CCColor3B color, string path) { Debug.Assert(!String.IsNullOrEmpty(path), "Invalid filename"); CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(path); return InitWithFade(fade, minSeg, stroke, color, texture); } public bool InitWithFade(float fade, float minSeg, float stroke, CCColor3B color, CCTexture2D texture) { Position = CCPoint.Zero; AnchorPoint = CCPoint.Zero; IgnoreAnchorPointForPosition = true; m_bStartingPositionInitialized = false; m_tPositionR = CCPoint.Zero; m_bFastMode = true; m_fMinSeg = (minSeg == -1.0f) ? stroke / 5.0f : minSeg; m_fMinSeg *= m_fMinSeg; m_fStroke = stroke; m_fFadeDelta = 1.0f / fade; m_uMaxPoints = (int) (fade * 60.0f) + 2; m_uNuPoints = 0; m_pPointState = new float[m_uMaxPoints]; m_pPointVertexes = new CCPoint[m_uMaxPoints]; m_pVertices = new CCV3F_C4B_T2F[(m_uMaxPoints + 1) * 2]; // Set blend mode m_tBlendFunc = CCBlendFunc.NonPremultiplied; Texture = texture; Color = color; ScheduleUpdate(); return true; } public void TintWithColor(CCColor3B colors) { Color = colors; for (int i = 0; i < m_uNuPoints * 2; i++) { m_pVertices[i].Colors = new CCColor4B(colors.R, colors.G, colors.B, 255); } } public override void Update(float delta) { if (!m_bStartingPositionInitialized) { return; } delta *= m_fFadeDelta; int newIdx, newIdx2, i, i2; int mov = 0; // Update current points for (i = 0; i < m_uNuPoints; i++) { m_pPointState[i] -= delta; if (m_pPointState[i] <= 0) { mov++; } else { newIdx = i - mov; if (mov > 0) { // Move data m_pPointState[newIdx] = m_pPointState[i]; // Move point m_pPointVertexes[newIdx] = m_pPointVertexes[i]; // Move vertices i2 = i * 2; newIdx2 = newIdx * 2; m_pVertices[newIdx2].Vertices = m_pVertices[i2].Vertices; m_pVertices[newIdx2 + 1].Vertices = m_pVertices[i2 + 1].Vertices; // Move color m_pVertices[newIdx2].Colors = m_pVertices[i2].Colors; m_pVertices[newIdx2 + 1].Colors = m_pVertices[i2 + 1].Colors; } else { newIdx2 = newIdx * 2; } m_pVertices[newIdx2].Colors.A = m_pVertices[newIdx2 + 1].Colors.A = (byte) (m_pPointState[newIdx] * 255.0f); } } m_uNuPoints -= mov; // Append new point bool appendNewPoint = true; if (m_uNuPoints >= m_uMaxPoints) { appendNewPoint = false; } else if (m_uNuPoints > 0) { bool a1 = m_pPointVertexes[m_uNuPoints - 1].DistanceSQ(ref m_tPositionR) < m_fMinSeg; bool a2 = (m_uNuPoints != 1) && (m_pPointVertexes[m_uNuPoints - 2].DistanceSQ(ref m_tPositionR) < (m_fMinSeg * 2.0f)); if (a1 || a2) { appendNewPoint = false; } } if (appendNewPoint) { m_pPointVertexes[m_uNuPoints] = m_tPositionR; m_pPointState[m_uNuPoints] = 1.0f; // Color asignation int offset = m_uNuPoints * 2; m_pVertices[offset].Colors = m_pVertices[offset + 1].Colors = new CCColor4B(_displayedColor.R, _displayedColor.G, _displayedColor.B, 255); // Generate polygon if (m_uNuPoints > 0 && m_bFastMode) { if (m_uNuPoints > 1) { VertexLineToPolygon(m_pPointVertexes, m_fStroke, m_pVertices, m_uNuPoints, 1); } else { VertexLineToPolygon(m_pPointVertexes, m_fStroke, m_pVertices, 0, 2); } } m_uNuPoints++; } if (!m_bFastMode) { VertexLineToPolygon(m_pPointVertexes, m_fStroke, m_pVertices, 0, m_uNuPoints); } // Updated Tex Coords only if they are different than previous step if (m_uNuPoints > 0 && m_uPreviousNuPoints != m_uNuPoints) { float texDelta = 1.0f / m_uNuPoints; for (i = 0; i < m_uNuPoints; i++) { m_pVertices[i * 2].TexCoords = new CCTex2F(0, texDelta * i); m_pVertices[i * 2 + 1].TexCoords = new CCTex2F(1, texDelta * i); } m_uPreviousNuPoints = m_uNuPoints; } } private void VertexLineToPolygon(CCPoint[] points, float stroke, CCV3F_C4B_T2F[] vertices, int offset, int nuPoints) { nuPoints += offset; if (nuPoints <= 1) return; stroke *= 0.5f; int idx; int nuPointsMinus = nuPoints - 1; float rad70 = MathHelper.ToRadians(70); float rad170 = MathHelper.ToRadians(170); for (int i = offset; i < nuPoints; i++) { idx = i * 2; CCPoint p1 = points[i]; CCPoint perpVector; if (i == 0) { perpVector = CCPoint.Perp(CCPoint.Normalize(p1 - points[i + 1])); } else if (i == nuPointsMinus) { perpVector = CCPoint.Perp(CCPoint.Normalize(points[i - 1] - p1)); } else { CCPoint p2 = points[i + 1]; CCPoint p0 = points[i - 1]; CCPoint p2p1 = CCPoint.Normalize(p2 - p1); CCPoint p0p1 = CCPoint.Normalize(p0 - p1); // Calculate angle between vectors var angle = (float) Math.Acos(CCPoint.Dot(p2p1, p0p1)); if (angle < rad70) { perpVector = CCPoint.Perp(CCPoint.Normalize(CCPoint.Midpoint(p2p1, p0p1))); } else if (angle < rad170) { perpVector = CCPoint.Normalize(CCPoint.Midpoint(p2p1, p0p1)); } else { perpVector = CCPoint.Perp(CCPoint.Normalize(p2 - p0)); } } perpVector = perpVector * stroke; vertices[idx].Vertices = new CCVertex3F(p1.X + perpVector.X, p1.Y + perpVector.Y, 0); vertices[idx + 1].Vertices = new CCVertex3F(p1.X - perpVector.X, p1.Y - perpVector.Y, 0); } // Validate vertexes offset = (offset == 0) ? 0 : offset - 1; for (int i = offset; i < nuPointsMinus; i++) { idx = i * 2; int idx1 = idx + 2; CCVertex3F p1 = vertices[idx].Vertices; CCVertex3F p2 = vertices[idx + 1].Vertices; CCVertex3F p3 = vertices[idx1].Vertices; CCVertex3F p4 = vertices[idx1 + 1].Vertices; float s; bool fixVertex = !ccVertexLineIntersect(p1.X, p1.Y, p4.X, p4.Y, p2.X, p2.Y, p3.X, p3.Y, out s); if (!fixVertex) { if (s < 0.0f || s > 1.0f) { fixVertex = true; } } if (fixVertex) { vertices[idx1].Vertices = p4; vertices[idx1 + 1].Vertices = p3; } } } private bool ccVertexLineIntersect(float Ax, float Ay, float Bx, float By, float Cx, float Cy, float Dx, float Dy, out float T) { float distAB, theCos, theSin, newX; T = 0; // FAIL: Line undefined if ((Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy)) return false; // Translate system to make A the origin Bx -= Ax; By -= Ay; Cx -= Ax; Cy -= Ay; Dx -= Ax; Dy -= Ay; // Length of segment AB distAB = (float) Math.Sqrt(Bx * Bx + By * By); // Rotate the system so that point B is on the positive X axis. theCos = Bx / distAB; theSin = By / distAB; newX = Cx * theCos + Cy * theSin; Cy = Cy * theCos - Cx * theSin; Cx = newX; newX = Dx * theCos + Dy * theSin; Dy = Dy * theCos - Dx * theSin; Dx = newX; // FAIL: Lines are parallel. if (Cy == Dy) return false; // Discover the relative position of the intersection in the line AB T = (Dx + (Cx - Dx) * Dy / (Dy - Cy)) / distAB; // Success. return true; } private void Reset() { m_uNuPoints = 0; } public override void Draw() { CCDrawManager.BlendFunc(m_tBlendFunc); CCDrawManager.BindTexture(m_pTexture); CCDrawManager.VertexColorEnabled = true; CCDrawManager.DrawPrimitives(PrimitiveType.TriangleStrip, m_pVertices, 0, m_uNuPoints * 2 - 2); } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Data; using System.Windows.Input; namespace System.Windows.Controls { /// <summary> /// A base class for specifying column definitions for certain standard /// types that do not allow arbitrary templates. /// </summary> public abstract class DataGridBoundColumn : DataGridColumn { #region Constructors static DataGridBoundColumn() { SortMemberPathProperty.OverrideMetadata(typeof(DataGridBoundColumn), new FrameworkPropertyMetadata(null, OnCoerceSortMemberPath)); } #endregion #region Binding private static object OnCoerceSortMemberPath(DependencyObject d, object baseValue) { var column = (DataGridBoundColumn)d; var sortMemberPath = (string)baseValue; if (string.IsNullOrEmpty(sortMemberPath)) { var bindingSortMemberPath = DataGridHelper.GetPathFromBinding(column.Binding as Binding); if (!string.IsNullOrEmpty(bindingSortMemberPath)) { sortMemberPath = bindingSortMemberPath; } } return sortMemberPath; } /// <summary> /// The binding that will be applied to the generated element. /// </summary> /// <remarks> /// This isn't a DP because if it were getting the value would evaluate the binding. /// </remarks> public virtual BindingBase Binding { get { return _binding; } set { if (_binding != value) { BindingBase oldBinding = _binding; _binding = value; CoerceValue(IsReadOnlyProperty); CoerceValue(SortMemberPathProperty); OnBindingChanged(oldBinding, _binding); } } } protected override bool OnCoerceIsReadOnly(bool baseValue) { if (DataGridHelper.IsOneWay(_binding)) { return true; } // only call the base if we dont want to force IsReadOnly true return base.OnCoerceIsReadOnly(baseValue); } /// <summary> /// Called when Binding changes. /// </summary> /// <remarks> /// Default implementation notifies the DataGrid and its subtree about the change. /// </remarks> /// <param name="oldBinding">The old binding.</param> /// <param name="newBinding">The new binding.</param> protected virtual void OnBindingChanged(BindingBase oldBinding, BindingBase newBinding) { NotifyPropertyChanged("Binding"); } /// <summary> /// Assigns the Binding to the desired property on the target object. /// </summary> internal void ApplyBinding(DependencyObject target, DependencyProperty property) { BindingBase binding = Binding; if (binding != null) { BindingOperations.SetBinding(target, property, binding); } else { BindingOperations.ClearBinding(target, property); } } #endregion #region Styling /// <summary> /// A style that is applied to the generated element when not editing. /// The TargetType of the style depends on the derived column class. /// </summary> public Style ElementStyle { get { return (Style)GetValue(ElementStyleProperty); } set { SetValue(ElementStyleProperty, value); } } /// <summary> /// The DependencyProperty for the ElementStyle property. /// </summary> public static readonly DependencyProperty ElementStyleProperty = DependencyProperty.Register( "ElementStyle", typeof(Style), typeof(DataGridBoundColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// A style that is applied to the generated element when editing. /// The TargetType of the style depends on the derived column class. /// </summary> public Style EditingElementStyle { get { return (Style)GetValue(EditingElementStyleProperty); } set { SetValue(EditingElementStyleProperty, value); } } /// <summary> /// The DependencyProperty for the EditingElementStyle property. /// </summary> public static readonly DependencyProperty EditingElementStyleProperty = DependencyProperty.Register( "EditingElementStyle", typeof(Style), typeof(DataGridBoundColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// Assigns the ElementStyle to the desired property on the given element. /// </summary> internal void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkElement element) { Style style = PickStyle(isEditing, defaultToElementStyle); if (style != null) { element.Style = style; } } private Style PickStyle(bool isEditing, bool defaultToElementStyle) { Style style = isEditing ? EditingElementStyle : ElementStyle; if (isEditing && defaultToElementStyle && (style == null)) { style = ElementStyle; } return style; } #endregion #region Clipboard Copy/Paste /// <summary> /// If base ClipboardContentBinding is not set we use Binding. /// </summary> public override BindingBase ClipboardContentBinding { get { return base.ClipboardContentBinding ?? Binding; } set { base.ClipboardContentBinding = value; } } #endregion #region Property Changed Handler /// <summary> /// Override which rebuilds the cell's visual tree for Binding change /// </summary> /// <param name="element"></param> /// <param name="propertyName"></param> protected internal override void RefreshCellContent(FrameworkElement element, string propertyName) { DataGridCell cell = element as DataGridCell; if (cell != null) { bool isCellEditing = cell.IsEditing; if ((string.Compare(propertyName, "Binding", StringComparison.Ordinal) == 0) || (string.Compare(propertyName, "ElementStyle", StringComparison.Ordinal) == 0 && !isCellEditing) || (string.Compare(propertyName, "EditingElementStyle", StringComparison.Ordinal) == 0 && isCellEditing)) { cell.BuildVisualTree(); return; } } base.RefreshCellContent(element, propertyName); } #endregion #region Data private BindingBase _binding; #endregion } }
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 entdemo.website.Areas.HelpPage.ModelDescriptions; using entdemo.website.Areas.HelpPage.Models; namespace entdemo.website.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 (C) 2011-2014 Kazunori Sakamoto // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.IO; using System.Linq; using Code2Xml.Core.Generators; using Code2Xml.Core.SyntaxTree; using NUnit.Framework; using ParserTests; namespace Code2Xml.Core.Tests.Generators { public abstract class SyntaxTreeGeneratorTest<TGenerator, TNode, TToken> where TGenerator : SyntaxTreeGenerator<TNode, TToken> where TNode : SyntaxTreeNode<TNode, TToken> where TToken : SyntaxTreeToken<TToken> { private long _codeLength; private long _timeToParseTree; private long _timeToGenerateTree; private long _timeToGenerateCode; private TGenerator _generator; protected TGenerator Generator { get { return _generator ?? (_generator = CreateGenerator()); } } protected abstract TGenerator CreateGenerator(); protected void StartMeasuringTimes() { _codeLength = 0; _timeToGenerateTree = 0; _timeToGenerateCode = 0; } protected void ShowTimes(string path, string url = null) { var name = Path.GetFileName(path); var total = _timeToGenerateTree + _timeToGenerateCode; Console.WriteLine( "Tree: " + _timeToGenerateTree + ", Code: " + _timeToGenerateCode + ", Total: " + total); var rootPath = Fixture.GetRootPath("Code2Xml.sln"); var info = new FileInfo(Path.Combine(rootPath, "Performance.md.latest")); var exists = info.Exists; using (var fs = info.Open(FileMode.Append, FileAccess.Write)) { using (var stream = new StreamWriter(fs)) { if (_timeToParseTree == 0) { _timeToParseTree = 1; } if (_timeToGenerateTree == 0) { _timeToGenerateTree = 1; } if (_timeToGenerateCode == 0) { _timeToGenerateCode = 1; } if (total == 0) { total = 1; } if (!exists) { stream.WriteLine("| Project | Size | Parse | Tree | Code | Total |"); stream.WriteLine("| --- | ---: | ---: | ---: | ---: | ---: |"); } stream.Write("| "); if (string.IsNullOrEmpty(url)) { stream.Write(name); } else { stream.Write("[" + name + "](" + url + ")"); } stream.Write(" | "); stream.Write(_codeLength.ToString("N0")); stream.Write(" | "); stream.Write(_timeToParseTree.ToString("N0")); stream.Write(" ("); stream.Write((_codeLength / _timeToParseTree).ToString("N0")); stream.Write(")"); stream.Write(" | "); stream.Write(_timeToGenerateTree.ToString("N0")); stream.Write(" ("); stream.Write((_codeLength / _timeToGenerateTree).ToString("N0")); stream.Write(")"); stream.Write(" | "); stream.Write(_timeToGenerateCode.ToString("N0")); stream.Write(" ("); stream.Write((_codeLength / _timeToGenerateCode).ToString("N0")); stream.Write(")"); stream.Write(" | "); stream.Write(total.ToString("N0")); stream.Write(" ("); stream.Write((_codeLength / total).ToString("N0")); stream.Write(")"); stream.WriteLine(" |"); } } } protected void VerifyParsing(string code) { var time = Environment.TickCount; var root = Generator.GenerateTreeFromCodeText(code); _timeToGenerateTree += (Environment.TickCount - time); Console.WriteLine(root.ToXml()); } protected void VerifyInterConverting(string code) { var time = Environment.TickCount; try { Generator.TryParseFromCodeText(code); } catch {} var time2 = Environment.TickCount; var r1 = Generator.GenerateTreeFromCodeText(code, true); var time3 = Environment.TickCount; var c1 = Generator.GenerateCodeFromTree(r1); _timeToGenerateCode += (Environment.TickCount - time3); _timeToGenerateTree += (time3 - time2); _timeToParseTree += (time2 - time); _codeLength += code.Length; var r2 = Generator.GenerateTreeFromCodeText(c1, true); var c2 = Generator.GenerateCodeFromTree(r2); var r3 = Generator.GenerateTreeFromCodeText(c2, true); var c3 = Generator.GenerateCodeFromTree(r3); Assert.That(r2, Is.EqualTo(r3)); Assert.That(c2, Is.EqualTo(c3)); } protected void VerifyRestoringCodeAndInspect(string code, bool write = true) { try { VerifyRestoringCode(code, write); } catch (Exception e) { Inspect(code); throw e; } } protected void MeasurePerformance( string url, string commitPointer, Action<string> parse, params string[] patterns) { var path = Fixture.GetGitRepositoryPath(url); Git.CloneAndCheckoutAndReset(path, url, commitPointer); StartMeasuringTimes(); var codes = patterns.SelectMany( pattern => Directory.GetFiles(path, pattern, SearchOption.AllDirectories)) .Select(File.ReadAllText) .ToList(); foreach (var code in codes) { _codeLength += code.Length; } codes = codes.Select(code => code.Replace("\r\n", "\n")).ToList(); if (parse == null) { foreach (var code in codes) { Generator.TryParseFromCodeText(code); } } else { foreach (var code in codes) { parse(code); } } var time = Environment.TickCount; var count = 20; for (int i = 0; i < count; i++) { if (parse == null) { foreach (var code in codes) { Generator.TryParseFromCodeText(code); } } else { foreach (var code in codes) { parse(code); } } } var time2 = Environment.TickCount; var dummy = 0; for (int i = 0; i < count; i++) { foreach (var code in codes) { var tree = Generator.GenerateTreeFromCodeText(code, true); dummy += tree.Name.Length; } } var time3 = Environment.TickCount; var trees = codes.Select(code => Generator.GenerateTreeFromCodeText(code, true)) .ToList(); var time4 = Environment.TickCount; for (int i = 0; i < count; i++) { foreach (var tree in trees) { var code = Generator.GenerateCodeFromTree(tree); dummy += code.Length; } } var time5 = Environment.TickCount; _timeToParseTree += (time2 - time) / count; _timeToGenerateTree += (time3 - time2) / count; _timeToGenerateCode += (time5 - time4) / count; ShowTimes(path, url); Console.WriteLine("Dummy: " + dummy); } protected void VerifyRestoringCode(string code, bool write = true) { _codeLength += code.Length; code = code.Replace("\r\n", "\n"); var time = Environment.TickCount; try { Generator.TryParseFromCodeText(code); } catch {} var time2 = Environment.TickCount; var tree = Generator.GenerateTreeFromCodeText(code, true); var time3 = Environment.TickCount; var code2 = Generator.GenerateCodeFromTree(tree); _timeToGenerateCode += (Environment.TickCount - time3); _timeToGenerateTree += (time3 - time2); _timeToParseTree += (time2 - time); Assert.That(code2, Is.EqualTo(code)); if (write) { Console.WriteLine(tree.ToXml()); } VerifyLocation(code, tree); } protected abstract void VerifyLocation(string code, TNode root); protected void VerifyRestoringFile(string langName, string fileName) { var path = Fixture.GetInputCodePath(langName, fileName); VerifyRestoringCode(File.ReadAllText(path)); } protected void VerifyRestoringProjectDirectory( string langName, string directoryName, params string[] patterns) { PrivateVerifyRestoringProjectDirectory( langName, directoryName, File.ReadAllText, patterns); } protected void VerifyRestoringProjectDirectory( string langName, string directoryName, Func<string, string> readFileFunc, params string[] patterns) { var path = Fixture.GetInputProjectPath(langName, directoryName); PrivateVerifyRestoringProjectDirectory(path, null, readFileFunc, patterns); } private void PrivateVerifyRestoringProjectDirectory( string path, string url, Func<string, string> readFileFunc, params string[] patterns) { StartMeasuringTimes(); var filePaths = patterns.SelectMany( pattern => Directory.GetFiles(path, pattern, SearchOption.AllDirectories)) .ToList(); foreach (var filePath in filePaths) { Console.Write("."); try { VerifyRestoringCode(readFileFunc(filePath), false); } catch (Exception e) { Console.WriteLine(); Console.WriteLine(filePath); throw new ParseException(e); } } Console.WriteLine(); ShowTimes(path, url); } protected void VerifyRestoringGitRepo( string url, string commitPointer, params string[] patterns) { VerifyRestoringGitRepo(url, commitPointer, File.ReadAllText, patterns); } protected void VerifyRestoringGitRepo( string url, string commitPointer, Func<string, string> readFileFunc, params string[] patterns) { var path = Fixture.GetGitRepositoryPath(url); Git.CloneAndCheckoutAndReset(path, url, commitPointer); PrivateVerifyRestoringProjectDirectory(path, url, readFileFunc, patterns); } protected void Inspect(string code) { code = code.Replace("\r\n", "\n"); var lines = code.Split('\n'); var length = code.Length; for (int i = lines.Length - 1; i >= 0; i--) { length -= lines[i].Length; try { var code2 = code.Substring(0, length); var tree = Generator.GenerateTreeFromCodeText(code2); var code3 = Generator.GenerateCodeFromTree(tree); if (code2 == code3) { Console.WriteLine(); Console.WriteLine("Max parsable line: " + i); return; } } catch {} } } } }
using System; using System.Threading; using System.Collections; using System.Collections.Generic; using Server; using Server.Items; using Server.Mobiles; using Server.Network; using Server.Factions; using Server.Accounting; using Server.Engines.ConPVP; namespace Server.Engines.Reports { public class Reports { public static bool Enabled = true; public static void Initialize() { if ( !Enabled ) return; m_StatsHistory = new SnapshotHistory(); m_StatsHistory.Load(); m_StaffHistory = new StaffHistory(); m_StaffHistory.Load(); DateTime now = DateTime.Now; DateTime date = now.Date; TimeSpan timeOfDay = now.TimeOfDay; m_GenerateTime = date + TimeSpan.FromHours( Math.Ceiling( timeOfDay.TotalHours ) ); Timer.DelayCall( TimeSpan.FromMinutes( 0.5 ), TimeSpan.FromMinutes( 0.5 ), new TimerCallback( CheckRegenerate ) ); } private static DateTime m_GenerateTime; public static void CheckRegenerate() { if ( DateTime.Now < m_GenerateTime ) return; Generate(); m_GenerateTime += TimeSpan.FromHours( 1.0 ); } private static SnapshotHistory m_StatsHistory; private static StaffHistory m_StaffHistory; public static StaffHistory StaffHistory{ get{ return m_StaffHistory; } } public static void Generate() { Snapshot ss = new Snapshot(); ss.TimeStamp = DateTime.Now; FillSnapshot( ss ); m_StatsHistory.Snapshots.Add( ss ); m_StaffHistory.QueueStats.Add( new QueueStatus( Engines.Help.PageQueue.List.Count ) ); ThreadPool.QueueUserWorkItem( new WaitCallback( UpdateOutput ), ss ); } private static void UpdateOutput( object state ) { m_StatsHistory.Save(); m_StaffHistory.Save(); HtmlRenderer renderer = new HtmlRenderer( "stats", (Snapshot) state, m_StatsHistory ); renderer.Render(); renderer.Upload(); renderer = new HtmlRenderer( "staff", m_StaffHistory ); renderer.Render(); renderer.Upload(); } public static void FillSnapshot( Snapshot ss ) { ss.Children.Add(CompileGeneralStats()); ss.Children.Add(CompilePCByDL()); ss.Children.Add(CompileTop15()); ss.Children.Add(CompileDislikedArenas()); ss.Children.Add(CompileStatChart()); PersistableObject[] obs = CompileSkillReports(); for ( int i = 0; i < obs.Length; ++i ) ss.Children.Add( obs[i] ); obs = CompileFactionReports(); for ( int i = 0; i < obs.Length; ++i ) ss.Children.Add( obs[i] ); } public static Report CompileGeneralStats() { Report report = new Report( "General Stats", "200" ); report.Columns.Add( "50%", "left" ); report.Columns.Add( "50%", "left" ); int npcs = 0, players = 0; foreach ( Mobile mob in World.Mobiles.Values ) { if ( mob.Player ) ++players; else ++npcs; } report.Items.Add( "NPCs", npcs, "N0" ); report.Items.Add( "Players", players, "N0" ); report.Items.Add( "Clients", NetState.Instances.Count, "N0" ); report.Items.Add( "Accounts", Accounts.Count, "N0" ); report.Items.Add( "Items", World.Items.Count, "N0" ); return report; } private static Chart CompilePCByDL() { BarGraph chart = new BarGraph("Player Count By Dueling Level", "graphs_pc_by_dl", 5, "Dueling Level", "Players", BarGraphRenderMode.Bars); int lastLevel = -1; ChartItem lastItem = null; Ladder ladder = Ladder.Instance; if (ladder != null) { ArrayList entries = ladder.ToArrayList(); for (int i = entries.Count - 1; i >= 0; --i) { LadderEntry entry = (LadderEntry)entries[i]; int level = Ladder.GetLevel(entry.Experience); if (lastItem == null || level != lastLevel) { chart.Items.Add(lastItem = new ChartItem(level.ToString(), 1)); lastLevel = level; } else { lastItem.Value++; } } } return chart; } private static Report CompileTop15() { Report report = new Report("Top 15 Duelists", "80%"); report.Columns.Add("6%", "center", "Rank"); report.Columns.Add("6%", "center", "Level"); report.Columns.Add("6%", "center", "Guild"); report.Columns.Add("70%", "left", "Name"); report.Columns.Add("6%", "center", "Wins"); report.Columns.Add("6%", "center", "Losses"); Ladder ladder = Ladder.Instance; if (ladder != null) { ArrayList entries = ladder.ToArrayList(); for (int i = 0; i < entries.Count && i < 15; ++i) { LadderEntry entry = (LadderEntry)entries[i]; int level = Ladder.GetLevel(entry.Experience); string guild = ""; if (entry.Mobile.Guild != null) guild = entry.Mobile.Guild.Abbreviation; ReportItem item = new ReportItem(); item.Values.Add(LadderGump.Rank(entry.Index + 1)); item.Values.Add(level.ToString(), "N0"); item.Values.Add(guild); item.Values.Add(entry.Mobile.Name); item.Values.Add(entry.Wins.ToString(), "N0"); item.Values.Add(entry.Losses.ToString(), "N0"); report.Items.Add(item); } } return report; } private static Chart CompileDislikedArenas() { PieChart chart = new PieChart("Most Disliked Arenas", "graphs_arenas_disliked", false); Preferences prefs = Preferences.Instance; if (prefs != null) { List<Arena> arenas = Arena.Arenas; for (int i = 0; i < arenas.Count; ++i) { Arena arena = arenas[i]; string name = arena.Name; if (name != null) chart.Items.Add(name, 0); } ArrayList entries = prefs.Entries; for (int i = 0; i < entries.Count; ++i) { PreferencesEntry entry = (PreferencesEntry)entries[i]; ArrayList list = entry.Disliked; for (int j = 0; j < list.Count; ++j) { string disliked = (string)list[j]; for (int k = 0; k < chart.Items.Count; ++k) { ChartItem item = chart.Items[k]; if (item.Name == disliked) { ++item.Value; break; } } } } } return chart; } public static Chart CompileStatChart() { PieChart chart = new PieChart( "Stat Distribution", "graphs_strdexint_distrib", true ); ChartItem strItem = new ChartItem( "Strength", 0 ); ChartItem dexItem = new ChartItem( "Dexterity", 0 ); ChartItem intItem = new ChartItem( "Intelligence", 0 ); foreach ( Mobile mob in World.Mobiles.Values ) { if ( mob.RawStatTotal == mob.StatCap && mob is PlayerMobile ) { strItem.Value += mob.RawStr; dexItem.Value += mob.RawDex; intItem.Value += mob.RawInt; } } chart.Items.Add( strItem ); chart.Items.Add( dexItem ); chart.Items.Add( intItem ); return chart; } public class SkillDistribution : IComparable { public SkillInfo m_Skill; public int m_NumberOfGMs; public SkillDistribution( SkillInfo skill ) { m_Skill = skill; } public int CompareTo( object obj ) { return ( ((SkillDistribution)obj).m_NumberOfGMs - m_NumberOfGMs ); } } public static SkillDistribution[] GetSkillDistribution() { int skip = ( Core.ML ? 0 : Core.SE ? 1 : Core.AOS ? 3 : 6 ); SkillDistribution[] distribs = new SkillDistribution[SkillInfo.Table.Length - skip]; for ( int i = 0; i < distribs.Length; ++i ) distribs[i] = new SkillDistribution( SkillInfo.Table[i] ); foreach ( Mobile mob in World.Mobiles.Values ) { if ( mob.SkillsTotal >= 1500 && mob.SkillsTotal <= 7200 && mob is PlayerMobile ) { Skills skills = mob.Skills; for ( int i = 0; i < skills.Length - skip; ++i ) { Skill skill = skills[i]; if ( skill.BaseFixedPoint >= 1000 ) distribs[i].m_NumberOfGMs++; } } } return distribs; } public static PersistableObject[] CompileSkillReports() { SkillDistribution[] distribs = GetSkillDistribution(); Array.Sort( distribs ); return new PersistableObject[]{ CompileSkillChart( distribs ), CompileSkillReport( distribs ) }; } public static Report CompileSkillReport( SkillDistribution[] distribs ) { Report report = new Report( "Skill Report", "300" ); report.Columns.Add( "70%", "left", "Name" ); report.Columns.Add( "30%", "center", "GMs" ); for ( int i = 0; i < distribs.Length; ++i ) report.Items.Add( distribs[i].m_Skill.Name, distribs[i].m_NumberOfGMs, "N0" ); return report; } public static Chart CompileSkillChart( SkillDistribution[] distribs ) { PieChart chart = new PieChart( "GM Skill Distribution", "graphs_skill_distrib", true ); for ( int i = 0; i < 12; ++i ) chart.Items.Add( distribs[i].m_Skill.Name, distribs[i].m_NumberOfGMs ); int rem = 0; for ( int i = 12; i < distribs.Length; ++i ) rem += distribs[i].m_NumberOfGMs; chart.Items.Add( "Other", rem ); return chart; } public static PersistableObject[] CompileFactionReports() { return new PersistableObject[]{ CompileFactionMembershipChart(), CompileFactionReport(), CompileFactionTownReport(), CompileSigilReport(), CompileFactionLeaderboard() }; } public static Chart CompileFactionMembershipChart() { PieChart chart = new PieChart( "Faction Membership", "graphs_faction_membership", true ); List<Faction> factions = Faction.Factions; for ( int i = 0; i < factions.Count; ++i ) chart.Items.Add( factions[i].Definition.FriendlyName, factions[i].Members.Count ); return chart; } public static Report CompileFactionLeaderboard() { Report report = new Report( "Faction Leaderboard", "60%" ); report.Columns.Add( "28%", "center", "Name" ); report.Columns.Add( "28%", "center", "Faction" ); report.Columns.Add( "28%", "center", "Office" ); report.Columns.Add( "16%", "center", "Kill Points" ); ArrayList list = new ArrayList(); List<Faction> factions = Faction.Factions; for ( int i = 0; i < factions.Count; ++i ) { Faction faction = factions[i]; list.AddRange( faction.Members ); } list.Sort(); list.Reverse(); for ( int i = 0; i < list.Count && i < 15; ++i ) { PlayerState pl = (PlayerState)list[i]; string office; if ( pl.Faction.Commander == pl.Mobile ) office = "Commanding Lord"; else if ( pl.Finance != null ) office = String.Format( "{0} Finance Minister", pl.Finance.Definition.FriendlyName ); else if ( pl.Sheriff != null ) office = String.Format( "{0} Sheriff", pl.Sheriff.Definition.FriendlyName ); else office = ""; ReportItem item = new ReportItem(); item.Values.Add( pl.Mobile.Name ); item.Values.Add( pl.Faction.Definition.FriendlyName ); item.Values.Add( office ); item.Values.Add( pl.KillPoints.ToString(), "N0" ); report.Items.Add( item ); } return report; } public static Report CompileFactionReport() { Report report = new Report( "Faction Statistics", "80%" ); report.Columns.Add( "20%", "center", "Name" ); report.Columns.Add( "20%", "center", "Commander" ); report.Columns.Add( "15%", "center", "Members" ); report.Columns.Add( "15%", "center", "Merchants" ); report.Columns.Add( "15%", "center", "Kill Points" ); report.Columns.Add( "15%", "center", "Silver" ); List<Faction> factions = Faction.Factions; for ( int i = 0; i < factions.Count; ++i ) { Faction faction = factions[i]; List<PlayerState> members = faction.Members; int totalKillPoints = 0; int totalMerchants = 0; for ( int j = 0; j < members.Count; ++j ) { totalKillPoints += members[j].KillPoints; if ( members[j].MerchantTitle != MerchantTitle.None ) ++totalMerchants; } ReportItem item = new ReportItem(); item.Values.Add( faction.Definition.FriendlyName ); item.Values.Add( faction.Commander == null ? "" : faction.Commander.Name ); item.Values.Add( faction.Members.Count.ToString(), "N0" ); item.Values.Add( totalMerchants.ToString(), "N0" ); item.Values.Add( totalKillPoints.ToString(), "N0" ); item.Values.Add( faction.Silver.ToString(), "N0" ); report.Items.Add( item ); } return report; } public static Report CompileSigilReport() { Report report = new Report( "Faction Town Sigils", "50%" ); report.Columns.Add( "35%", "center", "Town" ); report.Columns.Add( "35%", "center", "Controller" ); report.Columns.Add( "30%", "center", "Capturable" ); List<Sigil> sigils = Sigil.Sigils; for ( int i = 0; i < sigils.Count; ++i ) { Sigil sigil = sigils[i]; string controller = "Unknown"; Mobile mob = sigil.RootParent as Mobile; if ( mob != null ) { Faction faction = Faction.Find( mob ); if ( faction != null ) controller = faction.Definition.FriendlyName; } else if ( sigil.LastMonolith != null && sigil.LastMonolith.Faction != null ) { controller = sigil.LastMonolith.Faction.Definition.FriendlyName; } ReportItem item = new ReportItem(); item.Values.Add( sigil.Town == null ? "" : sigil.Town.Definition.FriendlyName ); item.Values.Add( controller ); item.Values.Add( sigil.IsPurifying ? "No" : "Yes" ); report.Items.Add( item ); } return report; } public static Report CompileFactionTownReport() { Report report = new Report( "Faction Towns", "80%" ); report.Columns.Add( "20%", "center", "Name" ); report.Columns.Add( "20%", "center", "Owner" ); report.Columns.Add( "17%", "center", "Sheriff" ); report.Columns.Add( "17%", "center", "Finance Minister" ); report.Columns.Add( "13%", "center", "Silver" ); report.Columns.Add( "13%", "center", "Prices" ); List<Town> towns = Town.Towns; for ( int i = 0; i < towns.Count; ++i ) { Town town = towns[i]; string prices = "Normal"; if ( town.Tax < 0 ) prices = town.Tax.ToString() + "%"; else if ( town.Tax > 0 ) prices = "+" + town.Tax.ToString() + "%"; ReportItem item = new ReportItem(); item.Values.Add( town.Definition.FriendlyName ); item.Values.Add( town.Owner == null ? "Neutral" : town.Owner.Definition.FriendlyName ); item.Values.Add( town.Sheriff == null ? "" : town.Sheriff.Name ); item.Values.Add( town.Finance == null ? "" : town.Finance.Name ); item.Values.Add( town.Silver.ToString(), "N0" ); item.Values.Add( prices ); report.Items.Add( item ); } return report; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using NPOI.HWPF.Model; using NPOI.Util; namespace NPOI.HWPF.UserModel { /** * TODO: document me * * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) */ public class FieldImpl : Field { private PlexOfField endPlex; private PlexOfField separatorPlex; private PlexOfField startPlex; public FieldImpl(PlexOfField startPlex, PlexOfField separatorPlex, PlexOfField endPlex) { if (startPlex == null) throw new ArgumentException("startPlex == null"); if (endPlex == null) throw new ArgumentException("endPlex == null"); if (startPlex.Fld.GetBoundaryType() != FieldDescriptor.FIELD_BEGIN_MARK) throw new ArgumentException("startPlex (" + startPlex + ") is not type of FIELD_BEGIN"); if (separatorPlex != null && separatorPlex.Fld.GetBoundaryType() != FieldDescriptor.FIELD_SEPARATOR_MARK) throw new ArgumentException("separatorPlex" + separatorPlex + ") is not type of FIELD_SEPARATOR"); if (endPlex.Fld.GetBoundaryType() != FieldDescriptor.FIELD_END_MARK) throw new ArgumentException("endPlex (" + endPlex + ") is not type of FIELD_END"); this.startPlex = startPlex; this.separatorPlex = separatorPlex; this.endPlex = endPlex; } public class FieldSubRange : Range { string className; public FieldSubRange(int start, int end, Range parent, string className) : base(start, end, parent) { this.className = className; } public override String ToString() { return this.className + " (" + base.ToString() + ")"; } } public Range FirstSubrange(Range parent) { if (HasSeparator()) { if (GetMarkStartOffset() + 1 == GetMarkSeparatorOffset()) return null; return new FieldSubRange(GetMarkStartOffset() + 1, GetMarkSeparatorOffset(), parent, "FieldSubrange1"); } if (GetMarkStartOffset() + 1 == GetMarkEndOffset()) return null; return new FieldSubRange(GetMarkStartOffset() + 1, GetMarkEndOffset(), parent, "FieldSubrange1"); } /** * @return character position of first character after field (i.e. * {@link #getMarkEndOffset()} + 1) */ public int GetFieldEndOffset() { /* * sometimes plex looks like [100, 2000), where 100 is the position of * field-end character, and 2000 - some other char position, far away * from field (not inside). So taking into account only start --sergey */ return endPlex.FcStart + 1; } /** * @return character position of first character in field (i.e. * {@link #getFieldStartOffset()}) */ public int GetFieldStartOffset() { return startPlex.FcStart; } public CharacterRun GetMarkEndCharacterRun(Range parent) { return new Range(GetMarkEndOffset(), GetMarkEndOffset() + 1, parent) .GetCharacterRun(0); } /** * @return character position of end field mark */ public int GetMarkEndOffset() { return endPlex.FcStart; } public CharacterRun GetMarkSeparatorCharacterRun(Range parent) { if (!HasSeparator()) return null; return new Range(GetMarkSeparatorOffset(), GetMarkSeparatorOffset() + 1, parent).GetCharacterRun(0); } /** * @return character position of separator field mark (if present, * {@link NullPointerException} otherwise) */ public int GetMarkSeparatorOffset() { return separatorPlex.FcStart; } public CharacterRun GetMarkStartCharacterRun(Range parent) { return new Range(GetMarkStartOffset(), GetMarkStartOffset() + 1, parent).GetCharacterRun(0); } /** * @return character position of start field mark */ public int GetMarkStartOffset() { return startPlex.FcStart; } public int Type { get { return startPlex.Fld.GetFieldType(); } } public bool HasSeparator() { return separatorPlex != null; } public bool IsHasSep() { return endPlex.Fld.IsFHasSep(); } public bool IsLocked() { return endPlex.Fld.IsFLocked(); } public bool IsNested() { return endPlex.Fld.IsFNested(); } public bool IsPrivateResult() { return endPlex.Fld.IsFPrivateResult(); } public bool IsResultDirty() { return endPlex.Fld.IsFResultDirty(); } public bool IsResultEdited() { return endPlex.Fld.IsFResultEdited(); } public bool IsZombieEmbed() { return endPlex.Fld.IsFZombieEmbed(); } public Range SecondSubrange(Range parent) { if (!HasSeparator() || GetMarkSeparatorOffset() + 1 == GetMarkEndOffset()) return null; return new FieldSubRange(GetMarkSeparatorOffset() + 1, GetMarkEndOffset(), parent, "FieldSubrange2"); } public override String ToString() { return "Field [" + GetFieldStartOffset() + "; " + GetFieldEndOffset() + "] (type: 0x" + StringUtil.ToHexString(Type) + " = " + GetType() + " )"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using witsmllib.util; namespace witsmllib { /// <summary> /// Class for controlling the WITSML queries. /// The WitsmlQuery instance is used to select which elements that should be /// included in a server query and to set query constraints. /// </summary> public sealed class WitsmlQuery { /** Elements to explicitly include. */ private List<String> includedElements = new List<String>(); /** Elements to explicitly exclude. */ private List<String> excludedElements = new List<String>(); /** Constraints to apply. Each entry is element of two: element,value. */ private List<ElementConstraint> elementConstraints = new List<ElementConstraint>(); /** Constraints to apply. Each entry is element of two: element,value. */ private List<AttributeConstraint> attributeConstraints = new List<AttributeConstraint>(); /// <summary> /// Create a default WITSML query containing all the elements /// specified by the given WITSML type and without any constraints. /// </summary> public WitsmlQuery() { // Nothing } /// <summary> /// Explicitly include the specified element from the query. As soon /// elements are explicitly included, no elements are included be default. /// </summary> /// <param name="elementName">Name of element to include. Non-null.</param> public void includeElement(String elementName) { if (elementName == null) throw new ArgumentException("elementName cannot be null"); includedElements.Add(elementName); } /// <summary> /// Explicitly exclude the specified element from the query. /// </summary> /// <param name="elementName">Name of element to exclude. Non-null.</param> public void excludeElement(String elementName) { if (elementName == null) throw new ArgumentException("elementName cannot be null"); excludedElements.Add(elementName); } /// <summary> /// Add the specified element constraint to this query. /// /// The same element may be constrained more than once, resulting in a /// deep duplication of the element with the new constraint applied. /// </summary> /// <param name="elementName">Name of element to constrain. Non-null.</param> /// <param name="value">The element constraint. May be null to indicate empty.</param> public void addElementConstraint(String elementName, Object value) { if (elementName == null) throw new ArgumentException("elementName cannot be null"); elementConstraints.Add(new ElementConstraint(elementName, value)); } /// <summary> /// Add the specified attribute constraint to this query. /// </summary> /// <param name="elementName">Name of element to constrain. Non-null.</param> /// <param name="attributeName">Name of attribute of element to constrain. Non-null.</param> /// <param name="value">The attribute constraint. May be null it indicate empty.</param> public void addAttributeConstraint(String elementName, String attributeName, Object value) { if (elementName == null) throw new ArgumentException("elementName cannot be null"); if (attributeName == null) throw new ArgumentException("attributeName cannot be null"); attributeConstraints.Add(new AttributeConstraint(elementName, attributeName, value)); } /// <summary> /// Find element with the specified name. /// </summary> /// <param name="root">Root element of where to start the search. Non-null.</param> /// <param name="name">Name of element to find. Non-null.</param> /// <returns></returns> private static XElement findElement(XElement root, String name) { if (root == null) throw new ArgumentException("root cannot be null"); if (name == null) throw new ArgumentException("name cannot be null"); XElement elmt = root.Descendants().Where(x => x.Name.LocalName == name).FirstOrDefault(); //foreach (XElement element in root.Descendants()) //{ // if (element.Name.LocalName.Equals(name)) // return element; //} return elmt; } /// <summary> /// Check if a certain element should be included or not. /// </summary> /// <param name="element">XElement to check. Non-null.</param> /// <returns>True if the element should be included, false otherwise.</returns> private bool shouldInclude(XElement element) { if (element == null) throw new ArgumentException("element cannot be null"); // XElement is included by default if none is explicitly included bool isDefaultIncluded = includedElements.Count == 0;// .IsEmpty(); // XElement is included if itself or any parent is explicitly included bool isExplicitlyIncluded = false; XElement e = element; while (e != null) { if (includedElements.Contains(e.Name.LocalName)) //.getName())) isExplicitlyIncluded = true; e = e.Parent; //.getParentElement(); } // XElement is excluded if itself or any parent is explicitly excluded bool isExplicitlyExcluded = false; e = element; while (e != null) { if (excludedElements.Contains(e.Name.LocalName)) //.getName())) isExplicitlyExcluded = true; e = e.Parent; //.getParentElement(); } bool isIncluded = !isExplicitlyExcluded && (isExplicitlyIncluded || isDefaultIncluded); return isIncluded; } /// <summary> /// Apply inclusions as specified in includedElements and /// excludedElements to the document rooted at the specified root /// element. /// </summary> /// <param name="root">Root element of tree to apply inclusions/exclusions to. Non-null.</param> private void applyInclusions(XElement root) { if (root == null) throw new ArgumentException("root cannot be null"); // Make a set of all elements HashSet<XElement> elementsToDelete = new HashSet<XElement>(); foreach (var i in root.Descendants()) //.getDescendants(new ElementFilter()); i.hasNext(); ) elementsToDelete.Add((XElement)i); //.next()); // Loop all elements, and possibly remove from the delete set //for (var i = root.getDescendants(new ElementFilter()); i.hasNext(); ) foreach (XElement element in root.Descendants()) { // If element should remain, include it and all its parents if (shouldInclude(element)) { XElement e = element; while (e != null) { elementsToDelete.Remove(e); //.remove(e); e = e.Parent; //.getParentElement(); } } } // Remove unwanted elements foreach (XElement element in elementsToDelete) element.Remove(); //.detach(); } /** * Apply element constraints. * * @param root Root element of tree to apply constraints to. * Non-null. */ private void applyElementConstraints(XElement root) { //Debug.Assert(root != null : "root cannot be null"; // Loop over all constraints foreach (ElementConstraint constraint in elementConstraints) { String elementName = constraint.getElementName(); // Find the corresponding element XElement element = findElement(root, elementName); if (element == null) continue; String value = constraint.getText(); // If the element has not yet been constrained, we // constrain it by applying the value as text if (element.Value.Length == 0) element.Value = value; //.setText(value); // If the element has already been constrained., we // (deep-) clone the parent and apply the constraint // on the clone. else { XElement parent = element.Parent; //.getParentElement(); XElement clone = new XElement(parent); // (XElement)parent.clone(); parent.Parent.Add(clone); //.addContent(clone); XElement newElement = findElement(clone, elementName); newElement.Value = value; //.setText(value); } } } /** * Apply element constraints. * * @param root Root element of tree to apply constraints to. * Non-null. */ private void applyAttributeConstraints(XElement root) { //Debug.Assert(root != null : "root cannot be null"; // Loop over all constraints foreach (AttributeConstraint constraint in attributeConstraints) { String elementName = constraint.getElementName(); // Find the corresponding element XElement element = findElement(root, elementName); if (element == null) continue; String attributeName = constraint.getAttributeName(); XAttribute attribute = element.Attribute(attributeName); if (attribute == null) continue; attribute.SetValue(constraint.getText()); } } /// <summary> /// Apply the given restrictions to the specified XML. /// </summary> /// <param name="queryXml">XML to apply restrictions to. Non-null.</param> /// <returns>A (possibly) modified XML. null if the parse process failed for some reason.</returns> internal String apply(String queryXml) { if (queryXml == null) throw new ArgumentNullException("queryXml cannot be null"); // Make a DOM tree of the XML //SAXBuilder builder = new SAXBuilder(); try { XDocument document = XDocument.Load(new StringReader(queryXml)); XElement root = document.Root; // Modify the DOM tree according to inclusions/exclusions and constraints if (includedElements.Count != 0) applyInclusions(root); if (elementConstraints.Count != 0) applyElementConstraints(root); if (attributeConstraints.Count != 0) applyAttributeConstraints(root); // Convert back to an XML string String xml = root.ToString(); // (new XMLOutputter()).outputString(root.getDocument()); return xml; } catch (IOException exception) { // Programming error Console.Write(exception.StackTrace); // exception.printStackTrace(); //Debug.Assert(false : "Unable to create XML document: " + queryXml; return null; } catch (Exception /*JDOMException*/ exception) { // Programming error //exception.printStackTrace(); Console.Write(exception.StackTrace); //Debug.Assert(false : "Unable to parse XML document: " + queryXml; return null; } } /** {@inheritDoc} */ public override String ToString() { StringBuilder s = new StringBuilder(); s.Append("Include elements:\n"); foreach (String element in includedElements) s.Append(" <" + element + "/>\n"); s.Append("Exclude elements:\n"); foreach (String element in excludedElements) s.Append(" <" + element + "/>\n"); s.Append("Constraints:\n"); foreach (ElementConstraint constraint in elementConstraints) s.Append(" " + constraint + "\n"); foreach (AttributeConstraint constraint in attributeConstraints) s.Append(" " + constraint + "\n"); return s.ToString(); } /** * Class for representing an element constraint. * * @author <a href="mailto:[email protected]">NWitsml</a> */ private /*static*/ class ElementConstraint { /** Name of element being constrained. Non-null. */ protected String elementName; /** Value to constrain element with. May be null for unconstrined. */ protected Object value; /** * Create a new element constraint. * * @param elementName XElement being constrained. Non-null. * @param value Value to constrin element with. Null to leave * unconstrined. */ internal ElementConstraint(String elementName, Object value) { //Debug.Assert(elementName != null : "elementName cannot be null"; this.elementName = elementName; this.value = value; } /** * Return name of element being constrined. * * @return Name of element being constrained. Never null. */ internal String getElementName() { return elementName; } /** * Return the string representing the constrining value. * * @return String representing the constrining value. Never null. */ internal String getText() { if (value == null) return ""; if (value is DateTime) { DateTime? time = (DateTime)value; return time.ToString(); } return value.ToString(); } /** {@inheritDoc} */ public override String ToString() { return "<" + elementName + ">" + getText() + "</" + elementName + ">"; } } /** * Class for representing an attribute constraint. * * @author <a href="mailto:[email protected]">NWitsml</a> */ private /*static*/ class AttributeConstraint : ElementConstraint { /** Attribute being constrined. */ private String attributeName; /** * Create a new attribute constraint. * * @param elementName Name of element of attribute being constrained. Non-null. * @param attributeName Name of attribute being constrained. Non-null. * @param value Value to constrin element with. Null to leave * unconstrined. */ internal AttributeConstraint(String elementName, String attributeName, Object value) : base(elementName, value) { //Debug.Assert(elementName != null : "elementName cannot be null"; //Debug.Assert(attributeName != null : "attributeName cannot be null"; this.attributeName = attributeName; } /** * Return name of attribute being constrained. * * @return Name of attribute being constrained. Never null. */ internal String getAttributeName() { return attributeName; } /** {@inheritDoc} */ public override String ToString() { return "<" + elementName + " " + attributeName + "=" + getText() + "/>"; } } } }
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 MvcVsWebApi.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; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.AccessControl; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32; using NuGet; using Splat; using Squirrel.Shell; namespace Squirrel { public sealed partial class UpdateManager : IUpdateManager, IEnableLogger { readonly string rootAppDirectory; readonly string applicationName; readonly IFileDownloader urlDownloader; readonly string updateUrlOrPath; IDisposable updateLock; public UpdateManager(string urlOrPath, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName ?? UpdateManager.getApplicationName(); this.urlDownloader = urlDownloader ?? new FileDownloader(); if (rootDirectory != null) { this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName); return; } this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName); } public async Task<UpdateInfo> CheckForUpdate(bool ignoreDeltaUpdates = false, Action<int> progress = null) { var checkForUpdate = new CheckForUpdateImpl(rootAppDirectory); await acquireUpdateLock(); return await checkForUpdate.CheckForUpdate(Utility.LocalReleaseFileForAppDir(rootAppDirectory), updateUrlOrPath, ignoreDeltaUpdates, progress, urlDownloader); } public async Task DownloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null) { var downloadReleases = new DownloadReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await downloadReleases.DownloadReleases(updateUrlOrPath, releasesToDownload, progress, urlDownloader); } public async Task<string> ApplyReleases(UpdateInfo updateInfo, Action<int> progress = null) { var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); return await applyReleases.ApplyReleases(updateInfo, false, false, progress); } public async Task FullInstall(bool silentInstall = false, Action<int> progress = null) { var updateInfo = await CheckForUpdate(); await DownloadReleases(updateInfo.ReleasesToApply); var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await applyReleases.ApplyReleases(updateInfo, silentInstall, true, progress); } public async Task FullUninstall() { var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); this.KillAllExecutablesBelongingToPackage(); await applyReleases.FullUninstall(); } public Task<RegistryKey> CreateUninstallerRegistryEntry(string uninstallCmd, string quietSwitch) { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); return installHelpers.CreateUninstallerRegistryEntry(uninstallCmd, quietSwitch); } public Task<RegistryKey> CreateUninstallerRegistryEntry() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); return installHelpers.CreateUninstallerRegistryEntry(); } public void RemoveUninstallerRegistryEntry() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); installHelpers.RemoveUninstallerRegistryEntry(); } public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly, string programArguments = null, string icon = null) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); installHelpers.CreateShortcutsForExecutable(exeName, locations, updateOnly, programArguments, icon); } public Dictionary<ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments = null) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); return installHelpers.GetShortcutsForExecutable(exeName, locations, programArguments); } public void RemoveShortcutsForExecutable(string exeName, ShortcutLocation locations) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); installHelpers.RemoveShortcutsForExecutable(exeName, locations); } public SemanticVersion CurrentlyInstalledVersion(string executable = null) { executable = executable ?? Path.GetDirectoryName(typeof(UpdateManager).Assembly.Location); if (!executable.StartsWith(rootAppDirectory, StringComparison.OrdinalIgnoreCase)) { return null; } var appDirName = executable.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) .FirstOrDefault(x => x.StartsWith("app-", StringComparison.OrdinalIgnoreCase)); if (appDirName == null) return null; return appDirName.ToSemanticVersion(); } public void KillAllExecutablesBelongingToPackage() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); installHelpers.KillAllProcessesBelongingToPackage(); } public string ApplicationName { get { return applicationName; } } public string RootAppDirectory { get { return rootAppDirectory; } } public bool IsInstalledApp { get { return Assembly.GetExecutingAssembly().Location.StartsWith(RootAppDirectory, StringComparison.OrdinalIgnoreCase); } } public void Dispose() { var disp = Interlocked.Exchange(ref updateLock, null); if (disp != null) { disp.Dispose(); } } static bool exiting = false; public static void RestartApp(string exeToStart = null, string arguments = null) { // NB: Here's how this method works: // // 1. We're going to pass the *name* of our EXE and the params to // Update.exe // 2. Update.exe is going to grab our PID (via getting its parent), // then wait for us to exit. // 3. We exit cleanly, dropping any single-instance mutexes or // whatever. // 4. Update.exe unblocks, then we launch the app again, possibly // launching a different version than we started with (this is why // we take the app's *name* rather than a full path) exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location); var argsArg = arguments != null ? String.Format("-a \"{0}\"", arguments) : ""; exiting = true; Process.Start(getUpdateExe(), String.Format("--processStartAndWait {0} {1}", exeToStart, argsArg)); // NB: We have to give update.exe some time to grab our PID, but // we can't use WaitForInputIdle because we probably don't have // whatever WaitForInputIdle considers a message loop. Thread.Sleep(500); Environment.Exit(0); } public static string GetLocalAppDataDirectory(string assemblyLocation = null) { // Try to divine our our own install location via reading tea leaves // // * We're Update.exe, running in the app's install folder // * We're Update.exe, running on initial install from SquirrelTemp // * We're a C# EXE with Squirrel linked in var assembly = Assembly.GetEntryAssembly(); if (assemblyLocation == null && assembly == null) { // dunno lol return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } assemblyLocation = assemblyLocation ?? assembly.Location; if (Path.GetFileName(assemblyLocation).Equals("update.exe", StringComparison.OrdinalIgnoreCase)) { // NB: Both the "SquirrelTemp" case and the "App's folder" case // mean that the root app dir is one up var oneFolderUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), ".."); return Path.GetFullPath(oneFolderUpFromAppFolder); } var twoFoldersUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..\\.."); return Path.GetFullPath(twoFoldersUpFromAppFolder); } ~UpdateManager() { if (updateLock != null && !exiting) { throw new Exception("You must dispose UpdateManager!"); } } Task<IDisposable> acquireUpdateLock() { if (updateLock != null) return Task.FromResult(updateLock); return Task.Run(() => { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); IDisposable theLock; try { theLock = ModeDetector.InUnitTestRunner() ? Disposable.Create(() => {}) : new SingleGlobalInstance(key, TimeSpan.FromMilliseconds(2000)); } catch (TimeoutException) { throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates"); } var ret = Disposable.Create(() => { theLock.Dispose(); updateLock = null; }); updateLock = ret; return ret; }); } static string getApplicationName() { var fi = new FileInfo(getUpdateExe()); return fi.Directory.Name; } static string getUpdateExe() { var assembly = Assembly.GetEntryAssembly(); // Are we update.exe? if (assembly != null && Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) && assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 && assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1) { return Path.GetFullPath(assembly.Location); } assembly = Assembly.GetExecutingAssembly(); var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe"); var target = new FileInfo(updateDotExe); if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?"); return target.FullName; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace DrillTime.WebApiNoEf.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // 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.Net.Http; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Management.SiteRecovery; namespace Microsoft.WindowsAzure.Management.SiteRecovery { public partial class SiteRecoveryManagementClient : ServiceClient<SiteRecoveryManagementClient>, ISiteRecoveryManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private string _cloudServiceName; public string CloudServiceName { get { return this._cloudServiceName; } set { this._cloudServiceName = value; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private string _resourceName; public string ResourceName { get { return this._resourceName; } set { this._resourceName = value; } } private IJobOperations _jobs; /// <summary> /// Definition for Job Operations. /// </summary> public virtual IJobOperations Jobs { get { return this._jobs; } } private IProtectionContainerOperations _protectionContainer; /// <summary> /// Definition of Protection Container operations for the Site Recovery /// extension. /// </summary> public virtual IProtectionContainerOperations ProtectionContainer { get { return this._protectionContainer; } } private IProtectionEntityOperations _protectionEntity; /// <summary> /// Definition of protection entity operations for the Site Recovery /// extension. /// </summary> public virtual IProtectionEntityOperations ProtectionEntity { get { return this._protectionEntity; } } private IRecoveryPlanOperations _recoveryPlan; /// <summary> /// Definition of recoveryplan operations for the Site Recovery /// extension. /// </summary> public virtual IRecoveryPlanOperations RecoveryPlan { get { return this._recoveryPlan; } } private IServerOperations _servers; /// <summary> /// Definition of server operations for the Site Recovery extension. /// </summary> public virtual IServerOperations Servers { get { return this._servers; } } private IVirtualMachineGroupOperations _vmGroup; /// <summary> /// Definition of virtual machine operations for the Site Recovery /// extension. /// </summary> public virtual IVirtualMachineGroupOperations VmGroup { get { return this._vmGroup; } } private IVirtualMachineOperations _vm; /// <summary> /// Definition of virtual machine operations for the Site Recovery /// extension. /// </summary> public virtual IVirtualMachineOperations Vm { get { return this._vm; } } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> private SiteRecoveryManagementClient() : base() { this._jobs = new JobOperations(this); this._protectionContainer = new ProtectionContainerOperations(this); this._protectionEntity = new ProtectionEntityOperations(this); this._recoveryPlan = new RecoveryPlanOperations(this); this._servers = new ServerOperations(this); this._vmGroup = new VirtualMachineGroupOperations(this); this._vm = new VirtualMachineOperations(this); this._apiVersion = "2013-03-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='cloudServiceName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._cloudServiceName = cloudServiceName; this._resourceName = resourceName; this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='cloudServiceName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials) : this() { if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this._cloudServiceName = cloudServiceName; this._resourceName = resourceName; this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private SiteRecoveryManagementClient(HttpClient httpClient) : base(httpClient) { this._jobs = new JobOperations(this); this._protectionContainer = new ProtectionContainerOperations(this); this._protectionEntity = new ProtectionEntityOperations(this); this._recoveryPlan = new RecoveryPlanOperations(this); this._servers = new ServerOperations(this); this._vmGroup = new VirtualMachineGroupOperations(this); this._vm = new VirtualMachineOperations(this); this._apiVersion = "2013-03-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='cloudServiceName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._cloudServiceName = cloudServiceName; this._resourceName = resourceName; this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='cloudServiceName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this._cloudServiceName = cloudServiceName; this._resourceName = resourceName; this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// SiteRecoveryManagementClient instance /// </summary> /// <param name='client'> /// Instance of SiteRecoveryManagementClient to clone to /// </param> protected override void Clone(ServiceClient<SiteRecoveryManagementClient> client) { base.Clone(client); if (client is SiteRecoveryManagementClient) { SiteRecoveryManagementClient clonedClient = ((SiteRecoveryManagementClient)client); clonedClient._cloudServiceName = this._cloudServiceName; clonedClient._resourceName = this._resourceName; clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Threading; using Mono.Collections.Generic; namespace Mono.Cecil.Cil { public sealed class MethodBody { readonly internal MethodDefinition method; internal ParameterDefinition this_parameter; internal int max_stack_size; internal int code_size; internal bool init_locals; internal MetadataToken local_var_token; internal Collection<Instruction> instructions; internal Collection<ExceptionHandler> exceptions; internal Collection<VariableDefinition> variables; public MethodDefinition Method { get { return method; } } public int MaxStackSize { get { return max_stack_size; } set { max_stack_size = value; } } public int CodeSize { get { return code_size; } } public bool InitLocals { get { return init_locals; } set { init_locals = value; } } public MetadataToken LocalVarToken { get { return local_var_token; } set { local_var_token = value; } } public Collection<Instruction> Instructions { get { return instructions ?? (instructions = new InstructionCollection (method)); } } public bool HasExceptionHandlers { get { return !exceptions.IsNullOrEmpty (); } } public Collection<ExceptionHandler> ExceptionHandlers { get { return exceptions ?? (exceptions = new Collection<ExceptionHandler> ()); } } public bool HasVariables { get { return !variables.IsNullOrEmpty (); } } public Collection<VariableDefinition> Variables { get { return variables ?? (variables = new VariableDefinitionCollection ()); } } public ParameterDefinition ThisParameter { get { if (method == null || method.DeclaringType == null) throw new NotSupportedException (); if (!method.HasThis) return null; if (this_parameter == null) Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null); return this_parameter; } } static ParameterDefinition CreateThisParameter (MethodDefinition method) { var parameter_type = method.DeclaringType as TypeReference; if (parameter_type.HasGenericParameters) { var instance = new GenericInstanceType (parameter_type); for (int i = 0; i < parameter_type.GenericParameters.Count; i++) instance.GenericArguments.Add (parameter_type.GenericParameters [i]); parameter_type = instance; } if (parameter_type.IsValueType || parameter_type.IsPrimitive) parameter_type = new ByReferenceType (parameter_type); return new ParameterDefinition (parameter_type, method); } public MethodBody (MethodDefinition method) { this.method = method; } public ILProcessor GetILProcessor () { return new ILProcessor (this); } } sealed class VariableDefinitionCollection : Collection<VariableDefinition> { internal VariableDefinitionCollection () { } internal VariableDefinitionCollection (int capacity) : base (capacity) { } protected override void OnAdd (VariableDefinition item, int index) { item.index = index; } protected override void OnInsert (VariableDefinition item, int index) { item.index = index; for (int i = index; i < size; i++) items [i].index = i + 1; } protected override void OnSet (VariableDefinition item, int index) { item.index = index; } protected override void OnRemove (VariableDefinition item, int index) { item.index = -1; for (int i = index + 1; i < size; i++) items [i].index = i - 1; } } class InstructionCollection : Collection<Instruction> { readonly MethodDefinition method; internal InstructionCollection (MethodDefinition method) { this.method = method; } internal InstructionCollection (MethodDefinition method, int capacity) : base (capacity) { this.method = method; } protected override void OnAdd (Instruction item, int index) { if (index == 0) return; var previous = items [index - 1]; previous.next = item; item.previous = previous; } protected override void OnInsert (Instruction item, int index) { if (size == 0) return; var current = items [index]; if (current == null) { var last = items [index - 1]; last.next = item; item.previous = last; return; } var previous = current.previous; if (previous != null) { previous.next = item; item.previous = previous; } current.previous = item; item.next = current; } protected override void OnSet (Instruction item, int index) { var current = items [index]; item.previous = current.previous; item.next = current.next; current.previous = null; current.next = null; } protected override void OnRemove (Instruction item, int index) { var previous = item.previous; if (previous != null) previous.next = item.next; var next = item.next; if (next != null) next.previous = item.previous; RemoveSequencePoint (item); item.previous = null; item.next = null; } void RemoveSequencePoint (Instruction instruction) { var debug_info = method.debug_info; if (debug_info == null || !debug_info.HasSequencePoints) return; var sequence_points = debug_info.sequence_points; for (int i = 0; i < sequence_points.Count; i++) { if (sequence_points [i].Offset == instruction.offset) { sequence_points.RemoveAt (i); return; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Enchant; using Palaso.i18n; using Palaso.Reporting; using Palaso.UI.WindowsForms.HotSpot; using Palaso.Spelling; using Palaso.UI.WindowsForms.i18n; namespace Palaso.UI.WindowsForms.Spelling { [ProvideProperty("LanguageForSpellChecking", typeof(TextBoxBase))] public class TextBoxSpellChecker : IExtenderProvider, IComponent { private readonly Dictionary<Control, string> _extendees; private readonly HotSpotProvider _hotSpotProvider; private ISite _site; private readonly Broker _broker; private readonly Dictionary<string, Dictionary> _dictionaries; [DebuggerStepThrough] public TextBoxSpellChecker() { _extendees = new Dictionary<Control, string>(); bool brokerSuccessfullyCreated = false; try { _broker = new Broker(); brokerSuccessfullyCreated = true; } catch { //it's okay if we can't create one. // probably because Enchant isn't installed on this machine } if (brokerSuccessfullyCreated) { _hotSpotProvider = new HotSpotProvider(); _hotSpotProvider.RetrieveHotSpots += CheckSpelling; _dictionaries = new Dictionary<string, Dictionary>(); } } #region Enchant Methods private void AddToDictionary(string language, string s) { _dictionaries[language].Add(s); _hotSpotProvider.RefreshAll(); } private IEnumerable<string> GetSuggestions(string language, string text) { try { return _dictionaries[language].Suggest(text); } catch (Exception error) { //the actual error messages are always worthless, talking about corrupted memory ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "There was a problem with the Enchant Spell-Checking system related to {0}", language); } return new List<string>(); } private bool IsWordSpelledCorrectly(string language, string s) { try { return _dictionaries[language].Check(s); } catch (Exception error) { //the actual error messages are always worthless, talking about corrupted memory ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "There was a problem with the Enchant Spell-Checking system related to {0}", language); } return true;//review } #endregion #region IExtenderProvider Members public bool CanExtend(object extendee) { return extendee is TextBoxBase; } #endregion #region IComponent Members public event EventHandler Disposed; public ISite Site { get { return _site; } set { _site = value; } } public void Dispose() { _hotSpotProvider.Dispose(); _extendees.Clear(); if (Disposed != null) { Disposed(this, new EventArgs()); } } #endregion private void CheckSpelling(object sender, RetrieveHotSpotsEventArgs e) { string text = e.Text; e.Color = Color.DarkSalmon; string language = GetLanguageForSpellChecking(e.Control); IEnumerable<WordTokenizer.Token> tokens = WordTokenizer.TokenizeText(text); foreach (WordTokenizer.Token token in tokens) { if (!IsWordSpelledCorrectly(language, token.Value)) { HotSpot.HotSpot hotArea = new HotSpot.HotSpot(e.Control, token.Offset, token.Length); hotArea.MouseLeave += OnMouseLeaveHotSpot; hotArea.MouseEnter += OnMouseEnterHotSpot; e.AddHotSpot(hotArea); } } } private void OnAddToDictionary(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; HotSpot.HotSpot hotSpot = (HotSpot.HotSpot)item.Tag; string language = GetLanguageForSpellChecking(hotSpot.Control); AddToDictionary(language, hotSpot.Text); } private static void OnChooseSuggestedSpelling(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; ReplaceText((HotSpot.HotSpot)item.Tag, item.Text); } private static void ReplaceText(HotSpot.HotSpot area, string text) { TextBoxBase control = area.Control; control.SelectionStart = area.Offset; control.SelectionLength = area.Text.Length; TextBox textBox = control as TextBox; if (textBox != null) { textBox.Paste(text); //allows it to be undone } else { control.SelectedText = text; } control.Invalidate(); } private ContextMenuStrip GetSuggestionContextMenu(string language, HotSpot.HotSpot hotSpot) { ContextMenuStrip strip = new ContextMenuStrip(); strip.ShowImageMargin = false; strip.ShowCheckMargin = false; ToolStripMenuItem item; int suggestionCount = 0; foreach (string suggestion in GetSuggestions(language, hotSpot.Text)) { if (++suggestionCount > 10) { break; } item = new ToolStripMenuItem(suggestion); item.Tag = hotSpot; item.Click += OnChooseSuggestedSpelling; strip.Items.Add(item); } if (strip.Items.Count == 0) { item = new ToolStripMenuItem(StringCatalog.Get("(No Spelling Suggestions)")); item.Enabled = false; strip.Items.Add(item); } strip.Items.Add(new ToolStripSeparator()); item = new ToolStripMenuItem(StringCatalog.Get("Add to Dictionary")); item.Tag = hotSpot; item.Click += OnAddToDictionary; strip.Items.Add(item); return strip; } private void OnMouseEnterHotSpot(object sender, EventArgs e) { HotSpot.HotSpot hotSpot = (HotSpot.HotSpot)sender; string language = GetLanguageForSpellChecking(hotSpot.Control); hotSpot.Control.ContextMenuStrip = GetSuggestionContextMenu(language, hotSpot); } private static void OnMouseLeaveHotSpot(object sender, EventArgs e) { ((HotSpot.HotSpot)sender).Control.ContextMenuStrip = null; } [DefaultValue("")] public string GetLanguageForSpellChecking(Control c) { if (c == null) { throw new ArgumentNullException(); } if (!CanExtend(c)) { throw new ArgumentException("Control must be derived from TextBoxBase"); } string value; if (_extendees.TryGetValue(c, out value)) { return value; } return string.Empty; } public void SetLanguageForSpellChecking(Control control, string language) { if (control == null) { throw new ArgumentNullException(); } if (!CanExtend(control)) { throw new ArgumentException("Control must be derived from TextBoxBase"); } if (String.IsNullOrEmpty(language)) { if (_hotSpotProvider != null) { _hotSpotProvider.SetEnableHotSpots(control, false); } _extendees.Remove(control); } else { if (_broker != null) { try { if (_broker.DictionaryExists(language)) { if (!_dictionaries.ContainsKey(language)) { _dictionaries.Add(language, _broker.RequestDictionary(language)); } _hotSpotProvider.SetEnableHotSpots(control, true); } } catch (Exception error) { //the actual error messages are always worthless, talking about corrupted memory //ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "There was a problem with the Enchant Spell-Checking system related to {0}", language); //The number of false errors here is so high that for now, let's not bother to scare the user } } _extendees[control] = language; } } } }
// 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 Microsoft.Win32.SafeHandles; #pragma warning disable SA1121 // we don't want to simplify built-ins here as we're using aliasing using CFStringRef = System.IntPtr; using CFArrayRef = System.IntPtr; using FSEventStreamRef = System.IntPtr; using size_t = System.IntPtr; using FSEventStreamEventId = System.UInt64; using CFTimeInterval = System.Double; using CFRunLoopRef = System.IntPtr; internal static partial class Interop { internal static partial class EventStream { /// <summary> /// This constant specifies that we don't want historical file system events, only new ones /// </summary> internal const ulong kFSEventStreamEventIdSinceNow = 0xFFFFFFFFFFFFFFFF; /// <summary> /// Flags that describe what happened in the event that was received. These come from the FSEvents.h header file in the CoreServices framework. /// </summary> [Flags] internal enum FSEventStreamEventFlags : uint { /* flags when creating the stream. */ kFSEventStreamEventFlagNone = 0x00000000, kFSEventStreamEventFlagMustScanSubDirs = 0x00000001, kFSEventStreamEventFlagUserDropped = 0x00000002, kFSEventStreamEventFlagKernelDropped = 0x00000004, kFSEventStreamEventFlagEventIdsWrapped = 0x00000008, kFSEventStreamEventFlagHistoryDone = 0x00000010, kFSEventStreamEventFlagRootChanged = 0x00000020, kFSEventStreamEventFlagMount = 0x00000040, kFSEventStreamEventFlagUnmount = 0x00000080, /* These flags are only set if you specified the FileEvents */ kFSEventStreamEventFlagItemCreated = 0x00000100, kFSEventStreamEventFlagItemRemoved = 0x00000200, kFSEventStreamEventFlagItemInodeMetaMod = 0x00000400, kFSEventStreamEventFlagItemRenamed = 0x00000800, kFSEventStreamEventFlagItemModified = 0x00001000, kFSEventStreamEventFlagItemFinderInfoMod = 0x00002000, kFSEventStreamEventFlagItemChangeOwner = 0x00004000, kFSEventStreamEventFlagItemXattrMod = 0x00008000, kFSEventStreamEventFlagItemIsFile = 0x00010000, kFSEventStreamEventFlagItemIsDir = 0x00020000, kFSEventStreamEventFlagItemIsSymlink = 0x00040000, kFSEventStreamEventFlagOwnEvent = 0x00080000, kFSEventStreamEventFlagItemIsHardlink = 0x00100000, kFSEventStreamEventFlagItemIsLastHardlink = 0x00200000, } /// <summary> /// Flags that describe what kind of event stream should be created (and therefore what events should be /// piped into this stream). These come from the FSEvents.h header file in the CoreServices framework. /// </summary> [Flags] internal enum FSEventStreamCreateFlags : uint { kFSEventStreamCreateFlagNone = 0x00000000, kFSEventStreamCreateFlagUseCFTypes = 0x00000001, kFSEventStreamCreateFlagNoDefer = 0x00000002, kFSEventStreamCreateFlagWatchRoot = 0x00000004, kFSEventStreamCreateFlagIgnoreSelf = 0x00000008, kFSEventStreamCreateFlagFileEvents = 0x00000010 } /// <summary> /// The EventStream callback that will be called for every event batch. /// </summary> /// <param name="streamReference">The stream that was created for this callback.</param> /// <param name="clientCallBackInfo">A pointer to optional context info; otherwise, IntPtr.Zero.</param> /// <param name="numEvents">The number of paths, events, and IDs. Path[2] corresponds to Event[2] and ID[2], etc.</param> /// <param name="eventPaths">The paths that have changed somehow, according to their corresponding event.</param> /// <param name="eventFlags">The events for the corresponding path.</param> /// <param name="eventIds">The machine-and-disk-drive-unique Event ID for the specific event.</param> [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate void FSEventStreamCallback( FSEventStreamRef streamReference, IntPtr clientCallBackInfo, size_t numEvents, byte** eventPaths, FSEventStreamEventFlags* eventFlags, FSEventStreamEventId* eventIds); /// <summary> /// Internal wrapper to create a new EventStream to listen to events from the core OS (such as File System events). /// </summary> /// <param name="allocator">Should be IntPtr.Zero</param> /// <param name="cb">A callback instance that will be called for every event batch.</param> /// <param name="context">Should be IntPtr.Zero</param> /// <param name="pathsToWatch">A CFArray of the path(s) to watch for events.</param> /// <param name="sinceWhen"> /// The start point to receive events from. This can be to retrieve historical events or only new events. /// To get historical events, pass in the corresponding ID of the event you want to start from. /// To get only new events, pass in kFSEventStreamEventIdSinceNow. /// </param> /// <param name="latency">Coalescing period to wait before sending events.</param> /// <param name="flags">Flags to say what kind of events should be sent through this stream.</param> /// <returns>On success, returns a pointer to an FSEventStream object; otherwise, returns IntPtr.Zero</returns> /// <remarks>For *nix systems, the CLR maps ANSI to UTF-8, so be explicit about that</remarks> [DllImport(Interop.Libraries.CoreServicesLibrary, CharSet = CharSet.Ansi)] private static extern SafeEventStreamHandle FSEventStreamCreate( IntPtr allocator, FSEventStreamCallback cb, IntPtr context, SafeCreateHandle pathsToWatch, FSEventStreamEventId sinceWhen, CFTimeInterval latency, FSEventStreamCreateFlags flags); /// <summary> /// Creates a new EventStream to listen to events from the core OS (such as File System events). /// </summary> /// <param name="cb">A callback instance that will be called for every event batch.</param> /// <param name="pathsToWatch">A CFArray of the path(s) to watch for events.</param> /// <param name="sinceWhen"> /// The start point to receive events from. This can be to retrieve historical events or only new events. /// To get historical events, pass in the corresponding ID of the event you want to start from. /// To get only new events, pass in kFSEventStreamEventIdSinceNow. /// </param> /// <param name="latency">Coalescing period to wait before sending events.</param> /// <param name="flags">Flags to say what kind of events should be sent through this stream.</param> /// <returns>On success, returns a valid SafeCreateHandle to an FSEventStream object; otherwise, returns an invalid SafeCreateHandle</returns> internal static SafeEventStreamHandle FSEventStreamCreate( FSEventStreamCallback cb, SafeCreateHandle pathsToWatch, FSEventStreamEventId sinceWhen, CFTimeInterval latency, FSEventStreamCreateFlags flags) { return FSEventStreamCreate(IntPtr.Zero, cb, IntPtr.Zero, pathsToWatch, sinceWhen, latency, flags); } /// <summary> /// Attaches an EventStream to a RunLoop so events can be received. This should usually be the current thread's RunLoop. /// </summary> /// <param name="streamRef">The stream to attach to the RunLoop</param> /// <param name="runLoop">The RunLoop to attach the stream to</param> /// <param name="runLoopMode">The mode of the RunLoop; this should usually be kCFRunLoopDefaultMode. See the documentation for RunLoops for more info.</param> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern void FSEventStreamScheduleWithRunLoop( SafeEventStreamHandle streamRef, CFRunLoopRef runLoop, SafeCreateHandle runLoopMode); /// <summary> /// Starts receiving events on the specified stream. /// </summary> /// <param name="streamRef">The stream to receive events on.</param> /// <returns>Returns true if the stream was started; otherwise, returns false and no events will be received.</returns> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern bool FSEventStreamStart(SafeEventStreamHandle streamRef); /// <summary> /// Stops receiving events on the specified stream. The stream can be restarted and not miss any events. /// </summary> /// <param name="streamRef">The stream to stop receiving events on.</param> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern void FSEventStreamStop(SafeEventStreamHandle streamRef); /// <summary> /// Stops receiving events on the specified stream. The stream can be restarted and not miss any events. /// </summary> /// <param name="streamRef">The stream to stop receiving events on.</param> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern void FSEventStreamStop(IntPtr streamRef); /// <summary> /// Invalidates an EventStream and removes it from any RunLoops. /// </summary> /// <param name="streamRef">The FSEventStream to invalidate</param> /// <remarks>This can only be called after FSEventStreamScheduleWithRunLoop has be called</remarks> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern void FSEventStreamInvalidate(IntPtr streamRef); /// <summary> /// Removes the event stream from the RunLoop. /// </summary> /// <param name="streamRef">The stream to remove from the RunLoop</param> /// <param name="runLoop">The RunLoop to remove the stream from.</param> /// <param name="runLoopMode">The mode of the RunLoop; this should usually be kCFRunLoopDefaultMode. See the documentation for RunLoops for more info.</param> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern void FSEventStreamUnscheduleFromRunLoop( SafeEventStreamHandle streamRef, CFRunLoopRef runLoop, SafeCreateHandle runLoopMode); /// <summary> /// Releases a reference count on the specified EventStream and, if necessary, cleans the stream up. /// </summary> /// <param name="streamRef">The stream on which to decrement the reference count.</param> [DllImport(Interop.Libraries.CoreServicesLibrary)] internal static extern void FSEventStreamRelease(IntPtr streamRef); } }
using Signum.Entities.Processes; using Signum.Entities.Reflection; using Signum.Utilities; using Signum.Utilities.Reflection; using System; using System.Linq; using System.Reflection; namespace Signum.Entities.MachineLearning { [Serializable, EntityKind(EntityKind.Part, EntityData.Master)] public class NeuralNetworkSettingsEntity : Entity, IPredictorAlgorithmSettings { [StringLengthValidator(Max = 100)] public string? Device { get; set; } public PredictionType PredictionType { get; set; } [PreserveOrder] [NoRepeatValidator] public MList<NeuralNetworkHidenLayerEmbedded> HiddenLayers { get; set; } = new MList<NeuralNetworkHidenLayerEmbedded>(); public NeuralNetworkActivation OutputActivation { get; set; } public NeuralNetworkInitializer OutputInitializer { get; set; } public TensorFlowOptimizer Optimizer { get; set; } public NeuralNetworkEvalFunction LossFunction { get; set; } public NeuralNetworkEvalFunction EvalErrorFunction { get; set; } [DecimalsValidator(5), NumberIsValidator(ComparisonType.GreaterThan, 0)] public double LearningRate { get; set; } = 0.001f; public double LearningEpsilon { get; set; } = 1e-8f; [NumberIsValidator(ComparisonType.GreaterThan, 0)] public int MinibatchSize { get; set; } = 1000; [NumberIsValidator(ComparisonType.GreaterThan, 0)] public int NumMinibatches { get; set; } = 100; [Unit("Minibaches"), NumberIsValidator(ComparisonType.GreaterThan, 0)] public int BestResultFromLast { get; set; } = 10; [Unit("Minibaches"), NumberIsValidator(ComparisonType.GreaterThan, 0)] public int SaveProgressEvery { get; set; } = 5; [Unit("Minibaches"), NumberIsValidator(ComparisonType.GreaterThan, 0)] public int SaveValidationProgressEvery { get; set; } = 10; protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(SaveValidationProgressEvery)) { if (SaveValidationProgressEvery % SaveProgressEvery != 0) { return PredictorMessage._0ShouldBeDivisibleBy12.NiceToString(pi.NiceName(), ReflectionTools.GetPropertyInfo(() => SaveProgressEvery).NiceName(), SaveProgressEvery); } } if (pi.Name == nameof(OutputActivation)) { if (OutputActivation == NeuralNetworkActivation.ReLU || OutputActivation == NeuralNetworkActivation.Sigmoid) { var p = this.GetParentEntity<PredictorEntity>(); var errors = p.MainQuery.Columns.Where(a => a.Usage == PredictorColumnUsage.Output && a.Encoding.Is(DefaultColumnEncodings.NormalizeZScore)).Select(a => a.Token).ToList(); errors.AddRange(p.SubQueries.SelectMany(sq => sq.Columns).Where(a => a.Usage == PredictorSubQueryColumnUsage.Output && a.Encoding.Is(DefaultColumnEncodings.NormalizeZScore)).Select(a => a.Token).ToList()); if (errors.Any()) return PredictorMessage._0CanNotBe1Because2Use3.NiceToString(pi.NiceName(), OutputActivation.NiceToString(), errors.CommaAnd(), DefaultColumnEncodings.NormalizeZScore.NiceToString()); } } string? Validate(NeuralNetworkEvalFunction function) { bool lossIsClassification = function == NeuralNetworkEvalFunction.sigmoid_cross_entropy_with_logits || function == NeuralNetworkEvalFunction.ClassificationError; bool typeIsClassification = this.PredictionType == PredictionType.Classification || this.PredictionType == PredictionType.MultiClassification; if (lossIsClassification != typeIsClassification) return PredictorMessage._0IsNotCompatibleWith12.NiceToString(function.NiceToString(), this.NicePropertyName(a => a.PredictionType), this.PredictionType.NiceToString()); return null; } if (pi.Name == nameof(LossFunction)) { return Validate(LossFunction); } if (pi.Name == nameof(EvalErrorFunction)) { return Validate(EvalErrorFunction); } return base.PropertyValidation(pi); } public IPredictorAlgorithmSettings Clone() => new NeuralNetworkSettingsEntity { Device = Device, PredictionType = PredictionType, HiddenLayers = HiddenLayers.Select(hl => hl.Clone()).ToMList(), OutputActivation = OutputActivation, OutputInitializer = OutputInitializer, LossFunction = LossFunction, EvalErrorFunction = EvalErrorFunction, Optimizer = Optimizer, LearningRate = LearningRate, MinibatchSize = MinibatchSize, NumMinibatches = NumMinibatches, BestResultFromLast = BestResultFromLast, SaveProgressEvery = SaveProgressEvery, SaveValidationProgressEvery = SaveValidationProgressEvery, }; } public enum PredictionType { Regression, MultiRegression, Classification, MultiClassification, } [Serializable] public class NeuralNetworkHidenLayerEmbedded : EmbeddedEntity { [Unit("Neurons")] public int Size { get; set; } public NeuralNetworkActivation Activation { get; set; } public NeuralNetworkInitializer Initializer { get; set; } internal NeuralNetworkHidenLayerEmbedded Clone() => new NeuralNetworkHidenLayerEmbedded { Size = Size, Activation = Activation, Initializer = Initializer }; } public enum NeuralNetworkActivation { None, ReLU, Sigmoid, Tanh } public enum NeuralNetworkInitializer { glorot_uniform_initializer, ones_initializer, zeros_initializer, random_uniform_initializer, orthogonal_initializer, random_normal_initializer, truncated_normal_initializer, variance_scaling_initializer, } public enum TensorFlowOptimizer { Adam, GradientDescentOptimizer, } public enum NeuralNetworkEvalFunction { softmax_cross_entropy_with_logits_v2, softmax_cross_entropy_with_logits, sigmoid_cross_entropy_with_logits, ClassificationError, MeanSquaredError, MeanAbsoluteError, MeanAbsolutePercentageError, } [Serializable, EntityKind(EntityKind.Part, EntityData.Transactional)] public class AutoconfigureNeuralNetworkEntity : Entity, IProcessDataEntity { public Lite<PredictorEntity> InitialPredictor { get; set; } public bool ExploreLearner { get; set; } public bool ExploreLearningValues { get; set; } public bool ExploreHiddenLayers { get; set; } public bool ExploreOutputLayer { get; set; } public int MaxLayers { get; set; } = 2; public int MinNeuronsPerLayer { get; set; } = 5; public int MaxNeuronsPerLayer { get; set; } = 20; [Unit("seconds")] public long? OneTrainingDuration { get; set; } public int Generations { get; set; } = 10; public int Population { get; set; } = 10; [Format("p")] public double SurvivalRate { get; set; } = 0.4; [Format("p")] public double InitialMutationProbability { get; set; } = 0.1; public int? Seed { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// A dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/> /// and other bulk change methods already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; /// <summary> /// The comparers. /// </summary> private Comparers _comparers; /// <summary> /// The number of elements in this collection. /// </summary> private int _count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableDictionary<TKey, TValue> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </summary> /// <param name="map">The map that serves as the basis for this Builder.</param> internal Builder(ImmutableDictionary<TKey, TValue> map) { Requires.NotNull(map, nameof(map)); _root = map._root; _count = map._count; _comparers = map._comparers; _immutable = map; } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } set { Requires.NotNull(value, nameof(value)); if (value != this.KeyComparer) { var comparers = Comparers.Get(value, this.ValueComparer); var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers); var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input); _immutable = null; _comparers = comparers; _count = result.CountAdjustment; // offset from 0 this.Root = result.Root; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } set { Requires.NotNull(value, nameof(value)); if (value != this.ValueComparer) { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. _comparers = _comparers.WithValueComparer(value); _immutable = null; // invalidate cached immutable } } } #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the number of elements contained in the <see cref="ICollection{T}"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Key; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Value; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } #endregion #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { this.Add((TKey)key, (TValue)value); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { this.Remove((TKey)key); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion #region ICollection methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, _comparers); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns>The element with the specified key.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception> /// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } set { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); this.Apply(result); } } #region Public Methods /// <summary> /// Adds a sequence of values to this collection. /// </summary> /// <param name="items">The items.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin); this.Apply(result); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="keys">The keys for entries to remove from the dictionary.</param> public void RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, nameof(keys)); foreach (var key in keys) { this.Remove(key); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root, this); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns> [Pure] public TValue GetValueOrDefault(TKey key) { return this.GetValueOrDefault(key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public TValue GetValueOrDefault(TKey key, TValue defaultValue) { Requires.NotNullAllowStructs(key, nameof(key)); TValue value; if (this.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Creates an immutable dictionary based on the contents of this instance. /// </summary> /// <returns>An immutable map.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableDictionary<TKey, TValue> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count); } return _immutable; } #endregion #region IDictionary<TKey, TValue> Members /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception> /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public void Add(TKey key, TValue value) { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param> /// <returns> /// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(TKey key) { return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public bool Remove(TKey key) { var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin); return this.Apply(result); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param> /// <returns> /// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(TKey key, out TValue value) { return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception> public void Clear() { this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode; _count = 0; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public bool Remove(KeyValuePair<TKey, TValue> item) { // Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well. if (this.Contains(item)) { return this.Remove(item.Key); } return false; } #endregion #region IEnumerator<T> methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private bool Apply(MutationResult result) { this.Root = result.Root; _count += result.CountAdjustment; return result.CountAdjustment != 0; } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableDictionary<TKey, TValue>.Builder _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map) { Requires.NotNull(map, nameof(map)); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(_map.Count); } return _contents; } } } }
// // Mono.Google.GoogleConnection.cs: // // Authors: // Gonzalo Paniagua Javier ([email protected]) // Stephane Delcroix ([email protected]) // // (C) Copyright 2006 Novell, Inc. (http://www.novell.com) // (C) Copyright 2007 S. Delcroix // // 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. // // Check the Google Authentication Page at http://code.google.com/apis/accounts/AuthForInstalledApps.html // using System; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Reflection; namespace Mono.Google { public class GoogleConnection { string user; GoogleService service; string auth; string appname; public GoogleConnection (GoogleService service) { this.service = service; } public string ApplicationName { get { if (appname == null) { Assembly assembly = Assembly.GetEntryAssembly (); if (assembly == null) throw new InvalidOperationException ("You need to set GoogleConnection.ApplicationName."); AssemblyName aname = assembly.GetName (); appname = String.Format ("{0}-{1}", aname.Name, aname.Version); } return appname; } set { if (value == null || value == "") throw new ArgumentException ("Cannot be null or empty", "value"); appname = value; } } public void Authenticate (string user, string password) { if (user == null) throw new ArgumentNullException ("user"); if (this.user != null) throw new InvalidOperationException (String.Format ("Already authenticated for {0}", this.user)); this.user = user; this.auth = Authentication.GetAuthorization (this, user, password, service, null, null); if (this.auth == null) { this.user = null; throw new Exception (String.Format ("Authentication failed for user {0}", user)); } } public void Authenticate (string user, string password, string token, string captcha) { if (user == null) throw new ArgumentNullException ("user"); if (token == null) throw new ArgumentNullException ("token"); if (captcha == null) throw new ArgumentNullException ("captcha"); if (this.user != null) throw new InvalidOperationException (String.Format ("Already authenticated for {0}", this.user)); this.user = user; this.auth = Authentication.GetAuthorization (this, user, password, service, token, captcha); if (this.auth == null) { this.user = null; throw new Exception (String.Format ("Authentication failed for user {0}", user)); } } public HttpWebRequest AuthenticatedRequest (string url) { if (url == null) throw new ArgumentNullException ("url"); HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url); req.AutomaticDecompression = DecompressionMethods.GZip; if (auth != null) req.Headers.Add ("Authorization: GoogleLogin auth=" + auth); return req; } public string DownloadString (string url) { if (url == null) throw new ArgumentNullException ("url"); string received = null; HttpWebRequest req = AuthenticatedRequest (url); req.AutomaticDecompression = DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse) req.GetResponse (); Encoding encoding = Encoding.UTF8; if (response.ContentEncoding != "") { try { encoding = Encoding.GetEncoding (response.ContentEncoding); } catch {} } using (Stream stream = response.GetResponseStream ()) { StreamReader sr = new StreamReader (stream, encoding); received = sr.ReadToEnd (); } response.Close (); return received; } public byte [] DownloadBytes (string url) { if (url == null) throw new ArgumentNullException ("url"); HttpWebRequest req = AuthenticatedRequest (url); req.AutomaticDecompression = DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse) req.GetResponse (); byte [] bytes = null; using (Stream stream = response.GetResponseStream ()) { if (response.ContentLength != -1) { bytes = new byte [response.ContentLength]; stream.Read (bytes, 0, bytes.Length); } else { MemoryStream ms = new MemoryStream (); bytes = new byte [4096]; int nread; while ((nread = stream.Read (bytes, 0, bytes.Length)) > 0) { ms.Write (bytes, 0, nread); if (nread < bytes.Length) break; } bytes = ms.ToArray (); } } response.Close (); return bytes; } public void DownloadToStream (string url, Stream output) { if (url == null) throw new ArgumentNullException ("url"); if (output == null) throw new ArgumentNullException ("output"); if (!output.CanWrite) throw new ArgumentException ("The stream is not writeable", "output"); HttpWebRequest req = AuthenticatedRequest (url); req.AutomaticDecompression = DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse) req.GetResponse (); byte [] bytes = null; using (Stream stream = response.GetResponseStream ()) { bytes = new byte [4096]; int nread; while ((nread = stream.Read (bytes, 0, bytes.Length)) > 0) { output.Write (bytes, 0, nread); } } response.Close (); } public string User { get { return user; } } public GoogleService Service { get { return service; } } internal string AuthToken { get { return auth; } } } }
// Copyright 2021, 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. using Google.Api.Ads.Common.Lib; using System; using System.Collections.Generic; using System.Reflection; namespace Google.Api.Ads.AdManager.Lib { /// <summary> /// Lists all the services available through this library. /// </summary> public partial class AdManagerService : AdsService { /// <summary> /// All the services available in v202108. /// </summary> public class v202108 { /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ActivityGroupService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ActivityGroupService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ActivityService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ActivityService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/AdExclusionRuleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdExclusionRuleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/AdjustmentRuleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdjustmentService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/AdRuleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdRuleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/AudienceSegmentService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AudienceSegmentService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CdnConfigurationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CdnConfigurationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CmsMetadataService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CmsMetadataService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ContactService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ContactService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CompanyService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CompanyService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ContentBundleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ContentBundleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ContentService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ContentService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CreativeService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CreativeReviewService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeReviewService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CreativeSetService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeSetService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CreativeTemplateService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeTemplateService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CreativeWrapperService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeWrapperService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CustomFieldService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CustomFieldService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/CustomTargetingService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CustomTargetingService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/DaiAuthenticationKeyService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature DaiAuthenticationKeyService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/DaiEncodingProfileService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature DaiEncodingProfileService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ForecastService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ForecastService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/InventoryService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature InventoryService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/LabelService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LabelService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/LineItemTemplateService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LineItemTemplateService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/LineItemService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LineItemService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/LineItemCreativeAssociationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LineItemCreativeAssociationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/LiveStreamEventService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LiveStreamEventService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/MobileApplicationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MobileApplicationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/NativeStyleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature NativeStyleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/NetworkService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature NetworkService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/OrderService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature OrderService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/PlacementService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature PlacementService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ProposalService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature ProposalService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ProposalLineItemService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature ProposalLineItemService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/PublisherQueryLanguageService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature PublisherQueryLanguageService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/ReportService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ReportService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/SiteService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SiteService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/StreamActivityMonitorService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature StreamActivityMonitorService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/SuggestedAdUnitService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SuggestedAdUnitService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/TargetingPresetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TargetingPresetService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/TeamService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TeamService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/UserService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature UserService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202108/UserTeamAssociationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature UserTeamAssociationService; /// <summary> /// Factory type for v202108 services. /// </summary> public static readonly Type factoryType = typeof(AdManagerServiceFactory); /// <summary> /// Static constructor to initialize the service constants. /// </summary> static v202108() { ActivityGroupService = AdManagerService.MakeServiceSignature("v202108", "ActivityGroupService"); ActivityService = AdManagerService.MakeServiceSignature("v202108", "ActivityService"); AdExclusionRuleService = AdManagerService.MakeServiceSignature("v202108", "AdExclusionRuleService"); AdjustmentService = AdManagerService.MakeServiceSignature("v202108", "AdjustmentService"); AdRuleService = AdManagerService.MakeServiceSignature("v202108", "AdRuleService"); AudienceSegmentService = AdManagerService.MakeServiceSignature("v202108", "AudienceSegmentService"); CdnConfigurationService = AdManagerService.MakeServiceSignature("v202108", "CdnConfigurationService"); CmsMetadataService = AdManagerService.MakeServiceSignature("v202108", "CmsMetadataService"); CompanyService = AdManagerService.MakeServiceSignature("v202108", "CompanyService"); ContactService = AdManagerService.MakeServiceSignature("v202108", "ContactService"); ContentBundleService = AdManagerService.MakeServiceSignature("v202108", "ContentBundleService"); ContentService = AdManagerService.MakeServiceSignature("v202108", "ContentService"); CreativeService = AdManagerService.MakeServiceSignature("v202108", "CreativeService"); CreativeReviewService = AdManagerService.MakeServiceSignature("v202108", "CreativeReviewService"); CreativeSetService = AdManagerService.MakeServiceSignature("v202108", "CreativeSetService"); CreativeTemplateService = AdManagerService.MakeServiceSignature("v202108", "CreativeTemplateService"); CreativeWrapperService = AdManagerService.MakeServiceSignature("v202108", "CreativeWrapperService"); CustomTargetingService = AdManagerService.MakeServiceSignature("v202108", "CustomTargetingService"); CustomFieldService = AdManagerService.MakeServiceSignature("v202108", "CustomFieldService"); DaiAuthenticationKeyService = AdManagerService.MakeServiceSignature("v202108", "DaiAuthenticationKeyService"); DaiEncodingProfileService = AdManagerService.MakeServiceSignature("v202108", "DaiEncodingProfileService"); ForecastService = AdManagerService.MakeServiceSignature("v202108", "ForecastService"); InventoryService = AdManagerService.MakeServiceSignature("v202108", "InventoryService"); LabelService = AdManagerService.MakeServiceSignature("v202108", "LabelService"); LineItemTemplateService = AdManagerService.MakeServiceSignature("v202108", "LineItemTemplateService"); LineItemService = AdManagerService.MakeServiceSignature("v202108", "LineItemService"); LineItemCreativeAssociationService = AdManagerService.MakeServiceSignature("v202108", "LineItemCreativeAssociationService"); LiveStreamEventService = AdManagerService.MakeServiceSignature("v202108", "LiveStreamEventService"); MobileApplicationService = AdManagerService.MakeServiceSignature("v202108", "MobileApplicationService"); NativeStyleService = AdManagerService.MakeServiceSignature("v202108", "NativeStyleService"); NetworkService = AdManagerService.MakeServiceSignature("v202108", "NetworkService"); OrderService = AdManagerService.MakeServiceSignature("v202108", "OrderService"); PlacementService = AdManagerService.MakeServiceSignature("v202108", "PlacementService"); ProposalService = AdManagerService.MakeServiceSignature("v202108", "ProposalService"); ProposalLineItemService = AdManagerService.MakeServiceSignature("v202108", "ProposalLineItemService"); PublisherQueryLanguageService = AdManagerService.MakeServiceSignature("v202108", "PublisherQueryLanguageService"); ReportService = AdManagerService.MakeServiceSignature("v202108", "ReportService"); SiteService = AdManagerService.MakeServiceSignature("v202108", "SiteService"); StreamActivityMonitorService = AdManagerService.MakeServiceSignature("v202108", "StreamActivityMonitorService"); SuggestedAdUnitService = AdManagerService.MakeServiceSignature("v202108", "SuggestedAdUnitService"); TargetingPresetService = AdManagerService.MakeServiceSignature("v202108", "TargetingPresetService"); TeamService = AdManagerService.MakeServiceSignature("v202108", "TeamService"); UserService = AdManagerService.MakeServiceSignature("v202108", "UserService"); UserTeamAssociationService = AdManagerService.MakeServiceSignature("v202108", "UserTeamAssociationService"); } } } }
//----------------------------------------------------------------------- // <copyright file="GlobalSerializationConfig.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // 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_EDITOR namespace Stratus.OdinSerializer.Utilities.Editor { using System; using System.Linq; using UnityEditor; public enum AssemblyImportSettings { BuildOnly, EditorOnly, BuildAndEditor, Exclude, } public static class OdinSerializationBuiltSettingsConfig { public static readonly OdinSerializationBuiltSettings AOT = new AOTImportSettingsConfig(); public static readonly OdinSerializationBuiltSettings JIT = new JITImportSettingsConfig(); public static readonly OdinSerializationBuiltSettings EditorOnly = new EditorOnlyImportSettingsConfig(); public static OdinSerializationBuiltSettings Current { get { var buildGroup = EditorUserBuildSettings.selectedBuildTargetGroup; #if UNITY_5_6_OR_NEWER var backend = PlayerSettings.GetScriptingBackend(buildGroup); #else var backend = (ScriptingImplementation)PlayerSettings.GetPropertyInt("ScriptingBackend", buildGroup); #endif if (backend != ScriptingImplementation.Mono2x) { return AOT; } var target = EditorUserBuildSettings.activeBuildTarget; if (OdinAssemblyImportSettingsUtility.JITPlatforms.Any(p => p == target)) { return JIT; } else { return AOT; } } } [MenuItem("Tools/Odin Serializer/Refresh Assembly Import Settings")] public static void RefreshAssemblyImportSettings() { Current.Apply(); } } public static class OdinAssemblyImportSettingsUtility { public static readonly BuildTarget[] Platforms = Enum.GetValues(typeof(BuildTarget)) .Cast<BuildTarget>() .Where(t => t >= 0 && typeof(BuildTarget).GetMember(t.ToString())[0].IsDefined(typeof(ObsoleteAttribute), false) == false) .ToArray(); public static readonly BuildTarget[] JITPlatforms = new BuildTarget[] { #if UNITY_2017_3_OR_NEWER BuildTarget.StandaloneOSX, #else BuildTarget.StandaloneOSXIntel, BuildTarget.StandaloneOSXIntel64, BuildTarget.StandaloneOSXUniversal, #endif BuildTarget.StandaloneWindows, BuildTarget.StandaloneWindows64, BuildTarget.StandaloneLinux, BuildTarget.StandaloneLinux64, BuildTarget.StandaloneLinuxUniversal, BuildTarget.Android, }; public static void ApplyImportSettings(string assemblyFilePath, AssemblyImportSettings importSettings) { bool includeInBuild = false; bool includeInEditor = false; switch (importSettings) { case AssemblyImportSettings.BuildAndEditor: includeInBuild = true; includeInEditor = true; break; case AssemblyImportSettings.BuildOnly: includeInBuild = true; break; case AssemblyImportSettings.EditorOnly: includeInEditor = true; break; case AssemblyImportSettings.Exclude: break; } ApplyImportSettings(assemblyFilePath, includeInBuild, includeInEditor); } private static void ApplyImportSettings(string assemblyFilePath, bool includeInBuild, bool includeInEditor) { var importer = (PluginImporter)AssetImporter.GetAtPath(assemblyFilePath); #if UNITY_5_6_OR_NEWER if (importer.GetCompatibleWithAnyPlatform() != includeInBuild || Platforms.Any(p => importer.GetCompatibleWithPlatform(p) != includeInBuild) || (includeInBuild && importer.GetExcludeEditorFromAnyPlatform() != !includeInEditor || importer.GetCompatibleWithEditor())) { importer.ClearSettings(); importer.SetCompatibleWithAnyPlatform(includeInBuild); Platforms.ForEach(p => importer.SetCompatibleWithPlatform(p, includeInBuild)); if (includeInBuild) { importer.SetExcludeEditorFromAnyPlatform(!includeInEditor); } else { importer.SetCompatibleWithEditor(includeInEditor); } importer.SaveAndReimport(); } #else if (importer.GetCompatibleWithAnyPlatform() != includeInBuild || Platforms.Any(p => importer.GetCompatibleWithPlatform(p) != includeInBuild) || importer.GetCompatibleWithEditor() != includeInEditor) { importer.SetCompatibleWithAnyPlatform(includeInBuild); Platforms.ForEach(p => importer.SetCompatibleWithPlatform(p, includeInBuild)); importer.SetCompatibleWithEditor(includeInEditor); importer.SaveAndReimport(); } #endif } } public abstract class OdinSerializationBuiltSettings { protected const string NoEditorSerializationMeta = "Assets/Plugins/Sirenix/Assemblies/NoEditor/Sirenix.Serialization.dll"; protected const string NoEditorUtilityMeta = "Assets/Plugins/Sirenix/Assemblies/NoEditor/Sirenix.Utilities.dll"; protected const string NoEmitNoEditorSerializationMeta = "Assets/Plugins/Sirenix/Assemblies/NoEmitAndNoEditor/Sirenix.Serialization.dll"; protected const string NoEmitNoEditorUtilityMeta = "Assets/Plugins/Sirenix/Assemblies/NoEmitAndNoEditor/Sirenix.Utilities.dll"; protected const string SerializationConfigMeta = "Assets/Plugins/Sirenix/Assemblies/Sirenix.Serialization.Config.dll"; public abstract void Apply(); } public class AOTImportSettingsConfig : OdinSerializationBuiltSettings { public override void Apply() { OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEmitNoEditorSerializationMeta, AssemblyImportSettings.BuildOnly); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEmitNoEditorUtilityMeta, AssemblyImportSettings.BuildOnly); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEditorSerializationMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEditorUtilityMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(SerializationConfigMeta, AssemblyImportSettings.BuildAndEditor); } } public class JITImportSettingsConfig : OdinSerializationBuiltSettings { public override void Apply() { OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEditorSerializationMeta, AssemblyImportSettings.BuildOnly); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEditorUtilityMeta, AssemblyImportSettings.BuildOnly); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEmitNoEditorSerializationMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEmitNoEditorUtilityMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(SerializationConfigMeta, AssemblyImportSettings.BuildAndEditor); } } public class EditorOnlyImportSettingsConfig : OdinSerializationBuiltSettings { public override void Apply() { OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEditorSerializationMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEditorUtilityMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEmitNoEditorSerializationMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(NoEmitNoEditorUtilityMeta, AssemblyImportSettings.Exclude); OdinAssemblyImportSettingsUtility.ApplyImportSettings(SerializationConfigMeta, AssemblyImportSettings.EditorOnly); } } } #endif
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int32 : IComparable, IConvertible, IFormattable, IComparable<int>, IEquatable<int>, ISpanFormattable { private readonly int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns : // 0 if the values are equal // Negative number if _value is less than value // Positive number if _value is more than value // null is considered to be less than any instance, hence returns positive number // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo(object value) { if (value == null) { return 1; } if (value is int) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. int i = (int)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeInt32); } public int CompareTo(int value) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(object obj) { if (!(obj is int)) { return false; } return m_value == ((int)obj).m_value; } [NonVersionable] public bool Equals(int obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } public override string ToString() { return Number.FormatInt32(m_value, null, null); } public string ToString(string format) { return Number.FormatInt32(m_value, format, null); } public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } public string ToString(string format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } public static int Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static int Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse(string s, out int result) { if (s == null) { result = 0; return false; } return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out int result) { return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto_defs/grpc/TransactionService.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 VirtualWallet.Proto.Grpc { /// <summary>Holder for reflection information generated from proto_defs/grpc/TransactionService.proto</summary> public static partial class TransactionServiceReflection { #region Descriptor /// <summary>File descriptor for proto_defs/grpc/TransactionService.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TransactionServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cihwcm90b19kZWZzL2dycGMvVHJhbnNhY3Rpb25TZXJ2aWNlLnByb3RvEhhW", "aXJ0dWFsV2FsbGV0LlByb3RvLkdycGMaG2dvb2dsZS9wcm90b2J1Zi9lbXB0", "eS5wcm90bxolcHJvdG9fZGVmcy9tZXNzYWdlcy9UcmFuc2FjdGlvbi5wcm90", "byJACgxUb3BVcFJlcXVlc3QSDgoGZGVhbGVyGAEgASgJEhAKCGN1c3RvbWVy", "GAIgASgJEg4KBmFtb3VudBgDIAEoBCJBCg9UcmFuc2ZlclJlcXVlc3QSDgoG", "b3JpZ2luGAEgASgJEg4KBnRhcmdldBgCIAEoCRIOCgZhbW91bnQYAyABKAQi", "QgoPUHVyY2hhc2VSZXF1ZXN0Eg0KBXN0b3JlGAEgASgJEhAKCGN1c3RvbWVy", "GAIgASgJEg4KBmFtb3VudBgDIAEoBCIbCg1UcmFuc2FjdGlvbklkEgoKAmlk", "GAEgASgEMoEEChJUcmFuc2FjdGlvblNlcnZpY2USWQoSR2V0QWxsVHJhbnNh", "Y3Rpb25zEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GikuVmlydHVhbFdhbGxl", "dC5Qcm90by5NZXNzYWdlcy5UcmFuc2FjdGlvbjABEl0KCE5ld1RvcFVwEiYu", "VmlydHVhbFdhbGxldC5Qcm90by5HcnBjLlRvcFVwUmVxdWVzdBopLlZpcnR1", "YWxXYWxsZXQuUHJvdG8uTWVzc2FnZXMuVHJhbnNhY3Rpb24SYwoLTmV3VHJh", "bnNmZXISKS5WaXJ0dWFsV2FsbGV0LlByb3RvLkdycGMuVHJhbnNmZXJSZXF1", "ZXN0GikuVmlydHVhbFdhbGxldC5Qcm90by5NZXNzYWdlcy5UcmFuc2FjdGlv", "bhJjCgtOZXdQdXJjaGFzZRIpLlZpcnR1YWxXYWxsZXQuUHJvdG8uR3JwYy5Q", "dXJjaGFzZVJlcXVlc3QaKS5WaXJ0dWFsV2FsbGV0LlByb3RvLk1lc3NhZ2Vz", "LlRyYW5zYWN0aW9uEmcKD1ZpZXdUcmFuc2FjdGlvbhInLlZpcnR1YWxXYWxs", "ZXQuUHJvdG8uR3JwYy5UcmFuc2FjdGlvbklkGikuVmlydHVhbFdhbGxldC5Q", "cm90by5NZXNzYWdlcy5UcmFuc2FjdGlvbjABYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::VirtualWallet.Proto.Messages.TransactionReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::VirtualWallet.Proto.Grpc.TopUpRequest), global::VirtualWallet.Proto.Grpc.TopUpRequest.Parser, new[]{ "Dealer", "Customer", "Amount" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::VirtualWallet.Proto.Grpc.TransferRequest), global::VirtualWallet.Proto.Grpc.TransferRequest.Parser, new[]{ "Origin", "Target", "Amount" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::VirtualWallet.Proto.Grpc.PurchaseRequest), global::VirtualWallet.Proto.Grpc.PurchaseRequest.Parser, new[]{ "Store", "Customer", "Amount" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::VirtualWallet.Proto.Grpc.TransactionId), global::VirtualWallet.Proto.Grpc.TransactionId.Parser, new[]{ "Id" }, null, null, null) })); } #endregion } #region Messages public sealed partial class TopUpRequest : pb::IMessage<TopUpRequest> { private static readonly pb::MessageParser<TopUpRequest> _parser = new pb::MessageParser<TopUpRequest>(() => new TopUpRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TopUpRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::VirtualWallet.Proto.Grpc.TransactionServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TopUpRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TopUpRequest(TopUpRequest other) : this() { dealer_ = other.dealer_; customer_ = other.customer_; amount_ = other.amount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TopUpRequest Clone() { return new TopUpRequest(this); } /// <summary>Field number for the "dealer" field.</summary> public const int DealerFieldNumber = 1; private string dealer_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Dealer { get { return dealer_; } set { dealer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "customer" field.</summary> public const int CustomerFieldNumber = 2; private string customer_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Customer { get { return customer_; } set { customer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "amount" field.</summary> public const int AmountFieldNumber = 3; private ulong amount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Amount { get { return amount_; } set { amount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TopUpRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TopUpRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Dealer != other.Dealer) return false; if (Customer != other.Customer) return false; if (Amount != other.Amount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Dealer.Length != 0) hash ^= Dealer.GetHashCode(); if (Customer.Length != 0) hash ^= Customer.GetHashCode(); if (Amount != 0UL) hash ^= Amount.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 (Dealer.Length != 0) { output.WriteRawTag(10); output.WriteString(Dealer); } if (Customer.Length != 0) { output.WriteRawTag(18); output.WriteString(Customer); } if (Amount != 0UL) { output.WriteRawTag(24); output.WriteUInt64(Amount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Dealer.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Dealer); } if (Customer.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Customer); } if (Amount != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Amount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TopUpRequest other) { if (other == null) { return; } if (other.Dealer.Length != 0) { Dealer = other.Dealer; } if (other.Customer.Length != 0) { Customer = other.Customer; } if (other.Amount != 0UL) { Amount = other.Amount; } } [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: { Dealer = input.ReadString(); break; } case 18: { Customer = input.ReadString(); break; } case 24: { Amount = input.ReadUInt64(); break; } } } } } public sealed partial class TransferRequest : pb::IMessage<TransferRequest> { private static readonly pb::MessageParser<TransferRequest> _parser = new pb::MessageParser<TransferRequest>(() => new TransferRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TransferRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::VirtualWallet.Proto.Grpc.TransactionServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransferRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransferRequest(TransferRequest other) : this() { origin_ = other.origin_; target_ = other.target_; amount_ = other.amount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransferRequest Clone() { return new TransferRequest(this); } /// <summary>Field number for the "origin" field.</summary> public const int OriginFieldNumber = 1; private string origin_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Origin { get { return origin_; } set { origin_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "target" field.</summary> public const int TargetFieldNumber = 2; private string target_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Target { get { return target_; } set { target_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "amount" field.</summary> public const int AmountFieldNumber = 3; private ulong amount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Amount { get { return amount_; } set { amount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TransferRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TransferRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Origin != other.Origin) return false; if (Target != other.Target) return false; if (Amount != other.Amount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Origin.Length != 0) hash ^= Origin.GetHashCode(); if (Target.Length != 0) hash ^= Target.GetHashCode(); if (Amount != 0UL) hash ^= Amount.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 (Origin.Length != 0) { output.WriteRawTag(10); output.WriteString(Origin); } if (Target.Length != 0) { output.WriteRawTag(18); output.WriteString(Target); } if (Amount != 0UL) { output.WriteRawTag(24); output.WriteUInt64(Amount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Origin.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Origin); } if (Target.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Target); } if (Amount != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Amount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TransferRequest other) { if (other == null) { return; } if (other.Origin.Length != 0) { Origin = other.Origin; } if (other.Target.Length != 0) { Target = other.Target; } if (other.Amount != 0UL) { Amount = other.Amount; } } [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: { Origin = input.ReadString(); break; } case 18: { Target = input.ReadString(); break; } case 24: { Amount = input.ReadUInt64(); break; } } } } } public sealed partial class PurchaseRequest : pb::IMessage<PurchaseRequest> { private static readonly pb::MessageParser<PurchaseRequest> _parser = new pb::MessageParser<PurchaseRequest>(() => new PurchaseRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PurchaseRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::VirtualWallet.Proto.Grpc.TransactionServiceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PurchaseRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PurchaseRequest(PurchaseRequest other) : this() { store_ = other.store_; customer_ = other.customer_; amount_ = other.amount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PurchaseRequest Clone() { return new PurchaseRequest(this); } /// <summary>Field number for the "store" field.</summary> public const int StoreFieldNumber = 1; private string store_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Store { get { return store_; } set { store_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "customer" field.</summary> public const int CustomerFieldNumber = 2; private string customer_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Customer { get { return customer_; } set { customer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "amount" field.</summary> public const int AmountFieldNumber = 3; private ulong amount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Amount { get { return amount_; } set { amount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PurchaseRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PurchaseRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Store != other.Store) return false; if (Customer != other.Customer) return false; if (Amount != other.Amount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Store.Length != 0) hash ^= Store.GetHashCode(); if (Customer.Length != 0) hash ^= Customer.GetHashCode(); if (Amount != 0UL) hash ^= Amount.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 (Store.Length != 0) { output.WriteRawTag(10); output.WriteString(Store); } if (Customer.Length != 0) { output.WriteRawTag(18); output.WriteString(Customer); } if (Amount != 0UL) { output.WriteRawTag(24); output.WriteUInt64(Amount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Store.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Store); } if (Customer.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Customer); } if (Amount != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Amount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PurchaseRequest other) { if (other == null) { return; } if (other.Store.Length != 0) { Store = other.Store; } if (other.Customer.Length != 0) { Customer = other.Customer; } if (other.Amount != 0UL) { Amount = other.Amount; } } [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: { Store = input.ReadString(); break; } case 18: { Customer = input.ReadString(); break; } case 24: { Amount = input.ReadUInt64(); break; } } } } } public sealed partial class TransactionId : pb::IMessage<TransactionId> { private static readonly pb::MessageParser<TransactionId> _parser = new pb::MessageParser<TransactionId>(() => new TransactionId()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TransactionId> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::VirtualWallet.Proto.Grpc.TransactionServiceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransactionId() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransactionId(TransactionId other) : this() { id_ = other.id_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransactionId Clone() { return new TransactionId(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private ulong id_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Id { get { return id_; } set { id_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TransactionId); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TransactionId other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Id != 0UL) hash ^= Id.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 (Id != 0UL) { output.WriteRawTag(8); output.WriteUInt64(Id); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Id != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Id); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TransactionId other) { if (other == null) { return; } if (other.Id != 0UL) { Id = other.Id; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Id = input.ReadUInt64(); break; } } } } } #endregion } #endregion Designer generated code
/* Copyright (c) Microsoft Corporation 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Xml; using System.Xml.Serialization; using Microsoft.Research.Dryad; namespace Microsoft.Research.Dryad.GraphManager { public class DryadLINQApp { public class OptionDescription { public enum OptionCategory { OC_General = 0, OC_Inputs, OC_Outputs, OC_VertexBehavior, OC_LAST }; public OptionCategory m_optionCategory; public int m_optionIndex; public string m_shortName; public string m_longName; public string m_arguments; public string m_descriptionText; public OptionDescription() { } public OptionDescription(OptionCategory optionCatagory, int index, string shortName, string longName, string args, string desc) { m_optionCategory = optionCatagory; m_optionIndex = index; m_shortName = shortName; m_longName = longName; m_arguments = args; m_descriptionText = desc; } }; enum DryadLINQAppOptions { BDAO_EmbeddedResource, BDAO_ReferenceResource, BDJAO_AMD64, BDJAO_I386, BDJAO_Retail, BDJAO_Debug, DNAO_MaxAggregateInputs, DNAO_MaxAggregateFilterInputs, DNAO_AggregateThreshold, DNAO_NoClusterAffinity, DNAO_LAST }; static OptionDescription []s_dryadLinqOptionArray = new OptionDescription[] { new OptionDescription ( OptionDescription.OptionCategory.OC_VertexBehavior, (int)DryadLINQAppOptions.BDJAO_AMD64, "amd64", "useamd64binary", "", "Dummy argument for legacy reasons" ), new OptionDescription ( OptionDescription.OptionCategory.OC_VertexBehavior, (int)DryadLINQAppOptions.BDJAO_I386, "i386", "usei386binary", "", "Dummy argument for legacy reasons" ), new OptionDescription ( OptionDescription.OptionCategory.OC_VertexBehavior, (int)DryadLINQAppOptions.BDJAO_Retail, "retail", "useretailbinary", "", "Dummy argument for legacy reasons" ), new OptionDescription ( OptionDescription.OptionCategory.OC_VertexBehavior, (int)DryadLINQAppOptions.BDJAO_Debug, "debug", "usedebugbinary", "", "Dummy argument for legacy reasons" ), new OptionDescription ( OptionDescription.OptionCategory.OC_General, (int)DryadLINQAppOptions.DNAO_MaxAggregateInputs, "mai", "maxaggregateinputs", "<maxInputs>", "Only allow aggregate vertices to use up to maxInputs inputs." ), new OptionDescription ( OptionDescription.OptionCategory.OC_General, (int)DryadLINQAppOptions.DNAO_MaxAggregateFilterInputs, "mafi", "maxaggregatefilterinputs", "<maxInputs>", "Only allow aggregate filter vertices to use up to maxInputs inputs." ), new OptionDescription ( OptionDescription.OptionCategory.OC_General, (int)DryadLINQAppOptions.DNAO_AggregateThreshold, "at", "aggregatethreshold", "<dataSize>", "Only allow aggregate and aggregate filter vertices to use inputs up to a total of size dataSize. dataSize can be specified as a number of bytes or with the (case-insensitive) suffix KB, MB, GB, TB, PB, i.e. 12KB. If a suffix is present then fractions are allowed, e.g. 20.5MB." ), new OptionDescription ( OptionDescription.OptionCategory.OC_General, (int)DryadLINQAppOptions.DNAO_NoClusterAffinity, "nca", "noclusteraffinity", "", "By default, LINQToHPC does not process DSC filesets from a different cluster. Specifying this flag overrides that" ) }; SortedDictionary<string, OptionDescription> m_optionMap; private DrGraph m_graph; private bool m_clusterAffinity; private int m_maxAggregateInputs; private int m_maxAggregateFilterInputs; private UInt64 m_aggregateThreshold; private UInt64 m_startTime; private FileStream m_identityMapFile; public DryadLINQApp(DrGraph graph) { m_graph = graph; m_clusterAffinity = true; m_maxAggregateInputs = 150; m_maxAggregateFilterInputs = 32; m_aggregateThreshold = 1024*1024*1024; // 1GB m_startTime = graph.GetCluster().GetCurrentTimeStamp(); m_identityMapFile = null; m_optionMap = new SortedDictionary<string,OptionDescription>(); AddOptionsToMap(s_dryadLinqOptionArray); } public void AddOptionsToMap(OptionDescription[] optionArray) { foreach (OptionDescription option in optionArray) { m_optionMap.Add(option.m_shortName, option); m_optionMap.Add(option.m_longName, option); } } public void PrintOptionUsage(OptionDescription option) { Console.WriteLine(" {-{0}|-{1}} {2}", option.m_shortName, option.m_longName, option.m_arguments); Console.WriteLine(" {0}", option.m_descriptionText); } static string[] s_optionCategoryName = new string[] { "General options", "Options to specify job inputs", "Options to specify job outputs", "Options to control vertex behavior" }; public void PrintCategoryUsage(OptionDescription.OptionCategory category) { Console.WriteLine(s_optionCategoryName[(int)category]); foreach (KeyValuePair<string, OptionDescription> kvp in m_optionMap) { OptionDescription option = kvp.Value; if (option.m_optionCategory == category && kvp.Key == option.m_shortName) { PrintOptionUsage(option); } } } public void PrintUsage(string exeName) { string leafName = Path.GetFileName(exeName); Console.WriteLine("usage: {0} [--debugbreak] [--popup] <options> <appSpecificArguments>\n<options> fall into the following categories:", leafName); for (OptionDescription.OptionCategory i=0; i<OptionDescription.OptionCategory.OC_LAST; ++i) { PrintCategoryUsage(i); } } public bool ParseCommandLineFlags(string[] args) { bool retVal = true; for (int index=0; index < args.Length; index++) { string arg = args[index].Substring(args[index].IndexOf("-")+1); OptionDescription option = null; m_optionMap.TryGetValue(arg, out option); if (option == null) { retVal = false; break; } int optionIndex = option.m_optionIndex; switch (optionIndex) { case (int)DryadLINQAppOptions.BDJAO_AMD64: case (int)DryadLINQAppOptions.BDJAO_I386: case (int)DryadLINQAppOptions.BDJAO_Retail: case (int)DryadLINQAppOptions.BDJAO_Debug: break; case (int)DryadLINQAppOptions.DNAO_MaxAggregateInputs: if ((index + 1) >= args.Length) { DryadLogger.LogCritical(String.Format("The argument for option '{0}' was missing.\n", args[index])); retVal = false; } else { int maxInputs; if (!Int32.TryParse(args[index+1], out maxInputs)) { DryadLogger.LogCritical(String.Format("The argument '{0}' for option '{1}' could not be parsed as an integer.\n", args[index + 1], args[index])); retVal = false; } else { m_maxAggregateInputs = maxInputs; index++; } } break; case (int)DryadLINQAppOptions.DNAO_MaxAggregateFilterInputs: if ((index + 1) >= args.Length) { DryadLogger.LogCritical(String.Format("The argument for option '{0}' was missing.\n", args[index])); retVal = false; } else { int maxInputs; if (!Int32.TryParse(args[index+1], out maxInputs)) { DryadLogger.LogCritical(String.Format("The argument '{0}' for option '{1}' could not be parsed as an integer.\n", args[index + 1], args[index])); retVal = false; } else { m_maxAggregateFilterInputs = maxInputs; index++; } } break; case (int)DryadLINQAppOptions.DNAO_AggregateThreshold: if ((index + 1) >= args.Length) { DryadLogger.LogCritical(String.Format("The argument for option '{0}' was missing.\n", args[index])); retVal = false; } else { UInt64 threshold; if (!UInt64.TryParse(args[index+1], out threshold)) { DryadLogger.LogCritical(String.Format("The argument '{0}' for option '{1}' could not be parsed as a UIN64.\n", args[index + 1], args[index])); retVal = false; } else { m_aggregateThreshold = threshold; index++; } } break; case (int)DryadLINQAppOptions.DNAO_NoClusterAffinity: m_clusterAffinity = false; break; default: DryadLogger.LogCritical(String.Format("Unknown command-line option {0}\n", optionIndex)); retVal = false; break; } } if (!retVal) { PrintUsage(args[0]); } return retVal; } internal bool ExtractReferenceResourceNameAndUri(string resourceSpec, ref string resourceUri, ref string resourceName) { // reference resourceSpec is of type name@uri string name = resourceSpec.Substring(0, resourceSpec.IndexOf('@')); string uri = resourceSpec.Substring(resourceSpec.IndexOf('@')); // resourceSpecCopy now is name\0uri with resourceName pointing to name and resourceUri pointing to uri resourceUri = uri; resourceName = name; return true; } public DrGraph GetGraph() { return m_graph; } public DrUniverse GetUniverse() { return m_graph.GetCluster().GetUniverse(); } public void SetClusterAffinity(bool flag) { m_clusterAffinity = flag; } public bool GetClusterAffinity() { return m_clusterAffinity; } public int GetMaxAggregateInputs() { return m_maxAggregateInputs; } public UInt64 GetAggregateThreshold() { return m_aggregateThreshold; } public int GetMaxAggregateFilterInputs() { return m_maxAggregateFilterInputs; } public UInt64 GetStartTime() { return m_startTime; } public void SetXmlFileName(string xml) { if (xml.Length >= 3) { string dup = xml.Substring(0, xml.Length-3); dup += "map"; m_identityMapFile = File.Open(dup, FileMode.Create); } } public FileStream GetIdentityMapFile() { return m_identityMapFile; } } } // namespace DryadLINQ
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass001.genclass001; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Reflection; public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass<T> { public string Property_string { set; get; } public float?[] Property_FloatNullArr { get; set; } public dynamic Property_Dynamic { get; set; } public T Property_T { get; set; } // Move declarations to the call site } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass001.genclass001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass001.genclass001; // <Title> Tests generic class auto property used in anonymous method.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass<int> mc = new MemberClass<int>(); mc.Property_string = "Test"; dynamic dy = mc; Func<string> func = delegate () { return dy.Property_string; } ; if (func() == "Test") return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass002.genclass002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass002.genclass002; // <Title> Tests generic class auto property used in query expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var list = new List<string>() { null, "b", null, "a" } ; var mc = new MemberClass<string>(); mc.Property_Dynamic = "a"; dynamic dy = mc; var result = list.Where(p => p == (string)dy.Property_Dynamic).ToList(); if (result.Count == 1 && result[0] == "a") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass003.genclass003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass003.genclass003; // <Title> Tests generic class auto property used in collection initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass<string> mc = new MemberClass<string>(); mc.Property_string = "Test1"; mc.Property_T = "Test2"; mc.Property_Dynamic = "Test3"; dynamic dy = mc; List<string> list = new List<string>() { (string)dy.Property_string, (string)dy.Property_T, (string)dy.Property_Dynamic } ; if (list.Count == 3 && list[0] == "Test1" && list[1] == "Test2" && list[2] == "Test3") return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass005.genclass005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass005.genclass005; // <Title> Tests generic class auto property used in lambda.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { private int _field; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var mc = new MemberClass<Test>(); dynamic dy = mc; dy.Property_T = new Test() { _field = 10 } ; Func<int, int, Test> func = (int arg1, int arg2) => dy.Property_T; if (func(1, 2)._field == 10) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass006.genclass006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass006.genclass006; // <Title> Tests generic class auto property used in using block.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; using System.IO; using System.Text; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass<bool> mc = new MemberClass<bool>(); mc.Property_string = "abc"; mc.Property_T = true; dynamic dy = mc; string result = null; using (MemoryStream sm = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(sm)) { sw.WriteLine((string)dy.Property_string); sw.Flush(); sm.Position = 0; using (StreamReader sr = new StreamReader(sm, (bool)dy.Property_T)) { result = sr.ReadToEnd(); } } } if (result.Trim() == "abc") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass007.genclass007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass007.genclass007; // <Title> Tests generic class auto property used inside #if, #else block.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { return Test.TestMethod() == 1 ? 0 : 1; } public static int TestMethod() { #if c1 MemberClass<int> mc = new MemberClass<int>(); mc.Property_T = 0; dynamic dy = mc; return dy.Property_T; #else MemberClass<int> mc = new MemberClass<int>(); mc.Property_T = 1; dynamic dy = mc; return dy.Property_T; #endif } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass008.genclass008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass008.genclass008; // <Title> Tests generic class auto property used in arguments to method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); var mc = new MemberClass<int>(); mc.Property_T = 2; mc.Property_string = "a"; dynamic dy = mc; int result1 = t.TestMethod(dy.Property_T); int result2 = Test.TestMethod(dy.Property_string); if (result1 == 0 && result2 == 0) return 0; else return 1; } public int TestMethod(int i) { if (i == 2) { return 0; } else { return 1; } } public static int TestMethod(string s) { if (s == "a") { return 0; } else { return 1; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass009.genclass009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass009.genclass009; // <Title> Tests generic class auto property used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var mc = new MemberClass<string>(); mc.Property_Dynamic = 10; mc.Property_string = null; mc.Property_T = string.Empty; dynamic dy = mc; var result = new object[] { dy.Property_Dynamic, dy.Property_string, dy.Property_T } ; if (result.Length == 3 && (int)result[0] == 10 && result[1] == null && (string)result[2] == string.Empty) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass010.genclass010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass010.genclass010; // <Title> Tests generic class auto property used in implicit operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { public class InnerTest1 { public int field; public static implicit operator InnerTest2(InnerTest1 t1) { MemberClass<object> mc = new MemberClass<object>(); mc.Property_Dynamic = t1.field; dynamic dy = mc; return new InnerTest2() { field = dy.Property_Dynamic } ; } } public class InnerTest2 { public int field; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { InnerTest1 t1 = new InnerTest1() { field = 10 } ; InnerTest2 result1 = t1; //implicit InnerTest2 result2 = (InnerTest2)t1; //explicit return (result1.field == 10 && result2.field == 10) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass012.genclass012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass012.genclass012; // <Title> Tests generic class auto property used in extension method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { public string Field; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = "abc".ExReturnTest(); if (t.Field == "abc") return 0; return 1; } } static public class Extension { public static Test ExReturnTest(this string s) { var mc = new MemberClass<string>(); mc.Property_T = s; dynamic dy = mc; return new Test() { Field = dy.Property_T } ; } } //</Code> }
/******************************************************************************* * Copyright 2017 ROBOTIS CO., LTD. * * 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. *******************************************************************************/ /* Author: Ryu Woon Jung (Leon) */ // // ********* MultiPort Example ********* // // // Available Dynamixel model on this example : All models using Protocol 2.0 // This example is designed for using two Dynamixel PRO 54-200, and two USB2DYNAMIXELs. // To use another Dynamixel model, such as X series, see their details in E-Manual(emanual.robotis.com) and edit below variables yourself. // Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600) // using System; using System.Runtime.InteropServices; using dynamixel_sdk; namespace read_write { class ReadWrite { // Control table address public const int ADDR_PRO_TORQUE_ENABLE = 562; // Control table address is different in Dynamixel model public const int ADDR_PRO_GOAL_POSITION = 596; public const int ADDR_PRO_PRESENT_POSITION = 611; // Protocol version public const int PROTOCOL_VERSION = 2; // See which protocol version is used in the Dynamixel // Default setting public const int DXL1_ID = 1; // Dynamixel ID: 1 public const int DXL2_ID = 2; // Dynamixel ID: 2 public const int BAUDRATE = 57600; public const string DEVICENAME1 = "COM1"; // Check which port is being used on your controller public const string DEVICENAME2 = "COM2"; // ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*" public const int TORQUE_ENABLE = 1; // Value for enabling the torque public const int TORQUE_DISABLE = 0; // Value for disabling the torque public const int DXL_MINIMUM_POSITION_VALUE = -150000; // Dynamixel will rotate between this value public const int DXL_MAXIMUM_POSITION_VALUE = 150000; // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.) public const int DXL_MOVING_STATUS_THRESHOLD = 20; // Dynamixel moving status threshold public const byte ESC_ASCII_VALUE = 0x1b; public const int COMM_SUCCESS = 0; // Communication Success result value public const int COMM_TX_FAIL = -1001; // Communication Tx Failed static void Main(string[] args) { // Initialize PortHandler Structs // Set the port path // Get methods and members of PortHandlerLinux or PortHandlerWindows int port_num1 = dynamixel.portHandler(DEVICENAME1); int port_num2 = dynamixel.portHandler(DEVICENAME2); // Initialize PacketHandler Structs dynamixel.packetHandler(); int index = 0; int dxl_comm_result = COMM_TX_FAIL; // Communication result int[] dxl_goal_position = new int[2]{ DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE }; // Goal position byte dxl_error = 0; // Dynamixel error Int32 dxl1_present_position = 0, dxl2_present_position = 0; // Present position // Open port1 if (dynamixel.openPort(port_num1)) { Console.WriteLine("Succeeded to open the port!"); } else { Console.WriteLine("Failed to open the port!"); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); return; } // Open port2 if (dynamixel.openPort(port_num2)) { Console.WriteLine("Succeeded to open the port!"); } else { Console.WriteLine("Failed to open the port!"); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); return; } // Set port1 baudrate if (dynamixel.setBaudRate(port_num1, BAUDRATE)) { Console.WriteLine("Succeeded to change the baudrate!"); } else { Console.WriteLine("Failed to change the baudrate!"); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); return; } // Set port2 baudrate if (dynamixel.setBaudRate(port_num2, BAUDRATE)) { Console.WriteLine("Succeeded to change the baudrate!"); } else { Console.WriteLine("Failed to change the baudrate!"); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); return; } // Enable Dynamixel#1 Torque dynamixel.write1ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } else { Console.WriteLine("Dynamixel#{0} has been successfully connected ", DXL1_ID); } // Enable Dynamixel#2 Torque dynamixel.write1ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } else { Console.WriteLine("Dynamixel#{0} has been successfully connected ", DXL2_ID); } while (true) { Console.WriteLine("Press any key to continue! (or press ESC to quit!)"); if (Console.ReadKey().KeyChar == ESC_ASCII_VALUE) break; // Write Dynamixel#1 goal position dynamixel.write4ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_PRO_GOAL_POSITION, (UInt32)dxl_goal_position[index]); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Write Dynamixel#2 goal position dynamixel.write4ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_PRO_GOAL_POSITION, (UInt32)dxl_goal_position[index]); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } do { // Read Dynamixel#1 present position dxl1_present_position = (Int32)dynamixel.read4ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_PRO_PRESENT_POSITION); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Read Dynamixel#2 present position dxl2_present_position = (Int32)dynamixel.read4ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_PRO_PRESENT_POSITION); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } Console.WriteLine("[ID: {0}] GoalPos: {1} PresPos: {2} [ID: {3}] GoalPos: {4} PresPos: {5}", DXL1_ID, dxl_goal_position[index], dxl1_present_position, DXL2_ID, dxl_goal_position[index], dxl2_present_position); } while ((Math.Abs(dxl_goal_position[index] - dxl1_present_position) > DXL_MOVING_STATUS_THRESHOLD) || (Math.Abs(dxl_goal_position[index] - dxl2_present_position) > DXL_MOVING_STATUS_THRESHOLD)); // Change goal position if (index == 0) { index = 1; } else { index = 0; } } // Disable Dynamixel#1 Torque dynamixel.write1ByteTxRx(port_num1, PROTOCOL_VERSION, DXL1_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num1, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num1, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Disable Dynamixel#2 Torque dynamixel.write1ByteTxRx(port_num2, PROTOCOL_VERSION, DXL2_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num2, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num2, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Close port1 dynamixel.closePort(port_num1); // Close port2 dynamixel.closePort(port_num2); return; } } }
using System; using System.Windows.Forms; using System.Collections; using System.Drawing; using PrimerProForms; using PrimerProObjects; //using PrimerProLocalization; using GenLib; namespace PrimerProSearch { /// <summary> /// /// </summary> public class BuildableWordSearchWL : Search { //Search parameters private ArrayList m_Graphemes; //list of graphemes for buildable words private ArrayList m_Highlights; //graphemes to highlight private bool m_BrowseView; //Display in browse view private SearchOptions m_SearchOptions; //search options filter private string m_Title; //search title private Settings m_Settings; //Application Settings private PSTable m_PSTable; //Parts of Speech private GraphemeInventory m_GI; //Grapheme Inventory private GraphemeTaughtOrder m_GraphemesTaught; //Grapheme Taught Order private Font m_DefaultFont; //Default Font //Search Definition tags private const string kGrapheme = "grapheme"; private const string kHighlight = "highlight"; private const string kBrowseView = "browseview"; //private const string kTitle = "Buildable Words Search"; //private const string kSearch = "Processing Buildable Word Search"; public BuildableWordSearchWL(int number, Settings s) : base(number, SearchDefinition.kBuildable) { m_Graphemes = null; m_Highlights = null; m_BrowseView = false; m_SearchOptions = null; m_Settings = s; //m_Title = BuildableWordsSearchWL.kTitle; m_Title = m_Settings.LocalizationTable.GetMessage("BuildableWordsSearchWLT"); if (m_Title == "") m_Title = "Buildale Words Search"; m_PSTable = m_Settings.PSTable; m_GI = m_Settings.GraphemeInventory; m_GraphemesTaught = m_Settings.GraphemesTaught; m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont(); } public ArrayList Graphemes { get { return m_Graphemes; } set { m_Graphemes = value; } } public ArrayList Highlights { get { return m_Highlights; } set { m_Highlights = value; } } public bool BrowseView { get { return m_BrowseView; } set { m_BrowseView = value; } } public SearchOptions SearchOptions { get {return m_SearchOptions;} set {m_SearchOptions = value;} } public string Title { get {return m_Title;} } public PSTable PSTable { get {return m_PSTable;} } public GraphemeInventory GI { get { return m_GI; } } public GraphemeTaughtOrder GraphemesTaught { get { return m_GraphemesTaught; } } public Font DefaultFont { get { return m_DefaultFont; } } public string GetGrapheme(int n) { return (string)m_Graphemes[n]; } public int GraphemesCount() { return m_Graphemes.Count; } public string GetHighlight(int n) { return (string) m_Highlights[n]; } public int HighlightsCount() { return m_Highlights.Count; } public bool SetupSearch() { bool flag = false; //FormBuildableWords fpb = new FormBuildableWords(m_GI, m_GraphemesTaught, // m_PSTable, m_DefaultFont); FormBuildableWordsWL form = new FormBuildableWordsWL(m_GI, m_GraphemesTaught, m_PSTable, m_DefaultFont, m_Settings.LocalizationTable, m_Settings.OptionSettings.UILanguage); DialogResult dr = form.ShowDialog(); if ( dr == DialogResult.OK ) { this.Graphemes = form.Graphemes; this.Highlights = form.Highlights; this.BrowseView = form.BrowseView; this.SearchOptions = form.SearchOptions; if (this.Graphemes != null) { SearchDefinition sd = new SearchDefinition(SearchDefinition.kBuildable); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; string strSym = ""; string strGrfs = ""; for (int i = 0; i < this.Graphemes.Count; i++) { strSym = this.Graphemes[i].ToString(); sdp = new SearchDefinitionParm(BuildableWordSearchWL.kGrapheme, strSym); sd.AddSearchParm(sdp); strGrfs += strSym + Constants.Space; } for (int i = 0; i < this.Highlights.Count; i++) { strSym = this.Highlights[i].ToString(); sdp = new SearchDefinitionParm(BuildableWordSearchWL.kHighlight, strSym); sd.AddSearchParm(sdp); } if (this.BrowseView) { sdp = new SearchDefinitionParm(BuildableWordSearchWL.kBrowseView); sd.AddSearchParm(sdp); } if (m_SearchOptions != null) { sd.AddSearchOptions(m_SearchOptions); } m_Title = m_Title + " - [" + strGrfs.Trim() + "]"; this.SearchDefinition = sd; flag = true; } //else MessageBox.Show("Must specified at least one grapheme"); else { string strMsg = m_Settings.LocalizationTable.GetMessage("BuildableWordsSearchWL1"); if (strMsg == "") strMsg = "Must specified at least one grapheme"; MessageBox.Show(strMsg); } } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; SearchOptions so = new SearchOptions(m_PSTable); string strTag = ""; string strContent = ""; string strGrfs = ""; ArrayList alG = new ArrayList(); ArrayList alH = new ArrayList(); for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); strContent = sd.GetSearchParmAt(i).GetContent(); if (strTag == BuildableWordSearchWL.kGrapheme) { alG.Add(strContent); strGrfs += strContent + Constants.Space; flag = true; } if (strTag == BuildableWordSearchWL.kHighlight) { alH.Add(strContent); } if (strTag == BuildableWordSearchWL.kBrowseView) this.m_BrowseView = true; } this.Graphemes = alG; this.Highlights = alH; m_Title = m_Title + " - [" + strGrfs.Trim() + "]"; this.SearchOptions = sd.MakeSearchOptions(so); this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string str = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser + Environment.NewLine; return strText; } public BuildableWordSearchWL ExecuteBuildableSearch(WordList wl) { SearchOptions so = this.SearchOptions; int nCount = 0; string strResult = wl.GetDisplayHeadings() + Environment.NewLine; Word wrd = null; int nWord = wl.WordCount(); for (int i = 0; i < nWord; i++) { wrd = wl.GetWord(i); if (so == null) { if (wrd.IsBuildableWord(this.Graphemes)) { nCount++; if ((this.Highlights != null) && (this.Highlights.Count > 0)) strResult += wl.GetDisplayLineForWord(i, this.Highlights) + Environment.NewLine; else strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; } } else { if (so.MatchesWord(wrd)) { if (wrd.IsBuildableWord(this.Graphemes)) { nCount++; if ((this.Highlights != null) && (this.Highlights.Count > 0)) strResult += wl.GetDisplayLineForWord(i, this.Highlights) + Environment.NewLine; else strResult +=wl.GetDisplayLineForWord(i) + Environment.NewLine; } } } } if (nCount > 0) { this.SearchResults = strResult; this.SearchCount = nCount; } else { //this.SearchResults = "***No Results***"; this.SearchResults = m_Settings.LocalizationTable.GetMessage("Search1"); if (this.SearchResults == "") this.SearchResults = "***No Results***"; this.SearchCount = 0; } return this; } public BuildableWordSearchWL BrowseBuildableSearch(WordList wl) { int nCount = 0; string str = ""; ArrayList al = null; Color clr = m_Settings.OptionSettings.HighlightColor; Font fnt = m_Settings.OptionSettings.GetDefaultFont(); Word wrd = null; SearchOptions so = this.SearchOptions; FormBrowse form = new FormBrowse(); //form.Text = m_Title + " - " + "Browse View"; str = m_Settings.LocalizationTable.GetMessage("SearchB"); if (str == "") str = "Browse View"; form.Text = m_Title + " - " + str; al = wl.GetDisplayHeadingsAsArray(); form.AddColHeaders(al, clr, fnt); for (int i = 0; i < wl.WordCount(); i++) { wrd = wl.GetWord(i); if (so == null) { if (wrd.IsBuildableWord(this.Graphemes)) { nCount++; al = wrd.GetWordInfoAsArray(); form.AddRow(al); } } else { so = this.SearchDefinition.MakeSearchOptions(so); if (so.MatchesWord(wrd)) { if (so.IsRootOnly) { if (wrd.IsBuildableWord(this.Graphemes)) { nCount++; al = wrd.GetWordInfoAsArray(); form.AddRow(al); } } else { if (wrd.IsBuildableWord(this.Graphemes)) { nCount++; al = wrd.GetWordInfoAsArray(); form.AddRow(al); } } } } } //form.Text += " - " + nCount.ToString() + " entries"; str = m_Settings.LocalizationTable.GetMessage("Search3"); if (str == "") str = "entries"; form.Text += " - " + nCount.ToString() + Constants.Space + str; form.Show(); return this; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Reflection.AssemblyName.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Reflection { sealed public partial class AssemblyName : System.Runtime.InteropServices._AssemblyName, ICloneable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { #region Methods and constructors public AssemblyName(string assemblyName) { } public AssemblyName() { } public Object Clone() { return default(Object); } public static System.Reflection.AssemblyName GetAssemblyName(string assemblyFile) { return default(System.Reflection.AssemblyName); } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public byte[] GetPublicKey() { return default(byte[]); } public byte[] GetPublicKeyToken() { return default(byte[]); } public void OnDeserialization(Object sender) { } public static bool ReferenceMatchesDefinition(System.Reflection.AssemblyName reference, System.Reflection.AssemblyName definition) { return default(bool); } public void SetPublicKey(byte[] publicKey) { } public void SetPublicKeyToken(byte[] publicKeyToken) { } void System.Runtime.InteropServices._AssemblyName.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { } void System.Runtime.InteropServices._AssemblyName.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { } void System.Runtime.InteropServices._AssemblyName.GetTypeInfoCount(out uint pcTInfo) { pcTInfo = default(uint); } void System.Runtime.InteropServices._AssemblyName.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { } public override string ToString() { return default(string); } #endregion #region Properties and indexers public string CodeBase { get { return default(string); } set { } } public System.Globalization.CultureInfo CultureInfo { get { return default(System.Globalization.CultureInfo); } set { } } public string EscapedCodeBase { get { return default(string); } } public AssemblyNameFlags Flags { get { return default(AssemblyNameFlags); } set { } } public string FullName { get { return default(string); } } public System.Configuration.Assemblies.AssemblyHashAlgorithm HashAlgorithm { get { return default(System.Configuration.Assemblies.AssemblyHashAlgorithm); } set { } } public StrongNameKeyPair KeyPair { get { return default(StrongNameKeyPair); } set { } } public string Name { get { return default(string); } set { } } public ProcessorArchitecture ProcessorArchitecture { get { Contract.Ensures(((System.Reflection.ProcessorArchitecture)(0)) <= Contract.Result<System.Reflection.ProcessorArchitecture>()); Contract.Ensures(Contract.Result<System.Reflection.ProcessorArchitecture>() <= ((System.Reflection.ProcessorArchitecture)(4))); return default(ProcessorArchitecture); } set { } } public Version Version { get { return default(Version); } set { } } public System.Configuration.Assemblies.AssemblyVersionCompatibility VersionCompatibility { get { return default(System.Configuration.Assemblies.AssemblyVersionCompatibility); } set { } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="DataViewManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.ComponentModel; using System.Collections; using System.IO; using System.Text; using System.Xml; [ Designer("Microsoft.VSDesigner.Data.VS.DataViewManagerDesigner, " + AssemblyRef.MicrosoftVSDesigner) ] public class DataViewManager : MarshalByValueComponent, IBindingList, System.ComponentModel.ITypedList { private DataViewSettingCollection dataViewSettingsCollection; private DataSet dataSet; private DataViewManagerListItemTypeDescriptor item; private bool locked; internal int nViews = 0; private System.ComponentModel.ListChangedEventHandler onListChanged; private static NotSupportedException NotSupported = new NotSupportedException(); public DataViewManager() : this(null, false) {} public DataViewManager(DataSet dataSet) : this(dataSet, false) {} internal DataViewManager(DataSet dataSet, bool locked) { GC.SuppressFinalize(this); this.dataSet = dataSet; if (this.dataSet != null) { this.dataSet.Tables.CollectionChanged += new CollectionChangeEventHandler(TableCollectionChanged); this.dataSet.Relations.CollectionChanged += new CollectionChangeEventHandler(RelationCollectionChanged); } this.locked = locked; this.item = new DataViewManagerListItemTypeDescriptor(this); this.dataViewSettingsCollection = new DataViewSettingCollection(this); } [ DefaultValue(null), ResDescriptionAttribute(Res.DataViewManagerDataSetDescr) ] public DataSet DataSet { get { return dataSet; } set { if (value == null) throw ExceptionBuilder.SetFailed("DataSet to null"); if (locked) throw ExceptionBuilder.SetDataSetFailed(); if (dataSet != null) { if (nViews > 0) throw ExceptionBuilder.CanNotSetDataSet(); this.dataSet.Tables.CollectionChanged -= new CollectionChangeEventHandler(TableCollectionChanged); this.dataSet.Relations.CollectionChanged -= new CollectionChangeEventHandler(RelationCollectionChanged); } this.dataSet = value; this.dataSet.Tables.CollectionChanged += new CollectionChangeEventHandler(TableCollectionChanged); this.dataSet.Relations.CollectionChanged += new CollectionChangeEventHandler(RelationCollectionChanged); this.dataViewSettingsCollection = new DataViewSettingCollection(this); item.Reset(); } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Content), ResDescriptionAttribute(Res.DataViewManagerTableSettingsDescr) ] public DataViewSettingCollection DataViewSettings { get { return dataViewSettingsCollection; } } public string DataViewSettingCollectionString { get { if (dataSet == null) return ""; StringBuilder builder = new StringBuilder(); builder.Append("<DataViewSettingCollectionString>"); foreach (DataTable dt in dataSet.Tables) { DataViewSetting ds = dataViewSettingsCollection[dt]; builder.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "<{0} Sort=\"{1}\" RowFilter=\"{2}\" RowStateFilter=\"{3}\"/>", dt.EncodedTableName, ds.Sort, ds.RowFilter, ds.RowStateFilter); } builder.Append("</DataViewSettingCollectionString>"); return builder.ToString(); } set { if (value == null || value.Length == 0) return; XmlTextReader r = new XmlTextReader(new StringReader(value)); r.WhitespaceHandling = WhitespaceHandling.None; r.Read(); if (r.Name != "DataViewSettingCollectionString") throw ExceptionBuilder.SetFailed("DataViewSettingCollectionString"); while (r.Read()) { if (r.NodeType != XmlNodeType.Element) continue; string table = XmlConvert.DecodeName(r.LocalName); if (r.MoveToAttribute("Sort")) dataViewSettingsCollection[table].Sort = r.Value; if (r.MoveToAttribute("RowFilter")) dataViewSettingsCollection[table].RowFilter = r.Value; if (r.MoveToAttribute("RowStateFilter")) dataViewSettingsCollection[table].RowStateFilter = (DataViewRowState)Enum.Parse(typeof(DataViewRowState),r.Value); } } } IEnumerator IEnumerable.GetEnumerator() { DataViewManagerListItemTypeDescriptor[] items = new DataViewManagerListItemTypeDescriptor[1]; ((ICollection)this).CopyTo(items, 0); return items.GetEnumerator(); } int ICollection.Count { get { return 1; } } object ICollection.SyncRoot { get { return this; } } bool ICollection.IsSynchronized { get { return false; } } bool IList.IsReadOnly { get { return true; } } bool IList.IsFixedSize { get { return true; } } void ICollection.CopyTo(Array array, int index) { array.SetValue((object)(new DataViewManagerListItemTypeDescriptor(this)), index); } object IList.this[int index] { get { return item; } set { throw ExceptionBuilder.CannotModifyCollection(); } } int IList.Add(object value) { throw ExceptionBuilder.CannotModifyCollection(); } void IList.Clear() { throw ExceptionBuilder.CannotModifyCollection(); } bool IList.Contains(object value) { return(value == item); } int IList.IndexOf(object value) { return(value == item) ? 1 : -1; } void IList.Insert(int index, object value) { throw ExceptionBuilder.CannotModifyCollection(); } void IList.Remove(object value) { throw ExceptionBuilder.CannotModifyCollection(); } void IList.RemoveAt(int index) { throw ExceptionBuilder.CannotModifyCollection(); } // ------------- IBindingList: --------------------------- bool IBindingList.AllowNew { get { return false; } } object IBindingList.AddNew() { throw NotSupported; } bool IBindingList.AllowEdit { get { return false; } } bool IBindingList.AllowRemove { get { return false; } } bool IBindingList.SupportsChangeNotification { get { return true; } } bool IBindingList.SupportsSearching { get { return false; } } bool IBindingList.SupportsSorting { get { return false; } } bool IBindingList.IsSorted { get { throw NotSupported; } } PropertyDescriptor IBindingList.SortProperty { get { throw NotSupported; } } ListSortDirection IBindingList.SortDirection { get { throw NotSupported; } } public event System.ComponentModel.ListChangedEventHandler ListChanged { add { onListChanged += value; } remove { onListChanged -= value; } } void IBindingList.AddIndex(PropertyDescriptor property) { // no operation } void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) { throw NotSupported; } int IBindingList.Find(PropertyDescriptor property, object key) { throw NotSupported; } void IBindingList.RemoveIndex(PropertyDescriptor property) { // no operation } void IBindingList.RemoveSort() { throw NotSupported; } /* string IBindingList.GetListName() { return ((System.Data.ITypedList)this).GetListName(null); } string IBindingList.GetListName(PropertyDescriptor[] listAccessors) { return ((System.Data.ITypedList)this).GetListName(listAccessors); } */ // [....]: GetListName and GetItemProperties almost the same in DataView and DataViewManager string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAccessors) { DataSet dataSet = DataSet; if (dataSet == null) throw ExceptionBuilder.CanNotUseDataViewManager(); if (listAccessors == null || listAccessors.Length == 0) { return dataSet.DataSetName; } else { DataTable table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { return table.TableName; } } return String.Empty; } PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { DataSet dataSet = DataSet; if (dataSet == null) throw ExceptionBuilder.CanNotUseDataViewManager(); if (listAccessors == null || listAccessors.Length == 0) { return((ICustomTypeDescriptor)(new DataViewManagerListItemTypeDescriptor(this))).GetProperties(); } else { DataTable table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { return table.GetPropertyDescriptorCollection(null); } } return new PropertyDescriptorCollection(null); } public DataView CreateDataView(DataTable table) { if (dataSet == null) throw ExceptionBuilder.CanNotUseDataViewManager(); DataView dataView = new DataView(table); dataView.SetDataViewManager(this); return dataView; } protected virtual void OnListChanged(ListChangedEventArgs e) { try { if (onListChanged != null) { onListChanged(this, e); } } catch (Exception f) { // if (!Common.ADP.IsCatchableExceptionType(f)) { throw; } ExceptionBuilder.TraceExceptionWithoutRethrow(f); // ignore the exception } } protected virtual void TableCollectionChanged(object sender, CollectionChangeEventArgs e) { PropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataTablePropertyDescriptor((System.Data.DataTable)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataTablePropertyDescriptor((System.Data.DataTable)e.Element)) : /*default*/ null ); } protected virtual void RelationCollectionChanged(object sender, CollectionChangeEventArgs e) { DataRelationPropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp): e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : /*default*/ null ); } } }
/* * Copyright 2012-2016 The Pkcs11Interop 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI41; using NUnit.Framework; using System; using System.Collections.Generic; using System.Reflection; using LLA41 = Net.Pkcs11Interop.LowLevelAPI41; namespace Net.Pkcs11Interop.Tests.HighLevelAPI41 { /// <summary> /// Object attributes tests. /// </summary> [TestFixture()] public class _13_ObjectAttributeTest { /// <summary> /// Attribute dispose test. /// </summary> [Test()] public void _01_DisposeAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); // Unmanaged memory for attribute value stored in low level CK_ATTRIBUTE struct // is allocated by constructor of ObjectAttribute class. ObjectAttribute attr1 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); // Do something interesting with attribute // This unmanaged memory is freed by Dispose() method. attr1.Dispose(); // ObjectAttribute class can be used in using statement which defines a scope // at the end of which an object will be disposed (and unmanaged memory freed). using (ObjectAttribute attr2 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA)) { // Do something interesting with attribute } #pragma warning disable 0219 // Explicit calling of Dispose() method can also be ommitted. ObjectAttribute attr3 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); // Do something interesting with attribute // Dispose() method will be called (and unmanaged memory freed) by GC eventually // but we cannot be sure when will this occur. #pragma warning restore 0219 } /// <summary> /// Attribute with empty value test. /// </summary> [Test()] public void _02_EmptyAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); // Create attribute without the value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_CLASS); Assert.IsTrue(attr.GetValueAsByteArray() == null); } } /// <summary> /// Attribute with uint value test. /// </summary> [Test()] public void _03_UintAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); uint value = (uint)CKO.CKO_DATA; // Create attribute with uint value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_CLASS); Assert.IsTrue(attr.GetValueAsUint() == value); } } /// <summary> /// Attribute with bool value test. /// </summary> [Test()] public void _04_BoolAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); bool value = true; // Create attribute with bool value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_TOKEN, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_TOKEN); Assert.IsTrue(attr.GetValueAsBool() == value); } } /// <summary> /// Attribute with string value test. /// </summary> [Test()] public void _05_StringAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); string value = "Hello world"; // Create attribute with string value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_LABEL); Assert.IsTrue(attr.GetValueAsString() == value); } value = null; // Create attribute with null string value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_LABEL); Assert.IsTrue(attr.GetValueAsString() == value); } } /// <summary> /// Attribute with byte array value test. /// </summary> [Test()] public void _06_ByteArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); byte[] value = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute with byte array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ID); Assert.IsTrue(Convert.ToBase64String(attr.GetValueAsByteArray()) == Convert.ToBase64String(value)); } value = null; // Create attribute with null byte array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ID); Assert.IsTrue(attr.GetValueAsByteArray() == value); } } /// <summary> /// Attribute with DateTime (CKA_DATE) value test. /// </summary> [Test()] public void _07_DateTimeAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); DateTime value = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc); // Create attribute with DateTime value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_START_DATE, value)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_START_DATE); Assert.IsTrue(attr.GetValueAsDateTime() == value); } } /// <summary> /// Attribute with attribute array value test. /// </summary> [Test()] public void _08_AttributeArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); ObjectAttribute nestedAttribute1 = new ObjectAttribute(CKA.CKA_TOKEN, true); ObjectAttribute nestedAttribute2 = new ObjectAttribute(CKA.CKA_PRIVATE, true); List<ObjectAttribute> originalValue = new List<ObjectAttribute>(); originalValue.Add(nestedAttribute1); originalValue.Add(nestedAttribute2); // Create attribute with attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_WRAP_TEMPLATE); List<ObjectAttribute> recoveredValue = attr.GetValueAsObjectAttributeList(); Assert.IsTrue(recoveredValue.Count == 2); Assert.IsTrue(recoveredValue[0].Type == (uint)CKA.CKA_TOKEN); Assert.IsTrue(recoveredValue[0].GetValueAsBool() == true); Assert.IsTrue(recoveredValue[1].Type == (uint)CKA.CKA_PRIVATE); Assert.IsTrue(recoveredValue[1].GetValueAsBool() == true); } // There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. LLA41.CK_ATTRIBUTE ckAttribute1 = (LLA41.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1); ckAttribute1.value = IntPtr.Zero; ckAttribute1.valueLen = 0; typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute1, ckAttribute1); // There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. LLA41.CK_ATTRIBUTE ckAttribute2 = (LLA41.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2); ckAttribute2.value = IntPtr.Zero; ckAttribute2.valueLen = 0; typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute2, ckAttribute2); originalValue = null; // Create attribute with null attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.GetValueAsObjectAttributeList() == originalValue); } originalValue = new List<ObjectAttribute>(); // Create attribute with empty attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.GetValueAsObjectAttributeList() == null); } } /// <summary> /// Attribute with uint array value test. /// </summary> [Test()] public void _09_UintArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); List<uint> originalValue = new List<uint>(); originalValue.Add(333333); originalValue.Add(666666); // Create attribute with uint array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS); List<uint> recoveredValue = attr.GetValueAsUintList(); for (int i = 0; i < recoveredValue.Count; i++) Assert.IsTrue(originalValue[i] == recoveredValue[i]); } originalValue = null; // Create attribute with null uint array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsUintList() == originalValue); } originalValue = new List<uint>(); // Create attribute with empty uint array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsUintList() == null); } } /// <summary> /// Attribute with mechanism array value test. /// </summary> [Test()] public void _10_MechanismArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); List<CKM> originalValue = new List<CKM>(); originalValue.Add(CKM.CKM_RSA_PKCS); originalValue.Add(CKM.CKM_AES_CBC); // Create attribute with mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS); List<CKM> recoveredValue = attr.GetValueAsCkmList(); for (int i = 0; i < recoveredValue.Count; i++) Assert.IsTrue(originalValue[i] == recoveredValue[i]); } originalValue = null; // Create attribute with null mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsCkmList() == originalValue); } originalValue = new List<CKM>(); // Create attribute with empty mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsCkmList() == null); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[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 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. // #if !SILVERLIGHT #define DEBUG namespace NLog.UnitTests { using System; using System.Diagnostics; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif [TestFixture] public class NLogTraceListenerTests : NLogTestBase { [Test] public void TraceWriteTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Debug.Write("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Debug.Write(3.1415); AssertDebugLastMessage("debug", "Logger1 Debug 3.1415"); Debug.Write(3.1415, "Cat2"); AssertDebugLastMessage("debug", "Logger1 Debug Cat2: 3.1415"); } [Test] public void TraceWriteLineTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.WriteLine("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Debug.WriteLine("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Debug.WriteLine(3.1415); AssertDebugLastMessage("debug", "Logger1 Debug 3.1415"); Debug.WriteLine(3.1415, "Cat2"); AssertDebugLastMessage("debug", "Logger1 Debug Cat2: 3.1415"); } [Test] public void TraceWriteNonDefaultLevelTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); Debug.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Trace Hello"); } #if !NET_CF [Test] public void TraceConfiguration() { var listener = new NLogTraceListener(); listener.Attributes.Add("defaultLogLevel", "Warn"); listener.Attributes.Add("forceLogLevel", "Error"); listener.Attributes.Add("autoLoggerName", "1"); Assert.AreEqual(LogLevel.Warn, listener.DefaultLogLevel); Assert.AreEqual(LogLevel.Error, listener.ForceLogLevel); Assert.IsTrue(listener.AutoLoggerName); } [Test] public void TraceFailTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.Fail("Message"); AssertDebugLastMessage("debug", "Logger1 Error Message"); Debug.Fail("Message", "Detailed Message"); AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message"); } [Test] public void AutoLoggerNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true }); Debug.Write("Hello"); AssertDebugLastMessage("debug", this.GetType().FullName + " Debug Hello"); } [Test] public void TraceDataTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceData(TraceEventType.Critical, 123, 42); AssertDebugLastMessage("debug", "MySource1 Fatal 42 123"); ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo"); AssertDebugLastMessage("debug", "MySource1 Fatal 42, 3.14, foo 145"); } [Test] public void LogInformationTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0"); } [Test] public void TraceEventTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123"); ts.TraceEvent(TraceEventType.Information, 123); AssertDebugLastMessage("debug", "MySource1 Info 123"); ts.TraceEvent(TraceEventType.Verbose, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Trace Bar 145"); ts.TraceEvent(TraceEventType.Error, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Error Foo 145"); ts.TraceEvent(TraceEventType.Suspend, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Debug Bar 145"); ts.TraceEvent(TraceEventType.Resume, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Debug Foo 145"); ts.TraceEvent(TraceEventType.Warning, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Warn Bar 145"); ts.TraceEvent(TraceEventType.Critical, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145"); } [Test] public void ForceLogLevelTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn }); // force all logs to be Warn, DefaultLogLevel has no effect on TraceSource ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0"); } private static TraceSource CreateTraceSource() { var ts = new TraceSource("MySource1", SourceLevels.All); #if MONO // for some reason needed on Mono ts.Switch = new SourceSwitch("MySource1", "Verbose"); ts.Switch.Level = SourceLevels.All; #endif return ts; } #endif } } #endif
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google.Protobuf.Compatibility; using System; namespace Google.Protobuf.Reflection { /// <summary> /// Descriptor for a field or extension within a message in a .proto file. /// </summary> public sealed class FieldDescriptor : DescriptorBase, IComparable<FieldDescriptor> { private EnumDescriptor enumType; private MessageDescriptor messageType; private FieldType fieldType; private readonly string propertyName; // Annoyingly, needed in Crosslink. private IFieldAccessor accessor; /// <summary> /// Get the field's containing message type. /// </summary> public MessageDescriptor ContainingType { get; } /// <summary> /// Returns the oneof containing this field, or <c>null</c> if it is not part of a oneof. /// </summary> public OneofDescriptor ContainingOneof { get; } /// <summary> /// The effective JSON name for this field. This is usually the lower-camel-cased form of the field name, /// but can be overridden using the <c>json_name</c> option in the .proto file. /// </summary> public string JsonName { get; } internal FieldDescriptorProto Proto { get; } internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, string propertyName) : base(file, file.ComputeFullName(parent, proto.Name), index) { Proto = proto; if (proto.Type != 0) { fieldType = GetFieldTypeFromProtoType(proto.Type); } if (FieldNumber <= 0) { throw new DescriptorValidationException(this, "Field numbers must be positive integers."); } ContainingType = parent; // OneofIndex "defaults" to -1 due to a hack in FieldDescriptor.OnConstruction. if (proto.OneofIndex != -1) { if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count) { throw new DescriptorValidationException(this, $"FieldDescriptorProto.oneof_index is out of range for type {parent.Name}"); } ContainingOneof = parent.Oneofs[proto.OneofIndex]; } file.DescriptorPool.AddSymbol(this); // We can't create the accessor until we've cross-linked, unfortunately, as we // may not know whether the type of the field is a map or not. Remember the property name // for later. // We could trust the generated code and check whether the type of the property is // a MapField, but that feels a tad nasty. this.propertyName = propertyName; JsonName = Proto.JsonName == "" ? JsonFormatter.ToJsonName(Proto.Name) : Proto.JsonName; } /// <summary> /// The brief name of the descriptor's target. /// </summary> public override string Name => Proto.Name; /// <summary> /// Returns the accessor for this field. /// </summary> /// <remarks> /// <para> /// While a <see cref="FieldDescriptor"/> describes the field, it does not provide /// any way of obtaining or changing the value of the field within a specific message; /// that is the responsibility of the accessor. /// </para> /// <para> /// The value returned by this property will be non-null for all regular fields. However, /// if a message containing a map field is introspected, the list of nested messages will include /// an auto-generated nested key/value pair message for the field. This is not represented in any /// generated type, and the value of the map field itself is represented by a dictionary in the /// reflection API. There are never instances of those "hidden" messages, so no accessor is provided /// and this property will return null. /// </para> /// </remarks> public IFieldAccessor Accessor => accessor; /// <summary> /// Maps a field type as included in the .proto file to a FieldType. /// </summary> private static FieldType GetFieldTypeFromProtoType(FieldDescriptorProto.Types.Type type) { switch (type) { case FieldDescriptorProto.Types.Type.Double: return FieldType.Double; case FieldDescriptorProto.Types.Type.Float: return FieldType.Float; case FieldDescriptorProto.Types.Type.Int64: return FieldType.Int64; case FieldDescriptorProto.Types.Type.Uint64: return FieldType.UInt64; case FieldDescriptorProto.Types.Type.Int32: return FieldType.Int32; case FieldDescriptorProto.Types.Type.Fixed64: return FieldType.Fixed64; case FieldDescriptorProto.Types.Type.Fixed32: return FieldType.Fixed32; case FieldDescriptorProto.Types.Type.Bool: return FieldType.Bool; case FieldDescriptorProto.Types.Type.String: return FieldType.String; case FieldDescriptorProto.Types.Type.Group: return FieldType.Group; case FieldDescriptorProto.Types.Type.Message: return FieldType.Message; case FieldDescriptorProto.Types.Type.Bytes: return FieldType.Bytes; case FieldDescriptorProto.Types.Type.Uint32: return FieldType.UInt32; case FieldDescriptorProto.Types.Type.Enum: return FieldType.Enum; case FieldDescriptorProto.Types.Type.Sfixed32: return FieldType.SFixed32; case FieldDescriptorProto.Types.Type.Sfixed64: return FieldType.SFixed64; case FieldDescriptorProto.Types.Type.Sint32: return FieldType.SInt32; case FieldDescriptorProto.Types.Type.Sint64: return FieldType.SInt64; default: throw new ArgumentException("Invalid type specified"); } } /// <summary> /// Returns <c>true</c> if this field is a repeated field; <c>false</c> otherwise. /// </summary> public bool IsRepeated => Proto.Label == FieldDescriptorProto.Types.Label.Repeated; /// <summary> /// Returns <c>true</c> if this field is a map field; <c>false</c> otherwise. /// </summary> public bool IsMap => fieldType == FieldType.Message && messageType.Proto.Options != null && messageType.Proto.Options.MapEntry; /// <summary> /// Returns <c>true</c> if this field is a packed, repeated field; <c>false</c> otherwise. /// </summary> public bool IsPacked => // Note the || rather than && here - we're effectively defaulting to packed, because that *is* // the default in proto3, which is all we support. We may give the wrong result for the protos // within descriptor.proto, but that's okay, as they're never exposed and we don't use IsPacked // within the runtime. Proto.Options == null || Proto.Options.Packed; /// <summary> /// Returns the type of the field. /// </summary> public FieldType FieldType => fieldType; /// <summary> /// Returns the field number declared in the proto file. /// </summary> public int FieldNumber => Proto.Number; /// <summary> /// Compares this descriptor with another one, ordering in "canonical" order /// which simply means ascending order by field number. <paramref name="other"/> /// must be a field of the same type, i.e. the <see cref="ContainingType"/> of /// both fields must be the same. /// </summary> public int CompareTo(FieldDescriptor other) { if (other.ContainingType != ContainingType) { throw new ArgumentException("FieldDescriptors can only be compared to other FieldDescriptors " + "for fields of the same message type."); } return FieldNumber - other.FieldNumber; } /// <summary> /// For enum fields, returns the field's type. /// </summary> public EnumDescriptor EnumType { get { if (fieldType != FieldType.Enum) { throw new InvalidOperationException("EnumType is only valid for enum fields."); } return enumType; } } /// <summary> /// For embedded message and group fields, returns the field's type. /// </summary> public MessageDescriptor MessageType { get { if (fieldType != FieldType.Message) { throw new InvalidOperationException("MessageType is only valid for message fields."); } return messageType; } } /// <summary> /// The (possibly empty) set of custom options for this field. /// </summary> public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty; /// <summary> /// Look up and cross-link all field types etc. /// </summary> internal void CrossLink() { if (Proto.TypeName != "") { IDescriptor typeDescriptor = File.DescriptorPool.LookupSymbol(Proto.TypeName, this); if (Proto.Type != 0) { // Choose field type based on symbol. if (typeDescriptor is MessageDescriptor) { fieldType = FieldType.Message; } else if (typeDescriptor is EnumDescriptor) { fieldType = FieldType.Enum; } else { throw new DescriptorValidationException(this, $"\"{Proto.TypeName}\" is not a type."); } } if (fieldType == FieldType.Message) { if (!(typeDescriptor is MessageDescriptor)) { throw new DescriptorValidationException(this, $"\"{Proto.TypeName}\" is not a message type."); } messageType = (MessageDescriptor) typeDescriptor; if (Proto.DefaultValue != "") { throw new DescriptorValidationException(this, "Messages can't have default values."); } } else if (fieldType == FieldType.Enum) { if (!(typeDescriptor is EnumDescriptor)) { throw new DescriptorValidationException(this, $"\"{Proto.TypeName}\" is not an enum type."); } enumType = (EnumDescriptor) typeDescriptor; } else { throw new DescriptorValidationException(this, "Field with primitive type has type_name."); } } else { if (fieldType == FieldType.Message || fieldType == FieldType.Enum) { throw new DescriptorValidationException(this, "Field with message or enum type missing type_name."); } } // Note: no attempt to perform any default value parsing File.DescriptorPool.AddFieldByNumber(this); if (ContainingType != null && ContainingType.Proto.Options != null && ContainingType.Proto.Options.MessageSetWireFormat) { throw new DescriptorValidationException(this, "MessageSet format is not supported."); } accessor = CreateAccessor(); } private IFieldAccessor CreateAccessor() { // If we're given no property name, that's because we really don't want an accessor. // (At the moment, that means it's a map entry message...) if (propertyName == null) { return null; } var property = ContainingType.ClrType.GetProperty(propertyName); if (property == null) { throw new DescriptorValidationException(this, $"Property {propertyName} not found in {ContainingType.ClrType}"); } return IsMap ? new MapFieldAccessor(property, this) : IsRepeated ? new RepeatedFieldAccessor(property, this) : (IFieldAccessor) new SingleFieldAccessor(property, this); } } }
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2012 MvvmFx project (http://mvvmfx.codeplex.com) // // Authors: // Tiago Freitas Leal // using System; using System.Collections.Concurrent; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using MvvmFx.Bindings; namespace MvvmFx.ComponentModel { /// <summary> /// DependencyPropertyDescriptor /// </summary> public sealed class DependencyPropertyDescriptor : PropertyDescriptor { private readonly PropertyDescriptor _property; private readonly Type _componentType; private readonly DependencyProperty _dependencyProperty; private readonly PropertyMetadata _metadata; private static readonly ConcurrentDictionary<object, DependencyPropertyDescriptor> CachedDpd = new ConcurrentDictionary<object, DependencyPropertyDescriptor>(new ReferenceEqualityComparer()); private DependencyPropertyDescriptor() : base(null) { } [SuppressMessage("Microsoft.Security", "CA2122", Justification = "temp")] private DependencyPropertyDescriptor(PropertyDescriptor property, Type componentType, DependencyProperty dependencyProperty) : base(dependencyProperty.Name, null) { _property = property; _componentType = componentType; _dependencyProperty = dependencyProperty; _metadata = dependencyProperty.GetMetadata(componentType); } public override AttributeCollection Attributes { get { return _property.Attributes; } } public override string Category { get { if (string.IsNullOrEmpty(_property.Category)) return "Misc"; return _property.Category; } } public override Type ComponentType { get { return _componentType; } } public override TypeConverter Converter { get { return _property.Converter; } } public DependencyProperty DependencyProperty { get { return _dependencyProperty; } } public override string Description { get { return _property.Description; } } public override bool DesignTimeOnly { get { return _property.DesignTimeOnly; } } public override string DisplayName { get { return _property.DisplayName; } } public bool IsAttached { get { return _dependencyProperty.IsAttached; } } public override bool IsBrowsable { get { return _property.IsBrowsable; } } public override bool IsLocalizable { get { return _property.IsLocalizable; } } public override bool IsReadOnly { get { return _property.IsReadOnly; } } public PropertyMetadata Metadata { get { return _metadata; } } public override Type PropertyType { get { return _dependencyProperty.PropertyType; } } public override bool SupportsChangeEvents { get { return true; //return _prop.SupportsChangeEvents; } } public override void AddValueChanged(object component, EventHandler handler) { base.AddValueChanged(component, handler); } public override bool CanResetValue(object component) { return _property.CanResetValue(component); } public override bool Equals(object obj) { var dpd = obj as DependencyPropertyDescriptor; if (dpd != null && dpd.DependencyProperty == _dependencyProperty && dpd.ComponentType == _componentType) return true; return false; } public override PropertyDescriptorCollection GetChildProperties(object instance, Attribute[] filter) { return _property.GetChildProperties(instance, filter); } public override object GetEditor(Type editorBaseType) { return _property.GetEditor(editorBaseType); } public override int GetHashCode() { return _dependencyProperty.GetHashCode() ^ _componentType.GetHashCode(); } public override object GetValue(object component) { return _property.GetValue(component); } public override void RemoveValueChanged(object component, EventHandler handler) { base.RemoveValueChanged(component, handler); } public override void ResetValue(object component) { _property.ResetValue(component); } public override void SetValue(object component, object value) { if (ComponentType.IsInstanceOfType(component)) { if (_property.GetValue(component) != value) { _property.SetValue(component, value); OnValueChanged(component); } } } internal void OnValueChanged(object component) { OnValueChanged(component, EventArgs.Empty); } public override bool ShouldSerializeValue(object component) { return _property.ShouldSerializeValue(component); } public override string ToString() { return Name; } public static DependencyPropertyDescriptor FromName(string name, Type ownerType, Type targetType) { if (name == null) throw new ArgumentNullException("name"); if (ownerType == null) throw new ArgumentNullException("ownerType"); if (targetType == null) throw new ArgumentNullException("targetType"); var dp = DependencyProperty.FromName(name, ownerType); if (dp != null) return FromProperty(dp, targetType); return null; } [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Signature compatibility.")] public static DependencyPropertyDescriptor FromName(string name, Type ownerType, Type targetType, bool ignorePropertyType) { if (name == null) throw new ArgumentNullException("name"); if (ownerType == null) throw new ArgumentNullException("ownerType"); if (targetType == null) throw new ArgumentNullException("targetType"); var dp = DependencyObject.FromName(name, ownerType); if (dp != null) return FromProperty(dp, targetType); return null; } public static DependencyPropertyDescriptor FromProperty(PropertyDescriptor property) { if (property == null) throw new ArgumentNullException("property"); DependencyPropertyDescriptor dpd; if (!CachedDpd.TryGetValue(property, out dpd)) { var dp = DependencyObject.FromName(property.Name, property.ComponentType); if (dp != null) { dpd = new DependencyPropertyDescriptor(property, dp.OwnerType, dp); CachedDpd.TryAdd(property, dpd); } } return dpd; // null if could't get a DependencyProperty } public static DependencyPropertyDescriptor FromProperty(DependencyProperty dependencyProperty, Type targetType) { if (dependencyProperty == null) throw new ArgumentNullException("dependencyProperty"); if (targetType == null) throw new ArgumentNullException("targetType"); #region find PropertyDescriptor PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(targetType); /*foreach (PropertyDescriptor pd in pdc) { if (pd.Name == dependencyProperty.Name) { property = pd; break; } }*/ var property = pdc.Cast<PropertyDescriptor>().FirstOrDefault(pd => pd.Name == dependencyProperty.Name); #endregion DependencyPropertyDescriptor dpd = null; if (property != null) { if (!CachedDpd.TryGetValue(property, out dpd)) { dpd = new DependencyPropertyDescriptor(property, targetType, dependencyProperty); CachedDpd.TryAdd(property, dpd); } } return dpd; } public CoerceValueCallback DesignerCoerceValueCallback { get; set; } #region internal methods internal static DependencyPropertyDescriptor FromProperty(DependencyProperty dependencyProperty) { if (dependencyProperty == null) throw new ArgumentNullException("dependencyProperty"); #region find PropertyDescriptor PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(dependencyProperty.OwnerType); /*foreach (PropertyDescriptor pd in pdc) { if (pd.Name == dependencyProperty.Name) { property = pd; break; } }*/ var property = pdc.Cast<PropertyDescriptor>().FirstOrDefault(pd => pd.Name == dependencyProperty.Name); #endregion DependencyPropertyDescriptor dpd = null; if (property != null) { if (!CachedDpd.TryGetValue(property, out dpd)) { dpd = new DependencyPropertyDescriptor(property, dependencyProperty.OwnerType, dependencyProperty); CachedDpd.TryAdd(property, dpd); } } return dpd; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Security { public enum EncryptionPolicy { // Prohibit null ciphers (current system defaults) RequireEncryption = 0, // Add null ciphers to current system defaults AllowNoEncryption, // Request null ciphers only NoEncryption } // A user delegate used to verify remote SSL certificate. public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); // A user delegate used to select local SSL certificate. public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers); // Internal versions of the above delegates. internal delegate bool RemoteCertValidationCallback(string host, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2 remoteCertificate, string[] acceptableIssuers); public class SslStream : AuthenticatedStream { private SslState _sslState; private RemoteCertificateValidationCallback _userCertificateValidationCallback; private LocalCertificateSelectionCallback _userCertificateSelectionCallback; private object _remoteCertificateOrBytes; public SslStream(Stream innerStream) : this(innerStream, false, null, null) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen) : this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(encryptionPolicy)); } _userCertificateValidationCallback = userCertificateValidationCallback; _userCertificateSelectionCallback = userCertificateSelectionCallback; RemoteCertValidationCallback _userCertValidationCallbackWrapper = new RemoteCertValidationCallback(UserCertValidationCallbackWrapper); LocalCertSelectionCallback _userCertSelectionCallbackWrapper = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); _sslState = new SslState(innerStream, _userCertValidationCallbackWrapper, _userCertSelectionCallbackWrapper, encryptionPolicy); } private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { _remoteCertificateOrBytes = certificate == null ? null : certificate.RawData; if (_userCertificateValidationCallback == null) { if (!_sslState.RemoteCertRequired) { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable; } return (sslPolicyErrors == SslPolicyErrors.None); } else { return _userCertificateValidationCallback(this, certificate, chain, sslPolicyErrors); } } private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return _userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); } // // Client side auth. // public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation); LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback); _sslState.ProcessAuthentication(result); return result; } public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) { _sslState.EndProcessAuthentication(asyncResult); } // // Server side auth. // public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation); LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback); _sslState.ProcessAuthentication(result); return result; } public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) { _sslState.EndProcessAuthentication(asyncResult); } internal virtual IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState) { return _sslState.BeginShutdown(asyncCallback, asyncState); } internal virtual void EndShutdown(IAsyncResult asyncResult) { _sslState.EndShutdown(asyncResult); } public TransportContext TransportContext { get { return new SslStreamContext(this); } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { return _sslState.GetChannelBinding(kind); } #region Synchronous methods public virtual void AuthenticateAsClient(string targetHost) { AuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation); _sslState.ProcessAuthentication(null); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate) { AuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { AuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation); _sslState.ProcessAuthentication(null); } #endregion #region Task-based async public methods public virtual Task AuthenticateAsClientAsync(string targetHost) => Task.Factory.FromAsync( (arg1, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, callback, state), iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar), targetHost, this); public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) => Task.Factory.FromAsync( (arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, SecurityProtocol.SystemDefaultSecurityProtocols, arg3, callback, state), iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar), targetHost, clientCertificates, checkCertificateRevocation, this); public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { var beginMethod = checkCertificateRevocation ? (Func<string, X509CertificateCollection, SslProtocols, AsyncCallback, object, IAsyncResult>) ((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, arg3, true, callback, state)) : ((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, arg3, false, callback, state)); return Task.Factory.FromAsync( beginMethod, iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar), targetHost, clientCertificates, enabledSslProtocols, this); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) => Task.Factory.FromAsync( (arg1, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, callback, state), iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar), serverCertificate, this); public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) => Task.Factory.FromAsync( (arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, SecurityProtocol.SystemDefaultSecurityProtocols, arg3, callback, state), iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar), serverCertificate, clientCertificateRequired, checkCertificateRevocation, this); public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { var beginMethod = checkCertificateRevocation ? (Func<X509Certificate, bool, SslProtocols, AsyncCallback, object, IAsyncResult>) ((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, arg3, true, callback, state)) : ((arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsServer(arg1, arg2, arg3, false, callback, state)); return Task.Factory.FromAsync( beginMethod, iar => ((SslStream)iar.AsyncState).EndAuthenticateAsServer(iar), serverCertificate, clientCertificateRequired, enabledSslProtocols, this); } public virtual Task ShutdownAsync() => Task.Factory.FromAsync( (callback, state) => ((SslStream)state).BeginShutdown(callback, state), iar => ((SslStream)iar.AsyncState).EndShutdown(iar), this); #endregion public override bool IsAuthenticated { get { return _sslState.IsAuthenticated; } } public override bool IsMutuallyAuthenticated { get { return _sslState.IsMutuallyAuthenticated; } } public override bool IsEncrypted { get { return IsAuthenticated; } } public override bool IsSigned { get { return IsAuthenticated; } } public override bool IsServer { get { return _sslState.IsServer; } } public virtual SslProtocols SslProtocol { get { return _sslState.SslProtocol; } } public virtual bool CheckCertRevocationStatus { get { return _sslState.CheckCertRevocationStatus; } } public virtual X509Certificate LocalCertificate { get { return _sslState.LocalCertificate; } } public virtual X509Certificate RemoteCertificate { get { _sslState.CheckThrow(true); object chkCertificateOrBytes = _remoteCertificateOrBytes; if (chkCertificateOrBytes != null && chkCertificateOrBytes.GetType() == typeof(byte[])) { return (X509Certificate)(_remoteCertificateOrBytes = new X509Certificate2((byte[])chkCertificateOrBytes)); } else { return chkCertificateOrBytes as X509Certificate; } } } public virtual CipherAlgorithmType CipherAlgorithm { get { return _sslState.CipherAlgorithm; } } public virtual int CipherStrength { get { return _sslState.CipherStrength; } } public virtual HashAlgorithmType HashAlgorithm { get { return _sslState.HashAlgorithm; } } public virtual int HashStrength { get { return _sslState.HashStrength; } } public virtual ExchangeAlgorithmType KeyExchangeAlgorithm { get { return _sslState.KeyExchangeAlgorithm; } } public virtual int KeyExchangeStrength { get { return _sslState.KeyExchangeStrength; } } // // Stream contract implementation. // public override bool CanSeek { get { return false; } } public override bool CanRead { get { return _sslState.IsAuthenticated && InnerStream.CanRead; } } public override bool CanTimeout { get { return InnerStream.CanTimeout; } } public override bool CanWrite { get { return _sslState.IsAuthenticated && InnerStream.CanWrite && !_sslState.IsShutdown; } } public override int ReadTimeout { get { return InnerStream.ReadTimeout; } set { InnerStream.ReadTimeout = value; } } public override int WriteTimeout { get { return InnerStream.WriteTimeout; } set { InnerStream.WriteTimeout = value; } } public override long Length { get { return InnerStream.Length; } } public override long Position { get { return InnerStream.Position; } set { throw new NotSupportedException(SR.net_noseek); } } public override void SetLength(long value) { InnerStream.SetLength(value); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } public override void Flush() { _sslState.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { return _sslState.FlushAsync(cancellationToken); } protected override void Dispose(bool disposing) { try { _sslState.Close(); } finally { base.Dispose(disposing); } } public override int ReadByte() { return _sslState.SecureStream.ReadByte(); } public override int Read(byte[] buffer, int offset, int count) { return _sslState.SecureStream.Read(buffer, offset, count); } public void Write(byte[] buffer) { _sslState.SecureStream.Write(buffer, 0, buffer.Length); } public override void Write(byte[] buffer, int offset, int count) { _sslState.SecureStream.Write(buffer, offset, count); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { return _sslState.SecureStream.BeginRead(buffer, offset, count, asyncCallback, asyncState); } public override int EndRead(IAsyncResult asyncResult) { return _sslState.SecureStream.EndRead(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { return _sslState.SecureStream.BeginWrite(buffer, offset, count, asyncCallback, asyncState); } public override void EndWrite(IAsyncResult asyncResult) { _sslState.SecureStream.EndWrite(asyncResult); } } }
using System.Data.Entity; namespace FCT.LLC.BusinessService.Entities { public partial class EFBusinessContext : DbContext { public EFBusinessContext() : base("name=EFBusinessContext") { Configuration.LazyLoadingEnabled = false; Configuration.ProxyCreationEnabled = false; } public virtual DbSet<dtproperty> dtproperties { get; set; } public virtual DbSet<tblAccessRole> tblAccessRoles { get; set; } public virtual DbSet<tblAddress> tblAddresses { get; set; } public virtual DbSet<tblAddressType> tblAddressTypes { get; set; } public virtual DbSet<tblAmendmentTrack> tblAmendmentTracks { get; set; } public virtual DbSet<tblAmendmentType> tblAmendmentTypes { get; set; } public virtual DbSet<tblApplicationConfigurationOption> tblApplicationConfigurationOptions { get; set; } public virtual DbSet<tblAttorney> tblAttorneys { get; set; } public virtual DbSet<tblAuditLog> tblAuditLogs { get; set; } public virtual DbSet<tblBCOnline> tblBCOnlines { get; set; } public virtual DbSet<tblBillingAmountDetail> tblBillingAmountDetails { get; set; } public virtual DbSet<tblBillingAmountDetailDiscount> tblBillingAmountDetailDiscounts { get; set; } public virtual DbSet<tblBillingAmountDetailTax> tblBillingAmountDetailTaxes { get; set; } public virtual DbSet<tblBranch> tblBranches { get; set; } public virtual DbSet<tblBridgeLoan> tblBridgeLoans { get; set; } public virtual DbSet<tblBusinessField> tblBusinessFields { get; set; } public virtual DbSet<tblBusinessFieldMap> tblBusinessFieldMaps { get; set; } public virtual DbSet<tblCadastre> tblCadastres { get; set; } public virtual DbSet<tblCalculationPeriodCode> tblCalculationPeriodCodes { get; set; } public virtual DbSet<tblCalculationPeriodDescription> tblCalculationPeriodDescriptions { get; set; } public virtual DbSet<tblChangeDetail> tblChangeDetails { get; set; } public virtual DbSet<tblCMHC> tblCMHCs { get; set; } public virtual DbSet<tblComment> tblComments { get; set; } public virtual DbSet<tblCompany> tblCompanies { get; set; } public virtual DbSet<tblCompanyIncorporationAuthority> tblCompanyIncorporationAuthorities { get; set; } public virtual DbSet<tblComponentFieldMapping> tblComponentFieldMappings { get; set; } public virtual DbSet<tblConfigurationCategory> tblConfigurationCategories { get; set; } public virtual DbSet<tblConfigurationOption> tblConfigurationOptions { get; set; } public virtual DbSet<tblContactInfo> tblContactInfoes { get; set; } public virtual DbSet<tblConversionHistory> tblConversionHistories { get; set; } public virtual DbSet<tblCreditCard> tblCreditCards { get; set; } public virtual DbSet<tblDealDocumentPackage> tblDealDocumentPackages { get; set; } public virtual DbSet<tblDealLock> tblDealLocks { get; set; } public virtual DbSet<tblDealTrustAccount> tblDealTrustAccounts { get; set; } public virtual DbSet<tblDocumentArchive> tblDocumentArchives { get; set; } public virtual DbSet<tblDocumentCache> tblDocumentCaches { get; set; } public virtual DbSet<tblDocumentCategory> tblDocumentCategories { get; set; } public virtual DbSet<tblDocumentComment> tblDocumentComments { get; set; } public virtual DbSet<tblDocumentField> tblDocumentFields { get; set; } public virtual DbSet<tblDocumentFileFormat> tblDocumentFileFormats { get; set; } public virtual DbSet<tblDocumentFileOutputInfo> tblDocumentFileOutputInfoes { get; set; } public virtual DbSet<tblDocumentKeyValue> tblDocumentKeyValues { get; set; } public virtual DbSet<tblDocumentMappingFile> tblDocumentMappingFiles { get; set; } public virtual DbSet<tblDocumentPackageMapping> tblDocumentPackageMappings { get; set; } public virtual DbSet<tblDocumentProvConfig> tblDocumentProvConfigs { get; set; } public virtual DbSet<tblDocumentTemplate> tblDocumentTemplates { get; set; } public virtual DbSet<tblDocumentTemplateFile> tblDocumentTemplateFiles { get; set; } public virtual DbSet<tblDocumentTypeCode> tblDocumentTypeCodes { get; set; } public virtual DbSet<tblDocumentTypeDisplay> tblDocumentTypeDisplays { get; set; } public virtual DbSet<tblDocumentTypeDisplayType> tblDocumentTypeDisplayTypes { get; set; } public virtual DbSet<tblDocumentTypeMapping> tblDocumentTypeMappings { get; set; } public virtual DbSet<tblDocumentTypeUserRole> tblDocumentTypeUserRoles { get; set; } public virtual DbSet<tblDropdown> tblDropdowns { get; set; } public virtual DbSet<tblEasyFundClosureDate> tblEasyFundClosureDates { get; set; } public virtual DbSet<tblEmailTemplate> tblEmailTemplates { get; set; } public virtual DbSet<tblEmailTemplateList> tblEmailTemplateLists { get; set; } public virtual DbSet<tblExistingMortgage> tblExistingMortgages { get; set; } public virtual DbSet<tblFinalReportClosingOption> tblFinalReportClosingOptions { get; set; } public virtual DbSet<tblFireInsurancePolicy> tblFireInsurancePolicies { get; set; } public virtual DbSet<tblFormNumber> tblFormNumbers { get; set; } public virtual DbSet<tblFundingPaymentMethod> tblFundingPaymentMethods { get; set; } public virtual DbSet<tblFundingRequest> tblFundingRequests { get; set; } public virtual DbSet<tblFundingRequestType> tblFundingRequestTypes { get; set; } public virtual DbSet<tblFundsDeliveryType> tblFundsDeliveryTypes { get; set; } public virtual DbSet<tblFundStatu> tblFundStatus { get; set; } public virtual DbSet<tblGuarantor> tblGuarantors { get; set; } public virtual DbSet<tblHoliday> tblHolidays { get; set; } public virtual DbSet<tblIdentification> tblIdentifications { get; set; } public virtual DbSet<tblInternalComponent> tblInternalComponents { get; set; } public virtual DbSet<tblLandLease> tblLandLeases { get; set; } public virtual DbSet<tblLanguage> tblLanguages { get; set; } public virtual DbSet<tblLawyerApplication> tblLawyerApplications { get; set; } public virtual DbSet<tblLawyerAuthorizedPaymentMethodType> tblLawyerAuthorizedPaymentMethodTypes { get; set; } public virtual DbSet<tblLawyerNotification> tblLawyerNotifications { get; set; } public virtual DbSet<tblLawyerNotificationEmail> tblLawyerNotificationEmails { get; set; } public virtual DbSet<tblLawyerPaymentAuthorizationMethod> tblLawyerPaymentAuthorizationMethods { get; set; } public virtual DbSet<tblLawyerSavedAmendment> tblLawyerSavedAmendments { get; set; } public virtual DbSet<tblLawyerSecurityQuestion> tblLawyerSecurityQuestions { get; set; } public virtual DbSet<tblLenderBusinessField> tblLenderBusinessFields { get; set; } public virtual DbSet<tblLenderChangeBridgeLoan> tblLenderChangeBridgeLoans { get; set; } public virtual DbSet<tblLenderChangeExistingMortgage> tblLenderChangeExistingMortgages { get; set; } public virtual DbSet<tblLenderChangeGuarantor> tblLenderChangeGuarantors { get; set; } public virtual DbSet<tblLenderChangeMortgagor> tblLenderChangeMortgagors { get; set; } public virtual DbSet<tblLenderChangePIN> tblLenderChangePINs { get; set; } public virtual DbSet<tblLenderChangeProperty> tblLenderChangeProperties { get; set; } public virtual DbSet<tblLenderChangeUnsecuredDebt> tblLenderChangeUnsecuredDebts { get; set; } public virtual DbSet<tblLenderClause> tblLenderClauses { get; set; } public virtual DbSet<tblLenderConfigurationOption> tblLenderConfigurationOptions { get; set; } public virtual DbSet<tblLenderFundingRequestType> tblLenderFundingRequestTypes { get; set; } public virtual DbSet<tblLenderInstruction> tblLenderInstructions { get; set; } public virtual DbSet<tblLenderSchemaField> tblLenderSchemaFields { get; set; } public virtual DbSet<tblLenderSchemaFieldsDescription> tblLenderSchemaFieldsDescriptions { get; set; } public virtual DbSet<tblLenderSecurityQuestion> tblLenderSecurityQuestions { get; set; } public virtual DbSet<tblLockLevel> tblLockLevels { get; set; } public virtual DbSet<tblMortgageFee> tblMortgageFees { get; set; } public virtual DbSet<tblMortgageFeeType> tblMortgageFeeTypes { get; set; } public virtual DbSet<tblMortgageILA> tblMortgageILAs { get; set; } public virtual DbSet<tblMortgagePayment> tblMortgagePayments { get; set; } public virtual DbSet<tblMortgagePaymentRegistrationData> tblMortgagePaymentRegistrationDatas { get; set; } public virtual DbSet<tblMortgageProduct> tblMortgageProducts { get; set; } public virtual DbSet<tblMortgageRegistrationData> tblMortgageRegistrationDatas { get; set; } public virtual DbSet<tblMortgageRegistrationDataField> tblMortgageRegistrationDataFields { get; set; } public virtual DbSet<tblMunicipality> tblMunicipalities { get; set; } public virtual DbSet<tblNotification> tblNotifications { get; set; } public virtual DbSet<tblPasswordHistory> tblPasswordHistories { get; set; } public virtual DbSet<tblPayeeTypeDocumentType> tblPayeeTypeDocumentTypes { get; set; } public virtual DbSet<tblPaymentAuthorization> tblPaymentAuthorizations { get; set; } public virtual DbSet<tblPaymentFrequencyType> tblPaymentFrequencyTypes { get; set; } public virtual DbSet<tblPerson> tblPersons { get; set; } public virtual DbSet<tblPlatformContactInfoMessage> tblPlatformContactInfoMessages { get; set; } public virtual DbSet<tblPlatformMessage> tblPlatformMessages { get; set; } public virtual DbSet<tblPOA> tblPOAs { get; set; } public virtual DbSet<tblPropertyLot> tblPropertyLots { get; set; } public virtual DbSet<tblProvince> tblProvinces { get; set; } public virtual DbSet<tblProvinceTax> tblProvinceTaxes { get; set; } public virtual DbSet<tblPublishedEventMessage> tblPublishedEventMessages { get; set; } public virtual DbSet<tblPublishedEventMessageBatchProcessing> tblPublishedEventMessageBatchProcessings { get; set; } public virtual DbSet<tblQuestionReference> tblQuestionReferences { get; set; } public virtual DbSet<tblRatioIndicatorType> tblRatioIndicatorTypes { get; set; } public virtual DbSet<tblRegisteredOwner> tblRegisteredOwners { get; set; } public virtual DbSet<tblRegistrationDataConfiguration> tblRegistrationDataConfigurations { get; set; } public virtual DbSet<tblRegistryOffice> tblRegistryOffices { get; set; } public virtual DbSet<tblRejectLenderAmendment> tblRejectLenderAmendments { get; set; } public virtual DbSet<tblResourceText> tblResourceTexts { get; set; } public virtual DbSet<tblSchemaFieldList> tblSchemaFieldLists { get; set; } public virtual DbSet<tblSchemaFieldListMapping> tblSchemaFieldListMappings { get; set; } public virtual DbSet<tblSecondaryDesignation> tblSecondaryDesignations { get; set; } public virtual DbSet<tblSharedFieldMap> tblSharedFieldMaps { get; set; } public virtual DbSet<tblSignatory> tblSignatories { get; set; } public virtual DbSet<tblSolicitorInstructionPOA> tblSolicitorInstructionPOAs { get; set; } public virtual DbSet<tblSolicitorSync> tblSolicitorSyncs { get; set; } public virtual DbSet<tblSolicitorSyncLastRunParameter> tblSolicitorSyncLastRunParameters { get; set; } public virtual DbSet<tblSolicitorSyncMarkedProfile> tblSolicitorSyncMarkedProfiles { get; set; } public virtual DbSet<tblSolicitorSyncReportData> tblSolicitorSyncReportDatas { get; set; } public virtual DbSet<tblStandardNotification> tblStandardNotifications { get; set; } public virtual DbSet<tblStandardNotificationList> tblStandardNotificationLists { get; set; } public virtual DbSet<tblStatu> tblStatus { get; set; } public virtual DbSet<tblSymmetricKey> tblSymmetricKeys { get; set; } public virtual DbSet<tblTitleInsurancePolicy> tblTitleInsurancePolicies { get; set; } public virtual DbSet<tblTitleInsuranceSelection> tblTitleInsuranceSelections { get; set; } public virtual DbSet<tblTrustAccount> tblTrustAccounts { get; set; } public virtual DbSet<tblTrustAccountLender> tblTrustAccountLenders { get; set; } public virtual DbSet<tblUIControlType> tblUIControlTypes { get; set; } public virtual DbSet<tblUnsecuredDebt> tblUnsecuredDebts { get; set; } public virtual DbSet<tblUserStatu> tblUserStatus { get; set; } public virtual DbSet<ChangeLog> ChangeLogs { get; set; } public virtual DbSet<ImportedQuestion> ImportedQuestions { get; set; } public virtual DbSet<tblBusinessModel> tblBusinessModels { get; set; } public virtual DbSet<tblDocumentConfiguration> tblDocumentConfigurations { get; set; } public virtual DbSet<tblBuilderUnitLevel> tblBuilderUnitLevels { get; set; } public virtual DbSet<tblBuilderLegalDescription> tblBuilderLegalDescriptions { get; set; } public virtual DbSet<tblDeal> tblDeals { get; set; } public virtual DbSet<tblDealContact> tblDealContacts { get; set; } public virtual DbSet<tblDealScope> tblDealScopes { get; set; } public virtual DbSet<tblLawyer> tblLawyers { get; set; } public virtual DbSet<tblMortgage> tblMortgages { get; set; } public virtual DbSet<tblMortgagor> tblMortgagors { get; set; } public virtual DbSet<tblPIN> tblPINs { get; set; } public virtual DbSet<tblProperty> tblProperties { get; set; } public virtual DbSet<tblVendor> tblVendors { get; set; } public virtual DbSet<tblDealHistory> tblDealHistories { get; set; } public virtual DbSet<tblLender> tblLenders { get; set; } public virtual DbSet<tblMilestone> tblMilestones { get; set; } public virtual DbSet<tblMilestoneCode> tblMilestoneCodes { get; set; } public virtual DbSet<tblMilestoneLabel> tblMilestoneLabels { get; set; } public virtual DbSet<tblNote> tblNotes { get; set; } public virtual DbSet<tblBranchContact> tblBranchContacts { get; set; } public virtual DbSet<tblDealFundsAllocation> tblDealFundsAllocations { get; set; } public virtual DbSet<tblFundingDeal> tblFundingDeals { get; set; } public virtual DbSet<tblDisbursement> tblDisbursements { get; set; } public virtual DbSet<tblDisbursementSummary> tblDisbursementSummaries { get; set; } public virtual DbSet<vw_EFDisbursementSummary> vw_EFDisbursementSummaries { get; set; } public virtual DbSet<vw_Deal> vw_Deals { get; set; } public virtual DbSet<tblDisbursementDealDocumentType> tblDisbursementDealDocumentTypes { get; set; } public virtual DbSet<vw_PayoutLetterWorklist> vw_PayoutLetterWorklist { get; set; } public virtual DbSet<tblPaymentRequest> tblPaymentRequests { get; set; } public virtual DbSet<tblPaymentNotification> tblPaymentNotifications { get; set; } public virtual DbSet<vw_ReconciliationItem> vw_ReconciliationItems { get; set; } public virtual DbSet<tblGlobalization> tblGlobalizations { get; set; } public virtual DbSet<tblStatusReason> tblStatusReasons { get; set; } public virtual DbSet<tblLawyerClerk> tblLawyerClerks { get; set; } public virtual DbSet<tblFee> tblFees { get; set; } public virtual DbSet<tblDocumentType> tblDocumentType { get; set; } public virtual DbSet<tblDealDocumentType> tblDealDocumentType { get; set; } public virtual DbSet<tblFinancialInstitutionNumber> tblFinancialInstitutionNumbers { get; set; } public virtual DbSet<tblQuestion> tblQuestions { get; set; } public virtual DbSet<tblAnswerType> tblAnswerTypes { get; set; } public virtual DbSet<tblAnswer> tblAnswers { get; set; } public virtual DbSet<tblPifInfo> tblPifInfos { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<EFBusinessContext>(null); modelBuilder.Entity<tblDeal>() .Property(e => e.FCTRefNum) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderRefNum) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderComment) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.Status) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.StatusUserType) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.StatusReason) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LawyerMatterNumber) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblDeal>() .Property(e => e.BusinessModel) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LawyerApplication) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.Encumbrances) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderDealRefNumber) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.RFFComment) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderRepresentativeFirstName) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderRepresentativeLastName) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderRepresentativeTitle) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.DistrictName) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LenderSecurityType) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.LawyerActingFor) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .Property(e => e.DealType) .IsUnicode(false); modelBuilder.Entity<tblDeal>() .HasMany(e => e.tblDealContacts) .WithRequired(e => e.tblDeal) .WillCascadeOnDelete(false); modelBuilder.Entity<tblDeal>() .HasMany(e => e.tblMortgagors) .WithRequired(e => e.tblDeal) .WillCascadeOnDelete(false); modelBuilder.Entity<tblDeal>() .HasMany(e => e.tblProperties) .WithRequired(e => e.tblDeal) .WillCascadeOnDelete(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.FCTRefNum) .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.LenderRefNum) .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.LLCRefNum) .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.Status) .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.StatusUserType) .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.StatusReason) .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.LawyerMatterNumber) .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.LastModified) // .IsFixedLength(); modelBuilder.Entity<vw_Deal>() .Property(e => e.BusinessModel) .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.LawyerApplication) // .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.Encumbrances) // .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.LenderDealRefNumber) // .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.RFFComment) // .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.LenderRepresentativeFirstName) // .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.LenderRepresentativeLastName) // .IsUnicode(false); //modelBuilder.Entity<vw_Deal>() // .Property(e => e.LenderRepresentativeTitle) // .IsUnicode(false); // modelBuilder.Entity<vw_Deal>() // .Property(e => e.DistrictName) // .IsUnicode(false); // modelBuilder.Entity<vw_Deal>() // .Property(e => e.LenderSecurityType) // .IsUnicode(false); modelBuilder.Entity<vw_Deal>() .Property(e => e.LawyerActingFor) .IsUnicode(false); // modelBuilder.Entity<vw_Deal>() // .Property(e => e.DealType) // .IsUnicode(false); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.AssignedTo) .IsUnicode(false); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.ChequeBatchDescription) .IsUnicode(false); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.ChequeBatchNumber) .IsUnicode(false); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.DealID); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.DisbursementDate); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.FCTURN) .IsUnicode(false); modelBuilder.Entity<vw_PayoutLetterWorklist>() .Property(e => e.NumberOfCheques); modelBuilder.Entity<tblDealScope>() .Property(e => e.FCTRefNumber) .IsUnicode(false); modelBuilder.Entity<tblDealScope>() .Property(e => e.ShortFCTRefNumber) .IsUnicode(false); modelBuilder.Entity<tblDealScope>() .HasMany(e => e.tblVendors) .WithRequired(e => e.tblDealScope) .WillCascadeOnDelete(false); modelBuilder.Entity<tblDealScope>() .HasMany(e => e.tblFundingDeals) .WithRequired(e => e.DealScope).WillCascadeOnDelete(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LastName) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.FirstName) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.MiddleName) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LawFirm) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.UnitNo) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Address) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Address2) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.City) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Province) .IsFixedLength() .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.PostalCode) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Phone) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.MobilePhone) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Fax) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.EMail) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.UserID) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblLawyer>() .Property(e => e.Comments) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LawyerSoftwareUsed) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Profession) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.StreetNumber) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.UserLanguage) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.Country) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.RequestSource) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.InternetBrowserUsed) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LawSocietyFirstName) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LawSocietyMiddleName) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.LawSocietyLastName) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .Property(e => e.SolicitorSyncLawSocietyStatus) .IsUnicode(false); modelBuilder.Entity<tblLawyer>() .HasMany(e => e.tblDeals) .WithRequired(e => e.tblLawyer) .WillCascadeOnDelete(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.MortgageNumber) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.MortgageAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.MortgageType) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.TransactionType) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.InterestRate) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.MaximumRate) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.BaseRate) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.MaximumAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.CalculationPeriod) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.StandardChargeTerm) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.PaymentDay) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.InterestAdjustAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.BonusDiscountAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.NetAdvance) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.BrokerName) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.BrokerPhone) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.RegisteredAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.MortgageInsurer) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.InterestRateType) .IsUnicode(false); modelBuilder.Entity<tblMortgage>() .Property(e => e.EquivalentRate) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.CashbackAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.PurchasePrice) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.IncrementAboveBelowPrime) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.ActualMortgageRate) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.MonthlyPayment) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgage>() .Property(e => e.EarlyPaymentAmount) .HasPrecision(18, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblMortgage>() .Property(e => e.IncrementAboveBelowPrimeInstruction) .HasPrecision(9, 5); modelBuilder.Entity<tblMortgage>() .Property(e => e.MortgageAmountAdvanced) .HasPrecision(19, 4); modelBuilder.Entity<tblMortgagor>() .Property(e => e.MortgagorType) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.LastName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.FirstName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.MiddleName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.CompanyName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.Address) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.City) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.Province) .IsFixedLength() .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.PostalCode) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.HomePhone) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.BusinessPhone) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.SpouseLastName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.SpouseFirstName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.SpouseMiddleName) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.Occupation) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblMortgagor>() .Property(e => e.UnitNumber) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.StreetNumber) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.Address2) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.Country) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.Language) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.SpousalStatement) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.SpouseOccupation) .IsUnicode(false); modelBuilder.Entity<tblMortgagor>() .Property(e => e.CompanyProvinceOfIncorporation) .IsFixedLength() .IsUnicode(false); modelBuilder.Entity<tblPIN>() .Property(e => e.PINNumber) .IsUnicode(false); modelBuilder.Entity<tblPIN>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblProperty>() .Property(e => e.Address) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.City) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.Province) .IsFixedLength() .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.PostalCode) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.HomePhone) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.BusinessPhone) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.LegalDescription) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.ARN) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.EstateType) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.InstrumentNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.AmountOfTaxesPaid) .HasPrecision(19, 4); modelBuilder.Entity<tblProperty>() .Property(e => e.PropertyType) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.OccupancyType) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.AnnualTaxAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblProperty>() .Property(e => e.RegistryOffice) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoLevel) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoUnitNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoCorporationNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblProperty>() .Property(e => e.UnitNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.StreetNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.Address2) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.Country) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.BookFolioRoll) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.PageFrame) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoDeclarationRegistrationNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoBookNoOfDeclaration) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoPageNumberOfDeclaration) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoPlanNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.AssignmentOfRentsRegistrationNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.MortgagePriority) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.OtherEstateTypeDescription) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.CondoDeclarationModificationNumber) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .Property(e => e.JudicialDistrict) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .HasMany(e => e.tblPINs) .WithRequired(e => e.tblProperty) .WillCascadeOnDelete(false); modelBuilder.Entity<tblVendor>() .Property(e => e.VendorType) .IsUnicode(false); modelBuilder.Entity<tblVendor>() .Property(e => e.FirstName) .IsUnicode(false); modelBuilder.Entity<tblVendor>() .Property(e => e.MiddleName) .IsUnicode(false); modelBuilder.Entity<tblVendor>() .Property(e => e.LastName) .IsUnicode(false); modelBuilder.Entity<tblVendor>() .Property(e => e.CompanyName) .IsUnicode(false); modelBuilder.Entity<tblDealHistory>() .Property(e => e.Activity) .IsUnicode(false); modelBuilder.Entity<tblDealHistory>() .Property(e => e.ActivityFrench) .IsUnicode(false); modelBuilder.Entity<tblDealHistory>() .Property(e => e.UserID) .IsUnicode(false); modelBuilder.Entity<tblDealHistory>() .Property(e => e.UserType) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.LenderCode) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.Address) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.City) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.Province) .IsFixedLength() .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.PostalCode) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.Phone) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.Fax) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.LogoName) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.BillingID) .IsUnicode(false); modelBuilder.Entity<tblLender>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblLender>() .Property(e => e.ShortName) .IsUnicode(false); modelBuilder.Entity<tblLender>() .HasMany(e => e.tblMilestoneLabels) .WithRequired(e => e.tblLender) .WillCascadeOnDelete(false); modelBuilder.Entity<tblMilestoneCode>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<tblMilestoneCode>() .Property(e => e.Description) .IsUnicode(false); modelBuilder.Entity<tblMilestoneCode>() .Property(e => e.BusinessModel) .IsUnicode(false); modelBuilder.Entity<tblMilestoneCode>() .HasMany(e => e.tblMilestones) .WithRequired(e => e.tblMilestoneCode) .WillCascadeOnDelete(false); modelBuilder.Entity<tblMilestoneCode>() .HasMany(e => e.tblMilestoneLabels) .WithRequired(e => e.tblMilestoneCode) .WillCascadeOnDelete(false); modelBuilder.Entity<tblMilestoneLabel>() .Property(e => e.LabelEnglish) .IsUnicode(false); modelBuilder.Entity<tblMilestoneLabel>() .Property(e => e.LabelFrench) .IsUnicode(false); modelBuilder.Entity<tblNote>() .Property(e => e.Notes) .IsUnicode(false); modelBuilder.Entity<tblNote>() .Property(e => e.Usertype) .IsUnicode(false); modelBuilder.Entity<tblNote>() .Property(e => e.Title) .IsUnicode(false); modelBuilder.Entity<tblNote>() .Property(e => e.NoteType) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.LastName) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.FirstName) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.MiddleName) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.Phone) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.Extension) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.Fax) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.EMail) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.UserID) .IsUnicode(false); modelBuilder.Entity<tblBranchContact>() .Property(e => e.LastModified) .IsFixedLength(); modelBuilder.Entity<tblBranchContact>() .Property(e => e.Comment) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.ReferenceNumber) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.Amount) .HasPrecision(19, 4); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.BankNumber) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.BranchNumber) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.AccountNumber) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.WireDepositDetails) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.ShortFCTRefNumber) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.AllocationStatus) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.Version) .IsFixedLength().IsRowVersion(); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.RecordType) .IsUnicode(false); modelBuilder.Entity<tblDealFundsAllocation>() .Property(e => e.ReconciledBy) .IsUnicode(false); modelBuilder.Entity<tblDisbursementSummary>() .Property(e => e.Version) .IsFixedLength().IsRowVersion(); modelBuilder.Entity<tblDisbursementSummary>() .Property(e => e.DepositAmountRequired) .HasPrecision(19, 4); modelBuilder.Entity<tblDisbursementSummary>() .Property(e => e.Comments) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.PayeeType) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.PayeeName) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.PayeeComments) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.Amount) .HasPrecision(19, 4); modelBuilder.Entity<tblDisbursement>() .Property(e => e.PaymentMethod) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.NameOnCheque) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.UnitNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.StreetNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.City) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.Province) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.PostalCode) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.Country) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.ReferenceNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.AssessmentRollNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.BankNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.BranchNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.AccountNumber) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.Instructions) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.AgentFirstName) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.AgentLastName) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.AccountAction) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.FCTFeeSplit) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.DisbursementComment) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.DisbursedAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblDisbursement>() .Property(e => e.DisbursementStatus) .IsUnicode(false); modelBuilder.Entity<tblDisbursement>() .Property(e => e.ReconciledBy) .IsUnicode(false); modelBuilder.Entity<tblGlobalization>() .Property(e => e.LocaleID) .IsUnicode(false); modelBuilder.Entity<tblGlobalization>() .Property(e => e.ResourceSet) .IsUnicode(false); modelBuilder.Entity<tblGlobalization>() .Property(e => e.ResourceKey) .IsUnicode(false); modelBuilder.Entity<vw_EFDisbursementSummary>() .Property(e => e.DepositAmountReceived) .HasPrecision(19, 4); modelBuilder.Entity<vw_EFDisbursementSummary>() .Property(e => e.DepositAmountRequired) .HasPrecision(19, 4); modelBuilder.Entity<tblFee>() .Property(e => e.Amount) .HasPrecision(19, 4); modelBuilder.Entity<tblFee>() .Property(e => e.HST) .HasPrecision(19, 4); modelBuilder.Entity<tblFee>() .Property(e => e.GST) .HasPrecision(19, 4); modelBuilder.Entity<tblFee>() .Property(e => e.QST) .HasPrecision(19, 4); modelBuilder.Entity<tblPaymentRequest>() .Property(e => e.Message) .IsUnicode(false); modelBuilder.Entity<tblPaymentNotification>() .Property(e => e.PaymentAmount) .HasPrecision(19, 4); modelBuilder.Entity<tblPaymentNotification>() .Property(e => e.NotificationType) .IsUnicode(false); modelBuilder.Entity<tblPaymentNotification>() .Property(e => e.ReferenceNumber) .IsUnicode(false); modelBuilder.Entity<tblPaymentNotification>() .Property(e => e.PaymentStatus) .IsUnicode(false); modelBuilder.Entity<tblPaymentNotification>() .Property(e => e.BatchDescription) .IsUnicode(false); modelBuilder.Entity<tblPaymentNotification>() .Property(e => e.BatchID) .IsUnicode(false); modelBuilder.Entity<vw_ReconciliationItem>() .Property(e => e.AmountIn) .HasPrecision(19, 4); modelBuilder.Entity<vw_ReconciliationItem>() .Property(e => e.AmountOut) .HasPrecision(19, 4); /* Builder Details */ modelBuilder.Entity<tblBuilderLegalDescription>() .Property(e => e.BuilderProjectReference) .IsUnicode(false); modelBuilder.Entity<tblBuilderLegalDescription>() .Property(e => e.BuilderLot) .IsUnicode(false); modelBuilder.Entity<tblBuilderLegalDescription>() .Property(e => e.Lot) .IsUnicode(false); modelBuilder.Entity<tblBuilderLegalDescription>() .Property(e => e.Plan) .IsUnicode(false); modelBuilder.Entity<tblBuilderUnitLevel>() .Property(e => e.Unit) .IsUnicode(false); modelBuilder.Entity<tblBuilderUnitLevel>() .Property(e => e.Level) .IsUnicode(false); modelBuilder.Entity<tblProperty>() .HasMany(e => e.tblBuilderLegalDescriptions) .WithRequired(e => e.tblProperty) .WillCascadeOnDelete(false); modelBuilder.Entity<tblBuilderLegalDescription>() .HasMany(e => e.tblBuilderUnitLevels) .WithRequired(e => e.tblBuilderLegalDescription) .WillCascadeOnDelete(false); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /** This is meant to contain useful utilities for IO related work **/ #define TRACE #define DEBUG using System; using System.IO; using System.Text; using System.Diagnostics; using System.Collections.Generic; using System.Threading.Tasks; using System.Runtime.InteropServices; //machine information public static class FileSystemDebugInfo { public static String MachineInfo() { StringBuilder builder = new StringBuilder(String.Format("{0}/////////Machine Info///////////{0}", Environment.NewLine)); builder.AppendLine(String.Format("CurrentDrive NTFS?: {0}", IsCurrentDriveNTFS())); builder.AppendLine(String.Format("////////////////////{0}", Environment.NewLine)); return builder.ToString(); } public static bool IsCurrentDriveNTFS() { return IOServices.IsDriveNTFS(IOServices.GetCurrentDrive()); } public static bool IsPathAdminAccessOnly(String path, bool treatPathAsFilePath) { //we leave invalid paths as valid testcase scenarios and dont filter these //1) We check if the path is root on a system drive //2) @TODO WinDir? String systemDrive = Environment.GetEnvironmentVariable("SystemDrive"); Char systemDriveLetter = systemDrive.ToLower()[0]; try { String dirName = Path.GetFullPath(path); if (treatPathAsFilePath) dirName = Path.GetDirectoryName(dirName); if ((new DirectoryInfo(dirName)).Parent == null) { if (Path.GetPathRoot(dirName).StartsWith(systemDriveLetter.ToString(), StringComparison.OrdinalIgnoreCase)) return true; } } catch (Exception) { } return false; } } /// <summary> /// Due to the increasing number of context indexing services (mssearch.exe, etrust) operating in our test run machines, Directory operations like Delete and Move /// are not guaranteed to work in first attempt. This utility class do these operations in a fail safe manner /// Possible solutions /// - Set FileAttributes.NotContentIndex on the directory. But there is a race between creating the directory and setting this property. Other than using ACL, can't see a good solution /// - encourage labs to stop these services before a test run. This is under review by CLRLab but there are lots of other labs that do these too /// - fail and retry attempt: which is what this class does /// VSW 446086 and 473287 have more information on this. /// </summary> public static class FailSafeDirectoryOperations { /// <summary> /// Deleting /// </summary> /// <param name="path"></param> /// <param name="recursive"></param> private const int MAX_ATTEMPT = 10; public static void DeleteDirectory(String path, bool recursive) { DeleteDirectoryInfo(new DirectoryInfo(path), recursive); } public static void DeleteDirectoryInfo(DirectoryInfo dirInfo, bool recursive) { int dirModificationAttemptCount; bool dirModificationOperationThrew; dirModificationAttemptCount = 0; do { dirModificationOperationThrew = false; try { if (dirInfo.Exists) dirInfo.Delete(recursive); } catch (IOException) { Console.Write("|"); dirModificationOperationThrew = true; } catch (UnauthorizedAccessException) { Console.Write("}"); dirModificationOperationThrew = true; } if (dirModificationOperationThrew) { Task.Delay(5000).Wait(); } } while (dirModificationOperationThrew && dirModificationAttemptCount++ < MAX_ATTEMPT); EnsureDirectoryNotExist(dirInfo.FullName); //We want to thrown if the operation failed if (Directory.Exists(dirInfo.FullName)) throw new ArgumentException("Throwing from FailSafeDirectoryOperations.DeleteDirectoryInfo. Delete unsucccesfull"); } /// <summary> /// Moving /// </summary> /// <param name="sourceName"></param> /// <param name="destName"></param> public static void MoveDirectory(String sourceName, String destName) { MoveDirectoryInfo(new DirectoryInfo(sourceName), destName); } public static DirectoryInfo MoveDirectoryInfo(DirectoryInfo dirInfo, String dirToMove) { int dirModificationAttemptCount; bool dirModificationOperationThrew; dirModificationAttemptCount = 0; String originalDirName = dirInfo.FullName; do { dirModificationOperationThrew = false; try { dirInfo.MoveTo(dirToMove); } catch (IOException) { Console.Write(">"); Task.Delay(5000).Wait(); dirModificationOperationThrew = true; } } while (dirModificationOperationThrew && dirModificationAttemptCount++ < MAX_ATTEMPT); EnsureDirectoryNotExist(originalDirName); //We want to thrown if the operation failed if (Directory.Exists(originalDirName)) throw new ArgumentException("Throwing from FailSafeDirectoryOperations.MoveDirectory. Move unsucccesfull"); return dirInfo; } /// <summary> /// It can take some time before the Directory.Exists will return false after a direcotry delete/Move /// </summary> /// <param name="path"></param> private static void EnsureDirectoryNotExist(String path) { int dirModificationAttemptCount; dirModificationAttemptCount = 0; while (Directory.Exists(path) && dirModificationAttemptCount++ < MAX_ATTEMPT) { // This is because something like antivirus software or // some disk indexing service has a handle to the directory. The directory // won't be deleted until all of the handles are closed. Task.Delay(5000).Wait(); Console.Write("<"); } } } /// <summary> /// This class is meant to create directory and files under it /// </summary> public class ManageFileSystem : IDisposable { private const int DefaultDirectoryDepth = 3; private const int DefaultNumberofFiles = 100; private const int MaxNumberOfSubDirsPerDir = 2; //@TODO public const String DirPrefixName = "Laks_"; private int _directoryLevel; private int _numberOfFiles; private string _startDir; private Random _random; private List<String> _listOfFiles; private List<String> _listOfAllDirs; private Dictionary<int, Dictionary<String, List<String>>> _allDirs; public ManageFileSystem() { Init(GetNonExistingDir(Directory.GetCurrentDirectory(), DirPrefixName), DefaultDirectoryDepth, DefaultNumberofFiles); } public ManageFileSystem(String startDirName) : this(startDirName, DefaultDirectoryDepth, DefaultNumberofFiles) { } public ManageFileSystem(String startDirName, int dirDepth, int numFiles) { Init(startDirName, dirDepth, numFiles); } public static String GetNonExistingDir(String parentDir, String prefix) { String tempPath; while (true) { tempPath = Path.Combine(parentDir, String.Format("{0}{1}", prefix, Path.GetFileNameWithoutExtension(Path.GetRandomFileName()))); if (!Directory.Exists(tempPath) && !File.Exists(tempPath)) break; } return tempPath; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // free other state (managed objects) // set interesting (large) fields to null } // free your own state (unmanaged objects) FailSafeDirectoryOperations.DeleteDirectory(_startDir, true); } ~ManageFileSystem() { Dispose(false); } private void Init(String startDirName, int dirDepth, int numFiles) { if (Directory.Exists(Path.GetFullPath(startDirName))) throw new ArgumentException(String.Format("ERROR: Directory exists : {0}", _startDir)); _startDir = Path.GetFullPath(startDirName); _directoryLevel = dirDepth; _numberOfFiles = numFiles; _random = new Random(-55); CreateFileSystem(); } /// <summary> /// This API creates a file system under m_startDir, m_DirectoryLevel deep with m_numberOfFiles /// We will store the created information on collections so as to get to them later /// </summary> private void CreateFileSystem() { _listOfFiles = new List<String>(); _listOfAllDirs = new List<String>(); Directory.CreateDirectory(_startDir); //we will not include this directory // m_listOfAllDirs.Add(m_startDir); String currentWorkingDir = _startDir; String parentDir = _startDir; _allDirs = new Dictionary<int, Dictionary<String, List<String>>>(); // List<String> dirsForOneLevel = new List<String>(); // List<String> tempDirsForOneLevel; List<String> filesForThisDir; Dictionary<String, List<String>> dirsForOneLevel = new Dictionary<String, List<String>>(); Dictionary<String, List<String>> tempDirsForOneLevel; dirsForOneLevel.Add(_startDir, new List<String>()); _allDirs.Add(0, dirsForOneLevel); //First we create the directories for (int i = 0; i < (_directoryLevel - 1); i++) { dirsForOneLevel = _allDirs[i]; int numOfDirForThisLevel = _random.Next((MaxNumberOfSubDirsPerDir + 1)); int numOfDirPerDir = numOfDirForThisLevel / dirsForOneLevel.Count; //@TODO!! we should handle this situation in a better way if (numOfDirPerDir == 0) numOfDirPerDir = 1; // Trace.Assert(numOfDirPerDir > 0, "Err_897324g! @TODO handle this scenaior"); tempDirsForOneLevel = new Dictionary<String, List<String>>(); foreach (String dir in dirsForOneLevel.Keys) // for (int j = 0; j < dirsForOneLevel.Count; j++) { for (int k = 0; k < numOfDirPerDir; k++) { String dirName = GetNonExistingDir(dir, DirPrefixName); Debug.Assert(!Directory.Exists(dirName), String.Format("ERR_93472g! Directory exists: {0}", dirName)); tempDirsForOneLevel.Add(dirName, new List<String>()); _listOfAllDirs.Add(dirName); Directory.CreateDirectory(dirName); } } _allDirs.Add(i + 1, tempDirsForOneLevel); } //Then we add the files //@TODO!! random or fixed? int numberOfFilePerDirLevel = _numberOfFiles / _directoryLevel; Byte[] bits; for (int i = 0; i < _directoryLevel; i++) { dirsForOneLevel = _allDirs[i]; int numOfFilesForThisLevel = _random.Next(numberOfFilePerDirLevel + 1); int numOFilesPerDir = numOfFilesForThisLevel / dirsForOneLevel.Count; //UPDATE: 2/1/2005, we will add at least 1 if (numOFilesPerDir == 0) numOFilesPerDir = 1; // for (int j = 0; j < dirsForOneLevel.Count; j++) foreach (String dir in dirsForOneLevel.Keys) { filesForThisDir = dirsForOneLevel[dir]; for (int k = 0; k < numOFilesPerDir; k++) { String fileName = Path.Combine(dir, Path.GetFileName(Path.GetRandomFileName())); bits = new Byte[_random.Next(10)]; _random.NextBytes(bits); File.WriteAllBytes(fileName, bits); _listOfFiles.Add(fileName); filesForThisDir.Add(fileName); } } } } public String StartDirectory { get { return _startDir; } } //some methods to help us public String[] GetDirectories(int level) { Dictionary<String, List<String>> dirsForThisLevel = null; if (_allDirs.TryGetValue(level, out dirsForThisLevel)) { // Dictionary<String, List<String>> dirsForThisLevel = m_allDirs[level]; ICollection<String> keys = dirsForThisLevel.Keys; String[] values = new String[keys.Count]; keys.CopyTo(values, 0); return values; } else return new String[0]; } /// <summary> /// Note that this doesn't return the m_startDir /// </summary> /// <returns></returns> public String[] GetAllDirectories() { return _listOfAllDirs.ToArray(); } public String[] GetFiles(String dirName, int level) { String dirFullName = Path.GetFullPath(dirName); Dictionary<String, List<String>> dirsForThisLevel = _allDirs[level]; foreach (String dir in dirsForThisLevel.Keys) { if (dir.Equals(dirFullName, StringComparison.CurrentCultureIgnoreCase)) return dirsForThisLevel[dir].ToArray(); } return null; } public String[] GetAllFiles() { return _listOfFiles.ToArray(); } } public class TestInfo { static TestInfo() { CurrentDirectory = Directory.GetCurrentDirectory(); } public static string CurrentDirectory { get; set; } private delegate void ExceptionCode(); private void DeleteFile(String fileName) { if (File.Exists(fileName)) File.Delete(fileName); } //Checks for error private static bool Eval(bool expression, String msg, params Object[] values) { return Eval(expression, String.Format(msg, values)); } private static bool Eval<T>(T actual, T expected, String errorMsg) { bool retValue = expected == null ? actual == null : expected.Equals(actual); if (!retValue) Eval(retValue, errorMsg + " Expected:" + (null == expected ? "<null>" : expected.ToString()) + " Actual:" + (null == actual ? "<null>" : actual.ToString())); return retValue; } private static bool Eval(bool expression, String msg) { if (!expression) { Console.WriteLine(msg); } return expression; } //Checks for a particular type of exception private static void CheckException<E>(ExceptionCode test, string error) { CheckException<E>(test, error, null); } //Checks for a particular type of exception and an Exception msg private static void CheckException<E>(ExceptionCode test, string error, String msgExpected) { bool exception = false; try { test(); error = String.Format("{0} Exception NOT thrown ", error); } catch (Exception e) { if (e.GetType() == typeof(E)) { exception = true; if (System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && msgExpected != null && e.Message != msgExpected) { exception = false; error = String.Format("{0} Message Different: <{1}>", error, e.Message); } } else error = String.Format("{0} Exception type: {1}", error, e.GetType().Name); } Eval(exception, error); } }
using System; using System.Drawing; using System.Drawing.Drawing2D; namespace Comzept.Library.Drawing.Shapes { public class ShapeRectangle : Shape,IDrawable,IFillable,IRectangle { private RectangleF _bounds; #region Constructors internal ShapeRectangle() { this.Rotation = 0; this.Pen = Pens.Transparent; } public ShapeRectangle(float left, float top, float width, float height) : this(new RectangleF(left, top, width, height), 0) { } public ShapeRectangle(float left, float top, float width, float height, float rotation) : this(new RectangleF(left, top, width, height), rotation) { } public ShapeRectangle(RectangleF bounds) : this(bounds, 0) { } public ShapeRectangle(RectangleF bounds, float rotation) { _bounds = bounds; this.Rotation = rotation; UpdatePath(); this.Pen = Pens.Transparent; } public ShapeRectangle(PointF firstCorner, PointF secondCorner) : this(firstCorner, secondCorner, 0) { } public ShapeRectangle(PointF firstCorner, PointF secondCorner, float rotation) { float left = Math.Min(firstCorner.X, secondCorner.X); float top = Math.Min(firstCorner.X, secondCorner.X); float width = Math.Abs(firstCorner.X - secondCorner.X); float height = Math.Abs(firstCorner.Y - secondCorner.Y); _bounds = new RectangleF(left, top, width, height); this.Rotation = rotation; UpdatePath(); this.Pen = Pens.Transparent; } public ShapeRectangle(float left, float top, float width, float height, Pen pen) : this(new RectangleF(left, top, width, height), 0, pen) { } public ShapeRectangle(float left, float top, float width, float height, float rotation, Pen pen) : this(new RectangleF(left, top, width, height), rotation, pen) { } public ShapeRectangle(RectangleF bounds, Pen pen) : this(bounds, 0, pen) { } public ShapeRectangle(RectangleF bounds, float rotation, Pen pen) : this(bounds, rotation) { this.Pen = pen; this.Brush = Brushes.Transparent; } public ShapeRectangle(PointF firstCorner, PointF secondCorner, Pen pen) : this(firstCorner, secondCorner, 0, pen) { } public ShapeRectangle(PointF firstCorner, PointF secondCorner, float rotation, Pen pen) : this(firstCorner, secondCorner, rotation) { this.Pen = pen; this.Brush = Brushes.Transparent; } public ShapeRectangle(float left, float top, float width, float height, Brush brush) : this(new RectangleF(left, top, width, height), 0, brush) { } public ShapeRectangle(float left, float top, float width, float height, float rotation, Brush brush) : this(new RectangleF(left, top, width, height), rotation, brush) { } public ShapeRectangle(RectangleF bounds, Brush brush) : this(bounds, 0, brush) { } public ShapeRectangle(RectangleF bounds, float rotation, Brush brush) : this(bounds, rotation) { this.Pen = Pens.Transparent; this.Brush = brush; } public ShapeRectangle(PointF firstCorner, PointF secondCorner, Brush brush) : this(firstCorner, secondCorner, 0, brush) { } public ShapeRectangle(PointF firstCorner, PointF secondCorner, float rotation, Brush brush) : this(firstCorner, secondCorner, rotation) { this.Pen = Pens.Transparent; this.Brush = brush; } public ShapeRectangle(float left, float top, float width, float height, Pen pen, Brush brush) : this(new RectangleF(left, top, width, height), 0, pen, brush) { } public ShapeRectangle(float left, float top, float width, float height, float rotation, Pen pen, Brush brush) : this(new RectangleF(left, top, width, height), 0, pen, brush) { } public ShapeRectangle(RectangleF bounds, Pen pen, Brush brush) : this(bounds, 0, pen, brush) { } public ShapeRectangle(RectangleF bounds, float rotation, Pen pen, Brush brush) : this(bounds, rotation) { this.Pen = pen; this.Brush = brush; } public ShapeRectangle(PointF firstCorner, PointF secondCorner, Pen pen, Brush brush) : this(firstCorner, secondCorner, 0, pen, brush) { } public ShapeRectangle(PointF firstCorner, PointF secondCorner, float rotation, Pen pen, Brush brush) : this(firstCorner, secondCorner, rotation) { this.Pen = pen; this.Brush = brush; } #endregion #region Overrides public override RectangleF Bounds { get { return _bounds; } } public override PointF Center { get { return new PointF ( (_bounds.Left + _bounds.Right) / 2, (_bounds.Top + _bounds.Bottom) / 2 ); } set { PointF oldCenter = this.Center; float dx = value.X - oldCenter.X; float dy = value.Y - oldCenter.Y; Translate(dx, dy); } } public override PointF Location { get { return _bounds.Location; } set { _bounds.Location = value; UpdatePath(); } } public override void Paint(Graphics graphics, SmoothingMode smoothingMode) { this.Fill(graphics); this.Draw(graphics, smoothingMode); } public override void Rotate(float value, PointF basePoint) { this.Rotation = value; InternalRotationBasePoint = basePoint; UpdatePath(); } public override void Translate(float dx, float dy) { _bounds.X += dx; _bounds.Y += dy; UpdatePath(); } public override Image GetThumb(ShapeThumbSize thumbSize) { throw new Exception("The method or operation is not implemented."); } public override string ToString() { return "{Comzept.Library.Drawing.Shapes.ShapeRectangle}"; } protected override void UpdatePath() { InternalPath = new GraphicsPath(FillMode.Winding); InternalPath.AddRectangle(_bounds); Matrix mtx = new Matrix(); mtx.RotateAt(this.Rotation, InternalRotationBasePoint); InternalPath.Transform(mtx); } #endregion #region IDrawable Members public void Draw(Graphics graphics) { this.Draw(graphics, graphics.SmoothingMode); } public void Draw(Graphics graphics, SmoothingMode smoothingMode) { SmoothingMode sMode = graphics.SmoothingMode; graphics.SmoothingMode = smoothingMode; if (this.Brush != null) graphics.FillPath(this.Brush, InternalPath); graphics.DrawPath(this.Pen, InternalPath); graphics.SmoothingMode = sMode; } #endregion #region IFillable Members public void Fill(Graphics graphics) { if(this.Brush != null) graphics.FillPath(this.Brush, InternalPath); } #endregion #region IRectangle Members - Virtuals public virtual float Left { get { return _bounds.Left; } set { _bounds.X = value; UpdatePath(); } } public virtual float Top { get { return _bounds.Top; } set { _bounds.Y = value; UpdatePath(); } } public virtual float Width { get { return _bounds.Width; } set { _bounds.Width = value; UpdatePath(); } } public virtual float Height { get { return _bounds.Height; } set { _bounds.Height = value; UpdatePath(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { public sealed partial class CryptographicAttributeObject { public CryptographicAttributeObject(System.Security.Cryptography.Oid oid) { } public CryptographicAttributeObject(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedDataCollection values) { } public System.Security.Cryptography.Oid Oid { get { throw null; } } public System.Security.Cryptography.AsnEncodedDataCollection Values { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public sealed partial class CryptographicAttributeObjectCollection : System.Collections.ICollection, System.Collections.IEnumerable { public CryptographicAttributeObjectCollection() { } public CryptographicAttributeObjectCollection(System.Security.Cryptography.CryptographicAttributeObject attribute) { } public int Count { get { throw null; } } public System.Security.Cryptography.CryptographicAttributeObject this[int index] { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public int Add(System.Security.Cryptography.AsnEncodedData asnEncodedData) { throw null; } public int Add(System.Security.Cryptography.CryptographicAttributeObject attribute) { throw null; } public void CopyTo(System.Security.Cryptography.CryptographicAttributeObject[] array, int index) { } public System.Security.Cryptography.CryptographicAttributeObjectEnumerator GetEnumerator() { throw null; } public void Remove(System.Security.Cryptography.CryptographicAttributeObject attribute) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class CryptographicAttributeObjectEnumerator : System.Collections.IEnumerator { internal CryptographicAttributeObjectEnumerator() { } public System.Security.Cryptography.CryptographicAttributeObject Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } } namespace System.Security.Cryptography.Pkcs { public sealed partial class AlgorithmIdentifier { public AlgorithmIdentifier() { } public AlgorithmIdentifier(System.Security.Cryptography.Oid oid) { } public AlgorithmIdentifier(System.Security.Cryptography.Oid oid, int keyLength) { } public int KeyLength { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.Security.Cryptography.Oid Oid { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public byte[] Parameters { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } public sealed partial class CmsRecipient { public CmsRecipient(System.Security.Cryptography.Pkcs.SubjectIdentifierType recipientIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public CmsRecipient(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.Security.Cryptography.Pkcs.SubjectIdentifierType RecipientIdentifierType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public sealed partial class CmsRecipientCollection : System.Collections.ICollection, System.Collections.IEnumerable { public CmsRecipientCollection() { } public CmsRecipientCollection(System.Security.Cryptography.Pkcs.CmsRecipient recipient) { } public CmsRecipientCollection(System.Security.Cryptography.Pkcs.SubjectIdentifierType recipientIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public int Count { get { throw null; } } public System.Security.Cryptography.Pkcs.CmsRecipient this[int index] { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public int Add(System.Security.Cryptography.Pkcs.CmsRecipient recipient) { throw null; } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Security.Cryptography.Pkcs.CmsRecipient[] array, int index) { } public System.Security.Cryptography.Pkcs.CmsRecipientEnumerator GetEnumerator() { throw null; } public void Remove(System.Security.Cryptography.Pkcs.CmsRecipient recipient) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class CmsRecipientEnumerator : System.Collections.IEnumerator { internal CmsRecipientEnumerator() { } public System.Security.Cryptography.Pkcs.CmsRecipient Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public sealed partial class CmsSigner { public CmsSigner() => throw null; public CmsSigner(SubjectIdentifierType signerIdentifierType) => throw null; public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) => throw null; [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public CmsSigner(CspParameters parameters) => throw null; public CmsSigner(SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) => throw null; public SubjectIdentifierType SignerIdentifierType { get => throw null; set => throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get => throw null; set => throw null; } public Oid DigestAlgorithm { get => throw null; set => throw null; } public CryptographicAttributeObjectCollection SignedAttributes { get => throw null; } public CryptographicAttributeObjectCollection UnsignedAttributes { get => throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get => throw null; } public System.Security.Cryptography.X509Certificates.X509IncludeOption IncludeOption { get => throw null; set => throw null; } } public sealed partial class ContentInfo { public ContentInfo(byte[] content) { } public ContentInfo(System.Security.Cryptography.Oid contentType, byte[] content) { } public byte[] Content { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.Security.Cryptography.Oid ContentType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public static System.Security.Cryptography.Oid GetContentType(byte[] encodedMessage) { throw null; } } public sealed partial class EnvelopedCms { public EnvelopedCms() { } public EnvelopedCms(System.Security.Cryptography.Pkcs.ContentInfo contentInfo) { } public EnvelopedCms(System.Security.Cryptography.Pkcs.ContentInfo contentInfo, System.Security.Cryptography.Pkcs.AlgorithmIdentifier encryptionAlgorithm) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.Security.Cryptography.Pkcs.AlgorithmIdentifier ContentEncryptionAlgorithm { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.Security.Cryptography.Pkcs.ContentInfo ContentInfo { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.Security.Cryptography.Pkcs.RecipientInfoCollection RecipientInfos { get { throw null; } } public System.Security.Cryptography.CryptographicAttributeObjectCollection UnprotectedAttributes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public int Version { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public void Decode(byte[] encodedMessage) { } public void Decrypt() { } public void Decrypt(System.Security.Cryptography.Pkcs.RecipientInfo recipientInfo) { } public void Decrypt(System.Security.Cryptography.Pkcs.RecipientInfo recipientInfo, System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraStore) { } public void Decrypt(System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraStore) { } public byte[] Encode() { throw null; } public void Encrypt(System.Security.Cryptography.Pkcs.CmsRecipient recipient) { } public void Encrypt(System.Security.Cryptography.Pkcs.CmsRecipientCollection recipients) { } } public sealed partial class KeyAgreeRecipientInfo : System.Security.Cryptography.Pkcs.RecipientInfo { internal KeyAgreeRecipientInfo() { } public System.DateTime Date { get { throw null; } } public override byte[] EncryptedKey { get { throw null; } } public override System.Security.Cryptography.Pkcs.AlgorithmIdentifier KeyEncryptionAlgorithm { get { throw null; } } public System.Security.Cryptography.Pkcs.SubjectIdentifierOrKey OriginatorIdentifierOrKey { get { throw null; } } public System.Security.Cryptography.CryptographicAttributeObject OtherKeyAttribute { get { throw null; } } public override System.Security.Cryptography.Pkcs.SubjectIdentifier RecipientIdentifier { get { throw null; } } public override int Version { get { throw null; } } } public sealed partial class KeyTransRecipientInfo : System.Security.Cryptography.Pkcs.RecipientInfo { internal KeyTransRecipientInfo() { } public override byte[] EncryptedKey { get { throw null; } } public override System.Security.Cryptography.Pkcs.AlgorithmIdentifier KeyEncryptionAlgorithm { get { throw null; } } public override System.Security.Cryptography.Pkcs.SubjectIdentifier RecipientIdentifier { get { throw null; } } public override int Version { get { throw null; } } } public partial class Pkcs9AttributeObject : System.Security.Cryptography.AsnEncodedData { public Pkcs9AttributeObject() { } public Pkcs9AttributeObject(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } public Pkcs9AttributeObject(System.Security.Cryptography.Oid oid, byte[] encodedData) { } public Pkcs9AttributeObject(string oid, byte[] encodedData) { } public new System.Security.Cryptography.Oid Oid { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class Pkcs9ContentType : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject { public Pkcs9ContentType() { } public System.Security.Cryptography.Oid ContentType { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class Pkcs9DocumentDescription : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject { public Pkcs9DocumentDescription() { } public Pkcs9DocumentDescription(byte[] encodedDocumentDescription) { } public Pkcs9DocumentDescription(string documentDescription) { } public string DocumentDescription { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class Pkcs9DocumentName : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject { public Pkcs9DocumentName() { } public Pkcs9DocumentName(byte[] encodedDocumentName) { } public Pkcs9DocumentName(string documentName) { } public string DocumentName { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class Pkcs9MessageDigest : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject { public Pkcs9MessageDigest() { } public byte[] MessageDigest { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class Pkcs9SigningTime : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject { public Pkcs9SigningTime() { } public Pkcs9SigningTime(byte[] encodedSigningTime) { } public Pkcs9SigningTime(System.DateTime signingTime) { } public System.DateTime SigningTime { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class PublicKeyInfo { internal PublicKeyInfo() { } public System.Security.Cryptography.Pkcs.AlgorithmIdentifier Algorithm { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public byte[] KeyValue { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public abstract partial class RecipientInfo { internal RecipientInfo() { } public abstract byte[] EncryptedKey { get; } public abstract System.Security.Cryptography.Pkcs.AlgorithmIdentifier KeyEncryptionAlgorithm { get; } public abstract System.Security.Cryptography.Pkcs.SubjectIdentifier RecipientIdentifier { get; } public System.Security.Cryptography.Pkcs.RecipientInfoType Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public abstract int Version { get; } } public sealed partial class RecipientInfoCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal RecipientInfoCollection() { } public int Count { get { throw null; } } public System.Security.Cryptography.Pkcs.RecipientInfo this[int index] { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Security.Cryptography.Pkcs.RecipientInfo[] array, int index) { } public System.Security.Cryptography.Pkcs.RecipientInfoEnumerator GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class RecipientInfoEnumerator : System.Collections.IEnumerator { internal RecipientInfoEnumerator() { } public System.Security.Cryptography.Pkcs.RecipientInfo Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public enum RecipientInfoType { KeyAgreement = 2, KeyTransport = 1, Unknown = 0, } public sealed partial class SignedCms { public SignedCms() => throw null; public SignedCms(SubjectIdentifierType signerIdentifierType) => throw null; public SignedCms(ContentInfo contentInfo) => throw null; public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo) => throw null; public SignedCms(ContentInfo contentInfo, bool detached) => throw null; public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached) => throw null; public int Version => throw null; public ContentInfo ContentInfo => throw null; public bool Detached => throw null; public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates => throw null; public SignerInfoCollection SignerInfos => throw null; public byte[] Encode() => throw null; public void Decode(byte[] encodedMessage) => throw null; [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void ComputeSignature() => throw null; public void ComputeSignature(CmsSigner signer) => throw null; public void ComputeSignature(CmsSigner signer, bool silent) => throw null; public void RemoveSignature(int index) => throw null; public void RemoveSignature(SignerInfo signerInfo) => throw null; public void CheckSignature(bool verifySignatureOnly) => throw null; public void CheckSignature(System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraStore, bool verifySignatureOnly) => throw null; public void CheckHash() => throw null; } public sealed partial class SignerInfo { private SignerInfo() => throw null; public int Version => throw null; public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate => throw null; public SubjectIdentifier SignerIdentifier => throw null; public Oid DigestAlgorithm => throw null; public CryptographicAttributeObjectCollection SignedAttributes => throw null; public CryptographicAttributeObjectCollection UnsignedAttributes => throw null; public SignerInfoCollection CounterSignerInfos => throw null; [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void ComputeCounterSignature() => throw null; public void ComputeCounterSignature(CmsSigner signer) => throw null; public void RemoveCounterSignature(int index) => throw null; public void RemoveCounterSignature(SignerInfo counterSignerInfo) => throw null; public void CheckSignature(bool verifySignatureOnly) => throw null; public void CheckSignature(System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraStore, bool verifySignatureOnly) => throw null; public void CheckHash() => throw null; } public sealed partial class SignerInfoCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal SignerInfoCollection() => throw null; public SignerInfo this[int index] => throw null; public int Count => throw null; public SignerInfoEnumerator GetEnumerator() => throw null; System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null; public void CopyTo(Array array, int index) => throw null; public void CopyTo(SignerInfo[] array, int index) => throw null; public bool IsSynchronized => throw null; public object SyncRoot => throw null; } public sealed partial class SignerInfoEnumerator : System.Collections.IEnumerator { private SignerInfoEnumerator() { } public SignerInfo Current => throw null; object System.Collections.IEnumerator.Current => throw null; public bool MoveNext() => throw null; public void Reset() => throw null; } public sealed partial class SubjectIdentifier { internal SubjectIdentifier() { } public System.Security.Cryptography.Pkcs.SubjectIdentifierType Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public object Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public sealed partial class SubjectIdentifierOrKey { internal SubjectIdentifierOrKey() { } public System.Security.Cryptography.Pkcs.SubjectIdentifierOrKeyType Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public object Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public enum SubjectIdentifierOrKeyType { IssuerAndSerialNumber = 1, PublicKeyInfo = 3, SubjectKeyIdentifier = 2, Unknown = 0, } public enum SubjectIdentifierType { IssuerAndSerialNumber = 1, NoSignature = 3, SubjectKeyIdentifier = 2, Unknown = 0, } } namespace System.Security.Cryptography.Xml { public partial struct X509IssuerSerial { private object _dummy; public string IssuerName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public string SerialNumber { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } }
/* * 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.Drawing; using System.Drawing.Imaging; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; using Mono.Addins; namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicTextureModule")] public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int ALL_SIDES = -1; public const int DISP_EXPIRE = 1; public const int DISP_TEMP = 2; /// <summary> /// If true then where possible dynamic textures are reused. /// </summary> public bool ReuseTextures { get; set; } /// <summary> /// If false, then textures which have a low data size are not reused when ReuseTextures = true. /// </summary> /// <remarks> /// LL viewers 3.3.4 and before appear to not fully render textures pulled from the viewer cache if those /// textures have a relatively high pixel surface but a small data size. Typically, this appears to happen /// if the data size is smaller than the viewer's discard level 2 size estimate. So if this is setting is /// false, textures smaller than the calculation in IsSizeReuseable are always regenerated rather than reused /// to work around this problem.</remarks> public bool ReuseLowDataTextures { get; set; } private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>(); private Dictionary<string, IDynamicTextureRender> RenderPlugins = new Dictionary<string, IDynamicTextureRender>(); private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>(); /// <summary> /// Record dynamic textures that we can reuse for a given data and parameter combination rather than /// regenerate. /// </summary> /// <remarks> /// Key is string.Format("{0}{1}", data /// </remarks> private Cache m_reuseableDynamicTextures; /// <summary> /// This constructor is only here because of the Unit Tests... /// Don't use it. /// </summary> public DynamicTextureModule() { m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative); m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0); } #region IDynamicTextureManager Members public void RegisterRender(string handleType, IDynamicTextureRender render) { if (!RenderPlugins.ContainsKey(handleType)) { RenderPlugins.Add(handleType, render); } } /// <summary> /// Called by code which actually renders the dynamic texture to supply texture data. /// </summary> /// <param name="updaterId"></param> /// <param name="texture"></param> public void ReturnData(UUID updaterId, IDynamicTexture texture) { DynamicTextureUpdater updater = null; lock (Updaters) { if (Updaters.ContainsKey(updaterId)) { updater = Updaters[updaterId]; } } if (updater != null) { if (RegisteredScenes.ContainsKey(updater.SimUUID)) { Scene scene = RegisteredScenes[updater.SimUUID]; UUID newTextureID = updater.DataReceived(texture.Data, scene); if (ReuseTextures && !updater.BlendWithOldTexture && texture.IsReuseable && (ReuseLowDataTextures || IsDataSizeReuseable(texture))) { m_reuseableDynamicTextures.Store( GenerateReusableTextureKey(texture.InputCommands, texture.InputParams), newTextureID); } } } if (updater.UpdateTimer == 0) { lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Remove(updater.UpdaterID); } } } } /// <summary> /// Determines whether the texture is reuseable based on its data size. /// </summary> /// <remarks> /// This is a workaround for a viewer bug where very small data size textures relative to their pixel size /// are not redisplayed properly when pulled from cache. The calculation here is based on the typical discard /// level of 2, a 'rate' of 0.125 and 4 components (which makes for a factor of 0.5). /// </remarks> /// <returns></returns> private bool IsDataSizeReuseable(IDynamicTexture texture) { // Console.WriteLine("{0} {1}", texture.Size.Width, texture.Size.Height); int discardLevel2DataThreshold = (int)Math.Ceiling((texture.Size.Width >> 2) * (texture.Size.Height >> 2) * 0.5); // m_log.DebugFormat( // "[DYNAMIC TEXTURE MODULE]: Discard level 2 threshold {0}, texture data length {1}", // discardLevel2DataThreshold, texture.Data.Length); return discardLevel2DataThreshold < texture.Data.Length; } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, SetBlending, (int)(DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face) { if (RenderPlugins.ContainsKey(contentType)) { DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.Url = url; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; updater.Face = face; updater.Disp = disp; lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Add(updater.UpdaterID, updater); } } RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams); return updater.UpdaterID; } return UUID.Zero; } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending, (int) (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face) { if (!RenderPlugins.ContainsKey(contentType)) return UUID.Zero; Scene scene; RegisteredScenes.TryGetValue(simID, out scene); if (scene == null) return UUID.Zero; SceneObjectPart part = scene.GetSceneObjectPart(primID); if (part == null) return UUID.Zero; // If we want to reuse dynamic textures then we have to ignore any request from the caller to expire // them. if (ReuseTextures) disp = disp & ~DISP_EXPIRE; DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.BodyData = data; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; updater.Face = face; updater.Url = "Local image"; updater.Disp = disp; object objReusableTextureUUID = null; if (ReuseTextures && !updater.BlendWithOldTexture) { string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams); objReusableTextureUUID = m_reuseableDynamicTextures.Get(reuseableTextureKey); if (objReusableTextureUUID != null) { // If something else has removed this temporary asset from the cache, detect and invalidate // our cached uuid. if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null) { m_reuseableDynamicTextures.Invalidate(reuseableTextureKey); objReusableTextureUUID = null; } } } // We cannot reuse a dynamic texture if the data is going to be blended with something already there. if (objReusableTextureUUID == null) { lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Add(updater.UpdaterID, updater); } } // m_log.DebugFormat( // "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}", // part.Name, part.ParentGroup.Scene.Name); RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams); } else { // m_log.DebugFormat( // "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}", // objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name); // No need to add to updaters as the texture is always the same. Not that this functionality // apppears to be implemented anyway. updater.UpdatePart(part, (UUID)objReusableTextureUUID); } return updater.UpdaterID; } private string GenerateReusableTextureKey(string data, string extraParams) { return string.Format("{0}{1}", data, extraParams); } public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize, out double xSize, out double ySize) { xSize = 0; ySize = 0; if (RenderPlugins.ContainsKey(contentType)) { RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize); } } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig texturesConfig = config.Configs["Textures"]; if (texturesConfig != null) { ReuseTextures = texturesConfig.GetBoolean("ReuseDynamicTextures", false); ReuseLowDataTextures = texturesConfig.GetBoolean("ReuseDynamicLowDataTextures", false); if (ReuseTextures) { m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative); m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0); } } } public void PostInitialise() { } public void AddRegion(Scene scene) { if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) { RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); scene.RegisterModuleInterface<IDynamicTextureManager>(this); } } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) RegisteredScenes.Remove(scene.RegionInfo.RegionID); } public void Close() { } public string Name { get { return "DynamicTextureModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region Nested type: DynamicTextureUpdater public class DynamicTextureUpdater { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool BlendWithOldTexture = false; public string BodyData; public string ContentType; public byte FrontAlpha = 255; public string Params; public UUID PrimID; public bool SetNewFrontAlpha = false; public UUID SimUUID; public UUID UpdaterID; public int UpdateTimer; public int Face; public int Disp; public string Url; public DynamicTextureUpdater() { UpdateTimer = 0; BodyData = null; } /// <summary> /// Update the given part with the new texture. /// </summary> /// <returns> /// The old texture UUID. /// </returns> public UUID UpdatePart(SceneObjectPart part, UUID textureID) { UUID oldID; lock (part) { // mostly keep the values from before Primitive.TextureEntry tmptex = part.Shape.Textures; // FIXME: Need to return the appropriate ID if only a single face is replaced. oldID = tmptex.DefaultTexture.TextureID; if (Face == ALL_SIDES) { oldID = tmptex.DefaultTexture.TextureID; tmptex.DefaultTexture.TextureID = textureID; } else { try { Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face); texface.TextureID = textureID; tmptex.FaceTextures[Face] = texface; } catch (Exception) { tmptex.DefaultTexture.TextureID = textureID; } } // I'm pretty sure we always want to force this to true // I'm pretty sure noone whats to set fullbright true if it wasn't true before. // tmptex.DefaultTexture.Fullbright = true; part.UpdateTextureEntry(tmptex.GetBytes()); } return oldID; } /// <summary> /// Called once new texture data has been received for this updater. /// </summary> /// <param name="data"></param> /// <param name="scene"></param> /// <param name="isReuseable">True if the data given is reuseable.</param> /// <returns>The asset UUID given to the incoming data.</returns> public UUID DataReceived(byte[] data, Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(PrimID); if (part == null || data == null || data.Length <= 1) { string msg = String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url); scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say, 0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false); return UUID.Zero; } byte[] assetData = null; AssetBase oldAsset = null; if (BlendWithOldTexture) { Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture; if (defaultFace != null) { oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString()); if (oldAsset != null) assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha); } } if (assetData == null) { assetData = new byte[data.Length]; Array.Copy(data, assetData, data.Length); } // Create a new asset for user AssetBase asset = new AssetBase( UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture, scene.RegionInfo.RegionID.ToString()); asset.Data = assetData; asset.Description = String.Format("URL image : {0}", Url); if (asset.Description.Length > 128) asset.Description = asset.Description.Substring(0, 128); asset.Local = true; // dynamic images aren't saved in the assets server asset.Temporary = ((Disp & DISP_TEMP) != 0); scene.AssetService.Store(asset); // this will only save the asset in the local asset cache IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) { if (!cacheLayerDecode.Decode(asset.FullID, asset.Data)) m_log.WarnFormat( "[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed", asset.ID, part.Name, part.ParentGroup.Scene.Name); } UUID oldID = UpdatePart(part, asset.FullID); if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0)) { if (oldAsset == null) oldAsset = scene.AssetService.Get(oldID.ToString()); if (oldAsset != null) { if (oldAsset.Temporary) { scene.AssetService.Delete(oldID.ToString()); } } } return asset.FullID; } private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image)) { Bitmap image1 = new Bitmap(image); if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image)) { Bitmap image2 = new Bitmap(image); if (setNewAlpha) SetAlpha(ref image1, newAlpha); Bitmap joint = MergeBitMaps(image1, image2); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception e) { m_log.ErrorFormat( "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}", e.Message, e.StackTrace); } return result; } } return null; } public Bitmap MergeBitMaps(Bitmap front, Bitmap back) { Bitmap joint; Graphics jG; joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb); jG = Graphics.FromImage(joint); jG.DrawImage(back, 0, 0, back.Width, back.Height); jG.DrawImage(front, 0, 0, back.Width, back.Height); return joint; } private void SetAlpha(ref Bitmap b, byte alpha) { for (int w = 0; w < b.Width; w++) { for (int h = 0; h < b.Height; h++) { b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h))); } } } } #endregion } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using dnlib.DotNet.MD; namespace dnlib.DotNet.Writer { /// <summary> /// Preserves metadata tokens /// </summary> sealed class PreserveTokensMetaData : MetaData { readonly ModuleDefMD mod; readonly Rows<TypeRef> typeRefInfos = new Rows<TypeRef>(); readonly Dictionary<TypeDef, uint> typeToRid = new Dictionary<TypeDef, uint>(); MemberDefDict<FieldDef> fieldDefInfos; MemberDefDict<MethodDef> methodDefInfos; MemberDefDict<ParamDef> paramDefInfos; readonly Rows<MemberRef> memberRefInfos = new Rows<MemberRef>(); readonly Rows<StandAloneSig> standAloneSigInfos = new Rows<StandAloneSig>(); MemberDefDict<EventDef> eventDefInfos; MemberDefDict<PropertyDef> propertyDefInfos; readonly Rows<TypeSpec> typeSpecInfos = new Rows<TypeSpec>(); readonly Rows<MethodSpec> methodSpecInfos = new Rows<MethodSpec>(); readonly Dictionary<uint, uint> callConvTokenToSignature = new Dictionary<uint, uint>(); [DebuggerDisplay("{Rid} -> {NewRid} {Def}")] sealed class MemberDefInfo<T> where T : IMDTokenProvider { public readonly T Def; /// <summary> /// Its real rid /// </summary> public uint Rid; /// <summary> /// Its logical rid or real rid. If the ptr table exists (eg. MethodPtr), then it's /// an index into it, else it's the real rid. /// </summary> public uint NewRid; public MemberDefInfo(T def, uint rid) { this.Def = def; this.Rid = rid; this.NewRid = rid; } } [DebuggerDisplay("Count = {Count}")] sealed class MemberDefDict<T> where T : IMDTokenProvider { readonly Type defMDType; uint userRid = 0x01000000; uint newRid = 1; int numDefMDs; int numDefUsers; int tableSize; bool wasSorted; readonly bool preserveRids; readonly bool enableRidToInfo; readonly Dictionary<T, MemberDefInfo<T>> defToInfo = new Dictionary<T, MemberDefInfo<T>>(); Dictionary<uint, MemberDefInfo<T>> ridToInfo; readonly List<MemberDefInfo<T>> defs = new List<MemberDefInfo<T>>(); List<MemberDefInfo<T>> sortedDefs; readonly Dictionary<T, int> collectionPositions = new Dictionary<T, int>(); /// <summary> /// Gets total number of defs in the list. It does <c>not</c> necessarily return /// the table size. Use <see cref="TableSize"/> for that. /// </summary> public int Count { get { return defs.Count; } } /// <summary> /// Gets the number of rows that need to be created in the table /// </summary> public int TableSize { get { return tableSize; } } /// <summary> /// Returns <c>true</c> if the ptr table (eg. <c>MethodPtr</c>) is needed /// </summary> public bool NeedPtrTable { get { return preserveRids && !wasSorted; } } public MemberDefDict(Type defMDType, bool preserveRids) : this(defMDType, preserveRids, false) { } public MemberDefDict(Type defMDType, bool preserveRids, bool enableRidToInfo) { this.defMDType = defMDType; this.preserveRids = preserveRids; this.enableRidToInfo = enableRidToInfo; } public uint Rid(T def) { return defToInfo[def].Rid; } public bool TryGetRid(T def, out uint rid) { MemberDefInfo<T> info; if (def == null || !defToInfo.TryGetValue(def, out info)) { rid = 0; return false; } rid = info.Rid; return true; } /// <summary> /// Sorts the table /// </summary> /// <param name="comparer">Comparer</param> public void Sort(Comparison<MemberDefInfo<T>> comparer) { if (!preserveRids) { // It's already sorted sortedDefs = defs; return; } sortedDefs = new List<MemberDefInfo<T>>(defs); sortedDefs.Sort(comparer); wasSorted = true; for (int i = 0; i < sortedDefs.Count; i++) { var def = sortedDefs[i]; uint newRid = (uint)i + 1; def.NewRid = newRid; if (def.Rid != newRid) wasSorted = false; } } public MemberDefInfo<T> Get(int i) { return defs[i]; } public MemberDefInfo<T> GetSorted(int i) { return sortedDefs[i]; } public MemberDefInfo<T> GetByRid(uint rid) { MemberDefInfo<T> info; ridToInfo.TryGetValue(rid, out info); return info; } /// <summary> /// Adds a def. <see cref="SortDefs()"/> must be called after adding the last def. /// </summary> /// <param name="def">The def</param> /// <param name="collPos">Collection position</param> public void Add(T def, int collPos) { uint rid; if (def.GetType() == defMDType) { numDefMDs++; rid = preserveRids ? def.Rid : newRid++; } else { numDefUsers++; rid = preserveRids ? userRid++ : newRid++; } var info = new MemberDefInfo<T>(def, rid); defToInfo[def] = info; defs.Add(info); collectionPositions.Add(def, collPos); } /// <summary> /// Must be called after <see cref="Add"/>'ing the last def /// </summary> public void SortDefs() { // It's already sorted if we don't preserve rids if (preserveRids) { // Sort all def MDs before user defs defs.Sort((a, b) => a.Rid.CompareTo(b.Rid)); // Fix user created defs' rids uint newRid = numDefMDs == 0 ? 1 : defs[numDefMDs - 1].Rid + 1; for (int i = numDefMDs; i < defs.Count; i++) defs[i].Rid = newRid++; // Now we know total table size tableSize = (int)newRid - 1; } else tableSize = defs.Count; if (enableRidToInfo) { ridToInfo = new Dictionary<uint, MemberDefInfo<T>>(defs.Count); foreach (var info in defs) ridToInfo.Add(info.Rid, info); } if ((uint)tableSize > 0x00FFFFFF) throw new ModuleWriterException("Table is too big"); } public int GetCollectionPosition(T def) { return collectionPositions[def]; } } protected override int NumberOfMethods { get { return methodDefInfos.Count; } } /// <summary> /// Constructor /// </summary> /// <param name="module">Module</param> /// <param name="constants">Constants list</param> /// <param name="methodBodies">Method bodies list</param> /// <param name="netResources">.NET resources list</param> /// <param name="options">Options</param> public PreserveTokensMetaData(ModuleDef module, UniqueChunkList<ByteArrayChunk> constants, MethodBodyChunks methodBodies, NetResources netResources, MetaDataOptions options) : base(module, constants, methodBodies, netResources, options) { mod = module as ModuleDefMD; if (mod == null) throw new ModuleWriterException("Not a ModuleDefMD"); } /// <inheritdoc/> public override uint GetRid(TypeRef tr) { uint rid; typeRefInfos.TryGetRid(tr, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(TypeDef td) { if (td == null) { Error("TypeDef is null"); return 0; } uint rid; if (typeToRid.TryGetValue(td, out rid)) return rid; Error("TypeDef {0} ({1:X8}) is not defined in this module ({2}). A type was removed that is still referenced by this module.", td, td.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(FieldDef fd) { uint rid; if (fieldDefInfos.TryGetRid(fd, out rid)) return rid; if (fd == null) Error("Field is null"); else Error("Field {0} ({1:X8}) is not defined in this module ({2}). A field was removed that is still referenced by this module.", fd, fd.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(MethodDef md) { uint rid; if (methodDefInfos.TryGetRid(md, out rid)) return rid; if (md == null) Error("Method is null"); else Error("Method {0} ({1:X8}) is not defined in this module ({2}). A method was removed that is still referenced by this module.", md, md.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(ParamDef pd) { uint rid; if (paramDefInfos.TryGetRid(pd, out rid)) return rid; if (pd == null) Error("Param is null"); else Error("Param {0} ({1:X8}) is not defined in this module ({2}). A parameter was removed that is still referenced by this module.", pd, pd.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(MemberRef mr) { uint rid; memberRefInfos.TryGetRid(mr, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(StandAloneSig sas) { uint rid; standAloneSigInfos.TryGetRid(sas, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(EventDef ed) { uint rid; if (eventDefInfos.TryGetRid(ed, out rid)) return rid; if (ed == null) Error("Event is null"); else Error("Event {0} ({1:X8}) is not defined in this module ({2}). An event was removed that is still referenced by this module.", ed, ed.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(PropertyDef pd) { uint rid; if (propertyDefInfos.TryGetRid(pd, out rid)) return rid; if (pd == null) Error("Property is null"); else Error("Property {0} ({1:X8}) is not defined in this module ({2}). A property was removed that is still referenced by this module.", pd, pd.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(TypeSpec ts) { uint rid; typeSpecInfos.TryGetRid(ts, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(MethodSpec ms) { uint rid; methodSpecInfos.TryGetRid(ms, out rid); return rid; } /// <inheritdoc/> protected override void Initialize() { fieldDefInfos = new MemberDefDict<FieldDef>(typeof(FieldDefMD), PreserveFieldRids); methodDefInfos = new MemberDefDict<MethodDef>(typeof(MethodDefMD), PreserveMethodRids, true); paramDefInfos = new MemberDefDict<ParamDef>(typeof(ParamDefMD), PreserveParamRids); eventDefInfos = new MemberDefDict<EventDef>(typeof(EventDefMD), PreserveEventRids); propertyDefInfos = new MemberDefDict<PropertyDef>(typeof(PropertyDefMD), PreservePropertyRids); CreateEmptyTableRows(); } /// <inheritdoc/> protected override List<TypeDef> GetAllTypeDefs() { if (!PreserveTypeDefRids) { var types2 = new List<TypeDef>(module.GetTypes()); InitializeTypeToRid(types2); return types2; } var typeToIndex = new Dictionary<TypeDef, uint>(); var types = new List<TypeDef>(); uint index = 0; const uint IS_TYPEDEFMD = 0x80000000; const uint INDEX_BITS = 0x00FFFFFF; foreach (var type in module.GetTypes()) { if (type == null) continue; types.Add(type); uint val = (uint)index++; if (type.GetType() == typeof(TypeDefMD)) val |= IS_TYPEDEFMD; typeToIndex[type] = val; } var globalType = types[0]; types.Sort((a, b) => { if (a == b) return 0; // Make sure the global <Module> type is always sorted first, even if it's // a TypeDefUser if (a == globalType) return -1; if (b == globalType) return 1; // Sort all TypeDefMDs before all TypeDefUsers uint ai = typeToIndex[a]; uint bi = typeToIndex[b]; bool amd = (ai & IS_TYPEDEFMD) != 0; bool bmd = (bi & IS_TYPEDEFMD) != 0; if (amd == bmd) { // Both are TypeDefMDs or both are TypeDefUsers // If TypeDefMDs, only compare rids since rids are preserved if (amd) return a.Rid.CompareTo(b.Rid); // If TypeDefUsers, rids aren't preserved so compare by index return (ai & INDEX_BITS).CompareTo(bi & INDEX_BITS); } if (amd) return -1; return 1; }); // Some of the original types may have been removed. Create dummy types // so TypeDef rids can be preserved. var newTypes = new List<TypeDef>(types.Count); uint prevRid = 1; newTypes.Add(globalType); for (int i = 1; i < types.Count; i++) { var type = types[i]; // TypeDefUsers were sorted last so when we reach one, we can stop if (type.GetType() != typeof(TypeDefMD)) { while (i < types.Count) newTypes.Add(types[i++]); break; } uint currRid = type.Rid; int extraTypes = (int)(currRid - prevRid - 1); if (extraTypes != 0) { // always >= 0 since currRid > prevRid // At least one type has been removed. Create dummy types. for (int j = 0; j < extraTypes; j++) newTypes.Add(new TypeDefUser("dummy", Guid.NewGuid().ToString("B"), module.CorLibTypes.Object.TypeDefOrRef)); } newTypes.Add(type); prevRid = currRid; } InitializeTypeToRid(newTypes); return newTypes; } void InitializeTypeToRid(IEnumerable<TypeDef> types) { uint rid = 1; foreach (var type in types) { if (type == null) continue; if (typeToRid.ContainsKey(type)) continue; typeToRid[type] = rid++; } } /// <inheritdoc/> protected override void AllocateTypeDefRids() { foreach (var type in allTypeDefs) { uint rid = tablesHeap.TypeDefTable.Create(new RawTypeDefRow()); if (typeToRid[type] != rid) throw new ModuleWriterException("Got a different rid than expected"); } } /// <summary> /// Reserves rows in <c>TypeRef</c>, <c>MemberRef</c>, <c>StandAloneSig</c>, /// <c>TypeSpec</c> and <c>MethodSpec</c> where we will store the original rows /// to make sure they get the same rid. Any user created rows will be stored at /// the end of each table. /// </summary> void CreateEmptyTableRows() { uint rows; if (PreserveTypeRefRids) { rows = mod.TablesStream.TypeRefTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.TypeRefTable.Create(new RawTypeRefRow()); } if (PreserveMemberRefRids) { rows = mod.TablesStream.MemberRefTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.MemberRefTable.Create(new RawMemberRefRow()); } if (PreserveStandAloneSigRids) { rows = mod.TablesStream.StandAloneSigTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.StandAloneSigTable.Create(new RawStandAloneSigRow()); } if (PreserveTypeSpecRids) { rows = mod.TablesStream.TypeSpecTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.TypeSpecTable.Create(new RawTypeSpecRow()); } if (PreserveMethodSpecRids) { rows = mod.TablesStream.MethodSpecTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.MethodSpecTable.Create(new RawMethodSpecRow()); } } /// <summary> /// Adds any non-referenced rows that haven't been added yet but are present in /// the original file. If there are any non-referenced rows, it's usually a sign /// that an obfuscator has encrypted one or more methods or that it has added /// some rows it uses to decrypt something. /// </summary> void InitializeUninitializedTableRows() { InitializeTypeRefTableRows(); InitializeMemberRefTableRows(); InitializeStandAloneSigTableRows(); InitializeTypeSpecTableRows(); InitializeMethodSpecTableRows(); } bool initdTypeRef = false; void InitializeTypeRefTableRows() { if (!PreserveTypeRefRids || initdTypeRef) return; initdTypeRef = true; uint rows = mod.TablesStream.TypeRefTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddTypeRef(mod.ResolveTypeRef(rid)); tablesHeap.TypeRefTable.ReAddRows(); } bool initdMemberRef = false; void InitializeMemberRefTableRows() { if (!PreserveMemberRefRids || initdMemberRef) return; initdMemberRef = true; uint rows = mod.TablesStream.MemberRefTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddMemberRef(mod.ResolveMemberRef(rid), true); tablesHeap.MemberRefTable.ReAddRows(); } bool initdStandAloneSig = false; void InitializeStandAloneSigTableRows() { if (!PreserveStandAloneSigRids || initdStandAloneSig) return; initdStandAloneSig = true; uint rows = mod.TablesStream.StandAloneSigTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddStandAloneSig(mod.ResolveStandAloneSig(rid), true); tablesHeap.StandAloneSigTable.ReAddRows(); } bool initdTypeSpec = false; void InitializeTypeSpecTableRows() { if (!PreserveTypeSpecRids || initdTypeSpec) return; initdTypeSpec = true; uint rows = mod.TablesStream.TypeSpecTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddTypeSpec(mod.ResolveTypeSpec(rid), true); tablesHeap.TypeSpecTable.ReAddRows(); } bool initdMethodSpec = false; void InitializeMethodSpecTableRows() { if (!PreserveMethodSpecRids || initdMethodSpec) return; initdMethodSpec = true; uint rows = mod.TablesStream.MethodSpecTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddMethodSpec(mod.ResolveMethodSpec(rid), true); tablesHeap.MethodSpecTable.ReAddRows(); } /// <inheritdoc/> protected override void AllocateMemberDefRids() { FindMemberDefs(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids0); for (int i = 1; i <= fieldDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.FieldTable.Create(new RawFieldRow())) throw new ModuleWriterException("Invalid field rid"); } for (int i = 1; i <= methodDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.MethodTable.Create(new RawMethodRow())) throw new ModuleWriterException("Invalid method rid"); } for (int i = 1; i <= paramDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.ParamTable.Create(new RawParamRow())) throw new ModuleWriterException("Invalid param rid"); } for (int i = 1; i <= eventDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.EventTable.Create(new RawEventRow())) throw new ModuleWriterException("Invalid event rid"); } for (int i = 1; i <= propertyDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.PropertyTable.Create(new RawPropertyRow())) throw new ModuleWriterException("Invalid property rid"); } SortFields(); SortMethods(); SortParameters(); SortEvents(); SortProperties(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids1); if (fieldDefInfos.NeedPtrTable) { for (int i = 0; i < fieldDefInfos.Count; i++) { var info = fieldDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.FieldPtrTable.Add(new RawFieldPtrRow(info.Rid))) throw new ModuleWriterException("Invalid field ptr rid"); } ReUseDeletedFieldRows(); } if (methodDefInfos.NeedPtrTable) { for (int i = 0; i < methodDefInfos.Count; i++) { var info = methodDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.MethodPtrTable.Add(new RawMethodPtrRow(info.Rid))) throw new ModuleWriterException("Invalid method ptr rid"); } ReUseDeletedMethodRows(); } if (paramDefInfos.NeedPtrTable) { // NOTE: peverify does not support the ParamPtr table. It's a bug. for (int i = 0; i < paramDefInfos.Count; i++) { var info = paramDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.ParamPtrTable.Add(new RawParamPtrRow(info.Rid))) throw new ModuleWriterException("Invalid param ptr rid"); } ReUseDeletedParamRows(); } if (eventDefInfos.NeedPtrTable) { for (int i = 0; i < eventDefInfos.Count; i++) { var info = eventDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.EventPtrTable.Add(new RawEventPtrRow(info.Rid))) throw new ModuleWriterException("Invalid event ptr rid"); } } if (propertyDefInfos.NeedPtrTable) { for (int i = 0; i < propertyDefInfos.Count; i++) { var info = propertyDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.PropertyPtrTable.Add(new RawPropertyPtrRow(info.Rid))) throw new ModuleWriterException("Invalid property ptr rid"); } } Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids2); InitializeMethodAndFieldList(); InitializeParamList(); InitializeEventMap(); InitializePropertyMap(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids3); // We must re-use deleted event/property rows after we've initialized // the event/prop map tables. if (eventDefInfos.NeedPtrTable) ReUseDeletedEventRows(); if (propertyDefInfos.NeedPtrTable) ReUseDeletedPropertyRows(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids4); InitializeTypeRefTableRows(); InitializeTypeSpecTableRows(); InitializeMemberRefTableRows(); InitializeMethodSpecTableRows(); } /// <summary> /// Re-uses all <c>Field</c> rows which aren't owned by any type due to the fields /// having been deleted by the user. The reason we must do this is that the /// <c>FieldPtr</c> and <c>Field</c> tables must be the same size. /// </summary> void ReUseDeletedFieldRows() { if (tablesHeap.FieldPtrTable.IsEmpty) return; if (fieldDefInfos.TableSize == tablesHeap.FieldPtrTable.Rows) return; var hasOwner = new bool[fieldDefInfos.TableSize]; for (int i = 0; i < fieldDefInfos.Count; i++) hasOwner[(int)fieldDefInfos.Get(i).Rid - 1] = true; CreateDummyPtrTableType(); uint fieldSig = GetSignature(new FieldSig(module.CorLibTypes.Byte)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint frid = (uint)i + 1; var frow = tablesHeap.FieldTable[frid]; frow.Flags = (ushort)(FieldAttributes.Public | FieldAttributes.Static); frow.Name = stringsHeap.Add(string.Format("f{0:X6}", frid)); frow.Signature = fieldSig; tablesHeap.FieldPtrTable.Create(new RawFieldPtrRow(frid)); } if (fieldDefInfos.TableSize != tablesHeap.FieldPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy fields"); } /// <summary> /// Re-uses all <c>Method</c> rows which aren't owned by any type due to the methods /// having been deleted by the user. The reason we must do this is that the /// <c>MethodPtr</c> and <c>Method</c> tables must be the same size. /// </summary> void ReUseDeletedMethodRows() { if (tablesHeap.MethodPtrTable.IsEmpty) return; if (methodDefInfos.TableSize == tablesHeap.MethodPtrTable.Rows) return; var hasOwner = new bool[methodDefInfos.TableSize]; for (int i = 0; i < methodDefInfos.Count; i++) hasOwner[(int)methodDefInfos.Get(i).Rid - 1] = true; CreateDummyPtrTableType(); uint methodSig = GetSignature(MethodSig.CreateInstance(module.CorLibTypes.Void)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint mrid = (uint)i + 1; var mrow = tablesHeap.MethodTable[mrid]; mrow.RVA = 0; mrow.ImplFlags = (ushort)(MethodImplAttributes.IL | MethodImplAttributes.Managed); mrow.Flags = (ushort)(MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Abstract); mrow.Name = stringsHeap.Add(string.Format("m{0:X6}", mrid)); mrow.Signature = methodSig; mrow.ParamList = (uint)paramDefInfos.Count; tablesHeap.MethodPtrTable.Create(new RawMethodPtrRow(mrid)); } if (methodDefInfos.TableSize != tablesHeap.MethodPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy methods"); } /// <summary> /// Re-uses all <c>Param</c> rows which aren't owned by any type due to the params /// having been deleted by the user. The reason we must do this is that the /// <c>ParamPtr</c> and <c>Param</c> tables must be the same size. /// This method must be called after <see cref="ReUseDeletedMethodRows()"/> since /// this method will create more methods at the end of the <c>Method</c> table. /// </summary> void ReUseDeletedParamRows() { if (tablesHeap.ParamPtrTable.IsEmpty) return; if (paramDefInfos.TableSize == tablesHeap.ParamPtrTable.Rows) return; var hasOwner = new bool[paramDefInfos.TableSize]; for (int i = 0; i < paramDefInfos.Count; i++) hasOwner[(int)paramDefInfos.Get(i).Rid - 1] = true; CreateDummyPtrTableType(); // For each param, attach it to a new method. Another alternative would be to create // one (or a few) methods with tons of parameters. uint methodSig = GetSignature(MethodSig.CreateInstance(module.CorLibTypes.Void)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint prid = (uint)i + 1; var prow = tablesHeap.ParamTable[prid]; prow.Flags = 0; prow.Sequence = 0; // Return type parameter prow.Name = stringsHeap.Add(string.Format("p{0:X6}", prid)); uint ptrRid = tablesHeap.ParamPtrTable.Create(new RawParamPtrRow(prid)); var mrow = new RawMethodRow(0, (ushort)(MethodImplAttributes.IL | MethodImplAttributes.Managed), (ushort)(MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Abstract), stringsHeap.Add(string.Format("mp{0:X6}", prid)), methodSig, ptrRid); uint mrid = tablesHeap.MethodTable.Create(mrow); if (tablesHeap.MethodPtrTable.Rows > 0) tablesHeap.MethodPtrTable.Create(new RawMethodPtrRow(mrid)); } if (paramDefInfos.TableSize != tablesHeap.ParamPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy params"); } /// <summary> /// Re-uses all <c>Event</c> rows which aren't owned by any type due to the events /// having been deleted by the user. The reason we must do this is that the /// <c>EventPtr</c> and <c>Event</c> tables must be the same size. /// </summary> void ReUseDeletedEventRows() { if (tablesHeap.EventPtrTable.IsEmpty) return; if (eventDefInfos.TableSize == tablesHeap.EventPtrTable.Rows) return; var hasOwner = new bool[eventDefInfos.TableSize]; for (int i = 0; i < eventDefInfos.Count; i++) hasOwner[(int)eventDefInfos.Get(i).Rid - 1] = true; uint typeRid = CreateDummyPtrTableType(); tablesHeap.EventMapTable.Create(new RawEventMapRow(typeRid, (uint)tablesHeap.EventPtrTable.Rows + 1)); uint eventType = AddTypeDefOrRef(module.CorLibTypes.Object.TypeDefOrRef); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint erid = (uint)i + 1; var frow = tablesHeap.EventTable[erid]; frow.EventFlags = 0; frow.Name = stringsHeap.Add(string.Format("E{0:X6}", erid)); frow.EventType = eventType; tablesHeap.EventPtrTable.Create(new RawEventPtrRow(erid)); } if (eventDefInfos.TableSize != tablesHeap.EventPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy events"); } /// <summary> /// Re-uses all <c>Property</c> rows which aren't owned by any type due to the properties /// having been deleted by the user. The reason we must do this is that the /// <c>PropertyPtr</c> and <c>Property</c> tables must be the same size. /// </summary> void ReUseDeletedPropertyRows() { if (tablesHeap.PropertyPtrTable.IsEmpty) return; if (propertyDefInfos.TableSize == tablesHeap.PropertyPtrTable.Rows) return; var hasOwner = new bool[propertyDefInfos.TableSize]; for (int i = 0; i < propertyDefInfos.Count; i++) hasOwner[(int)propertyDefInfos.Get(i).Rid - 1] = true; uint typeRid = CreateDummyPtrTableType(); tablesHeap.PropertyMapTable.Create(new RawPropertyMapRow(typeRid, (uint)tablesHeap.PropertyPtrTable.Rows + 1)); uint propertySig = GetSignature(PropertySig.CreateStatic(module.CorLibTypes.Object)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint prid = (uint)i + 1; var frow = tablesHeap.PropertyTable[prid]; frow.PropFlags = 0; frow.Name = stringsHeap.Add(string.Format("P{0:X6}", prid)); frow.Type = propertySig; tablesHeap.PropertyPtrTable.Create(new RawPropertyPtrRow(prid)); } if (propertyDefInfos.TableSize != tablesHeap.PropertyPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy properties"); } /// <summary> /// Creates a dummy <c>TypeDef</c> at the end of the <c>TypeDef</c> table that will own /// dummy methods and fields. These dummy methods and fields are only created if the size /// of the ptr table is less than the size of the non-ptr table (eg. size MethodPtr table /// is less than size Method table). The only reason the ptr table would be smaller than /// the non-ptr table is when some field/method has been deleted and we must preserve /// all method/field rids. /// </summary> uint CreateDummyPtrTableType() { if (dummyPtrTableTypeRid != 0) return dummyPtrTableTypeRid; var flags = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.AnsiClass; int numFields = fieldDefInfos.NeedPtrTable ? fieldDefInfos.Count : fieldDefInfos.TableSize; int numMethods = methodDefInfos.NeedPtrTable ? methodDefInfos.Count : methodDefInfos.TableSize; var row = new RawTypeDefRow((uint)flags, stringsHeap.Add(Guid.NewGuid().ToString("B")), stringsHeap.Add("dummy_ptr"), AddTypeDefOrRef(module.CorLibTypes.Object.TypeDefOrRef), (uint)numFields + 1, (uint)numMethods + 1); dummyPtrTableTypeRid = tablesHeap.TypeDefTable.Create(row); if (dummyPtrTableTypeRid == 1) throw new ModuleWriterException("Dummy ptr type is the first type"); return dummyPtrTableTypeRid; } uint dummyPtrTableTypeRid; void FindMemberDefs() { var added = new Dictionary<object, bool>(); int pos; foreach (var type in allTypeDefs) { if (type == null) continue; pos = 0; foreach (var field in type.Fields) { if (field == null) continue; fieldDefInfos.Add(field, pos++); } pos = 0; foreach (var method in type.Methods) { if (method == null) continue; methodDefInfos.Add(method, pos++); } pos = 0; foreach (var evt in type.Events) { if (evt == null || added.ContainsKey(evt)) continue; added[evt] = true; eventDefInfos.Add(evt, pos++); } pos = 0; foreach (var prop in type.Properties) { if (prop == null || added.ContainsKey(prop)) continue; added[prop] = true; propertyDefInfos.Add(prop, pos++); } } fieldDefInfos.SortDefs(); methodDefInfos.SortDefs(); eventDefInfos.SortDefs(); propertyDefInfos.SortDefs(); for (int i = 0; i < methodDefInfos.Count; i++) { var method = methodDefInfos.Get(i).Def; pos = 0; foreach (var param in Sort(method.ParamDefs)) { if (param == null) continue; paramDefInfos.Add(param, pos++); } } paramDefInfos.SortDefs(); } void SortFields() { fieldDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return fieldDefInfos.GetCollectionPosition(a.Def).CompareTo(fieldDefInfos.GetCollectionPosition(b.Def)); }); } void SortMethods() { methodDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return methodDefInfos.GetCollectionPosition(a.Def).CompareTo(methodDefInfos.GetCollectionPosition(b.Def)); }); } void SortParameters() { paramDefInfos.Sort((a, b) => { var dma = a.Def.DeclaringMethod == null ? 0 : methodDefInfos.Rid(a.Def.DeclaringMethod); var dmb = b.Def.DeclaringMethod == null ? 0 : methodDefInfos.Rid(b.Def.DeclaringMethod); if (dma == 0 || dmb == 0) return a.Rid.CompareTo(b.Rid); if (dma != dmb) return dma.CompareTo(dmb); return paramDefInfos.GetCollectionPosition(a.Def).CompareTo(paramDefInfos.GetCollectionPosition(b.Def)); }); } void SortEvents() { eventDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return eventDefInfos.GetCollectionPosition(a.Def).CompareTo(eventDefInfos.GetCollectionPosition(b.Def)); }); } void SortProperties() { propertyDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return propertyDefInfos.GetCollectionPosition(a.Def).CompareTo(propertyDefInfos.GetCollectionPosition(b.Def)); }); } void InitializeMethodAndFieldList() { uint fieldList = 1, methodList = 1; foreach (var type in allTypeDefs) { var typeRow = tablesHeap.TypeDefTable[typeToRid[type]]; typeRow.FieldList = fieldList; typeRow.MethodList = methodList; fieldList += (uint)type.Fields.Count; methodList += (uint)type.Methods.Count; } } void InitializeParamList() { uint ridList = 1; for (uint methodRid = 1; methodRid <= methodDefInfos.TableSize; methodRid++) { var methodInfo = methodDefInfos.GetByRid(methodRid); var row = tablesHeap.MethodTable[methodRid]; row.ParamList = ridList; if (methodInfo != null) ridList += (uint)methodInfo.Def.ParamDefs.Count; } } void InitializeEventMap() { if (!tablesHeap.EventMapTable.IsEmpty) throw new ModuleWriterException("EventMap table isn't empty"); TypeDef type = null; for (int i = 0; i < eventDefInfos.Count; i++) { var info = eventDefInfos.GetSorted(i); if (type == info.Def.DeclaringType) continue; type = info.Def.DeclaringType; var row = new RawEventMapRow(typeToRid[type], info.NewRid); uint eventMapRid = tablesHeap.EventMapTable.Create(row); eventMapInfos.Add(type, eventMapRid); } } void InitializePropertyMap() { if (!tablesHeap.PropertyMapTable.IsEmpty) throw new ModuleWriterException("PropertyMap table isn't empty"); TypeDef type = null; for (int i = 0; i < propertyDefInfos.Count; i++) { var info = propertyDefInfos.GetSorted(i); if (type == info.Def.DeclaringType) continue; type = info.Def.DeclaringType; var row = new RawPropertyMapRow(typeToRid[type], info.NewRid); uint propertyMapRid = tablesHeap.PropertyMapTable.Create(row); propertyMapInfos.Add(type, propertyMapRid); } } /// <inheritdoc/> protected override uint AddTypeRef(TypeRef tr) { if (tr == null) { Error("TypeRef is null"); return 0; } uint rid; if (typeRefInfos.TryGetRid(tr, out rid)) { if (rid == 0) Error("TypeRef {0:X8} has an infinite ResolutionScope loop", tr.MDToken.Raw); return rid; } typeRefInfos.Add(tr, 0); // Prevent inf recursion bool isOld = PreserveTypeRefRids && mod.ResolveTypeRef(tr.Rid) == tr; var row = isOld ? tablesHeap.TypeRefTable[tr.Rid] : new RawTypeRefRow(); row.ResolutionScope = AddResolutionScope(tr.ResolutionScope); row.Name = stringsHeap.Add(tr.Name); row.Namespace = stringsHeap.Add(tr.Namespace); rid = isOld ? tr.Rid : tablesHeap.TypeRefTable.Add(row); typeRefInfos.SetRid(tr, rid); AddCustomAttributes(Table.TypeRef, rid, tr); return rid; } /// <inheritdoc/> protected override uint AddTypeSpec(TypeSpec ts) { return AddTypeSpec(ts, false); } uint AddTypeSpec(TypeSpec ts, bool forceIsOld) { if (ts == null) { Error("TypeSpec is null"); return 0; } uint rid; if (typeSpecInfos.TryGetRid(ts, out rid)) { if (rid == 0) Error("TypeSpec {0:X8} has an infinite TypeSig loop", ts.MDToken.Raw); return rid; } typeSpecInfos.Add(ts, 0); // Prevent inf recursion bool isOld = forceIsOld || (PreserveTypeSpecRids && mod.ResolveTypeSpec(ts.Rid) == ts); var row = isOld ? tablesHeap.TypeSpecTable[ts.Rid] : new RawTypeSpecRow(); row.Signature = GetSignature(ts.TypeSig, ts.ExtraData); rid = isOld ? ts.Rid : tablesHeap.TypeSpecTable.Add(row); typeSpecInfos.SetRid(ts, rid); AddCustomAttributes(Table.TypeSpec, rid, ts); return rid; } /// <inheritdoc/> protected override uint AddMemberRef(MemberRef mr) { return AddMemberRef(mr, false); } uint AddMemberRef(MemberRef mr, bool forceIsOld) { if (mr == null) { Error("MemberRef is null"); return 0; } uint rid; if (memberRefInfos.TryGetRid(mr, out rid)) return rid; bool isOld = forceIsOld || (PreserveMemberRefRids && mod.ResolveMemberRef(mr.Rid) == mr); var row = isOld ? tablesHeap.MemberRefTable[mr.Rid] : new RawMemberRefRow(); row.Class = AddMemberRefParent(mr.Class); row.Name = stringsHeap.Add(mr.Name); row.Signature = GetSignature(mr.Signature); rid = isOld ? mr.Rid : tablesHeap.MemberRefTable.Add(row); memberRefInfos.Add(mr, rid); AddCustomAttributes(Table.MemberRef, rid, mr); return rid; } /// <inheritdoc/> protected override uint AddStandAloneSig(StandAloneSig sas) { return AddStandAloneSig(sas, false); } uint AddStandAloneSig(StandAloneSig sas, bool forceIsOld) { if (sas == null) { Error("StandAloneSig is null"); return 0; } uint rid; if (standAloneSigInfos.TryGetRid(sas, out rid)) return rid; bool isOld = forceIsOld || (PreserveStandAloneSigRids && mod.ResolveStandAloneSig(sas.Rid) == sas); var row = isOld ? tablesHeap.StandAloneSigTable[sas.Rid] : new RawStandAloneSigRow(); row.Signature = GetSignature(sas.Signature); rid = isOld ? sas.Rid : tablesHeap.StandAloneSigTable.Add(row); standAloneSigInfos.Add(sas, rid); AddCustomAttributes(Table.StandAloneSig, rid, sas); return rid; } /// <inheritdoc/> public override MDToken GetToken(IList<TypeSig> locals, uint origToken) { if (!PreserveStandAloneSigRids || !IsValidStandAloneSigToken(origToken)) return base.GetToken(locals, origToken); uint rid = AddStandAloneSig(new LocalSig(locals, false), origToken); if (rid == 0) return base.GetToken(locals, origToken); return new MDToken(Table.StandAloneSig, rid); } /// <inheritdoc/> protected override uint AddStandAloneSig(MethodSig methodSig, uint origToken) { if (!PreserveStandAloneSigRids || !IsValidStandAloneSigToken(origToken)) return base.AddStandAloneSig(methodSig, origToken); uint rid = AddStandAloneSig(methodSig, origToken); if (rid == 0) return base.AddStandAloneSig(methodSig, origToken); return rid; } uint AddStandAloneSig(CallingConventionSig callConvSig, uint origToken) { uint sig = GetSignature(callConvSig); uint otherSig; if (callConvTokenToSignature.TryGetValue(origToken, out otherSig)) { if (sig == otherSig) return MDToken.ToRID(origToken); Warning("Could not preserve StandAloneSig token {0:X8}", origToken); return 0; } uint rid = MDToken.ToRID(origToken); var sas = mod.ResolveStandAloneSig(rid); if (standAloneSigInfos.Exists(sas)) { Warning("StandAloneSig {0:X8} already exists", origToken); return 0; } // Make sure it uses the updated sig var oldSig = sas.Signature; try { sas.Signature = callConvSig; AddStandAloneSig(sas, true); } finally { sas.Signature = oldSig; } callConvTokenToSignature.Add(origToken, sig); return MDToken.ToRID(origToken); } bool IsValidStandAloneSigToken(uint token) { if (MDToken.ToTable(token) != Table.StandAloneSig) return false; uint rid = MDToken.ToRID(token); return mod.TablesStream.StandAloneSigTable.IsValidRID(rid); } /// <inheritdoc/> protected override uint AddMethodSpec(MethodSpec ms) { return AddMethodSpec(ms, false); } uint AddMethodSpec(MethodSpec ms, bool forceIsOld) { if (ms == null) { Error("MethodSpec is null"); return 0; } uint rid; if (methodSpecInfos.TryGetRid(ms, out rid)) return rid; bool isOld = forceIsOld || (PreserveMethodSpecRids && mod.ResolveMethodSpec(ms.Rid) == ms); var row = isOld ? tablesHeap.MethodSpecTable[ms.Rid] : new RawMethodSpecRow(); row.Method = AddMethodDefOrRef(ms.Method); row.Instantiation = GetSignature(ms.Instantiation); rid = isOld ? ms.Rid : tablesHeap.MethodSpecTable.Add(row); methodSpecInfos.Add(ms, rid); AddCustomAttributes(Table.MethodSpec, rid, ms); return rid; } /// <inheritdoc/> protected override void BeforeSortingCustomAttributes() { InitializeUninitializedTableRows(); } } }
/* * 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 OpenMetaverse; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.FrameworkTests { internal class SceneUtil { private readonly static Random rand = new Random(); public static Vector3 RandomVector() { return new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); } public static Quaternion RandomQuat() { return new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); } internal static byte RandomByte() { return (byte)rand.Next(byte.MaxValue); } public static SceneObjectPart RandomSOP(string name, uint localId) { OpenSim.Framework.PrimitiveBaseShape shape = MockPrmitiveBaseShape(); SceneObjectPart part = new SceneObjectPart(UUID.Zero, shape, new Vector3(1, 2, 3), new Quaternion(4, 5, 6, 7), Vector3.Zero, false); part.Name = name; part.Description = "Desc"; part.AngularVelocity = SceneUtil.RandomVector(); part.BaseMask = 0x0876; part.Category = 10; part.ClickAction = 5; part.CollisionSound = UUID.Random(); part.CollisionSoundVolume = 1.1f; part.CreationDate = OpenSim.Framework.Util.UnixTimeSinceEpoch(); part.CreatorID = UUID.Random(); part.EveryoneMask = 0x0543; part.Flags = PrimFlags.CameraSource | PrimFlags.DieAtEdge; part.GroupID = UUID.Random(); part.GroupMask = 0x0210; part.LastOwnerID = UUID.Random(); part.LinkNum = 4; part.LocalId = localId; part.Material = 0x1; part.MediaUrl = "http://bam"; part.NextOwnerMask = 0x0234; part.CreatorID = UUID.Random(); part.ObjectFlags = 10101; part.OwnerID = UUID.Random(); part.OwnerMask = 0x0567; part.OwnershipCost = 5; part.ParentID = 0202; part.ParticleSystem = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, }; part.PassTouches = true; part.PhysicalAngularVelocity = SceneUtil.RandomVector(); part.RegionHandle = 1234567; part.RegionID = UUID.Random(); part.RotationOffset = SceneUtil.RandomQuat(); part.SalePrice = 42; part.SavedAttachmentPoint = 6; part.SavedAttachmentPos = SceneUtil.RandomVector(); part.SavedAttachmentRot = SceneUtil.RandomQuat(); part.ScriptAccessPin = 87654; part.SerializedPhysicsData = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, }; part.ServerWeight = 3.0f; part.StreamingCost = 2.0f; part.SitName = "Sitting"; part.Sound = UUID.Random(); part.SoundGain = 3.4f; part.SoundOptions = 9; part.SoundRadius = 10.3f; part.Text = "Test"; part.TextColor = System.Drawing.Color.FromArgb(1, 2, 3, 4); part.TextureAnimation = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD }; part.TouchName = "DoIt"; part.UUID = UUID.Random(); part.Velocity = SceneUtil.RandomVector(); part.FromItemID = UUID.Random(); part.SetSitTarget(SceneUtil.RandomVector(), SceneUtil.RandomQuat(), false); return part; } public static OpenSim.Framework.PrimitiveBaseShape MockPrmitiveBaseShape() { var shape = new OpenSim.Framework.PrimitiveBaseShape(); shape.ExtraParams = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; shape.FlexiDrag = 0.3f; shape.FlexiEntry = true; shape.FlexiForceX = 1.0f; shape.FlexiForceY = 2.0f; shape.FlexiForceZ = 3.0f; shape.FlexiGravity = 10.0f; shape.FlexiSoftness = 1; shape.FlexiTension = 999.4f; shape.FlexiWind = 9292.33f; shape.HollowShape = OpenSim.Framework.HollowShape.Square; shape.LightColorA = 0.3f; shape.LightColorB = 0.22f; shape.LightColorG = 0.44f; shape.LightColorR = 0.77f; shape.LightCutoff = 0.4f; shape.LightEntry = true; shape.LightFalloff = 7474; shape.LightIntensity = 0.0f; shape.LightRadius = 10.0f; shape.Media = new OpenSim.Framework.PrimitiveBaseShape.PrimMedia(); shape.Media.New(2); shape.Media[0] = new MediaEntry { AutoLoop = true, AutoPlay = true, AutoScale = true, AutoZoom = true, ControlPermissions = MediaPermission.All, Controls = MediaControls.Standard, CurrentURL = "bam.com", EnableAlterntiveImage = true, EnableWhiteList = false, Height = 1, HomeURL = "anotherbam.com", InteractOnFirstClick = true, InteractPermissions = MediaPermission.Group, WhiteList = new string[] { "yo mamma" }, Width = 5 }; shape.Media[1] = new MediaEntry { AutoLoop = true, AutoPlay = true, AutoScale = true, AutoZoom = true, ControlPermissions = MediaPermission.All, Controls = MediaControls.Standard, CurrentURL = "kabam.com", EnableAlterntiveImage = true, EnableWhiteList = true, Height = 1, HomeURL = "anotherbam.com", InteractOnFirstClick = true, InteractPermissions = MediaPermission.Group, WhiteList = new string[] { "ur mamma" }, Width = 5 }; shape.PathBegin = 3; shape.PathCurve = 127; shape.PathEnd = 10; shape.PathRadiusOffset = 127; shape.PathRevolutions = 2; shape.PathScaleX = 50; shape.PathScaleY = 100; shape.PathShearX = 33; shape.PathShearY = 44; shape.PathSkew = 126; shape.PathTaperX = 110; shape.PathTaperY = 66; shape.PathTwist = 99; shape.PathTwistBegin = 3; shape.PCode = 3; shape.PreferredPhysicsShape = PhysicsShapeType.Prim; shape.ProfileBegin = 77; shape.ProfileCurve = 5; shape.ProfileEnd = 7; shape.ProfileHollow = 9; shape.ProfileShape = OpenSim.Framework.ProfileShape.IsometricTriangle; shape.ProjectionAmbiance = 0.1f; shape.ProjectionEntry = true; shape.ProjectionFocus = 3.4f; shape.ProjectionFOV = 4.0f; shape.ProjectionTextureUUID = UUID.Random(); shape.Scale = SceneUtil.RandomVector(); shape.SculptEntry = true; shape.SculptTexture = UUID.Random(); shape.SculptType = 40; shape.VertexCount = 1; shape.HighLODBytes = 2; shape.MidLODBytes = 3; shape.LowLODBytes = 4; shape.LowestLODBytes = 5; return shape; } } }
// 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.Diagnostics; namespace System.Xml { internal class XmlElementList : XmlNodeList { string asterisk; int changeCount; //recording the total number that the dom tree has been changed ( insertion and deletetion ) //the member vars below are saved for further reconstruction string name; //only one of 2 string groups will be initialized depends on which constructor is called. string localName; string namespaceURI; XmlNode rootNode; // the memeber vars belwo serves the optimization of accessing of the elements in the list int curInd; // -1 means the starting point for a new search round XmlNode curElem; // if sets to rootNode, means the starting point for a new search round bool empty; // whether the list is empty bool atomized; //whether the localname and namespaceuri are aomized int matchCount; // cached list count. -1 means it needs reconstruction WeakReference listener; // XmlElementListListener private XmlElementList(XmlNode parent) { Debug.Assert(parent != null); Debug.Assert(parent.NodeType == XmlNodeType.Element || parent.NodeType == XmlNodeType.Document); this.rootNode = parent; Debug.Assert(parent.Document != null); this.curInd = -1; this.curElem = rootNode; this.changeCount = 0; this.empty = false; this.atomized = true; this.matchCount = -1; // This can be a regular reference, but it would cause some kind of loop inside the GC this.listener = new WeakReference(new XmlElementListListener(parent.Document, this)); } ~XmlElementList() { Dispose(false); } internal void ConcurrencyCheck(XmlNodeChangedEventArgs args) { if (atomized == false) { XmlNameTable nameTable = this.rootNode.Document.NameTable; this.localName = nameTable.Add(this.localName); this.namespaceURI = nameTable.Add(this.namespaceURI); this.atomized = true; } if (IsMatch(args.Node)) { this.changeCount++; this.curInd = -1; this.curElem = rootNode; if (args.Action == XmlNodeChangedAction.Insert) this.empty = false; } this.matchCount = -1; } internal XmlElementList(XmlNode parent, string name) : this(parent) { Debug.Assert(parent.Document != null); XmlNameTable nt = parent.Document.NameTable; Debug.Assert(nt != null); asterisk = nt.Add("*"); this.name = nt.Add(name); this.localName = null; this.namespaceURI = null; } internal XmlElementList(XmlNode parent, string localName, string namespaceURI) : this(parent) { Debug.Assert(parent.Document != null); XmlNameTable nt = parent.Document.NameTable; Debug.Assert(nt != null); asterisk = nt.Add("*"); this.localName = nt.Get(localName); this.namespaceURI = nt.Get(namespaceURI); if ((this.localName == null) || (this.namespaceURI == null)) { this.empty = true; this.atomized = false; this.localName = localName; this.namespaceURI = namespaceURI; } this.name = null; } internal int ChangeCount { get { return changeCount; } } // return the next element node that is in PreOrder private XmlNode NextElemInPreOrder(XmlNode curNode) { Debug.Assert(curNode != null); //For preorder walking, first try its child XmlNode retNode = curNode.FirstChild; if (retNode == null) { //if no child, the next node forward will the be the NextSibling of the first ancestor which has NextSibling //so, first while-loop find out such an ancestor (until no more ancestor or the ancestor is the rootNode retNode = curNode; while (retNode != null && retNode != rootNode && retNode.NextSibling == null) { retNode = retNode.ParentNode; } //then if such ancestor exists, set the retNode to its NextSibling if (retNode != null && retNode != rootNode) retNode = retNode.NextSibling; } if (retNode == this.rootNode) //if reach the rootNode, consider having walked through the whole tree and no more element after the curNode retNode = null; return retNode; } // return the previous element node that is in PreOrder private XmlNode PrevElemInPreOrder(XmlNode curNode) { Debug.Assert(curNode != null); //For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode XmlNode retNode = curNode.PreviousSibling; // so if the PreviousSibling is not null, going through the tree down to find the right-most node while (retNode != null) { if (retNode.LastChild == null) break; retNode = retNode.LastChild; } // if no PreviousSibling, the previous node will be the curNode's parentNode if (retNode == null) retNode = curNode.ParentNode; // if the final retNode is rootNode, consider having walked through the tree and no more previous node if (retNode == this.rootNode) retNode = null; return retNode; } // if the current node a matching element node private bool IsMatch(XmlNode curNode) { if (curNode.NodeType == XmlNodeType.Element) { if (this.name != null) { if (Ref.Equal(this.name, asterisk) || Ref.Equal(curNode.Name, this.name)) return true; } else { if ( (Ref.Equal(this.localName, asterisk) || Ref.Equal(curNode.LocalName, this.localName)) && (Ref.Equal(this.namespaceURI, asterisk) || curNode.NamespaceURI == this.namespaceURI) ) { return true; } } } return false; } private XmlNode GetMatchingNode(XmlNode n, bool bNext) { Debug.Assert(n != null); XmlNode node = n; do { if (bNext) node = NextElemInPreOrder(node); else node = PrevElemInPreOrder(node); } while (node != null && !IsMatch(node)); return node; } private XmlNode GetNthMatchingNode(XmlNode n, bool bNext, int nCount) { Debug.Assert(n != null); XmlNode node = n; for (int ind = 0; ind < nCount; ind++) { node = GetMatchingNode(node, bNext); if (node == null) return null; } return node; } //the function is for the enumerator to find out the next available matching element node public XmlNode GetNextNode(XmlNode n) { if (this.empty == true) return null; XmlNode node = (n == null) ? rootNode : n; return GetMatchingNode(node, true); } public override XmlNode Item(int index) { if (rootNode == null || index < 0) return null; if (this.empty == true) return null; if (curInd == index) return curElem; int nDiff = index - curInd; bool bForward = (nDiff > 0); if (nDiff < 0) nDiff = -nDiff; XmlNode node; if ((node = GetNthMatchingNode(curElem, bForward, nDiff)) != null) { curInd = index; curElem = node; return curElem; } return null; } public override int Count { get { if (this.empty == true) return 0; if (this.matchCount < 0) { int currMatchCount = 0; int currChangeCount = this.changeCount; XmlNode node = rootNode; while ((node = GetMatchingNode(node, true)) != null) { currMatchCount++; } if (currChangeCount != this.changeCount) { return currMatchCount; } this.matchCount = currMatchCount; } return this.matchCount; } } public override IEnumerator GetEnumerator() { if (this.empty == true) return new XmlEmptyElementListEnumerator(this);; return new XmlElementListEnumerator(this); } protected override void PrivateDisposeNodeList() { GC.SuppressFinalize(this); Dispose(true); } protected virtual void Dispose(bool disposing) { if (this.listener != null) { XmlElementListListener listener = (XmlElementListListener)this.listener.Target; if (listener != null) { listener.Unregister(); } this.listener = null; } } } internal class XmlElementListEnumerator : IEnumerator { XmlElementList list; XmlNode curElem; int changeCount; //save the total number that the dom tree has been changed ( insertion and deletetion ) when this enumerator is created public XmlElementListEnumerator(XmlElementList list) { this.list = list; this.curElem = null; this.changeCount = list.ChangeCount; } public bool MoveNext() { if (list.ChangeCount != this.changeCount) { //the number mismatch, there is new change(s) happened since last MoveNext() is called. throw new InvalidOperationException(SR.Xdom_Enum_ElementList); } else { curElem = list.GetNextNode(curElem); } return curElem != null; } public void Reset() { curElem = null; //reset the number of changes to be synced with current dom tree as well this.changeCount = list.ChangeCount; } public object Current { get { return curElem; } } } internal class XmlEmptyElementListEnumerator : IEnumerator { public XmlEmptyElementListEnumerator(XmlElementList list) { } public bool MoveNext() { return false; } public void Reset() { } public object Current { get { return null; } } } internal class XmlElementListListener { WeakReference elemList; XmlDocument doc; XmlNodeChangedEventHandler nodeChangeHandler = null; internal XmlElementListListener(XmlDocument doc, XmlElementList elemList) { this.doc = doc; this.elemList = new WeakReference(elemList); this.nodeChangeHandler = new XmlNodeChangedEventHandler(this.OnListChanged); doc.NodeInserted += this.nodeChangeHandler; doc.NodeRemoved += this.nodeChangeHandler; } private void OnListChanged(object sender, XmlNodeChangedEventArgs args) { lock (this) { if (this.elemList != null) { XmlElementList el = (XmlElementList)this.elemList.Target; if (null != el) { el.ConcurrencyCheck(args); } else { this.doc.NodeInserted -= this.nodeChangeHandler; this.doc.NodeRemoved -= this.nodeChangeHandler; this.elemList = null; } } } } // This method is called from the finalizer of XmlElementList internal void Unregister() { lock (this) { if (elemList != null) { this.doc.NodeInserted -= this.nodeChangeHandler; this.doc.NodeRemoved -= this.nodeChangeHandler; this.elemList = null; } } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[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 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.Layouts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; /// <summary> /// Parses layout strings. /// </summary> internal sealed class LayoutParser { internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text) { var result = new List<LayoutRenderer>(); var literalBuf = new StringBuilder(); int ch; int p0 = sr.Position; while ((ch = sr.Peek()) != -1) { if (isNested && (ch == '}' || ch == ':')) { break; } sr.Read(); if (ch == '$' && sr.Peek() == '{') { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr); if (CanBeConvertedToLiteral(newLayoutRenderer)) { newLayoutRenderer = ConvertToLiteral(newLayoutRenderer); } // layout renderer result.Add(newLayoutRenderer); } else { literalBuf.Append((char)ch); } } if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } int p1 = sr.Position; MergeLiterals(result); text = sr.Substring(p0, p1); return result.ToArray(); } private static string ParseLayoutRendererName(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterName(SimpleStringReader sr) { int ch; int nestLevel = 0; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if ((ch == '=' || ch == '}' || ch == ':') && nestLevel == 0) { break; } if (ch == '$') { sr.Read(); nameBuf.Append('$'); if (sr.Peek() == '{') { nameBuf.Append('{'); nestLevel++; sr.Read(); } continue; } if (ch == '}') { nestLevel--; } if (ch == '\\') { // skip the backslash sr.Read(); // append next character nameBuf.Append((char)sr.Read()); continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterValue(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } if (ch == '\\') { // skip the backslash sr.Read(); // append next character nameBuf.Append((char)sr.Read()); continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr) { int ch = sr.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(sr); LayoutRenderer lr = configurationItemFactory.LayoutRenderers.CreateInstance(name); var wrappers = new Dictionary<Type, LayoutRenderer>(); var orderedWrappers = new List<LayoutRenderer>(); ch = sr.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(sr).Trim(); if (sr.Peek() == '=') { sr.Read(); // skip the '=' PropertyInfo pi; LayoutRenderer parameterTarget = lr; if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi)) { Type wrapperType; if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType)) { LayoutRenderer wrapperRenderer; if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi)) { pi = null; } else { parameterTarget = wrapperRenderer; } } } if (pi == null) { ParseParameterValue(sr); } else { if (typeof(Layout).IsAssignableFrom(pi.PropertyType)) { var nestedLayout = new SimpleLayout(); string txt; LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt); nestedLayout.SetRenderers(renderers, txt); pi.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(pi.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(sr, configurationItemFactory); pi.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(sr); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) PropertyInfo pi; if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi)) { if (typeof(SimpleLayout) == pi.PropertyType) { pi.SetValue(lr, new SimpleLayout(parameterName), null); } else { string value = parameterName; PropertyHelper.SetPropertyFromString(lr, pi.Name, value, configurationItemFactory); } } else { InternalLogger.Warn("{0} has no default property", lr.GetType().FullName); } } ch = sr.Read(); } lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers); return lr; } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers) { for (int i = orderedWrappers.Count - 1; i >= 0; --i) { var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType().Name, newRenderer.GetType().Name); if (CanBeConvertedToLiteral(lr)) { lr = ConvertToLiteral(lr); } newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory); lr = newRenderer; } return lr; } private static bool CanBeConvertedToLiteral(LayoutRenderer lr) { foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(lr)) { if (renderable.GetType() == typeof(SimpleLayout)) { continue; } if (!renderable.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), false)) { return false; } } return true; } private static void MergeLiterals(List<LayoutRenderer> list) { for (int i = 0; i + 1 < list.Count;) { var lr1 = list[i] as LiteralLayoutRenderer; var lr2 = list[i + 1] as LiteralLayoutRenderer; if (lr1 != null && lr2 != null) { lr1.Text += lr2.Text; list.RemoveAt(i + 1); } else { i++; } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { return new LiteralLayoutRenderer(renderer.Render(LogEventInfo.CreateNullEvent())); } } }
//------------------------------------------------------------------------------ // <copyright file="ProcessStartInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Diagnostics { using System.Threading; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Security; using System.Security.Permissions; using Microsoft.Win32; using System.IO; using System.ComponentModel.Design; using System.Collections.Specialized; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Runtime.Versioning; /// <devdoc> /// A set of values used to specify a process to start. This is /// used in conjunction with the <see cref='System.Diagnostics.Process'/> /// component. /// </devdoc> [ TypeConverter(typeof(ExpandableObjectConverter)), // Disabling partial trust scenarios PermissionSet(SecurityAction.LinkDemand, Name="FullTrust"), HostProtection(SharedState=true, SelfAffectingProcessMgmt=true) ] public sealed class ProcessStartInfo { string fileName; string arguments; string directory; string verb; ProcessWindowStyle windowStyle; bool errorDialog; IntPtr errorDialogParentHandle; #if FEATURE_PAL bool useShellExecute = false; #else //FEATURE_PAL bool useShellExecute = true; string userName; string domain; SecureString password; bool loadUserProfile; #endif //FEATURE_PAL bool redirectStandardInput = false; bool redirectStandardOutput = false; bool redirectStandardError = false; Encoding standardOutputEncoding; Encoding standardErrorEncoding; bool createNoWindow = false; WeakReference weakParentProcess; internal StringDictionary environmentVariables; /// <devdoc> /// Default constructor. At least the <see cref='System.Diagnostics.ProcessStartInfo.FileName'/> /// property must be set before starting the process. /// </devdoc> public ProcessStartInfo() { } internal ProcessStartInfo(Process parent) { this.weakParentProcess = new WeakReference(parent); } /// <devdoc> /// Specifies the name of the application or document that is to be started. /// </devdoc> [ResourceExposure(ResourceScope.Machine)] public ProcessStartInfo(string fileName) { this.fileName = fileName; } /// <devdoc> /// Specifies the name of the application that is to be started, as well as a set /// of command line arguments to pass to the application. /// </devdoc> [ResourceExposure(ResourceScope.Machine)] public ProcessStartInfo(string fileName, string arguments) { this.fileName = fileName; this.arguments = arguments; } /// <devdoc> /// <para> /// Specifies the verb to use when opening the filename. For example, the "print" /// verb will print a document specified using <see cref='System.Diagnostics.ProcessStartInfo.FileName'/>. /// Each file extension has it's own set of verbs, which can be obtained using the /// <see cref='System.Diagnostics.ProcessStartInfo.Verbs'/> property. /// The default verb can be specified using "". /// </para> /// <note type="rnotes"> /// Discuss 'opening' vs. 'starting.' I think the part about the /// default verb was a dev comment. /// Find out what /// that means. /// </note> /// </devdoc> [ DefaultValueAttribute(""), TypeConverter("System.Diagnostics.Design.VerbConverter, " + AssemblyRef.SystemDesign), MonitoringDescription(SR.ProcessVerb), NotifyParentProperty(true) ] public string Verb { get { if (verb == null) return string.Empty; return verb; } set { verb = value; } } /// <devdoc> /// Specifies the set of command line arguments to use when starting the application. /// </devdoc> [ DefaultValueAttribute(""), MonitoringDescription(SR.ProcessArguments), SettingsBindable(true), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), NotifyParentProperty(true) ] public string Arguments { get { if (arguments == null) return string.Empty; return arguments; } set { arguments = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessCreateNoWindow), NotifyParentProperty(true) ] public bool CreateNoWindow { get { return createNoWindow; } set { createNoWindow = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ Editor("System.Diagnostics.Design.StringDictionaryEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), DefaultValue( null ), MonitoringDescription(SR.ProcessEnvironmentVariables), NotifyParentProperty(true) ] public StringDictionary EnvironmentVariables { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { // Note: // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. // When used with an existing Process.ProcessStartInfo the following behavior // * Desktop - Populates with current Environment (rather than that of the process) if (environmentVariables == null) { #if PLATFORM_UNIX environmentVariables = new CaseSensitiveStringDictionary(); #else environmentVariables = new StringDictionaryWithComparer (); #endif // PLATFORM_UNIX // if not in design mode, initialize the child environment block with all the parent variables if (!(this.weakParentProcess != null && this.weakParentProcess.IsAlive && ((Component)this.weakParentProcess.Target).Site != null && ((Component)this.weakParentProcess.Target).Site.DesignMode)) { foreach (DictionaryEntry entry in System.Environment.GetEnvironmentVariables()) environmentVariables.Add((string)entry.Key, (string)entry.Value); } } return environmentVariables; } } private IDictionary<string,string> environment; [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null), NotifyParentProperty(true) ] public IDictionary<string, string> Environment { get { if (environment == null) { environment = this.EnvironmentVariables.AsGenericDictionary(); } return environment; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessRedirectStandardInput), NotifyParentProperty(true) ] public bool RedirectStandardInput { get { return redirectStandardInput; } set { redirectStandardInput = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessRedirectStandardOutput), NotifyParentProperty(true) ] public bool RedirectStandardOutput { get { return redirectStandardOutput; } set { redirectStandardOutput = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessRedirectStandardError), NotifyParentProperty(true) ] public bool RedirectStandardError { get { return redirectStandardError; } set { redirectStandardError = value; } } public Encoding StandardErrorEncoding { get { return standardErrorEncoding; } set { standardErrorEncoding = value; } } public Encoding StandardOutputEncoding { get { return standardOutputEncoding; } set { standardOutputEncoding = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(true), MonitoringDescription(SR.ProcessUseShellExecute), NotifyParentProperty(true) ] public bool UseShellExecute { get { return useShellExecute; } set { useShellExecute = value; } } #if !FEATURE_PAL /// <devdoc> /// Returns the set of verbs associated with the file specified by the /// <see cref='System.Diagnostics.ProcessStartInfo.FileName'/> property. /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string[] Verbs { [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] get { ArrayList verbs = new ArrayList(); RegistryKey key = null; string extension = Path.GetExtension(FileName); try { if (extension != null && extension.Length > 0) { key = Registry.ClassesRoot.OpenSubKey(extension); if (key != null) { string value = (string)key.GetValue(String.Empty); key.Close(); key = Registry.ClassesRoot.OpenSubKey(value + "\\shell"); if (key != null) { string[] names = key.GetSubKeyNames(); for (int i = 0; i < names.Length; i++) if (string.Compare(names[i], "new", StringComparison.OrdinalIgnoreCase) != 0) verbs.Add(names[i]); key.Close(); key = null; } } } } finally { if (key != null) key.Close(); } string[] temp = new string[verbs.Count]; verbs.CopyTo(temp, 0); return temp; } } [NotifyParentProperty(true)] public string UserName { get { if( userName == null) { return string.Empty; } else { return userName; } } set { userName = value; } } public SecureString Password { get { return password; } set { password = value; } } [NotifyParentProperty(true)] public string Domain { get { if( domain == null) { return string.Empty; } else { return domain; } } set { domain = value;} } [NotifyParentProperty(true)] public bool LoadUserProfile { get { return loadUserProfile;} set { loadUserProfile = value; } } #endif // !FEATURE_PAL /// <devdoc> /// <para> /// Returns or sets the application, document, or URL that is to be launched. /// </para> /// </devdoc> [ DefaultValue(""), Editor("System.Diagnostics.Design.StartFileNameEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), MonitoringDescription(SR.ProcessFileName), SettingsBindable(true), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), NotifyParentProperty(true) ] public string FileName { [ResourceExposure(ResourceScope.Machine)] get { if (fileName == null) return string.Empty; return fileName; } [ResourceExposure(ResourceScope.Machine)] set { fileName = value;} } /// <devdoc> /// Returns or sets the initial directory for the process that is started. /// Specify "" to if the default is desired. /// </devdoc> [ DefaultValue(""), MonitoringDescription(SR.ProcessWorkingDirectory), Editor("System.Diagnostics.Design.WorkingDirectoryEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), SettingsBindable(true), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), NotifyParentProperty(true) ] public string WorkingDirectory { [ResourceExposure(ResourceScope.Machine)] get { if (directory == null) return string.Empty; return directory; } [ResourceExposure(ResourceScope.Machine)] set { directory = value; } } /// <devdoc> /// Sets or returns whether or not an error dialog should be displayed to the user /// if the process can not be started. /// </devdoc> [ DefaultValueAttribute(false), MonitoringDescription(SR.ProcessErrorDialog), NotifyParentProperty(true) ] public bool ErrorDialog { get { return errorDialog;} set { errorDialog = value;} } /// <devdoc> /// Sets or returns the window handle to use for the error dialog that is shown /// when a process can not be started. If <see cref='System.Diagnostics.ProcessStartInfo.ErrorDialog'/> /// is true, this specifies the parent window for the dialog that is shown. It is /// useful to specify a parent in order to keep the dialog in front of the application. /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IntPtr ErrorDialogParentHandle { get { return errorDialogParentHandle;} set { errorDialogParentHandle = value;} } /// <devdoc> /// Sets or returns the style of window that should be used for the newly created process. /// </devdoc> [ DefaultValueAttribute(System.Diagnostics.ProcessWindowStyle.Normal), MonitoringDescription(SR.ProcessWindowStyle), NotifyParentProperty(true) ] public ProcessWindowStyle WindowStyle { get { return windowStyle;} set { if (!Enum.IsDefined(typeof(ProcessWindowStyle), value)) throw new InvalidEnumArgumentException("value", (int)value, typeof(ProcessWindowStyle)); windowStyle = value; } } } }
// 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.Xml; using System.Collections; namespace System.Data.Common { internal sealed class SingleStorage : DataStorage { private const float defaultValue = 0.0f; private float[] _values; public SingleStorage(DataColumn column) : base(column, typeof(float), defaultValue, StorageType.Single) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: float sum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += _values[record]; } hasData = true; } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: double meanSum = defaultValue; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += _values[record]; } meanCount++; hasData = true; } if (hasData) { float mean; checked { mean = (float)(meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = defaultValue; double prec = defaultValue; double dsum = defaultValue; double sqrsum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; dsum += _values[record]; sqrsum += _values[record] * (double)_values[record]; count++; } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return _nullValue; case AggregateType.Min: float min = float.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; min = Math.Min(_values[record], min); hasData = true; } if (hasData) { return min; } return _nullValue; case AggregateType.Max: float max = float.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; max = Math.Max(_values[record], max); hasData = true; } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null; case AggregateType.Count: return base.Aggregate(records, kind); } } catch (OverflowException) { throw ExprException.Overflow(typeof(float)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { float valueNo1 = _values[recordNo1]; float valueNo2 = _values[recordNo2]; if (valueNo1 == defaultValue || valueNo2 == defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) return bitCheck; } return valueNo1.CompareTo(valueNo2); // not simple, checks Nan } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { if (IsNull(recordNo)) { return 0; } return 1; } float valueNo1 = _values[recordNo]; if ((defaultValue == valueNo1) && IsNull(recordNo)) { return -1; } return valueNo1.CompareTo((float)value); } public override object ConvertValue(object value) { if (_nullValue != value) { if (null != value) { value = ((IConvertible)value).ToSingle(FormatProvider); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { float value = _values[record]; if (value != defaultValue) { return value; } return GetBits(record); } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = defaultValue; SetNullBit(record, true); } else { _values[record] = ((IConvertible)value).ToSingle(FormatProvider); SetNullBit(record, false); } } public override void SetCapacity(int capacity) { float[] newValues = new float[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } public override object ConvertXmlToObject(string s) { return XmlConvert.ToSingle(s); } public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((float)value); } protected override object GetEmptyStorage(int recordCount) { return new float[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { float[] typedStore = (float[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (float[])store; SetNullStorage(nullbits); } } }
// jQueryAjaxOptions.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; namespace jQueryApi { /// <summary> /// Represents Ajax request settings or options. /// </summary> [Imported] [Serializable] public sealed class jQueryAjaxOptions<T> { /// <summary> /// Initializes an empty instance of a jQueryAjaxOptions object. /// </summary> public jQueryAjaxOptions() { } /// <summary> /// Gets or sets whether the request is async. /// </summary> public bool Async { get { return false; } set { } } /// <summary> /// Gets or sets the callback to invoke before the request is sent. /// </summary> public AjaxSendingCallback<T> BeforeSend { get { return null; } set { } } /// <summary> /// Gets or sets whether the request can be cached. /// </summary> public bool Cache { get { return false; } set { } } /// <summary> /// Gets or sets the callback invoked after the request is completed /// and success or error callbacks have been invoked. /// </summary> public AjaxCompletedCallback<T> Complete { get { return null; } set { } } /// <summary> /// Gets or sets the content type of the data sent to the server. /// </summary> public string ContentType { get { return null; } set { } } /// <summary> /// Gets or sets the element that will be the context for the request. /// </summary> public object Context { get { return null; } set { } } /// <summary> /// A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. /// </summary> public JsDictionary<string, Func<string, object>> Converters { get; set; } /// <summary> /// Gets or sets the data to be sent to the server. /// </summary> public TypeOption<JsDictionary<string, object>, Array, string> Data { get { return null; } set { } } /// <summary> /// Gets or sets the data type expected in response from the server. /// </summary> public string DataType { get { return null; } set { } } /// <summary> /// Gets or sets the callback to be invoked if the request fails. /// </summary> public AjaxErrorCallback<T> Error { get { return null; } set { } } /// <summary> /// Gets or sets the function to be used to handle the raw response data of XMLHttpRequest. /// </summary> public AjaxDataFilterCallback DataFilter { get { return null; } set { } } /// <summary> /// Gets or sets whether to trigger global event handlers for this Ajax request. /// </summary> public bool Global { get { return false; } set { } } /// <summary> /// Gets or sets additional header key/value pairs to send along with requests using the XMLHttpRequest transport. /// </summary> public JsDictionary<string, string> Headers { get { return null; } set { } } /// <summary> /// Gets or sets whether the request is successful only if its been modified since /// the last request. /// </summary> public bool IfModified { get { return false; } set { } } /// <summary> /// Gets or sets whether the current environment should be treated as a local /// environment (eg. when the page is loaded using file://). /// </summary> public bool IsLocal { get { return false; } set { } } /// <summary> /// Gets or sets the callback parameter name to use for JSONP requests. /// </summary> public string Jsonp { get { return null; } set { } } /// <summary> /// Gets or sets the callback name to use for JSONP requests. /// </summary> public string JsonpCallback { get { return null; } set { } } /// <summary> /// Gets or sets the mime type of the request. /// </summary> public string MimeType { get { return null; } set { } } /// <summary> /// Gets or sets the password to be used for an HTTP authentication request. /// </summary> public string Password { get { return null; } set { } } /// <summary> /// Gets or sets whether the data passed in will be processed. /// </summary> public bool ProcessData { get { return false; } set { } } /// <summary> /// Gets or sets how to handle character sets for script and JSONP requests. /// </summary> public string ScriptCharset { get { return null; } set { } } /// <summary> /// Gets or sets the function to invoke upon successful completion of the request. /// </summary> public AjaxRequestCallback<T> Success { get { return null; } set { } } /// <summary> /// Gets or sets the timeout in milliseconds for the request. /// </summary> public int Timeout { get { return 0; } set { } } /// <summary> /// Gets or sets if you want to use traditional parameter serialization. /// </summary> public bool Traditional { get { return false; } set { } } /// <summary> /// Gets or sets the type or HTTP verb associated with the request. /// </summary> public string Type { get { return null; } set { } } /// <summary> /// Gets or sets the URL to be requested. /// </summary> public string Url { get { return null; } set { } } /// <summary> /// Gets or sets the name of the user to use in a HTTP authentication request. /// </summary> public string Username { get { return null; } set { } } /// <summary> /// Gets or sets the function creating the XmlHttpRequest instance. /// </summary> [ScriptName("xhr")] public XmlHttpRequestCreator<T> XmlHttpRequestCreator { get { return null; } set { } } /// <summary> /// Gets or sets a set of additional name/value pairs set of the XmlHttpRequest /// object. /// </summary> public JsDictionary<string, object> XhrFields { get { return null; } set { } } } }
#region License /* * Copyright 2004 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.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; using NUnit.Framework; using Spring.Objects; #endregion namespace Spring.Util { /// <summary> /// Unit tests for the AssertUtils class. /// </summary> /// <author>Rick Evans</author> [TestFixture] public sealed class AssertUtilsTests { [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "foo")] public void IsTrueWithMesssage() { AssertUtils.IsTrue(false, "foo"); } [Test] public void IsTrueWithMessageValidExpression() { AssertUtils.IsTrue(true, "foo"); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "[Assertion failed] - this expression must be true")] public void IsTrue() { AssertUtils.IsTrue(false); } [Test] public void IsTrueValidExpression() { AssertUtils.IsTrue(true); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void StateTrue() { AssertUtils.State(false, "foo"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentNotNull() { AssertUtils.ArgumentNotNull(null, "foo"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentNotNullWithMessage() { AssertUtils.ArgumentNotNull(null, "foo", "Bang!"); } [Test] public void ArgumentHasTextWithValidText() { AssertUtils.ArgumentHasText("... and no-one's getting fat 'cept Mama Cas!", "foo"); } [Test] public void ArgumentHasTextWithValidTextAndMessage() { AssertUtils.ArgumentHasText("... and no-one's getting fat 'cept Mama Cas!", "foo", "Bang!"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentHasText() { AssertUtils.ArgumentHasText(null, "foo"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentHasTextWithMessage() { AssertUtils.ArgumentHasText(null, "foo", "Bang!"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentHasLengthArgumentIsNull() { AssertUtils.ArgumentHasLength(null, "foo"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentHasLengthArgumentIsNullWithMessage() { AssertUtils.ArgumentHasLength(null, "foo", "Bang!"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentHasLengthArgumentIsEmpty() { AssertUtils.ArgumentHasLength(new byte[0], "foo"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ArgumentHasLengthArgumentIsEmptyWithMessage() { AssertUtils.ArgumentHasLength(new byte[0], "foo", "Bang!"); } [Test] public void ArgumentHasLengthArgumentHasElements() { AssertUtils.ArgumentHasLength(new byte[1], "foo"); } [Test] public void ArgumentHasLengthArgumentHasElementsWithMessage() { AssertUtils.ArgumentHasLength(new byte[1], "foo", "Bang!"); } [Test] [ExpectedException(typeof(ArgumentException))] public void ArgumentHasElementsArgumentIsNull() { AssertUtils.ArgumentHasElements(null, "foo"); } [Test] [ExpectedException(typeof(ArgumentException))] public void ArgumentHasElementsArgumentIsEmpty() { AssertUtils.ArgumentHasElements(new object[0], "foo"); } [Test] [ExpectedException(typeof(ArgumentException))] public void ArgumentHasElementsArgumentContainsNull() { AssertUtils.ArgumentHasElements(new object[] { new object(), null, new object() }, "foo"); } [Test] public void ArgumentHasElementsArgumentContainsNonNullsOnly() { AssertUtils.ArgumentHasElements(new object[] { new object(), new object(), new object() }, "foo"); } [Test] public void UnderstandsType() { MethodInfo getDescriptionMethod = typeof(ITestObject).GetMethod("GetDescription", new Type[0]); MethodInfo understandsMethod = typeof(AssertUtils).GetMethod("Understands", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof (object), typeof(string), typeof (MethodBase)}, null); // null target, any type AssertNotUnderstandsType(null, "target", typeof(object), typeof(NotSupportedException), "Target 'target' is null."); // any target, null type AssertNotUnderstandsType(new object(), "target", null, typeof(ArgumentNullException), "Argument 'requiredType' cannot be null."); } [Test] public void UnderstandsMethod() { MethodInfo getDescriptionMethod = typeof(ITestObject).GetMethod("GetDescription", new Type[0]); MethodInfo understandsMethod = typeof(AssertUtils).GetMethod("Understands", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof (object), typeof(string), typeof (MethodBase)}, null); // null target, static method AssertUtils.Understands(null, "target", understandsMethod); // null target, instance method AssertNotUnderstandsMethod(null, "target", getDescriptionMethod, typeof(NotSupportedException), "Target 'target' is null and target method 'Spring.Objects.ITestObject.GetDescription' is not static."); // compatible target, instance method AssertUtils.Understands(new TestObject(), "target", getDescriptionMethod); // incompatible target, instance method AssertNotUnderstandsMethod(new object(), "target", getDescriptionMethod, typeof(NotSupportedException), "Target 'target' of type 'System.Object' does not support methods of 'Spring.Objects.ITestObject'."); // compatible transparent proxy, instance method object compatibleProxy = new TestProxy(new TestObject()).GetTransparentProxy(); AssertUtils.Understands(compatibleProxy, "compatibleProxy", getDescriptionMethod); // incompatible transparent proxy, instance method object incompatibleProxy = new TestProxy(new object()).GetTransparentProxy(); AssertNotUnderstandsMethod(incompatibleProxy, "incompatibleProxy", getDescriptionMethod, typeof(NotSupportedException), "Target 'incompatibleProxy' is a transparent proxy that does not support methods of 'Spring.Objects.ITestObject'."); } private void AssertNotUnderstandsType(object target, string targetName, Type requiredType, Type exceptionType, string partialMessage) { try { AssertUtils.Understands(target, targetName, requiredType); Assert.Fail(); } catch(Exception ex) { if (ex.GetType() != exceptionType) { Assert.Fail("Expected Exception of type {0}, but was {1}", exceptionType, ex.GetType()); } if (-1 == ex.Message.IndexOf(partialMessage)) { Assert.Fail("Expected Message '{0}', but got '{1}'", partialMessage, ex.Message); } } } private void AssertNotUnderstandsMethod(object target, string targetName, MethodBase method, Type exceptionType, string partialMessage) { try { AssertUtils.Understands(target, targetName, method); Assert.Fail(); } catch(Exception ex) { if (ex.GetType() != exceptionType) { Assert.Fail("Expected Exception of type {0}, but was {1}", exceptionType, ex.GetType()); } if (-1 == ex.Message.IndexOf(partialMessage)) { Assert.Fail("Expected Message '{0}', but got '{1}'", partialMessage, ex.Message); } } } private class TestProxy : RealProxy, IRemotingTypeInfo { private readonly object targetInstance; public TestProxy(object targetInstance) : base(typeof(MarshalByRefObject)) { this.targetInstance = targetInstance; } public override IMessage Invoke(IMessage msg) { // return new ReturnMessage(result, null, 0, null, callMsg); throw new NotSupportedException(); } public bool CanCastTo(Type fromType, object o) { bool res = fromType.IsAssignableFrom(targetInstance.GetType()); return res; } public string TypeName { get { return targetInstance.GetType().AssemblyQualifiedName; } set { throw new System.NotSupportedException(); } } } } }
using System; using System.Collections.Concurrent; using System.IO.Ports; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; using Microsoft.Win32; namespace LazerTagHostLibrary { public class LazerTagSerial : IDisposable { private const int InterSignatureDelayMilliseconds = 50; private string _portName; private SerialPort _serialPort; private string _readBuffer; private readonly BlockingCollection<byte[]> _writeQueue; private Thread _writeThread; public LazerTagSerial() { _writeQueue = new BlockingCollection<byte[]>(); SystemEvents.PowerModeChanged += PowerModeChanged; } ~LazerTagSerial() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) // release managed resources { Disconnect(); if (_serialPort != null) _serialPort.Dispose(); if (_writeQueue != null) _writeQueue.Dispose(); } // release unmanaged resources } static public string[] GetSerialPorts() { try { return SerialPort.GetPortNames(); } catch (Exception ex) { Log.Add("GetSerialPorts() failed.", ex); return new string[] {}; } } public bool Connect(string portName) { try { if (string.IsNullOrWhiteSpace(portName)) return false; _portName = portName; if (_serialPort != null) { Disconnect(); Thread.Sleep(5); } _serialPort = new SerialPort(_portName, 115200, Parity.None, 8, StopBits.One) { Handshake = Handshake.None, DtrEnable = true, RtsEnable = true }; _serialPort.PinChanged += SerialPinChanged; _serialPort.DataReceived += SerialDataReceived; _serialPort.ErrorReceived += SerialErrorReceived; _serialPort.Open(); _writeThread = new Thread(WriteThread) { IsBackground = true }; _writeThread.Start(); } catch (Exception ex) { Log.Add("Connect() failed.", ex); Disconnect(); return false; } return true; } public void Disconnect() { AbortWriteThread(); if (_serialPort == null) return; try { _serialPort.Close(); } catch (Exception ex) { Log.Add("LazerTagSerial.Disconnect() failed.", ex); } _serialPort = null; } private static void SerialPinChanged(object sender, SerialPinChangedEventArgs e) { Log.Add(Log.Severity.Debug, "SerialPinChanged(): {0}", e.EventType); } private void SerialDataReceived(object sender, SerialDataReceivedEventArgs e) { if (sender != _serialPort) return; _readBuffer += _serialPort.ReadExisting(); foreach (var line in SplitBufferLines(_readBuffer, out _readBuffer)) { OnDataReceived(new DataReceivedEventArgs(line)); } } private static IEnumerable<string> SplitBufferLines(string buffer, out string remainingBuffer) { var lines = new List<string>(); var match = Regex.Match(buffer, @"(.+?)(\r?\n|\r)"); var lastMatchPosition = 0; while (match.Success) { if (match.Groups.Count < 2) continue; lines.Add(match.Groups[1].Value); lastMatchPosition = match.Index + match.Length; match = match.NextMatch(); } remainingBuffer = buffer.Substring(lastMatchPosition); return lines; } private static void SerialErrorReceived(object sender, SerialErrorReceivedEventArgs e) { Log.Add(Log.Severity.Debug, "SerialErrorReceived(): {0}", e.EventType); } public void Enqueue(byte[] bytes) { if (_serialPort == null || !_serialPort.IsOpen) { if (!Connect(_portName)) return; } _writeQueue.Add(bytes); } private void WriteThread() { try { while (_serialPort != null && _serialPort.IsOpen) { var data = _writeQueue.Take(); _serialPort.Write(data, 0, data.Length); _serialPort.BaseStream.Flush(); // TODO: Move this to the device firmware Thread.Sleep(InterSignatureDelayMilliseconds); } } catch (ThreadAbortException) { Log.Add(Log.Severity.Debug, "LazerTagSerial.WriteThread() abort requested."); } catch (Exception ex) { Log.Add("WriteThread() failed.", ex); OnIoError(new IoErrorEventArgs(null, ex)); } finally { // not much use if we can't send anymore so disconnect it Disconnect(); } Log.Add(Log.Severity.Debug, "LazerTagSerial.WriteThread() exiting."); } private void AbortWriteThread() { if (_writeThread == null) return; if (_serialPort != null && _serialPort.IsOpen) { try { _serialPort.DiscardOutBuffer(); } catch (Exception ex) { Log.Add("LazerTagSerial.AbortWriteThread() failed at _serialPort.DiscardOutBuffer().", ex); } } try { if ((_writeThread.ThreadState & (ThreadState.AbortRequested | ThreadState.Aborted)) == 0) { _writeThread.Abort(); } } catch (Exception ex) { Log.Add("LazerTagSerial.AbortWriteThread() failed.", ex); } } private void PowerModeChanged(object sender, PowerModeChangedEventArgs e) { Log.Add(Log.Severity.Debug, "LazerTagSerial.PowerModeChanged(): {0}", e.Mode); if (e.Mode == PowerModes.Resume) Connect(_portName); } public class IoErrorEventArgs : EventArgs { public IoErrorEventArgs(string message, Exception ex) { Message = message; Exception = ex; } public string Message; public Exception Exception; } public delegate void IoErrorEventHandler(object sender, IoErrorEventArgs e); public event IoErrorEventHandler IoError; protected virtual void OnIoError(IoErrorEventArgs e) { if (IoError != null) IoError(this, e); } public class DataReceivedEventArgs : EventArgs { public DataReceivedEventArgs(string data) { Data = data; } public string Data { get; set; } } public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e); public event DataReceivedEventHandler DataReceived; protected virtual void OnDataReceived(DataReceivedEventArgs e) { if (DataReceived != null) DataReceived(this, e); } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ExpressRouteCircuitPeeringsOperations. /// </summary> public static partial class ExpressRouteCircuitPeeringsOperationsExtensions { /// <summary> /// Deletes the specified peering from the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> public static void Delete(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName) { operations.DeleteAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified peering from the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified authorization from the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> public static ExpressRouteCircuitPeering Get(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName) { return operations.GetAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified authorization from the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitPeering> GetAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a peering in the specified express route circuits. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create or update express route circuit peering /// operation. /// </param> public static ExpressRouteCircuitPeering CreateOrUpdate(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, peeringName, peeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified express route circuits. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create or update express route circuit peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitPeering> CreateOrUpdateAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all peerings in a specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> public static IPage<ExpressRouteCircuitPeering> List(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName) { return operations.ListAsync(resourceGroupName, circuitName).GetAwaiter().GetResult(); } /// <summary> /// Gets all peerings in a specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ExpressRouteCircuitPeering>> ListAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified peering from the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> public static void BeginDelete(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName) { operations.BeginDeleteAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified peering from the specified express route circuit. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates a peering in the specified express route circuits. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create or update express route circuit peering /// operation. /// </param> public static ExpressRouteCircuitPeering BeginCreateOrUpdate(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, peeringName, peeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified express route circuits. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create or update express route circuit peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ExpressRouteCircuitPeering> BeginCreateOrUpdateAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all peerings in a specified express route circuit. /// </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<ExpressRouteCircuitPeering> ListNext(this IExpressRouteCircuitPeeringsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all peerings in a specified express route circuit. /// </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<ExpressRouteCircuitPeering>> ListNextAsync(this IExpressRouteCircuitPeeringsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#pragma warning disable 618 // ReSharper disable once CheckNamespace namespace ControlzEx.Behaviors { using System; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Interop; using System.Windows.Media; using ControlzEx.Internal; using ControlzEx.Native; using global::Windows.Win32; public class NonClientControlManager { private DependencyObject? trackedControl; public NonClientControlManager(Window window) { this.Owner = window ?? throw new ArgumentNullException(nameof(window)); this.OwnerHandle = new WindowInteropHelper(this.Owner).Handle; } private Window Owner { get; } private IntPtr OwnerHandle { get; } public void ClearTrackedControl() { if (this.trackedControl is null) { return; } NonClientControlProperties.SetIsNCMouseOver(this.trackedControl, false); NonClientControlProperties.SetIsNCPressed(this.trackedControl, false); this.trackedControl = null; } public bool HoverTrackedControl(IntPtr lParam) { var controlUnderMouse = this.GetControlUnderMouse(lParam); if (controlUnderMouse == this.trackedControl) { return true; } if (this.trackedControl is not null) { NonClientControlProperties.SetIsNCMouseOver(this.trackedControl, false); NonClientControlProperties.SetIsNCPressed(this.trackedControl, false); } this.trackedControl = controlUnderMouse; if (this.trackedControl is not null) { NonClientControlProperties.SetIsNCMouseOver(this.trackedControl, true); } return true; } public bool PressTrackedControl(IntPtr lParam) { var controlUnderMouse = this.GetControlUnderMouse(lParam); if (controlUnderMouse != this.trackedControl) { this.HoverTrackedControl(lParam); } if (this.trackedControl is null) { return false; } NonClientControlProperties.SetIsNCPressed(this.trackedControl, true); var nonClientControlClickStrategy = NonClientControlProperties.GetClickStrategy(this.trackedControl); if (nonClientControlClickStrategy is NonClientControlClickStrategy.MouseEvent) { // Raising LBUTTONDOWN here automatically causes a LBUTTONUP to be raised by windows later correctly PInvoke.RaiseMouseMessage(this.OwnerHandle, WM.LBUTTONDOWN, default, lParam); return true; } return nonClientControlClickStrategy != NonClientControlClickStrategy.None; } public bool ClickTrackedControl(IntPtr lParam) { var controlUnderMouse = this.GetControlUnderMouse(lParam); if (controlUnderMouse != this.trackedControl) { return false; } if (this.trackedControl is null) { return false; } if (NonClientControlProperties.GetIsNCPressed(this.trackedControl) == false) { return false; } NonClientControlProperties.SetIsNCPressed(this.trackedControl, false); if (NonClientControlProperties.GetClickStrategy(this.trackedControl) is NonClientControlClickStrategy.AutomationPeer && this.trackedControl is UIElement uiElement && UIElementAutomationPeer.CreatePeerForElement(uiElement).GetPattern(PatternInterface.Invoke) is IInvokeProvider invokeProvider) { invokeProvider.Invoke(); } return false; } public DependencyObject? GetControlUnderMouse(IntPtr lParam) { return GetControlUnderMouse(this.Owner, lParam); } public static DependencyObject? GetControlUnderMouse(Window owner, IntPtr lParam) { return GetControlUnderMouse(owner, lParam, out _); } public static DependencyObject? GetControlUnderMouse(Window owner, IntPtr lParam, out HT hitTestResult) { if (lParam == IntPtr.Zero) { hitTestResult = HT.NOWHERE; return null; } var point = LogicalPointFromLParam(owner, lParam); if (owner.InputHitTest(point) is Visual visualHit && NonClientControlProperties.GetHitTestResult(visualHit) is var res && res != HT.NOWHERE) { hitTestResult = res; // If the cursor is on the window edge we must not hit test controls. // Otherwise we have no chance to un-track controls when the cursor leaves the window. // todo: find a better solution as this does not completely solve the problem when the mouse is moved over the buttons fast and then leaves the window... if (hitTestResult is HT.MAXBUTTON or HT.MINBUTTON or HT.CLOSE) { if (point.X.AreClose(0) || point.X.AreClose(owner.Width) || point.Y.AreClose(0) || point.Y.AreClose(owner.Height)) { hitTestResult = HT.NOWHERE; return null; } } DependencyObject control = visualHit; var currentControl = control; while (currentControl is not null) { var valueSource = DependencyPropertyHelper.GetValueSource(currentControl, NonClientControlProperties.HitTestResultProperty); if (valueSource.BaseValueSource is not BaseValueSource.Inherited and not BaseValueSource.Unknown) { control = currentControl; break; } currentControl = GetVisualOrLogicalParent(currentControl); } return control; } hitTestResult = HT.NOWHERE; return null; static Point LogicalPointFromLParam(Window owner, IntPtr lParam) { var point2 = Utility.GetPoint(lParam); return owner.PointFromScreen(point2); } } private static DependencyObject? GetVisualOrLogicalParent(DependencyObject? sourceElement) { return sourceElement switch { null => null, Visual => VisualTreeHelper.GetParent(sourceElement) ?? LogicalTreeHelper.GetParent(sourceElement), _ => LogicalTreeHelper.GetParent(sourceElement) }; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Management.Automation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Extensions; using Microsoft.PowerShell.EditorServices.VSCode.CustomViews; using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace Microsoft.PowerShell.EditorServices.VSCode { /// [Cmdlet(VerbsCommon.New,"VSCodeHtmlContentView")] [OutputType(typeof(IHtmlContentView))] public class NewVSCodeHtmlContentViewCommand : PSCmdlet { private HtmlContentViewsFeature _htmlContentViewsFeature; private ViewColumn? _showInColumn; /// [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] public string Title { get; set; } /// [Parameter(Position = 1)] public ViewColumn ShowInColumn { get => _showInColumn.GetValueOrDefault(); set => _showInColumn = value; } /// protected override void BeginProcessing() { if (_htmlContentViewsFeature == null) { if (GetVariableValue("psEditor") is EditorObject psEditor) { _htmlContentViewsFeature = new HtmlContentViewsFeature( psEditor.GetExtensionServiceProvider().LanguageServer); } else { ThrowTerminatingError( new ErrorRecord( new ItemNotFoundException("Cannot find the '$psEditor' variable."), "PSEditorNotFound", ErrorCategory.ObjectNotFound, targetObject: null)); return; } } IHtmlContentView view = _htmlContentViewsFeature.CreateHtmlContentViewAsync(Title) .GetAwaiter() .GetResult(); if (_showInColumn != null) { try { view.Show(_showInColumn.Value).GetAwaiter().GetResult(); } catch (Exception e) { WriteError( new ErrorRecord( e, "HtmlContentViewCouldNotShow", ErrorCategory.OpenError, targetObject: null)); return; } } WriteObject(view); } } /// [Cmdlet(VerbsCommon.Set,"VSCodeHtmlContentView")] public class SetVSCodeHtmlContentViewCommand : PSCmdlet { /// [Parameter(Mandatory = true, Position = 0)] [Alias("View")] [ValidateNotNull] public IHtmlContentView HtmlContentView { get; set; } /// [Parameter(Mandatory = true, Position = 1)] [Alias("Content")] [AllowEmptyString] public string HtmlBodyContent { get; set; } /// [Parameter(Position = 2)] public string[] JavaScriptPaths { get; set; } /// [Parameter(Position = 3)] public string[] StyleSheetPaths { get; set; } /// protected override void BeginProcessing() { var htmlContent = new HtmlContent(); htmlContent.BodyContent = HtmlBodyContent; htmlContent.JavaScriptPaths = JavaScriptPaths; htmlContent.StyleSheetPaths = StyleSheetPaths; try { HtmlContentView.SetContentAsync(htmlContent).GetAwaiter().GetResult(); } catch (Exception e) { WriteError( new ErrorRecord( e, "HtmlContentViewCouldNotSet", ErrorCategory.WriteError, targetObject: null)); } } } /// [Cmdlet(VerbsCommon.Close,"VSCodeHtmlContentView")] public class CloseVSCodeHtmlContentViewCommand : PSCmdlet { /// [Parameter(Mandatory = true, Position = 0)] [Alias("View")] [ValidateNotNull] public IHtmlContentView HtmlContentView { get; set; } /// protected override void BeginProcessing() { try { HtmlContentView.Close().GetAwaiter().GetResult(); } catch (Exception e) { WriteError( new ErrorRecord( e, "HtmlContentViewCouldNotClose", ErrorCategory.CloseError, targetObject: null)); } } } /// [Cmdlet(VerbsCommon.Show,"VSCodeHtmlContentView")] public class ShowVSCodeHtmlContentViewCommand : PSCmdlet { /// [Parameter(Mandatory = true, Position = 0)] [Alias("View")] [ValidateNotNull] public IHtmlContentView HtmlContentView { get; set; } /// [Parameter(Position = 1)] [Alias("Column")] [ValidateNotNull] public ViewColumn ViewColumn { get; set; } = ViewColumn.One; /// protected override void BeginProcessing() { try { HtmlContentView.Show(ViewColumn).GetAwaiter().GetResult(); } catch (Exception e) { WriteError( new ErrorRecord( e, "HtmlContentViewCouldNotShow", ErrorCategory.OpenError, targetObject: null)); } } } /// [Cmdlet(VerbsCommunications.Write,"VSCodeHtmlContentView")] public class WriteVSCodeHtmlContentViewCommand : PSCmdlet { /// [Parameter(Mandatory = true, Position = 0)] [Alias("View")] [ValidateNotNull] public IHtmlContentView HtmlContentView { get; set; } /// [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 1)] [Alias("Content")] [ValidateNotNull] public string AppendedHtmlBodyContent { get; set; } /// protected override void ProcessRecord() { try { HtmlContentView.AppendContentAsync(AppendedHtmlBodyContent).GetAwaiter().GetResult(); } catch (Exception e) { WriteError( new ErrorRecord( e, "HtmlContentViewCouldNotWrite", ErrorCategory.WriteError, targetObject: null)); } } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923121")] [WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationServiceFactory.Service); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923196")] [WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [WpfFact] public async Task TestPreviewDiagnosticTagger() { using (var workspace = await TestWorkspace.CreateCSharpAsync("class { }")) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { //// preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); //// enable preview diagnostics previewWorkspace.EnableDiagnostic(); var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpans(workspace); const string AnalzyerCount = "Analyzer Count: "; Assert.Equal(AnalzyerCount + 1, AnalzyerCount + diagnosticsAndErrorsSpans.Item1.Length); const string SquigglesCount = "Squiggles Count: "; Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Count); } } [WpfFact] public async Task TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = await TestWorkspace.CreateCSharpAsync("class { }")) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view WpfTestCase.RequireWpfFact($"{nameof(TestPreviewDiagnosticTaggerInPreviewPane)} creates a {nameof(DifferenceViewerPreview)}"); var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); using (var diffView = (DifferenceViewerPreview)(await previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None))) { var foregroundService = workspace.GetService<IForegroundNotificationService>(); var waiter = new ErrorSquiggleWaiter(); var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter); // set up tagger for both buffers var leftBuffer = diffView.Viewer.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftProvider = new DiagnosticsSquiggleTaggerProvider(diagnosticService, foregroundService, listeners); var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer); using (var leftDisposable = leftTagger as IDisposable) { var rightBuffer = diffView.Viewer.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightProvider = new DiagnosticsSquiggleTaggerProvider(diagnosticService, foregroundService, listeners); var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer); using (var rightDisposable = rightTagger as IDisposable) { // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers await waiter.CreateWaitTask(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(0, rightSpans.Count); } } } } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
// // Catalog.cs // // Author: // Aaron Bockover <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright 2012 Rdio, Inc. // Copyright 2012 S. Delcroix // // 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.Text; using System.Collections.Generic; using System.Globalization; namespace Vernacular { public abstract class Catalog { private sealed class DefaultCatalog : Catalog { public override string CoreGetString (string message) { return message; } public override string CoreGetPluralString (string singularMessage, string pluralMessage, int n) { return n == 1 ? singularMessage : pluralMessage; } public override string CoreGetGenderString (LanguageGender gender, string masculineMessage, string feminineMessage) { return gender == LanguageGender.Feminine ? feminineMessage : masculineMessage; } public override string CoreGetPluralGenderString (LanguageGender gender, string singularMasculineMessage, string pluralMasculineMessage, string singularFeminineMessage, string pluralFeminineMessage, int n) { return gender == LanguageGender.Feminine ? (n == 1 ? singularFeminineMessage : pluralFeminineMessage) : (n == 1 ? singularMasculineMessage : pluralMasculineMessage); } } private static Catalog default_implementation; public static Catalog DefaultImplementation { get { return default_implementation ?? (default_implementation = new DefaultCatalog ()); } } private static Catalog active_implementation; public static Catalog Implementation { get { return active_implementation ?? DefaultImplementation; } set { active_implementation = value; } } private string current_iso_language_code; /// <summary> /// The current 2-letters ISO language code. <seealso cref="http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes"/> /// </summary> public virtual string CurrentIsoLanguageCode { get { return current_iso_language_code ?? CultureInfo.CurrentCulture.TwoLetterISOLanguageName; } set { current_iso_language_code = value; } } #region Implementation Abstract Methods /// <summary> /// When overridden in a derived class, gets the localized version of <param name="message"/>. /// </summary> /// <param name="message">The original message</param> /// <returns>The localized message</returns> public abstract string CoreGetString (string message); /// <summary> /// When overridden in a derived class, gets the localized singular or plural message, depending on n /// </summary> /// <param name="singularMessage">The singular message</param> /// <param name="pluralMessage">The plural message</param> /// <param name="n">The plural count</param> /// <returns>The localized and pluralized message</returns> public abstract string CoreGetPluralString (string singularMessage, string pluralMessage, int n); public abstract string CoreGetGenderString (LanguageGender gender, string masculineMessage, string feminineMessage); public abstract string CoreGetPluralGenderString (LanguageGender gender, string singularMasculineMessage, string pluralMasculineMessage, string singularFeminineMessage, string pluralFeminineMessage, int n); #endregion public Func<string, string> MessageFilter { get; set; } protected virtual string CoreFilter (string message) { return MessageFilter == null ? message : MessageFilter (message); } #region Public GetString Methods /// <summary> /// Return the localized translation of message, based on the current <see cref="Implementation">Catalog Implementation</see> /// and <see cref="CurrentIsoLanguageCode">ISO language code</see>>. /// </summary> /// <param name="message">The message to be localized</param> /// <param name="comment">Developer's comment, only visible by translators</param> /// <param name="implementation">Optionally provide a catalog implementation valid for this code only </param> /// <returns></returns> public static string GetString (string message, string comment = null) { return Implementation.CoreGetString (message); } public static string GetString (string message, Catalog implementation) { if (implementation == null) throw new ArgumentNullException("implementation"); return implementation.CoreGetString (message); } public static string GetString (string message, string comment, Catalog implementation) { if (implementation == null) throw new ArgumentNullException("implementation"); return implementation.CoreGetString (message); } /// <summary> /// Like <see cref="GetString(string, string)"/>, but consider plural forms. If a translation is found, apply the plural /// formula to <param name="n"/>, and return the resulting message (some languages have more than two plural forms). /// If no translation is found, return <param name="singularMessage"/> if <param name="n"> is 1; return <param name="pluralMessage"> otherwise. /// /// The Plural formula is computed from the <see cref="CurrentIsoLanguageCode"/> /// </summary> /// <param name="singularMessage">The singular message</param> /// <param name="pluralMessage">The plural message</param> /// <param name="n">The plural count</param> /// <param name="comment">Developer's comment, only visible by translators</param> /// <param name="implementation">Optionally provide a catalog implementation valid for this code only </param> /// <returns>The localized message, pluralized if required</returns> public static string GetPluralString (string singularMessage, string pluralMessage, int n, string comment = null) { return Implementation.CoreGetPluralString (singularMessage, pluralMessage, n); } public static string GetPluralString (string singularMessage, string pluralMessage, int n, Catalog implementation) { if (implementation == null) throw new ArgumentNullException("implementation"); return implementation.CoreGetPluralString (singularMessage, pluralMessage, n); } public static string GetPluralString (string singularMessage, string pluralMessage, int n, string comment, Catalog implementation) { if (implementation==null) throw new ArgumentNullException("implementation"); return implementation.CoreGetPluralString (singularMessage, pluralMessage, n); } public static string GetGenderString (LanguageGender gender, string masculineMessage, string feminineMessage, string comment = null) { return Implementation.CoreGetGenderString (gender, masculineMessage, feminineMessage); } public static string GetGenderString (LanguageGender gender, string message, string comment = null) { return Implementation.CoreGetGenderString (gender, message, message); } public static string GetPluralGenderString (LanguageGender gender, string singularMasculineMessage, string pluralMasculineMessage, string singularFeminineMessage, string pluralFeminineMessage, int n, string comment = null) { return Implementation.CoreGetPluralGenderString (gender, singularMasculineMessage, pluralMasculineMessage, singularFeminineMessage, pluralFeminineMessage, n); } public static string GetPluralGenderString (LanguageGender gender, string singularMessage, string pluralMessage, int n, string comment = null) { return Implementation.CoreGetPluralGenderString (gender, singularMessage, pluralMessage, singularMessage, pluralMessage, n); } public static string GetGenderString (ILanguageGenderProvider provider, string masculineMessage, string feminineMessage, string comment = null) { return Implementation.CoreGetGenderString (provider.LanguageGender, masculineMessage, feminineMessage); } public static string GetGenderString (ILanguageGenderProvider provider, string message, string comment = null) { return Implementation.CoreGetGenderString (provider.LanguageGender, message, message); } public static string GetPluralGenderString (ILanguageGenderProvider provider, string singularMasculineMessage, string pluralMasculineMessage, string singularFeminineMessage, string pluralFeminineMessage, int n, string comment = null) { return Implementation.CoreGetPluralGenderString (provider.LanguageGender, singularMasculineMessage, pluralMasculineMessage, singularFeminineMessage, pluralFeminineMessage, n); } public static string GetPluralGenderString (ILanguageGenderProvider provider, string singularMessage, string pluralMessage, int n, string comment = null) { return Implementation.CoreGetPluralGenderString (provider.LanguageGender, singularMessage, pluralMessage, singularMessage, pluralMessage, n); } #endregion #region Utilities /// <summary> /// An error handler for the FormatExceptions caught by Catalog.Format on translated strings. /// It is recommended that you log those and reports the issue to the translator. /// </summary> public static Action<Exception, string> ErrorHandler; public static string Format (string format, params object [] args) { try { return String.Format (format, args); } catch (FormatException e) { if (ErrorHandler != null) { ErrorHandler (e, "Vernacular.Catalog.Format: invalid format string"); } return format; } } public static string GetResourceId (ResourceIdType resourceIdType, string context, string message, LanguageGender gender, int pluralOrder) { if (message == null) { throw new ArgumentNullException ("message"); } var builder = new StringBuilder ("Vernacular_P"); if (!String.IsNullOrEmpty (context)) { message = context + "__" + message; } builder.Append (pluralOrder); builder.Append ('_'); if (gender != LanguageGender.Neutral) { builder.Append (gender == LanguageGender.Masculine ? "M_" : "F_"); } switch (resourceIdType) { case ResourceIdType.ComprehensibleIdentifier: break; case ResourceIdType.Base64: message = Convert.ToBase64String (Encoding.UTF8.GetBytes (message)); break; default: throw new Exception ("Unknown ResourceIdType"); } foreach (var c in message) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') { builder.Append (c); } else if (c != ' ') { builder.Append ((int)c); } } return builder.ToString (); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Application.Threading; using JetBrains.Collections; using JetBrains.Diagnostics; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements.Prefabs; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.References; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetInspectorValues.Deserializers; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetInspectorValues.Values; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.Utils; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Search; using JetBrains.ReSharper.Plugins.Yaml.Psi; using JetBrains.ReSharper.Psi; using JetBrains.Util; using JetBrains.Util.Collections; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetInspectorValues { [SolutionComponent] public class AssetInspectorValuesContainer : IUnityAssetDataElementContainer { private readonly IShellLocks myShellLocks; private readonly AssetDocumentHierarchyElementContainer myHierarchyElementContainer; private readonly ILogger myLogger; private readonly List<IAssetInspectorValueDeserializer> myDeserializers; private readonly Dictionary<IPsiSourceFile, IUnityAssetDataElementPointer> myPointers = new Dictionary<IPsiSourceFile, IUnityAssetDataElementPointer>(); private readonly OneToCompactCountingSet<MonoBehaviourField, int> myUniqueValuesCount = new OneToCompactCountingSet<MonoBehaviourField, int>(); private readonly OneToCompactCountingSet<MonoBehaviourField, IPsiSourceFile> myChangesInFiles = new OneToCompactCountingSet<MonoBehaviourField, IPsiSourceFile>(); private readonly OneToCompactCountingSet<MonoBehaviourField, int> myValueCountPerPropertyAndFile = new OneToCompactCountingSet<MonoBehaviourField, int>(); private readonly CountingSet<MonoBehaviourFieldWithValue> myValuesWhichAreUniqueInWholeFile = new CountingSet<MonoBehaviourFieldWithValue>(); // cached value for fast presentation private readonly OneToSetMap<MonoBehaviourField, IAssetValue> myUniqueValuesInstances = new OneToSetMap<MonoBehaviourField, IAssetValue>(); // For estimated counter (it's hard to track real counter due to chain resolve, prefab modifications points to another file, another file could point to another file and so on) // Also, it is possible that field name are used in script components with different guids. If there is only `1 guid, we could resolve type element and check that field belongs to that type element. // but if there are a lot of guids, we could not resolve each type element due to performance reason, several guids could be accepted, because field could belong to abstract class private readonly OneToCompactCountingSet<int, Guid> myNameHashToGuids = new OneToCompactCountingSet<int, Guid>(); private readonly CountingSet<string> myNamesInPrefabModifications = new CountingSet<string>(); // find usage scope private readonly OneToCompactCountingSet<string, IPsiSourceFile> myNameToSourceFile = new OneToCompactCountingSet<string, IPsiSourceFile>(); public AssetInspectorValuesContainer(IShellLocks shellLocks, AssetDocumentHierarchyElementContainer hierarchyElementContainer, IEnumerable<IAssetInspectorValueDeserializer> assetInspectorValueDeserializer, ILogger logger) { myShellLocks = shellLocks; myHierarchyElementContainer = hierarchyElementContainer; myLogger = logger; myDeserializers = assetInspectorValueDeserializer.OrderByDescending(t => t.Order).ToList(); } public IUnityAssetDataElement CreateDataElement(IPsiSourceFile sourceFile) { return new AssetInspectorValuesDataElement(); } public bool IsApplicable(IPsiSourceFile currentAssetSourceFile) { return true; } public object Build(IPsiSourceFile currentAssetSourceFile, AssetDocument assetDocument) { var modifications = ProcessPrefabModifications(currentAssetSourceFile, assetDocument); if (AssetUtils.IsMonoBehaviourDocument(assetDocument.Buffer)) { var anchor = AssetUtils.GetAnchorFromBuffer(assetDocument.Buffer); if (!anchor.HasValue) return new InspectorValuesBuildResult(new LocalList<InspectorVariableUsage>(), modifications); var dictionary = new Dictionary<string, IAssetValue>(); var entries = assetDocument.Document.GetUnityObjectProperties()?.Entries; if (entries == null) return new InspectorValuesBuildResult(new LocalList<InspectorVariableUsage>(), modifications); foreach (var entry in entries) { var key = entry.Key.GetPlainScalarText(); if (key == null || ourIgnoredMonoBehaviourEntries.Contains(key)) continue; foreach (var deserializer in myDeserializers) { try { if (deserializer.TryGetInspectorValue(currentAssetSourceFile, entry.Content, out var resultValue)) { dictionary[key] = resultValue; break; } } catch (Exception e) { myLogger.Error(e, "An error occurred while deserializing value {0}", deserializer.GetType().Name); } } } if (dictionary.TryGetValue(UnityYamlConstants.ScriptProperty, out var scriptValue) && scriptValue is AssetReferenceValue referenceValue && referenceValue.Reference is ExternalReference script) { var location = new LocalReference(currentAssetSourceFile.PsiStorage.PersistentIndex.NotNull("owningPsiPersistentIndex != null"), anchor.Value); var result = new LocalList<InspectorVariableUsage>(); foreach (var (key, value) in dictionary) { if (key.Equals(UnityYamlConstants.ScriptProperty) || key.Equals(UnityYamlConstants.GameObjectProperty)) continue; result.Add(new InspectorVariableUsage(location, script, key, value)); } return new InspectorValuesBuildResult(result, modifications); } } return new InspectorValuesBuildResult(new LocalList<InspectorVariableUsage>(), modifications); } private ImportedInspectorValues ProcessPrefabModifications(IPsiSourceFile currentSourceFile, AssetDocument assetDocument) { var result = new ImportedInspectorValues(); if (assetDocument.HierarchyElement is IPrefabInstanceHierarchy prefabInstanceHierarchy) { foreach (var modification in prefabInstanceHierarchy.PrefabModifications) { if (!(modification.Target is ExternalReference externalReference)) continue; if (modification.PropertyPath.Contains(".")) continue; var location = new LocalReference(currentSourceFile.PsiStorage.PersistentIndex.NotNull("owningPsiPersistentIndex != null"), PrefabsUtil.GetImportedDocumentAnchor(prefabInstanceHierarchy.Location.LocalDocumentAnchor, externalReference.LocalDocumentAnchor)); result.Modifications[new ImportedValueReference(location, modification.PropertyPath)] = (modification.Value, new AssetReferenceValue(modification.ObjectReference)); } } return result; } public void Drop(IPsiSourceFile currentAssetSourceFile, AssetDocumentHierarchyElement assetDocumentHierarchyElement, IUnityAssetDataElement unityAssetDataElement) { var element = unityAssetDataElement as AssetInspectorValuesDataElement; var usages = element.VariableUsages; // inverted order is matter for Remove/AddUniqueValue for (int i = usages.Count - 1; i >= 0; i--) { var variableUsage = usages[i]; var scriptReference = variableUsage.ScriptReference; var guid = scriptReference.ExternalAssetGuid; myNameToSourceFile.Remove(variableUsage.Name, currentAssetSourceFile); var mbField = new MonoBehaviourField(guid, variableUsage.Name.GetPlatformIndependentHashCode()); RemoveUniqueValue(mbField, variableUsage); myChangesInFiles.Remove(mbField, currentAssetSourceFile); RemoveChangesPerFile(new MonoBehaviourField(guid, variableUsage.Name.GetPlatformIndependentHashCode(), currentAssetSourceFile), variableUsage); myNameHashToGuids.Remove(variableUsage.Name.GetPlatformIndependentHashCode(), scriptReference.ExternalAssetGuid); } foreach (var (reference, _) in element.ImportedInspectorValues.Modifications) { myNamesInPrefabModifications.Remove(reference.Name); } myPointers.Remove(currentAssetSourceFile); } private void RemoveChangesPerFile(MonoBehaviourField monoBehaviourField, InspectorVariableUsage variableUsage) { var beforeRemoveDifferentValuesCount = myValueCountPerPropertyAndFile.GetOrEmpty(monoBehaviourField).Count; myValueCountPerPropertyAndFile.Remove(monoBehaviourField, variableUsage.Value.GetHashCode()); var afterRemoveDifferentValuesCount = myValueCountPerPropertyAndFile.GetOrEmpty(monoBehaviourField).Count; if (beforeRemoveDifferentValuesCount == 2 && afterRemoveDifferentValuesCount == 1) { var uniqueValue = myValueCountPerPropertyAndFile.GetOrEmpty(monoBehaviourField).First().Key; var fieldWithValue = new MonoBehaviourFieldWithValue(new MonoBehaviourField(monoBehaviourField.ScriptGuid, monoBehaviourField.NameHash), uniqueValue); myValuesWhichAreUniqueInWholeFile.Add(fieldWithValue); } else if (beforeRemoveDifferentValuesCount == 1 && afterRemoveDifferentValuesCount == 0) { var fieldWithValue = new MonoBehaviourFieldWithValue(new MonoBehaviourField(monoBehaviourField.ScriptGuid, monoBehaviourField.NameHash), variableUsage.Value.GetHashCode()); myValuesWhichAreUniqueInWholeFile.Remove(fieldWithValue); } } private void RemoveUniqueValue(MonoBehaviourField mbField, InspectorVariableUsage variableUsage) { var valueHash = variableUsage.Value.GetHashCode(); var previousCount = myUniqueValuesCount.GetOrEmpty(mbField).Count; myUniqueValuesCount.Remove(mbField, valueHash); var newCount = myUniqueValuesCount.GetOrEmpty(mbField).Count; if (newCount < 2 && newCount != previousCount) { var isRemoved = myUniqueValuesInstances.Remove(mbField, variableUsage.Value); Assertion.Assert(isRemoved, "value should be presented"); } } public void Merge(IPsiSourceFile currentAssetSourceFile, AssetDocumentHierarchyElement assetDocumentHierarchyElement, IUnityAssetDataElementPointer unityAssetDataElementPointer, IUnityAssetDataElement unityAssetDataElement) { myPointers[currentAssetSourceFile] = unityAssetDataElementPointer; var element = unityAssetDataElement as AssetInspectorValuesDataElement; foreach (var variableUsage in element.VariableUsages) { var scriptReference = variableUsage.ScriptReference; var guid = scriptReference.ExternalAssetGuid; myNameToSourceFile.Add(variableUsage.Name, currentAssetSourceFile); var mbField = new MonoBehaviourField(guid, variableUsage.Name.GetPlatformIndependentHashCode()); AddUniqueValue(mbField, variableUsage); myChangesInFiles.Add(mbField, currentAssetSourceFile); AddChangesPerFile(new MonoBehaviourField(guid, variableUsage.Name.GetPlatformIndependentHashCode(), currentAssetSourceFile), variableUsage); myNameHashToGuids.Add(variableUsage.Name.GetPlatformIndependentHashCode(), scriptReference.ExternalAssetGuid); } foreach (var (reference, _) in element.ImportedInspectorValues.Modifications) { myNamesInPrefabModifications.Add(reference.Name); myNameToSourceFile.Add(reference.Name, currentAssetSourceFile); } } private void AddChangesPerFile(MonoBehaviourField monoBehaviourField, InspectorVariableUsage variableUsage) { var beforeAddDifferentValuesCount = myValueCountPerPropertyAndFile.GetOrEmpty(monoBehaviourField).Count; if (beforeAddDifferentValuesCount == 0) { myValueCountPerPropertyAndFile.Add(monoBehaviourField, variableUsage.Value.GetHashCode()); var fieldWithValue = new MonoBehaviourFieldWithValue(new MonoBehaviourField(monoBehaviourField.ScriptGuid, monoBehaviourField.NameHash), variableUsage.Value.GetHashCode()); myValuesWhichAreUniqueInWholeFile.Add(fieldWithValue); } else if (beforeAddDifferentValuesCount == 1) { var previousValue = myValueCountPerPropertyAndFile.GetOrEmpty(monoBehaviourField).First().Key; myValueCountPerPropertyAndFile.Add(monoBehaviourField, variableUsage.Value.GetHashCode()); var afterAddDifferentValuesCount = myValueCountPerPropertyAndFile.GetOrEmpty(monoBehaviourField).Count; if (afterAddDifferentValuesCount == 2) { var fieldWithValue = new MonoBehaviourFieldWithValue(new MonoBehaviourField(monoBehaviourField.ScriptGuid, monoBehaviourField.NameHash), previousValue); myValuesWhichAreUniqueInWholeFile.Remove(fieldWithValue); } } else { myValueCountPerPropertyAndFile.Add(monoBehaviourField, variableUsage.Value.GetHashCode()); } } private void AddUniqueValue(MonoBehaviourField field, InspectorVariableUsage variableUsage) { var uniqueValuePtr = variableUsage.Value.GetHashCode(); var previousCount = myUniqueValuesCount.GetOrEmpty(field).Count; myUniqueValuesCount.Add(field, uniqueValuePtr); var newCount = myUniqueValuesCount.GetOrEmpty(field).Count; if (previousCount < 2 && newCount != previousCount) { var isAdded = myUniqueValuesInstances.Add(field, variableUsage.Value); Assertion.Assert(isAdded, "value should not be presented"); } } public int GetValueCount(Guid guid, IEnumerable<string> possibleNames, IAssetValue assetValue) { myShellLocks.AssertReadAccessAllowed(); var count = 0; foreach (var name in possibleNames) { var mbField = new MonoBehaviourField(guid, name.GetPlatformIndependentHashCode()); count += myUniqueValuesCount.GetCount(mbField, assetValue.GetHashCode()); } return count; } public int GetUniqueValuesCount(Guid guid, IEnumerable<string> possibleNames) { myShellLocks.AssertReadAccessAllowed(); var count = 0; foreach (var name in possibleNames) { var mbField = new MonoBehaviourField(guid, name.GetPlatformIndependentHashCode()); count += myUniqueValuesCount.GetOrEmpty(mbField).Count; } return count; } public bool IsIndexResultEstimated(Guid ownerGuid, ITypeElement containingType, IEnumerable<string> possibleNames) { myShellLocks.AssertReadAccessAllowed(); var names = possibleNames.ToArray(); foreach (var name in names) { if (myNamesInPrefabModifications.GetCount(name) > 0) return true; } return AssetUtils.HasPossibleDerivedTypesWithMember(ownerGuid, containingType, names, myNameHashToGuids); } public IAssetValue GetUniqueValueDifferTo(Guid guid, IEnumerable<string> possibleNames, IAssetValue assetValue) { myShellLocks.AssertReadAccessAllowed(); var result = new List<IAssetValue>(); foreach (var possibleName in possibleNames) { var mbField = new MonoBehaviourField(guid, possibleName.GetPlatformIndependentHashCode()); foreach (var value in myUniqueValuesInstances.GetValuesSafe(mbField)) { result.Add(value); } } Assertion.Assert(result.Count <= 2, "result.Count <= 2"); if (assetValue == null) return result.First(); return result.First(t => !t.Equals(assetValue)); } public int GetAffectedFiles(Guid guid, IEnumerable<string> possibleNames) { myShellLocks.AssertReadAccessAllowed(); var result = 0; foreach (var possibleName in possibleNames) { result += myChangesInFiles.GetOrEmpty(new MonoBehaviourField(guid, possibleName.GetPlatformIndependentHashCode())).Count; } return result; } public int GetAffectedFilesWithSpecificValue(Guid guid, IEnumerable<string> possibleNames, IAssetValue value) { myShellLocks.AssertReadAccessAllowed(); var result = 0; foreach (var possibleName in possibleNames) { result += myValuesWhichAreUniqueInWholeFile.GetCount(new MonoBehaviourFieldWithValue(new MonoBehaviourField(guid, possibleName.GetPlatformIndependentHashCode()), value.GetHashCode())); } return result; } private static readonly HashSet<string> ourIgnoredMonoBehaviourEntries = new HashSet<string>() { "serializedVersion", "m_ObjectHideFlags", "m_CorrespondingSourceObject", "m_PrefabInstance", "m_PrefabAsset", "m_Enabled", "m_EditorHideFlags", "m_EditorClassIdentifier" }; public string Id => nameof(AssetInspectorValuesContainer); public int Order => 0; public void Invalidate() { myUniqueValuesCount.Clear(); myChangesInFiles.Clear(); myValuesWhichAreUniqueInWholeFile.Clear(); myValueCountPerPropertyAndFile.Clear(); myPointers.Clear(); } private class MonoBehaviourField { public readonly Guid ScriptGuid; public readonly int NameHash; public readonly IPsiSourceFile AssetSourceFile; public MonoBehaviourField(Guid scriptGuid, int nameHash, IPsiSourceFile assetSourceFile = null) { ScriptGuid = scriptGuid; NameHash = nameHash; AssetSourceFile = assetSourceFile; } public bool Equals(MonoBehaviourField other) { return ScriptGuid == other.ScriptGuid && NameHash == other.NameHash && Equals(AssetSourceFile, other.AssetSourceFile); } public override bool Equals(object obj) { return obj is MonoBehaviourField other && Equals(other); } public override int GetHashCode() { unchecked { var hashCode = ScriptGuid.GetHashCode(); hashCode = (hashCode * 397) ^ NameHash.GetHashCode(); hashCode = (hashCode * 397) ^ (AssetSourceFile != null ? AssetSourceFile.GetHashCode() : 0); return hashCode; } } } private class MonoBehaviourFieldWithValue { private readonly MonoBehaviourField myField; private readonly int myValueHash; public MonoBehaviourFieldWithValue(MonoBehaviourField field, int valueHash) { myField = field; myValueHash = valueHash; } protected bool Equals(MonoBehaviourFieldWithValue other) { return Equals(myField, other.myField) && Equals(myValueHash, other.myValueHash); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((MonoBehaviourFieldWithValue) obj); } public override int GetHashCode() { unchecked { return ((myField != null ? myField.GetHashCode() : 0) * 397) ^ (myValueHash.GetHashCode()); } } } public IEnumerable<UnityInspectorFindResult> GetAssetUsagesFor(IPsiSourceFile sourceFile, IField element) { myShellLocks.AssertReadAccessAllowed(); var containingType = element?.GetContainingType(); if (containingType == null) yield break; var names = AssetUtils.GetAllNamesFor(element).ToJetHashSet(); foreach (var (usage, isPrefabModification) in GetUsages(sourceFile)) { if (!names.Contains(usage.Name)) continue; var scriptReference = usage.ScriptReference; var guid = scriptReference.ExternalAssetGuid; var typeElement = AssetUtils.GetTypeElementFromScriptAssetGuid(element.GetSolution(), guid); if (typeElement == null || !typeElement.IsDescendantOf(containingType)) continue; yield return new UnityInspectorFindResult(sourceFile, element, usage, usage.Location, isPrefabModification); } } private IEnumerable<(InspectorVariableUsage usage, bool isPrefabModification)> GetUsages(IPsiSourceFile sourceFile) { var dataElement = myPointers.GetValueSafe(sourceFile)?.GetElement(sourceFile, Id) as AssetInspectorValuesDataElement; if (dataElement == null) yield break; foreach (var usage in dataElement.VariableUsages) yield return (usage, false); foreach (var (reference, modification) in dataElement.ImportedInspectorValues.Modifications) { var hierearchyElement = myHierarchyElementContainer.GetHierarchyElement(reference.LocalReference, true); Assertion.Assert(hierearchyElement != null, "hierearchyElement != null"); if (!(hierearchyElement is IScriptComponentHierarchy scriptElement)) continue; yield return (new InspectorVariableUsage(reference.LocalReference, scriptElement.ScriptReference, reference.Name, modification.value ?? modification.objectReference), true); } } public LocalList<IPsiSourceFile> GetPossibleFilesWithUsage(IField element) { var result = new LocalList<IPsiSourceFile>(); foreach (var name in AssetUtils.GetAllNamesFor(element)) { foreach (var sourceFile in myNameToSourceFile.GetValues(name)) { result.Add(sourceFile); } } return result; } } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * 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; namespace Aerospike.Client { public sealed class BatchNode { public static List<BatchNode> GenerateList(Cluster cluster, BatchPolicy policy, Key[] keys) { Node[] nodes = cluster.Nodes; if (nodes.Length == 0) { throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Command failed because cluster is empty."); } // Create initial key capacity for each node as average + 25%. int keysPerNode = keys.Length / nodes.Length; keysPerNode += (int)((uint)keysPerNode >> 2); // The minimum key capacity is 10. if (keysPerNode < 10) { keysPerNode = 10; } // Split keys by server node. List<BatchNode> batchNodes = new List<BatchNode>(nodes.Length); for (int i = 0; i < keys.Length; i++) { Partition partition = new Partition(keys[i]); Node node = cluster.GetReadNode(partition, policy.replica); BatchNode batchNode = FindBatchNode(batchNodes, node); if (batchNode == null) { batchNodes.Add(new BatchNode(node, keysPerNode, i)); } else { batchNode.AddKey(i); } } return batchNodes; } public static List<BatchNode> GenerateList(Cluster cluster, BatchPolicy policy, List<BatchRead> records) { Node[] nodes = cluster.Nodes; if (nodes.Length == 0) { throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Command failed because cluster is empty."); } // Create initial key capacity for each node as average + 25%. int max = records.Count; int keysPerNode = max / nodes.Length; keysPerNode += (int)((uint)keysPerNode >> 2); // The minimum key capacity is 10. if (keysPerNode < 10) { keysPerNode = 10; } // Split keys by server node. List<BatchNode> batchNodes = new List<BatchNode>(nodes.Length); for (int i = 0; i < max; i++) { Partition partition = new Partition(records[i].key); Node node = cluster.GetReadNode(partition, policy.replica); BatchNode batchNode = FindBatchNode(batchNodes, node); if (batchNode == null) { batchNodes.Add(new BatchNode(node, keysPerNode, i)); } else { batchNode.AddKey(i); } } return batchNodes; } private static BatchNode FindBatchNode(IList<BatchNode> nodes, Node node) { foreach (BatchNode batchNode in nodes) { // Note: using pointer equality for performance. if (batchNode.node == node) { return batchNode; } } return null; } public readonly Node node; public int[] offsets; public int offsetsSize; public List<BatchNamespace> batchNamespaces; // used by old batch only public BatchNode(Node node, int capacity, int offset) { this.node = node; this.offsets = new int[capacity]; this.offsets[0] = offset; this.offsetsSize = 1; } public BatchNode(Node node, Key[] keys) { this.node = node; this.offsets = new int[keys.Length]; this.offsetsSize = keys.Length; for (int i = 0; i < offsetsSize; i++) { offsets[i] = i; } } public void AddKey(int offset) { if (offsetsSize >= offsets.Length) { int[] copy = new int[offsetsSize * 2]; Array.Copy(offsets, 0, copy, 0, offsetsSize); offsets = copy; } offsets[offsetsSize++] = offset; } public void SplitByNamespace(Key[] keys) { string first = keys[offsets[0]].ns; // Optimize for single namespace. if (IsSingleNamespace(keys, first)) { batchNamespaces = new List<BatchNamespace>(1); batchNamespaces.Add(new BatchNamespace(first, offsets, offsetsSize)); return; } // Process multiple namespaces. batchNamespaces = new List<BatchNamespace>(4); for (int i = 0; i < offsetsSize; i++) { int offset = offsets[i]; string ns = keys[offset].ns; BatchNamespace batchNamespace = FindNamespace(batchNamespaces, ns); if (batchNamespace == null) { batchNamespaces.Add(new BatchNamespace(ns, offsetsSize, offset)); } else { batchNamespace.Add(offset); } } } private bool IsSingleNamespace(Key[] keys, string first) { for (int i = 1; i < offsetsSize; i++) { string ns = keys[offsets[i]].ns; if (!(ns == first || ns.Equals(first))) { return false; } } return true; } private BatchNamespace FindNamespace(List<BatchNamespace> batchNamespaces, string ns) { foreach (BatchNamespace batchNamespace in batchNamespaces) { // Note: use both pointer equality and equals. if (batchNamespace.ns == ns || batchNamespace.ns.Equals(ns)) { return batchNamespace; } } return null; } public sealed class BatchNamespace { public readonly string ns; public int[] offsets; public int offsetsSize; public BatchNamespace(string ns, int capacity, int offset) { this.ns = ns; this.offsets = new int[capacity]; this.offsets[0] = offset; this.offsetsSize = 1; } public BatchNamespace(string ns, int[] offsets, int offsetsSize) { this.ns = ns; this.offsets = offsets; this.offsetsSize = offsetsSize; } public void Add(int offset) { offsets[offsetsSize++] = offset; } } } }
namespace XenAdmin.SettingsPanels { partial class CPUMemoryEditPage { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CPUMemoryEditPage)); this.lblSliderHighest = new System.Windows.Forms.Label(); this.lblSliderNormal = new System.Windows.Forms.Label(); this.lblSliderLowest = new System.Windows.Forms.Label(); this.lblPriority = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.labelInvalidVCPUWarning = new System.Windows.Forms.Label(); this.comboBoxTopology = new XenAdmin.Controls.CPUTopologyComboBox(); this.labelTopology = new System.Windows.Forms.Label(); this.MemWarningLabel = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.lblMB = new System.Windows.Forms.Label(); this.nudMemory = new System.Windows.Forms.NumericUpDown(); this.panel1 = new System.Windows.Forms.Panel(); this.transparentTrackBar1 = new XenAdmin.Controls.TransparentTrackBar(); this.lblVCPUs = new System.Windows.Forms.Label(); this.lblVcpuWarning = new System.Windows.Forms.LinkLabel(); this.lblMemory = new System.Windows.Forms.Label(); this.VCPUWarningLabel = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.comboBoxVCPUs = new System.Windows.Forms.ComboBox(); this.tableLayoutPanel1.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudMemory)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // lblSliderHighest // resources.ApplyResources(this.lblSliderHighest, "lblSliderHighest"); this.lblSliderHighest.Name = "lblSliderHighest"; // // lblSliderNormal // resources.ApplyResources(this.lblSliderNormal, "lblSliderNormal"); this.lblSliderNormal.Name = "lblSliderNormal"; // // lblSliderLowest // resources.ApplyResources(this.lblSliderLowest, "lblSliderLowest"); this.lblSliderLowest.Name = "lblSliderLowest"; // // lblPriority // resources.ApplyResources(this.lblPriority, "lblPriority"); this.tableLayoutPanel1.SetColumnSpan(this.lblPriority, 2); this.lblPriority.Name = "lblPriority"; // // tableLayoutPanel1 // this.tableLayoutPanel1.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelInvalidVCPUWarning, 1, 5); this.tableLayoutPanel1.Controls.Add(this.comboBoxTopology, 1, 4); this.tableLayoutPanel1.Controls.Add(this.labelTopology, 0, 4); this.tableLayoutPanel1.Controls.Add(this.MemWarningLabel, 2, 8); this.tableLayoutPanel1.Controls.Add(this.panel2, 1, 8); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 7); this.tableLayoutPanel1.Controls.Add(this.lblPriority, 0, 6); this.tableLayoutPanel1.Controls.Add(this.lblVCPUs, 0, 2); this.tableLayoutPanel1.Controls.Add(this.lblVcpuWarning, 0, 1); this.tableLayoutPanel1.Controls.Add(this.lblMemory, 0, 8); this.tableLayoutPanel1.Controls.Add(this.VCPUWarningLabel, 2, 2); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.comboBoxVCPUs, 1, 2); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // labelInvalidVCPUWarning // resources.ApplyResources(this.labelInvalidVCPUWarning, "labelInvalidVCPUWarning"); this.tableLayoutPanel1.SetColumnSpan(this.labelInvalidVCPUWarning, 2); this.labelInvalidVCPUWarning.ForeColor = System.Drawing.Color.Red; this.labelInvalidVCPUWarning.Name = "labelInvalidVCPUWarning"; // // comboBoxTopology // this.tableLayoutPanel1.SetColumnSpan(this.comboBoxTopology, 2); this.comboBoxTopology.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.comboBoxTopology, "comboBoxTopology"); this.comboBoxTopology.FormattingEnabled = true; this.comboBoxTopology.Name = "comboBoxTopology"; this.comboBoxTopology.SelectedIndexChanged += new System.EventHandler(this.comboBoxTopology_SelectedIndexChanged); // // labelTopology // resources.ApplyResources(this.labelTopology, "labelTopology"); this.labelTopology.Name = "labelTopology"; // // MemWarningLabel // resources.ApplyResources(this.MemWarningLabel, "MemWarningLabel"); this.MemWarningLabel.ForeColor = System.Drawing.Color.Red; this.MemWarningLabel.Name = "MemWarningLabel"; this.tableLayoutPanel1.SetRowSpan(this.MemWarningLabel, 2); // // panel2 // resources.ApplyResources(this.panel2, "panel2"); this.panel2.Controls.Add(this.lblMB); this.panel2.Controls.Add(this.nudMemory); this.panel2.Name = "panel2"; // // lblMB // resources.ApplyResources(this.lblMB, "lblMB"); this.lblMB.Name = "lblMB"; // // nudMemory // resources.ApplyResources(this.nudMemory, "nudMemory"); this.nudMemory.Maximum = new decimal(new int[] { 1048576, 0, 0, 0}); this.nudMemory.Minimum = new decimal(new int[] { 64, 0, 0, 0}); this.nudMemory.Name = "nudMemory"; this.nudMemory.Value = new decimal(new int[] { 64, 0, 0, 0}); this.nudMemory.ValueChanged += new System.EventHandler(this.nudMemory_ValueChanged); // // panel1 // resources.ApplyResources(this.panel1, "panel1"); this.tableLayoutPanel1.SetColumnSpan(this.panel1, 3); this.panel1.Controls.Add(this.lblSliderHighest); this.panel1.Controls.Add(this.lblSliderNormal); this.panel1.Controls.Add(this.lblSliderLowest); this.panel1.Controls.Add(this.transparentTrackBar1); this.panel1.Name = "panel1"; // // transparentTrackBar1 // resources.ApplyResources(this.transparentTrackBar1, "transparentTrackBar1"); this.transparentTrackBar1.BackColor = System.Drawing.Color.Transparent; this.transparentTrackBar1.Name = "transparentTrackBar1"; this.transparentTrackBar1.TabStop = false; // // lblVCPUs // resources.ApplyResources(this.lblVCPUs, "lblVCPUs"); this.lblVCPUs.Name = "lblVCPUs"; // // lblVcpuWarning // resources.ApplyResources(this.lblVcpuWarning, "lblVcpuWarning"); this.tableLayoutPanel1.SetColumnSpan(this.lblVcpuWarning, 2); this.lblVcpuWarning.LinkColor = System.Drawing.SystemColors.ActiveCaption; this.lblVcpuWarning.Name = "lblVcpuWarning"; this.lblVcpuWarning.TabStop = true; this.lblVcpuWarning.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblVcpuWarning_LinkClicked); // // lblMemory // resources.ApplyResources(this.lblMemory, "lblMemory"); this.lblMemory.Name = "lblMemory"; // // VCPUWarningLabel // resources.ApplyResources(this.VCPUWarningLabel, "VCPUWarningLabel"); this.VCPUWarningLabel.ForeColor = System.Drawing.Color.Red; this.VCPUWarningLabel.Name = "VCPUWarningLabel"; this.tableLayoutPanel1.SetRowSpan(this.VCPUWarningLabel, 2); // // label1 // resources.ApplyResources(this.label1, "label1"); this.tableLayoutPanel1.SetColumnSpan(this.label1, 3); this.label1.Name = "label1"; // // comboBoxVCPUs // this.comboBoxVCPUs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxVCPUs.FormattingEnabled = true; resources.ApplyResources(this.comboBoxVCPUs, "comboBoxVCPUs"); this.comboBoxVCPUs.Name = "comboBoxVCPUs"; this.comboBoxVCPUs.SelectedIndexChanged += new System.EventHandler(this.comboBoxVCPUs_SelectedIndexChanged); // // CPUMemoryEditPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.SystemColors.Control; this.Controls.Add(this.tableLayoutPanel1); this.DoubleBuffered = true; this.ForeColor = System.Drawing.SystemColors.ControlText; this.Name = "CPUMemoryEditPage"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudMemory)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; public System.Windows.Forms.NumericUpDown nudMemory; private System.Windows.Forms.Label lblMB; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label lblSliderHighest; private System.Windows.Forms.Label lblSliderNormal; private System.Windows.Forms.Label lblSliderLowest; private System.Windows.Forms.Label lblPriority; private System.Windows.Forms.Label lblVCPUs; private System.Windows.Forms.Label lblMemory; private System.Windows.Forms.LinkLabel lblVcpuWarning; private XenAdmin.Controls.TransparentTrackBar transparentTrackBar1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label VCPUWarningLabel; private System.Windows.Forms.Label MemWarningLabel; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label labelTopology; private XenAdmin.Controls.CPUTopologyComboBox comboBoxTopology; private System.Windows.Forms.Label labelInvalidVCPUWarning; private System.Windows.Forms.ComboBox comboBoxVCPUs; } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, 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. //using System; using System.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Support { public class BatcherTest : LiteTestCase { /// <summary> /// Submit 101 objects to batcher, and make sure that batch /// of first 100 are processed "immediately" (as opposed to being /// subjected to a delay which would add latency) /// </summary> /// <exception cref="System.Exception"></exception> public virtual void TestBatcherLatencyInitialBatch() { CountDownLatch doneSignal = new CountDownLatch(1); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 100; int processorDelay = 500; AtomicLong timeProcessed = new AtomicLong(); Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay , new _BatchProcessor_34(timeProcessed, doneSignal)); AList<string> objectsToQueue = new AList<string>(); for (int i = 0; i < inboxCapacity + 1; i++) { objectsToQueue.AddItem(Sharpen.Extensions.ToString(i)); } long timeQueued = Runtime.CurrentTimeMillis(); batcher.QueueObjects(objectsToQueue); bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(didNotTimeOut); long delta = timeProcessed.Get() - timeQueued; NUnit.Framework.Assert.IsTrue(delta > 0); // we want the delta between the time it was queued until the // time it was processed to be as small as possible. since // there is some overhead, rather than using a hardcoded number // express it as a ratio of the processor delay, asserting // that the entire processor delay never kicked in. int acceptableDelta = processorDelay - 1; Log.V(Log.Tag, "delta: %d", delta); NUnit.Framework.Assert.IsTrue(delta < acceptableDelta); } private sealed class _BatchProcessor_34 : BatchProcessor<string> { public _BatchProcessor_34(AtomicLong timeProcessed, CountDownLatch doneSignal) { this.timeProcessed = timeProcessed; this.doneSignal = doneSignal; } public void Process(IList<string> itemsToProcess) { Log.V(Database.Tag, "process called with: " + itemsToProcess); timeProcessed.Set(Runtime.CurrentTimeMillis()); doneSignal.CountDown(); } private readonly AtomicLong timeProcessed; private readonly CountDownLatch doneSignal; } /// <summary> /// Set batch processing delay to 500 ms, and every second, add a new item /// to the batcher queue. /// </summary> /// <remarks> /// Set batch processing delay to 500 ms, and every second, add a new item /// to the batcher queue. Make sure that each item is processed immediately. /// </remarks> /// <exception cref="System.Exception"></exception> public virtual void TestBatcherLatencyTrickleIn() { CountDownLatch doneSignal = new CountDownLatch(10); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 100; int processorDelay = 500; AtomicLong maxObservedDelta = new AtomicLong(-1); Batcher batcher = new Batcher<long>(workExecutor, inboxCapacity, processorDelay, new _BatchProcessor_91(maxObservedDelta, doneSignal)); AList<long> objectsToQueue = new AList<long>(); for (int i = 0; i < 10; i++) { batcher.QueueObjects(Arrays.AsList(Runtime.CurrentTimeMillis())); Sharpen.Thread.Sleep(1000); } bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(didNotTimeOut); Log.V(Log.Tag, "maxDelta: %d", maxObservedDelta.Get()); // we want the max observed delta between the time it was queued until the // time it was processed to be as small as possible. since // there is some overhead, rather than using a hardcoded number // express it as a ratio of 1/4th the processor delay, asserting // that the entire processor delay never kicked in. int acceptableMaxDelta = processorDelay - 1; Log.V(Log.Tag, "maxObservedDelta: %d", maxObservedDelta.Get()); NUnit.Framework.Assert.IsTrue((maxObservedDelta.Get() < acceptableMaxDelta)); } private sealed class _BatchProcessor_91 : BatchProcessor<long> { public _BatchProcessor_91(AtomicLong maxObservedDelta, CountDownLatch doneSignal) { this.maxObservedDelta = maxObservedDelta; this.doneSignal = doneSignal; } public void Process(IList<long> itemsToProcess) { if (itemsToProcess.Count != 1) { throw new RuntimeException("Unexpected itemsToProcess"); } long timeSubmitted = itemsToProcess[0]; long delta = Runtime.CurrentTimeMillis() - timeSubmitted; if (delta > maxObservedDelta.Get()) { maxObservedDelta.Set(delta); } doneSignal.CountDown(); } private readonly AtomicLong maxObservedDelta; private readonly CountDownLatch doneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestBatcherSingleBatch() { CountDownLatch doneSignal = new CountDownLatch(10); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 10; int processorDelay = 1000; Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay , new _BatchProcessor_146(doneSignal)); // add this to make it a bit more realistic AList<string> objectsToQueue = new AList<string>(); for (int i = 0; i < inboxCapacity * 10; i++) { objectsToQueue.AddItem(Sharpen.Extensions.ToString(i)); } batcher.QueueObjects(objectsToQueue); bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(didNotTimeOut); } private sealed class _BatchProcessor_146 : BatchProcessor<string> { public _BatchProcessor_146(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public void Process(IList<string> itemsToProcess) { Log.V(Database.Tag, "process called with: " + itemsToProcess); try { Sharpen.Thread.Sleep(100); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } BatcherTest.AssertNumbersConsecutive(itemsToProcess); doneSignal.CountDown(); } private readonly CountDownLatch doneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestBatcherBatchSize5() { CountDownLatch doneSignal = new CountDownLatch(10); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 10; int processorDelay = 1000; Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay , new _BatchProcessor_185(processorDelay, doneSignal)); // add this to make it a bit more realistic AList<string> objectsToQueue = new AList<string>(); for (int i = 0; i < inboxCapacity * 10; i++) { objectsToQueue.AddItem(Sharpen.Extensions.ToString(i)); if (objectsToQueue.Count == 5) { batcher.QueueObjects(objectsToQueue); objectsToQueue = new AList<string>(); } } bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(didNotTimeOut); } private sealed class _BatchProcessor_185 : BatchProcessor<string> { public _BatchProcessor_185(int processorDelay, CountDownLatch doneSignal) { this.processorDelay = processorDelay; this.doneSignal = doneSignal; } public void Process(IList<string> itemsToProcess) { Log.V(Database.Tag, "process called with: " + itemsToProcess); try { Sharpen.Thread.Sleep(processorDelay * 2); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } BatcherTest.AssertNumbersConsecutive(itemsToProcess); doneSignal.CountDown(); } private readonly int processorDelay; private readonly CountDownLatch doneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestBatcherBatchSize1() { CountDownLatch doneSignal = new CountDownLatch(1); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 100; int processorDelay = 1000; Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay , new _BatchProcessor_227(processorDelay, doneSignal)); // add this to make it a bit more realistic AList<string> objectsToQueue = new AList<string>(); for (int i = 0; i < inboxCapacity; i++) { objectsToQueue.AddItem(Sharpen.Extensions.ToString(i)); if (objectsToQueue.Count == 5) { batcher.QueueObjects(objectsToQueue); objectsToQueue = new AList<string>(); } } bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(didNotTimeOut); } private sealed class _BatchProcessor_227 : BatchProcessor<string> { public _BatchProcessor_227(int processorDelay, CountDownLatch doneSignal) { this.processorDelay = processorDelay; this.doneSignal = doneSignal; } public void Process(IList<string> itemsToProcess) { Log.V(Database.Tag, "process called with: " + itemsToProcess); try { Sharpen.Thread.Sleep(processorDelay * 2); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } BatcherTest.AssertNumbersConsecutive(itemsToProcess); doneSignal.CountDown(); } private readonly int processorDelay; private readonly CountDownLatch doneSignal; } private static void AssertNumbersConsecutive(IList<string> itemsToProcess) { int previousItemNumber = -1; foreach (string itemString in itemsToProcess) { if (previousItemNumber == -1) { previousItemNumber = System.Convert.ToInt32(itemString); } else { int curItemNumber = System.Convert.ToInt32(itemString); NUnit.Framework.Assert.IsTrue(curItemNumber == previousItemNumber + 1); previousItemNumber = curItemNumber; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Windows; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer; using Microsoft.VisualStudio.ExtensionsExplorer.UI; using NuGet.VisualStudio; using NuGetConsole; using NuGetConsole.Host.PowerShellProvider; namespace NuGet.Dialog.Providers { /// <summary> /// Base class for all tree node types. /// </summary> internal abstract class PackagesProviderBase : VsExtensionsProvider, ILogger { private PackagesSearchNode _searchNode; private PackagesTreeNodeBase _lastSelectedNode; private readonly ResourceDictionary _resources; private readonly Lazy<IConsole> _outputConsole; private readonly IPackageRepository _localRepository; private readonly ProviderServices _providerServices; private Dictionary<Project, Exception> _failedProjects; private string _readmeFile, _originalPackageId; private object _mediumIconDataTemplate; private object _detailViewDataTemplate; private IList<IVsSortDescriptor> _sortDescriptors; private readonly IProgressProvider _progressProvider; private CultureInfo _uiCulture, _culture; private readonly ISolutionManager _solutionManager; private IDisposable _expandedNodesDisposable; protected PackagesProviderBase( IPackageRepository localRepository, ResourceDictionary resources, ProviderServices providerServices, IProgressProvider progressProvider, ISolutionManager solutionManager) { if (resources == null) { throw new ArgumentNullException("resources"); } if (providerServices == null) { throw new ArgumentNullException("providerServices"); } if (solutionManager == null) { throw new ArgumentNullException("solutionManager"); } _localRepository = localRepository; _providerServices = providerServices; _progressProvider = progressProvider; _solutionManager = solutionManager; _resources = resources; _outputConsole = new Lazy<IConsole>(() => providerServices.OutputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false)); } /// <summary> /// Returns either the solution repository or the active project repository, depending on whether we are targeting solution. /// </summary> protected IPackageRepository LocalRepository { get { return _localRepository; } } public virtual bool RefreshOnNodeSelection { get { return false; } } public PackagesTreeNodeBase SelectedNode { get; set; } public bool SuppressNextRefresh { get; private set; } /// <summary> /// Gets the root node of the tree /// </summary> protected IVsExtensionsTreeNode RootNode { get; set; } public PackageSortDescriptor CurrentSort { get; set; } public virtual bool ShowPrereleaseComboBox { get { return true; } } internal bool IncludePrerelease { get; set; } public virtual IEnumerable<string> SupportedFrameworks { get { yield break; } } protected static string GetTargetFramework(Project project) { if (project == null) { return null; } return project.GetTargetFramework(); } public override IVsExtensionsTreeNode ExtensionsTree { get { if (RootNode == null) { RootNode = new RootPackagesTreeNode(null, String.Empty); CreateExtensionsTree(); } return RootNode; } } public override object MediumIconDataTemplate { get { if (_mediumIconDataTemplate == null) { _mediumIconDataTemplate = _resources["PackageItemTemplate"]; } return _mediumIconDataTemplate; } } public override object DetailViewDataTemplate { get { if (_detailViewDataTemplate == null) { _detailViewDataTemplate = _resources["PackageDetailTemplate"]; } return _detailViewDataTemplate; } } // hook for unit test internal Action ExecuteCompletedCallback { get; set; } public IList<IVsSortDescriptor> SortDescriptors { get { if (_sortDescriptors == null) { _sortDescriptors = CreateSortDescriptors(); } return _sortDescriptors; } } protected virtual IList<IVsSortDescriptor> CreateSortDescriptors() { return new List<IVsSortDescriptor> { new PackageSortDescriptor(Resources.Dialog_SortOption_MostDownloads, "DownloadCount", ListSortDirection.Descending), new PackageSortDescriptor(Resources.Dialog_SortOption_PublishedDate, "Published", ListSortDirection.Descending), new PackageSortDescriptor(String.Format(CultureInfo.CurrentCulture, "{0}: {1}", Resources.Dialog_SortOption_Name, Resources.Dialog_SortAscending), new[] { "Title", "Id" }, ListSortDirection.Ascending), new PackageSortDescriptor(String.Format(CultureInfo.CurrentCulture, "{0}: {1}", Resources.Dialog_SortOption_Name, Resources.Dialog_SortDescending), new[] { "Title", "Id" }, ListSortDirection.Descending) }; } public override string ToString() { return Name; } public override IVsExtensionsTreeNode Search(string searchText) { if (OperationCoordinator.IsBusy) { return null; } if (!String.IsNullOrWhiteSpace(searchText) && SelectedNode != null) { searchText = searchText.Trim(); if (_searchNode != null) { _searchNode.Extensions.Clear(); _searchNode.SetSearchText(searchText); } else { _searchNode = new PackagesSearchNode(this, RootNode, SelectedNode, searchText); AddSearchNode(); } } else { RemoveSearchNode(); } return _searchNode; } private void RemoveSearchNode() { if (_searchNode != null) { // When remove the search node, the dialog will automatically select the first node (All node) // Since we are going to restore the previously selected node anyway, we don't want the first node // to refresh. Hence suppress it here. SuppressNextRefresh = true; try { // dispose any search results RootNode.Nodes.Remove(_searchNode); } finally { _searchNode = null; SuppressNextRefresh = false; } if (_lastSelectedNode != null) { // after search, we want to reset the original node to page 1 (Work Item #461) _lastSelectedNode.CurrentPage = 1; SelectNode(_lastSelectedNode); } } } private void AddSearchNode() { if (_searchNode != null && !RootNode.Nodes.Contains(_searchNode)) { // remember the currently selected node so that when search term is cleared, we can restore it. _lastSelectedNode = SelectedNode; RootNode.Nodes.Add(_searchNode); SelectNode(_searchNode); } } protected void SelectNode(PackagesTreeNodeBase node) { node.IsSelected = true; SelectedNode = node; } private void CreateExtensionsTree() { // The user may have done a search before we finished getting the category list; temporarily remove it RemoveSearchNode(); // give subclass a chance to populate the child nodes under Root node FillRootNodes(); // Re-add the search node and select it if the user was doing a search AddSearchNode(); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "NuGet.Dialog.Providers.PackagesProviderBase.WriteLineToOutputWindow(System.String)", Justification = "No need to localize the --- strings"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public virtual void Execute(PackageItem item) { if (OperationCoordinator.IsBusy) { return; } // disable all operations while this install is in progress OperationCoordinator.IsBusy = true; _readmeFile = null; _originalPackageId = item.Id; _progressProvider.ProgressAvailable += OnProgressAvailable; _uiCulture = System.Threading.Thread.CurrentThread.CurrentUICulture; _culture = System.Threading.Thread.CurrentThread.CurrentCulture; _failedProjects = new Dictionary<Project, Exception>(); ClearProgressMessages(); SaveExpandedNodes(); var worker = new BackgroundWorker(); worker.DoWork += OnRunWorkerDoWork; worker.RunWorkerCompleted += OnRunWorkerCompleted; worker.RunWorkerAsync(item); // write an introductory sentence before every operation starts to make the console easier to read string progressMessage = GetProgressMessage(item.PackageIdentity); WriteLineToOutputWindow("------- " + progressMessage + " -------"); } private void OnProgressAvailable(object sender, ProgressEventArgs e) { _providerServices.ProgressWindow.ShowProgress(e.Operation, e.PercentComplete); } private void OnRunWorkerDoWork(object sender, DoWorkEventArgs e) { // make sure the new thread has the same cultures as the UI thread's cultures System.Threading.Thread.CurrentThread.CurrentUICulture = _uiCulture; System.Threading.Thread.CurrentThread.CurrentCulture = _culture; var item = (PackageItem)e.Argument; bool succeeded = ExecuteCore(item); e.Cancel = !succeeded; e.Result = item; } private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { OperationCoordinator.IsBusy = false; _progressProvider.ProgressAvailable -= OnProgressAvailable; if (e.Error == null) { if (e.Cancelled) { CloseProgressWindow(); } else { OnExecuteCompleted((PackageItem)e.Result); _providerServices.ProgressWindow.SetCompleted(successful: true); OpenReadMeFile(); CollapseNodes(); } } else { // show error message in the progress window in case of error Log(MessageLevel.Error, ExceptionUtility.Unwrap(e.Error).Message); _providerServices.ProgressWindow.SetCompleted(successful: false); } if (_failedProjects != null && _failedProjects.Count > 0) { // BUG 1401: if we are going to show the Summary window, // then hide the progress window. _providerServices.ProgressWindow.Close(); _providerServices.UserNotifierServices.ShowSummaryWindow(_failedProjects); } // write a blank line into the output window to separate entries from different operations WriteLineToOutputWindow(new string('=', 30)); WriteLineToOutputWindow(); if (ExecuteCompletedCallback != null) { ExecuteCompletedCallback(); } } private void ClearProgressMessages() { _providerServices.ProgressWindow.ClearMessages(); } protected void ShowProgressWindow() { _providerServices.ProgressWindow.Show(ProgressWindowTitle, PackageManagerWindow.CurrentInstance); } protected void HideProgressWindow() { _providerServices.ProgressWindow.Hide(); } protected void CloseProgressWindow() { _providerServices.ProgressWindow.Close(); } protected virtual void FillRootNodes() { } protected void AddFailedProject(Project project, Exception exception) { if (project == null) { throw new ArgumentNullException("project"); } if (exception == null) { throw new ArgumentNullException("exception"); } _failedProjects[project] = ExceptionUtility.Unwrap(exception); } public abstract IVsExtension CreateExtension(IPackage package); public abstract bool CanExecute(PackageItem item); protected virtual string GetProgressMessage(IPackage package) { return package.ToString(); } /// <summary> /// This method is called on background thread. /// </summary> /// <returns><c>true</c> if the method succeeded. <c>false</c> otherwise.</returns> protected virtual bool ExecuteCore(PackageItem item) { return true; } protected virtual void OnExecuteCompleted(PackageItem item) { // After every operation, just update the status of all packages in the current node. // Strictly speaking, this is not required; only affected packages need to be updated. // But doing so would require us to keep a Dictionary<IPackage, PackageItem> which is not worth it. if (SelectedNode != null) { foreach (PackageItem node in SelectedNode.Extensions) { node.UpdateEnabledStatus(); } } } public virtual string NoItemsMessage { get { return String.Empty; } } public virtual string ProgressWindowTitle { get { return String.Empty; } } public void Log(MessageLevel level, string message, params object[] args) { string formattedMessage = String.Format(CultureInfo.CurrentCulture, message, args); // for the dialog we ignore debug messages if (_providerServices.ProgressWindow.IsOpen && level != MessageLevel.Debug) { _providerServices.ProgressWindow.AddMessage(level, formattedMessage); } WriteLineToOutputWindow(formattedMessage); } protected void WriteLineToOutputWindow(string message = "") { _outputConsole.Value.WriteLine(message); } protected void ShowProgress(string operation, int percentComplete) { if (_providerServices.ProgressWindow.IsOpen) { _providerServices.ProgressWindow.ShowProgress(operation, percentComplete); } } protected void RegisterPackageOperationEvents(IPackageManager packageManager, IProjectManager projectManager) { if (packageManager != null) { packageManager.PackageInstalled += OnPackageInstalled; } if (projectManager != null) { projectManager.PackageReferenceAdded += OnPackageReferenceAdded; projectManager.PackageReferenceRemoving += OnPackageReferenceRemoving; } } protected void UnregisterPackageOperationEvents(IPackageManager packageManager, IProjectManager projectManager) { if (packageManager != null) { packageManager.PackageInstalled -= OnPackageInstalled; } if (projectManager != null) { projectManager.PackageReferenceAdded -= OnPackageReferenceAdded; projectManager.PackageReferenceRemoving -= OnPackageReferenceRemoving; } } private void OnPackageInstalled(object sender, PackageOperationEventArgs e) { _providerServices.ScriptExecutor.ExecuteInitScript(e.InstallPath, e.Package, this); PrepareOpenReadMeFile(e); } private void OnPackageReferenceAdded(object sender, PackageOperationEventArgs e) { Project project = FindProjectFromFileSystem(e.FileSystem); Debug.Assert(project != null); _providerServices.ScriptExecutor.ExecuteScript(e.InstallPath, PowerShellScripts.Install, e.Package, project, this); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void OnPackageReferenceRemoving(object sender, PackageOperationEventArgs e) { Project project = FindProjectFromFileSystem(e.FileSystem); Debug.Assert(project != null); try { _providerServices.ScriptExecutor.ExecuteScript(e.InstallPath, PowerShellScripts.Uninstall, e.Package, project, this); } catch (Exception ex) { // Swallow exception for uninstall.ps1. Otherwise, there is no way to uninstall a package. // But we log it as a warning. Log(MessageLevel.Warning, ExceptionUtility.Unwrap(ex).Message); } } private Project FindProjectFromFileSystem(IFileSystem fileSystem) { var projectSystem = fileSystem as IVsProjectSystem; return _solutionManager.GetProject(projectSystem.UniqueName); } protected void CheckInstallPSScripts( IPackage package, IPackageRepository sourceRepository, bool includePrerelease, out IList<PackageOperation> operations) { // Review: Is there any way the user could get into a position that we would need to allow pre release versions here? var walker = new InstallWalker( LocalRepository, sourceRepository, this, ignoreDependencies: false, allowPrereleaseVersions: includePrerelease); operations = walker.ResolveOperations(package).ToList(); var scriptPackages = from o in operations where o.Package.HasPowerShellScript() select o.Package; if (scriptPackages.Any()) { if (!RegistryHelper.CheckIfPowerShell2Installed()) { throw new InvalidOperationException(Resources.Dialog_PackageHasPSScript); } } } private void PrepareOpenReadMeFile(PackageOperationEventArgs e) { // only open the read me file for the first package that initiates this operation. if (e.Package.Id.Equals(_originalPackageId, StringComparison.OrdinalIgnoreCase) && e.Package.HasReadMeFileAtRoot()) { _readmeFile = Path.Combine(e.InstallPath, NuGetConstants.ReadmeFileName); } } private void OpenReadMeFile() { if (_readmeFile != null) { _providerServices.VsCommonOperations.OpenFile(_readmeFile); } } private void SaveExpandedNodes() { // remember which nodes are currently open so that we can keep them open after the operation _expandedNodesDisposable = _providerServices.VsCommonOperations.SaveSolutionExplorerNodeStates(_solutionManager); } private void CollapseNodes() { // collapse all nodes in solution explorer that we expanded during the operation if (_expandedNodesDisposable != null) { _expandedNodesDisposable.Dispose(); _expandedNodesDisposable = null; } } } }
// 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.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// SyncGroupsOperations operations. /// </summary> public partial interface ISyncGroupsOperations { /// <summary> /// Gets a collection of sync database ids. /// </summary> /// <param name='locationName'> /// The name of the region where the resource is located. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncDatabaseIdProperties>>> ListSyncDatabaseIdsWithHttpMessagesAsync(string locationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Refreshes a hub database schema. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> RefreshHubSchemaWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a collection of hub database schemas. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncFullSchemaProperties>>> ListHubSchemasWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a collection of sync group logs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='startTime'> /// Get logs generated after this time. /// </param> /// <param name='endTime'> /// Get logs generated before this time. /// </param> /// <param name='type'> /// The types of logs to retrieve. Possible values include: 'All', /// 'Error', 'Warning', 'Success' /// </param> /// <param name='continuationToken'> /// The continuation token for this operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncGroupLogProperties>>> ListLogsWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, string startTime, string endTime, string type, string continuationToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Cancels a sync group synchronization. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> CancelSyncWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Triggers a sync group synchronization. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> TriggerSyncWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SyncGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='parameters'> /// The requested sync group resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SyncGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='parameters'> /// The requested sync group resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SyncGroup>> UpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists sync groups under a hub database. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncGroup>>> ListByDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Refreshes a hub database schema. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginRefreshHubSchemaWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='parameters'> /// The requested sync group resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SyncGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a sync group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='databaseName'> /// The name of the database on which the sync group is hosted. /// </param> /// <param name='syncGroupName'> /// The name of the sync group. /// </param> /// <param name='parameters'> /// The requested sync group resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SyncGroup>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, string syncGroupName, SyncGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a collection of sync database ids. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncDatabaseIdProperties>>> ListSyncDatabaseIdsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a collection of hub database schemas. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncFullSchemaProperties>>> ListHubSchemasNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a collection of sync group logs. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncGroupLogProperties>>> ListLogsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists sync groups under a hub database. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SyncGroup>>> ListByDatabaseNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Apache.Geode.Client.UnitTests { using Apache.Geode.Client; using Apache.Geode.Client.Tests; using Apache.Geode.DUnitFramework; using NUnit.Framework; using QueryCategory = Apache.Geode.Client.Tests.QueryCategory; using QueryStatics = Apache.Geode.Client.Tests.QueryStatics; using QueryStrings = Apache.Geode.Client.Tests.QueryStrings; [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] internal class ThinClientAppDomainQueryTests : ThinClientRegionSteps { #region Private members private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2", "Portfolios3" }; #endregion Private members protected override ClientBase[] GetClients() { return new ClientBase[] { }; } [TestFixtureSetUp] public override void InitTests() { CacheHelper.Init(); } [TearDown] public override void EndTest() { CacheHelper.StopJavaServers(); base.EndTest(); } #region Functions invoked by the tests public void InitClient() { CacheHelper.DCache.TypeRegistry.RegisterType(Portfolio.CreateDeserializable, 8); CacheHelper.DCache.TypeRegistry.RegisterType(Position.CreateDeserializable, 7); CacheHelper.DCache.TypeRegistry.RegisterPdxType(PortfolioPdx.CreateDeserializable); CacheHelper.DCache.TypeRegistry.RegisterPdxType(PositionPdx.CreateDeserializable); } public void CreateCache(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes; region.CreateSubRegion(QueryRegionNames[1], regattrs); } public void PopulateRegions() { IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = (IRegion<object, object>)region0.GetSubRegion(QueryRegionNames[1]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]); IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]); IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } public void VerifyQueries() { bool ErrorOccurred = false; QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries) { if (qrystr.Category == QueryCategory.Unsupported) { Util.Log("Skipping query index {0} because it is unsupported.", qryIdx); qryIdx++; continue; } if (qryIdx == 2 || qryIdx == 3 || qryIdx == 4) { Util.Log("Skipping query index {0} for Pdx because it is function type.", qryIdx); qryIdx++; continue; } Util.Log("Evaluating query index {0}. Query string {1}", qryIdx, qrystr.Query); Query<object> query = qs.NewQuery<object>(qrystr.Query); ISelectResults<object> results = query.Execute(); int expectedRowCount = qh.IsExpectedRowsConstantRS(qryIdx) ? QueryStatics.ResultSetRowCounts[qryIdx] : QueryStatics.ResultSetRowCounts[qryIdx] * qh.PortfolioNumSets; if (!qh.VerifyRS(results, expectedRowCount)) { ErrorOccurred = true; Util.Log("Query verify failed for query index {0}.", qryIdx); qryIdx++; continue; } ResultSet<object> rs = results as ResultSet<object>; foreach (object item in rs) { PortfolioPdx port = item as PortfolioPdx; if (port == null) { PositionPdx pos = item as PositionPdx; if (pos == null) { string cs = item.ToString(); if (cs == null) { Util.Log("Query got other/unknown object."); } else { Util.Log("Query got string : {0}.", cs); } } else { Util.Log("Query got Position object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding); } } else { Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } qryIdx++; } Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred."); } public void VerifyUnsupporteQueries() { bool ErrorOccurred = false; QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries) { if (qrystr.Category != QueryCategory.Unsupported) { qryIdx++; continue; } Util.Log("Evaluating unsupported query index {0}.", qryIdx); Query<object> query = qs.NewQuery<object>(qrystr.Query); try { ISelectResults<object> results = query.Execute(); Util.Log("Query exception did not occur for index {0}.", qryIdx); ErrorOccurred = true; qryIdx++; } catch (GeodeException) { // ok, exception expected, do nothing. qryIdx++; } catch (Exception) { Util.Log("Query unexpected exception occurred for index {0}.", qryIdx); ErrorOccurred = true; qryIdx++; } } Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur."); } #endregion Functions invoked by the tests [Test] public void RemoteQueryRS() { Util.Log("DoRemoteQueryRS: AppDomain: " + AppDomain.CurrentDomain.Id); CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); CreateCache(CacheHelper.Locators); Util.Log("CreateCache complete."); PopulateRegions(); Util.Log("PopulateRegions complete."); VerifyQueries(); Util.Log("VerifyQueries complete."); VerifyUnsupporteQueries(); Util.Log("VerifyUnsupporteQueries complete."); Close(); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } } }
// // WebHeaderCollection.cs // Copied from System.Net.WebHeaderCollection.cs // // Authors: // Lawrence Pit ([email protected]) // Gonzalo Paniagua Javier ([email protected]) // Miguel de Icaza ([email protected]) // sta ([email protected]) // // Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com) // Copyright (c) 2007 Novell, Inc. (http://www.novell.com) // Copyright (c) 2012-2013 sta.blockhead // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; namespace Reactor.Net { [Serializable] [ComVisible(true)] public class WebHeaderCollection : NameValueCollection, ISerializable { [Flags] internal enum HeaderInfo { Request = 1, Response = 1 << 1, MultiValue = 1 << 10 } static readonly bool[] allowed_chars = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, true, true, false, false, false, true, true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false }; static readonly Dictionary<string, HeaderInfo> headers; HeaderInfo? headerRestriction; HeaderInfo? headerConsistency; static WebHeaderCollection() { headers = new Dictionary<string, HeaderInfo>(StringComparer.OrdinalIgnoreCase) { { "Allow", HeaderInfo.MultiValue }, { "Accept", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Accept-Charset", HeaderInfo.MultiValue }, { "Accept-Encoding", HeaderInfo.MultiValue }, { "Accept-Language", HeaderInfo.MultiValue }, { "Accept-Ranges", HeaderInfo.MultiValue }, { "Authorization", HeaderInfo.MultiValue }, { "Cache-Control", HeaderInfo.MultiValue }, { "Cookie", HeaderInfo.MultiValue }, { "Connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Content-Encoding", HeaderInfo.MultiValue }, { "Content-Length", HeaderInfo.Request | HeaderInfo.Response }, { "Content-Type", HeaderInfo.Request }, { "Content-Language", HeaderInfo.MultiValue }, { "Date", HeaderInfo.Request }, { "Expect", HeaderInfo.Request | HeaderInfo.MultiValue}, { "Host", HeaderInfo.Request }, { "If-Match", HeaderInfo.MultiValue }, { "If-Modified-Since", HeaderInfo.Request }, { "If-None-Match", HeaderInfo.MultiValue }, { "Keep-Alive", HeaderInfo.Response }, { "Pragma", HeaderInfo.MultiValue }, { "Proxy-Authenticate", HeaderInfo.MultiValue }, { "Proxy-Authorization", HeaderInfo.MultiValue }, { "Proxy-Connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Range", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Referer", HeaderInfo.Request }, { "Set-Cookie", HeaderInfo.MultiValue }, { "Set-Cookie2", HeaderInfo.MultiValue }, { "TE", HeaderInfo.MultiValue }, { "Trailer", HeaderInfo.MultiValue }, { "Transfer-Encoding", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo.MultiValue }, { "Upgrade", HeaderInfo.MultiValue }, { "User-Agent", HeaderInfo.Request }, { "Vary", HeaderInfo.MultiValue }, { "Via", HeaderInfo.MultiValue }, { "Warning", HeaderInfo.MultiValue }, { "WWW-Authenticate", HeaderInfo.Response | HeaderInfo. MultiValue } }; } // Constructors public WebHeaderCollection() { } protected WebHeaderCollection(SerializationInfo serializationInfo, StreamingContext streamingContext) { int count; try { count = serializationInfo.GetInt32("Count"); for (int i = 0; i < count; i++) { this.Add(serializationInfo.GetString(i.ToString()), serializationInfo.GetString((count + i).ToString())); } } catch (SerializationException) { count = serializationInfo.GetInt32("count"); for (int i = 0; i < count; i++) { this.Add(serializationInfo.GetString("k" + i), serializationInfo.GetString("v" + i)); } } } internal WebHeaderCollection(HeaderInfo headerRestriction) { this.headerRestriction = headerRestriction; } // Methods public void Add(string header) { if (header == null) { throw new ArgumentNullException("header"); } int pos = header.IndexOf(':'); if (pos == -1) { throw new ArgumentException("no colon found", "header"); } this.Add(header.Substring(0, pos), header.Substring(pos + 1)); } public override void Add(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } CheckRestrictedHeader(name); this.AddWithoutValidate(name, value); } protected void AddWithoutValidate(string headerName, string headerValue) { if (!IsHeaderName(headerName)) { throw new ArgumentException("invalid header name: " + headerName, "headerName"); } if (headerValue == null) { headerValue = String.Empty; } else { headerValue = headerValue.Trim(); } if (!IsHeaderValue(headerValue)) { throw new ArgumentException("invalid header value: " + headerValue, "headerValue"); } AddValue(headerName, headerValue); } internal void AddValue(string headerName, string headerValue) { base.Add(headerName, headerValue); } internal string[] GetValues_internal(string header, bool split) { if (header == null) { throw new ArgumentNullException("header"); } string[] values = base.GetValues(header); if (values == null || values.Length == 0) { return null; } if (split && IsMultiValue(header)) { List<string> separated = null; foreach (var value in values) { if (value.IndexOf(',') < 0) { continue; } if (separated == null) { separated = new List<string>(values.Length + 1); foreach (var v in values) { if (v == value) { break; } separated.Add(v); } } var slices = value.Split(','); var slices_length = slices.Length; if (value[value.Length - 1] == ',') { --slices_length; } for (int i = 0; i < slices_length; ++i) { separated.Add(slices[i].Trim()); } } if (separated != null) { return separated.ToArray(); } } return values; } public override string[] GetValues(string header) { return GetValues_internal(header, true); } public override string[] GetValues(int index) { string[] values = base.GetValues(index); if (values == null || values.Length == 0) { return null; } return values; } public static bool IsRestricted(string headerName) { return IsRestricted(headerName, false); } public static bool IsRestricted(string headerName, bool response) { if (headerName == null) { throw new ArgumentNullException("headerName"); } if (headerName.Length == 0) { throw new ArgumentException("empty string", "headerName"); } if (!IsHeaderName(headerName)) { throw new ArgumentException("Invalid character in header"); } HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) { return false; } var flag = response ? HeaderInfo.Response : HeaderInfo.Request; return (info & flag) != 0; } public override void OnDeserialization(object sender) { } public override void Remove(string name) { if (name == null) { throw new ArgumentNullException("name"); } CheckRestrictedHeader(name); base.Remove(name); } public override void Set(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } if (!IsHeaderName(name)) { throw new ArgumentException("invalid header name"); } if (value == null) { value = String.Empty; } else { value = value.Trim(); } if (!IsHeaderValue(value)) { throw new ArgumentException("invalid header value"); } CheckRestrictedHeader(name); base.Set(name, value); } public byte[] ToByteArray() { return Encoding.UTF8.GetBytes(ToString()); } internal string ToStringMultiValue() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) { string key = GetKey(i); if (IsMultiValue(key)) { foreach (string v in GetValues(i)) { sb.Append(key) .Append(": ") .Append(v) .Append("\r\n"); } } else { sb.Append(key) .Append(": ") .Append(Get(i)) .Append("\r\n"); } } return sb.Append("\r\n").ToString(); } public override string ToString() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) { sb.Append(GetKey(i)) .Append(": ") .Append(Get(i)) .Append("\r\n"); } return sb.Append("\r\n").ToString(); } public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { int count = base.Count; serializationInfo.AddValue("Count", count); for (int i = 0; i < count; i++) { serializationInfo.AddValue(i.ToString(), GetKey(i)); serializationInfo.AddValue((count + i).ToString(), Get(i)); } } public override string[] AllKeys { get { return base.AllKeys; } } public override int Count { get { return base.Count; } } public override KeysCollection Keys { get { return base.Keys; } } public override string Get(int index) { return base.Get(index); } public override string Get(string name) { return base.Get(name); } public override string GetKey(int index) { return base.GetKey(index); } public void Add(HttpRequestHeader header, string value) { Add(RequestHeaderToString(header), value); } public void Remove(HttpRequestHeader header) { Remove(RequestHeaderToString(header)); } public void Set(HttpRequestHeader header, string value) { Set(RequestHeaderToString(header), value); } public void Add(HttpResponseHeader header, string value) { Add(ResponseHeaderToString(header), value); } public void Remove(HttpResponseHeader header) { Remove(ResponseHeaderToString(header)); } public void Set(HttpResponseHeader header, string value) { Set(ResponseHeaderToString(header), value); } public string this[HttpRequestHeader header] { get { return Get(RequestHeaderToString(header)); } set { Set(header, value); } } public string this[HttpResponseHeader header] { get { return Get(ResponseHeaderToString(header)); } set { Set(header, value); } } public override void Clear() { base.Clear(); } public override IEnumerator GetEnumerator() { return base.GetEnumerator(); } // Internal Methods // With this we don't check for invalid characters in header. See bug #55994. internal void SetInternal(string header) { int pos = header.IndexOf(':'); if (pos == -1) { throw new ArgumentException("no colon found", "header"); } SetInternal(header.Substring(0, pos), header.Substring(pos + 1)); } internal void SetInternal(string name, string value) { if (value == null) { value = String.Empty; } else { value = value.Trim(); } if (!IsHeaderValue(value)) { throw new ArgumentException("invalid header value"); } if (IsMultiValue(name)) { base.Add(name, value); } else { base.Remove(name); base.Set(name, value); } } internal void RemoveAndAdd(string name, string value) { if (value == null) { value = String.Empty; } else { value = value.Trim(); } base.Remove(name); base.Set(name, value); } internal void RemoveInternal(string name) { if (name == null) { throw new ArgumentNullException("name"); } base.Remove(name); } // Private Methods string RequestHeaderToString(HttpRequestHeader value) { CheckHeaderConsistency(HeaderInfo.Request); switch (value) { case HttpRequestHeader.CacheControl: return "Cache-Control"; case HttpRequestHeader.Connection: return "Connection"; case HttpRequestHeader.Date: return "Date"; case HttpRequestHeader.KeepAlive: return "Keep-Alive"; case HttpRequestHeader.Pragma: return "Pragma"; case HttpRequestHeader.Trailer: return "Trailer"; case HttpRequestHeader.TransferEncoding: return "Transfer-Encoding"; case HttpRequestHeader.Upgrade: return "Upgrade"; case HttpRequestHeader.Via: return "Via"; case HttpRequestHeader.Warning: return "Warning"; case HttpRequestHeader.Allow: return "Allow"; case HttpRequestHeader.ContentLength: return "Content-Length"; case HttpRequestHeader.ContentType: return "Content-Type"; case HttpRequestHeader.ContentEncoding: return "Content-Encoding"; case HttpRequestHeader.ContentLanguage: return "Content-Language"; case HttpRequestHeader.ContentLocation: return "Content-Location"; case HttpRequestHeader.ContentMd5: return "Content-MD5"; case HttpRequestHeader.ContentRange: return "Content-Range"; case HttpRequestHeader.Expires: return "Expires"; case HttpRequestHeader.LastModified: return "Last-Modified"; case HttpRequestHeader.Accept: return "Accept"; case HttpRequestHeader.AcceptCharset: return "Accept-Charset"; case HttpRequestHeader.AcceptEncoding: return "Accept-Encoding"; case HttpRequestHeader.AcceptLanguage: return "accept-language"; case HttpRequestHeader.Authorization: return "Authorization"; case HttpRequestHeader.Cookie: return "Cookie"; case HttpRequestHeader.Expect: return "Expect"; case HttpRequestHeader.From: return "From"; case HttpRequestHeader.Host: return "Host"; case HttpRequestHeader.IfMatch: return "If-Match"; case HttpRequestHeader.IfModifiedSince: return "If-Modified-Since"; case HttpRequestHeader.IfNoneMatch: return "If-None-Match"; case HttpRequestHeader.IfRange: return "If-Range"; case HttpRequestHeader.IfUnmodifiedSince: return "If-Unmodified-Since"; case HttpRequestHeader.MaxForwards: return "Max-Forwards"; case HttpRequestHeader.ProxyAuthorization: return "Proxy-Authorization"; case HttpRequestHeader.Referer: return "Referer"; case HttpRequestHeader.Range: return "Range"; case HttpRequestHeader.Te: return "TE"; case HttpRequestHeader.Translate: return "Translate"; case HttpRequestHeader.UserAgent: return "User-Agent"; default: throw new InvalidOperationException(); } } string ResponseHeaderToString(HttpResponseHeader value) { CheckHeaderConsistency(HeaderInfo.Response); switch (value) { case HttpResponseHeader.CacheControl: return "Cache-Control"; case HttpResponseHeader.Connection: return "Connection"; case HttpResponseHeader.Date: return "Date"; case HttpResponseHeader.KeepAlive: return "Keep-Alive"; case HttpResponseHeader.Pragma: return "Pragma"; case HttpResponseHeader.Trailer: return "Trailer"; case HttpResponseHeader.TransferEncoding: return "Transfer-Encoding"; case HttpResponseHeader.Upgrade: return "Upgrade"; case HttpResponseHeader.Via: return "Via"; case HttpResponseHeader.Warning: return "Warning"; case HttpResponseHeader.Allow: return "Allow"; case HttpResponseHeader.ContentLength: return "Content-Length"; case HttpResponseHeader.ContentType: return "Content-Type"; case HttpResponseHeader.ContentEncoding: return "Content-Encoding"; case HttpResponseHeader.ContentLanguage: return "Content-Language"; case HttpResponseHeader.ContentLocation: return "Content-Location"; case HttpResponseHeader.ContentMd5: return "Content-MD5"; case HttpResponseHeader.ContentRange: return "Content-Range"; case HttpResponseHeader.Expires: return "Expires"; case HttpResponseHeader.LastModified: return "Last-Modified"; case HttpResponseHeader.AcceptRanges: return "Accept-Ranges"; case HttpResponseHeader.Age: return "Age"; case HttpResponseHeader.ETag: return "ETag"; case HttpResponseHeader.Location: return "Location"; case HttpResponseHeader.ProxyAuthenticate: return "Proxy-Authenticate"; case HttpResponseHeader.RetryAfter: return "Retry-After"; case HttpResponseHeader.Server: return "Server"; case HttpResponseHeader.SetCookie: return "Set-Cookie"; case HttpResponseHeader.Vary: return "Vary"; case HttpResponseHeader.WwwAuthenticate: return "WWW-Authenticate"; default: throw new InvalidOperationException(); } } void CheckRestrictedHeader(string headerName) { if (!headerRestriction.HasValue) { return; } HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) { return; } if ((info & headerRestriction.Value) != 0) { throw new ArgumentException("This header must be modified with the appropiate property."); } } void CheckHeaderConsistency(HeaderInfo value) { if (!headerConsistency.HasValue) { headerConsistency = value; return; } if ((headerConsistency & value) == 0) { throw new InvalidOperationException(); } } internal static bool IsMultiValue(string headerName) { if (headerName == null) { return false; } HeaderInfo info; return headers.TryGetValue(headerName, out info) && (info & HeaderInfo.MultiValue) != 0; } internal static bool IsHeaderValue(string value) { // TEXT any 8 bit value except CTL's (0-31 and 127) // but including \r\n space and \t // after a newline at least one space or \t must follow // certain header fields allow comments () int len = value.Length; for (int i = 0; i < len; i++) { char c = value[i]; if (c == 127) { return false; } if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t')) { return false; } if (c == '\n' && ++i < len) { c = value[i]; if (c != ' ' && c != '\t') { return false; } } } return true; } internal static bool IsHeaderName(string name) { if (name == null || name.Length == 0) { return false; } int len = name.Length; for (int i = 0; i < len; i++) { char c = name[i]; if (c > 126 || !allowed_chars[c]) { return false; } } return true; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPricelistFilterItem { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPricelistFilterItem() : base() { Load += frmPricelistFilterItem_Load; KeyPress += frmPricelistFilterItem_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.Button _cmdClick_1; public System.Windows.Forms.Button _cmdClick_2; public System.Windows.Forms.Button _cmdClick_3; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } private System.Windows.Forms.CheckedListBox withEventsField_lstStockItem; public System.Windows.Forms.CheckedListBox lstStockItem { get { return withEventsField_lstStockItem; } set { if (withEventsField_lstStockItem != null) { withEventsField_lstStockItem.SelectedIndexChanged -= lstStockItem_SelectedIndexChanged; } withEventsField_lstStockItem = value; if (withEventsField_lstStockItem != null) { withEventsField_lstStockItem.SelectedIndexChanged += lstStockItem_SelectedIndexChanged; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button1; public System.Windows.Forms.ToolStripButton _tbStockItem_Button1 { get { return withEventsField__tbStockItem_Button1; } set { if (withEventsField__tbStockItem_Button1 != null) { withEventsField__tbStockItem_Button1.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button1 = value; if (withEventsField__tbStockItem_Button1 != null) { withEventsField__tbStockItem_Button1.Click += tbStockItem_ButtonClick; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button2; public System.Windows.Forms.ToolStripButton _tbStockItem_Button2 { get { return withEventsField__tbStockItem_Button2; } set { if (withEventsField__tbStockItem_Button2 != null) { withEventsField__tbStockItem_Button2.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button2 = value; if (withEventsField__tbStockItem_Button2 != null) { withEventsField__tbStockItem_Button2.Click += tbStockItem_ButtonClick; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button3; public System.Windows.Forms.ToolStripButton _tbStockItem_Button3 { get { return withEventsField__tbStockItem_Button3; } set { if (withEventsField__tbStockItem_Button3 != null) { withEventsField__tbStockItem_Button3.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button3 = value; if (withEventsField__tbStockItem_Button3 != null) { withEventsField__tbStockItem_Button3.Click += tbStockItem_ButtonClick; } } } public System.Windows.Forms.ToolStrip tbStockItem; public System.Windows.Forms.ImageList ilSelect; public System.Windows.Forms.Label lblHeading; public System.Windows.Forms.Label _lbl_2; //Public WithEvents cmdClick As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPricelistFilterItem)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this._cmdClick_1 = new System.Windows.Forms.Button(); this._cmdClick_2 = new System.Windows.Forms.Button(); this._cmdClick_3 = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.lstStockItem = new System.Windows.Forms.CheckedListBox(); this.txtSearch = new System.Windows.Forms.TextBox(); this.tbStockItem = new System.Windows.Forms.ToolStrip(); this._tbStockItem_Button1 = new System.Windows.Forms.ToolStripButton(); this._tbStockItem_Button2 = new System.Windows.Forms.ToolStripButton(); this._tbStockItem_Button3 = new System.Windows.Forms.ToolStripButton(); this.ilSelect = new System.Windows.Forms.ImageList(); this.lblHeading = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); //Me.cmdClick = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.tbStockItem.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Allocate Stock Items to Price List Group"; this.ClientSize = new System.Drawing.Size(271, 452); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPricelistFilterItem"; this._cmdClick_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_1.Text = "&A"; this._cmdClick_1.Size = new System.Drawing.Size(103, 34); this._cmdClick_1.Location = new System.Drawing.Point(303, 162); this._cmdClick_1.TabIndex = 8; this._cmdClick_1.TabStop = false; this._cmdClick_1.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_1.CausesValidation = true; this._cmdClick_1.Enabled = true; this._cmdClick_1.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_1.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_1.Name = "_cmdClick_1"; this._cmdClick_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_2.Text = "&S"; this._cmdClick_2.Size = new System.Drawing.Size(103, 34); this._cmdClick_2.Location = new System.Drawing.Point(306, 210); this._cmdClick_2.TabIndex = 7; this._cmdClick_2.TabStop = false; this._cmdClick_2.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_2.CausesValidation = true; this._cmdClick_2.Enabled = true; this._cmdClick_2.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_2.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_2.Name = "_cmdClick_2"; this._cmdClick_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_3.Text = "&U"; this._cmdClick_3.Size = new System.Drawing.Size(103, 34); this._cmdClick_3.Location = new System.Drawing.Point(297, 261); this._cmdClick_3.TabIndex = 6; this._cmdClick_3.TabStop = false; this._cmdClick_3.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_3.CausesValidation = true; this._cmdClick_3.Enabled = true; this._cmdClick_3.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_3.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_3.Name = "_cmdClick_3"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(168, 393); this.cmdExit.TabIndex = 4; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lstStockItem.Size = new System.Drawing.Size(254, 304); this.lstStockItem.Location = new System.Drawing.Point(9, 81); this.lstStockItem.Sorted = true; this.lstStockItem.TabIndex = 1; this.lstStockItem.Tag = "0"; this.lstStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lstStockItem.BackColor = System.Drawing.SystemColors.Window; this.lstStockItem.CausesValidation = true; this.lstStockItem.Enabled = true; this.lstStockItem.ForeColor = System.Drawing.SystemColors.WindowText; this.lstStockItem.IntegralHeight = true; this.lstStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lstStockItem.SelectionMode = System.Windows.Forms.SelectionMode.One; this.lstStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstStockItem.TabStop = true; this.lstStockItem.Visible = true; this.lstStockItem.MultiColumn = false; this.lstStockItem.Name = "lstStockItem"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(215, 19); this.txtSearch.Location = new System.Drawing.Point(48, 57); this.txtSearch.TabIndex = 0; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.tbStockItem.ShowItemToolTips = true; this.tbStockItem.Size = new System.Drawing.Size(272, 40); this.tbStockItem.Location = new System.Drawing.Point(0, 18); this.tbStockItem.TabIndex = 2; this.tbStockItem.ImageList = ilSelect; this.tbStockItem.Name = "tbStockItem"; this._tbStockItem_Button1.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button1.AutoSize = false; this._tbStockItem_Button1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button1.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button1.Text = "&All"; this._tbStockItem_Button1.Name = "All"; this._tbStockItem_Button1.ImageIndex = 0; this._tbStockItem_Button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this._tbStockItem_Button2.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button2.AutoSize = false; this._tbStockItem_Button2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button2.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button2.Text = "&Selected"; this._tbStockItem_Button2.Name = "Selected"; this._tbStockItem_Button2.ImageIndex = 1; this._tbStockItem_Button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this._tbStockItem_Button3.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button3.AutoSize = false; this._tbStockItem_Button3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button3.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button3.Text = "&Unselected"; this._tbStockItem_Button3.Name = "Unselected"; this._tbStockItem_Button3.ImageIndex = 2; this._tbStockItem_Button3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.ilSelect.ImageSize = new System.Drawing.Size(20, 20); this.ilSelect.TransparentColor = System.Drawing.Color.FromArgb(255, 0, 255); this.ilSelect.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("ilSelect.ImageStream"); this.ilSelect.Images.SetKeyName(0, ""); this.ilSelect.Images.SetKeyName(1, ""); this.ilSelect.Images.SetKeyName(2, ""); this.lblHeading.Text = "Label1"; this.lblHeading.Size = new System.Drawing.Size(273, 19); this.lblHeading.Location = new System.Drawing.Point(0, 0); this.lblHeading.TabIndex = 5; this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblHeading.BackColor = System.Drawing.SystemColors.Control; this.lblHeading.Enabled = true; this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.UseMnemonic = true; this.lblHeading.Visible = true; this.lblHeading.AutoSize = false; this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblHeading.Name = "lblHeading"; this._lbl_2.Text = "Search:"; this._lbl_2.Size = new System.Drawing.Size(40, 13); this._lbl_2.Location = new System.Drawing.Point(6, 60); this._lbl_2.TabIndex = 3; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = false; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this.Controls.Add(_cmdClick_1); this.Controls.Add(_cmdClick_2); this.Controls.Add(_cmdClick_3); this.Controls.Add(cmdExit); this.Controls.Add(lstStockItem); this.Controls.Add(txtSearch); this.Controls.Add(tbStockItem); this.Controls.Add(lblHeading); this.Controls.Add(_lbl_2); this.tbStockItem.Items.Add(_tbStockItem_Button1); this.tbStockItem.Items.Add(_tbStockItem_Button2); this.tbStockItem.Items.Add(_tbStockItem_Button3); //Me.cmdClick.SetIndex(_cmdClick_1, CType(1, Short)) //Me.cmdClick.SetIndex(_cmdClick_2, CType(2, Short)) //Me.cmdClick.SetIndex(_cmdClick_3, CType(3, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).EndInit() this.tbStockItem.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; namespace OmniSharp.Utilities { public static class PlatformHelper { private static IEnumerable<string> s_searchPaths; private static string s_monoRuntimePath; private static string s_monoLibDirPath; public static bool IsMono => Type.GetType("Mono.Runtime") != null; public static bool IsWindows => Path.DirectorySeparatorChar == '\\'; public static IEnumerable<string> GetSearchPaths() { if (s_searchPaths == null) { var path = Environment.GetEnvironmentVariable("PATH"); if (path == null) { return Array.Empty<string>(); } s_searchPaths = path .Split(Path.PathSeparator) .Select(p => p.Trim('"')); } return s_searchPaths; } // http://man7.org/linux/man-pages/man3/realpath.3.html // CharSet.Ansi is UTF8 on Unix [DllImport("libc", EntryPoint = "realpath", CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr Unix_realpath(string path, IntPtr buffer); // http://man7.org/linux/man-pages/man3/free.3.html [DllImport("libc", EntryPoint = "free", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] private static extern void Unix_free(IntPtr ptr); /// <summary> /// Returns the conanicalized absolute path from a given path, expanding symbolic links and resolving /// references to /./, /../ and extra '/' path characters. /// </summary> private static string RealPath(string path) { if (IsWindows) { throw new PlatformNotSupportedException($"{nameof(RealPath)} can only be called on Unix."); } var ptr = Unix_realpath(path, IntPtr.Zero); var result = Marshal.PtrToStringAnsi(ptr); // uses UTF8 on Unix Unix_free(ptr); return result; } public static Version GetMonoVersion() { var output = ProcessHelper.RunAndCaptureOutput("mono", "--version"); if (output == null) { return null; } // The mono --version text contains several lines. We'll just walk through the first line, // word by word, until we find a word that parses as a version number. Normally, this should // be the *fifth* word. E.g. "Mono JIT compiler version 4.8.0" var lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var words = lines[0].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var word in words) { if (Version.TryParse(word, out var version)) { return version; } } return null; } public static string GetMonoRuntimePath() { if (IsWindows) { return null; } if (s_monoRuntimePath == null) { var monoPath = GetSearchPaths() .Select(p => Path.Combine(p, "mono")) .FirstOrDefault(File.Exists); if (monoPath == null) { return null; } s_monoRuntimePath = RealPath(monoPath); } return s_monoRuntimePath; } public static string GetMonoLibDirPath() { if (IsWindows) { return null; } const string DefaultMonoLibPath = "/usr/lib/mono"; if (Directory.Exists(DefaultMonoLibPath)) { return DefaultMonoLibPath; } // The normal Unix path doesn't exist, so we'll fallback to finding Mono using the // runtime location. This is the likely situation on macOS. if (s_monoLibDirPath == null) { var monoRuntimePath = GetMonoRuntimePath(); if (monoRuntimePath == null) { return null; } var monoDirPath = Path.GetDirectoryName(monoRuntimePath); var monoLibDirPath = Path.Combine(monoDirPath, "..", "lib", "mono"); monoLibDirPath = Path.GetFullPath(monoLibDirPath); s_monoLibDirPath = Directory.Exists(monoLibDirPath) ? monoLibDirPath : null; } return s_monoLibDirPath; } public static string GetMonoMSBuildDirPath() { if (IsWindows) { return null; } var monoLibDirPath = GetMonoLibDirPath(); if (monoLibDirPath == null) { return null; } var monoMSBuildDirPath = Path.Combine(monoLibDirPath, "msbuild"); monoMSBuildDirPath = Path.GetFullPath(monoMSBuildDirPath); return Directory.Exists(monoMSBuildDirPath) ? monoMSBuildDirPath : null; } public static string GetMonoXBuildDirPath() { if (IsWindows) { return null; } const string DefaultMonoXBuildDirPath = "/usr/lib/mono/xbuild"; if (Directory.Exists(DefaultMonoXBuildDirPath)) { return DefaultMonoXBuildDirPath; } var monoLibDirPath = GetMonoLibDirPath(); if (monoLibDirPath == null) { return null; } var monoXBuildDirPath = Path.Combine(monoLibDirPath, "xbuild"); monoXBuildDirPath = Path.GetFullPath(monoXBuildDirPath); return Directory.Exists(monoXBuildDirPath) ? monoXBuildDirPath : null; } public static string GetMonoXBuildFrameworksDirPath() { if (IsWindows) { return null; } const string DefaultMonoXBuildFrameworksDirPath = "/usr/lib/mono/xbuild-frameworks"; if (Directory.Exists(DefaultMonoXBuildFrameworksDirPath)) { return DefaultMonoXBuildFrameworksDirPath; } var monoLibDirPath = GetMonoLibDirPath(); if (monoLibDirPath == null) { return null; } var monoXBuildFrameworksDirPath = Path.Combine(monoLibDirPath, "xbuild-frameworks"); monoXBuildFrameworksDirPath = Path.GetFullPath(monoXBuildFrameworksDirPath); return Directory.Exists(monoXBuildFrameworksDirPath) ? monoXBuildFrameworksDirPath : null; } } }
//----------------------------------------------------------------------- // <copyright file="Detokenise.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> // This task is a derivative of the task posted here: http://freetodev.spaces.live.com/blog/cns!EC3C8F2028D842D5!244.entry //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.FileSystem { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.Build.Evaluation; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Analyse</i> (<b>Required: </b>TargetFiles or TargetPath <b>Optional: </b> CommandLineValues, DisplayFiles, TextEncoding, ForceWrite, ReplacementValues, Separator, TokenPattern, TokenExtractionPattern <b>Output: </b>FilesProcessed)</para> /// <para><i>Detokenise</i> (<b>Required: </b>TargetFiles or TargetPath <b>Optional: </b> SearchAllStores, IgnoreUnknownTokens, CommandLineValues, DisplayFiles, TextEncoding, ForceWrite, ReplacementValues, Separator, TokenPattern, TokenExtractionPattern <b>Output: </b>FilesProcessed, FilesDetokenised)</para> /// <para><i>Report</i> (<b>Required: </b>TargetFiles or TargetPath <b>Optional: </b> DisplayFiles, TokenPattern, ReportUnusedTokens <b>Output: </b>FilesProcessed, TokenReport, UnusedTokens)</para> /// <para><b>Remote Execution Support:</b> No</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default;Report" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <PropertyGroup> /// <PathToDetokenise>C:\Demo\*</PathToDetokenise> /// <CPHome>www.codeplex.com/MSBuildExtensionPack</CPHome> /// <Title>A New Title</Title> /// <clv>hello=hello#~#hello1=how#~#hello2=are#~#Configuration=debug</clv> /// <Configuration>debug</Configuration> /// <Platform>x86</Platform> /// <HiImAnUnsedToken>TheReportWillFindMe</HiImAnUnsedToken> /// </PropertyGroup> /// <Target Name="Default"> /// <ItemGroup> /// <FileCollection Include="C:\Demo1\TestFile.txt"/> /// <FileCollection2 Include="C:\Demo1\TestFile2.txt"/> /// <FileCollection3 Include="C:\Demo1\TestFile3.txt"/> /// </ItemGroup> /// <ItemGroup> /// <TokenValues Include="Title"> /// <Replacement>ANewTextString</Replacement> /// </TokenValues > /// <TokenValues Include="ProjectHome"> /// <Replacement>www.codeplex.com/MSBuildExtensionPack</Replacement> /// </TokenValues > /// </ItemGroup> /// <!-- Analyse a collection of files. This can be used to ensure that all tokens are known. --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Analyse" TargetFiles="@(FileCollection)" ReplacementValues="@(TokenValues)"/> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Analyse" TargetFiles="@(FileCollection2)"/> /// <!-- 1 Detokenise the files defined in FileCollection and use the TokenValues collection for substitution. --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetFiles="@(FileCollection)" ReplacementValues="@(TokenValues)"/> /// <!-- 2 Detokenise the files defined in FileCollection2 and use the tokens defined by the .proj properties --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetFiles="@(FileCollection2)"/> /// <!-- 3 Detokenise the files at the given TargetPath and perform a recursive search --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetPath="$(PathToDetokenise)"/> /// <!-- 4 This will produce the same result as #3, but no file processing will be logged to the console. Because ForceWrite has been specified, all files will be re-written --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetPath="$(PathToDetokenise)" DisplayFiles="false" ForceWrite="true"/> /// <!-- 5 This will produce the same result as 4, though ForceWrite is false by default so the difference can be displayed using the output parameters --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetPath="$(PathToDetokenise)" DisplayFiles="false"> /// <Output TaskParameter="FilesProcessed" ItemName="FilesProcessed"/> /// <Output TaskParameter="FilesDetokenised" ItemName="FilesDetokenised"/> /// </MSBuild.ExtensionPack.FileSystem.Detokenise> /// <Message Text="FilesDetokenised = @(FilesDetokenised), FilesProcessed = @(FilesProcessed)"/> /// <!-- 6 Detokenise using values that can be passed in via the command line --> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetFiles="@(FileCollection3)" CommandLineValues="$(clv)"/> /// </Target> /// <!--- Generate a report of files showing which tokens are used in files --> /// <Target Name="Report" DependsOnTargets="GetFiles"> /// <CallTarget Targets="List"/> /// </Target> /// <Target Name="List" Inputs="@(Report1)" Outputs="%(Identity)"> /// <Message Text="Token: @(Report1)"/> /// <Message Text="%(Report1.Files)"/> /// </Target> /// <Target Name="GetFiles"> /// <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Report" TargetPath="C:\Demo1*" DisplayFiles="true" ReportUnusedTokens="true"> /// <Output TaskParameter="TokenReport" ItemName="Report1"/> /// <Output TaskParameter="UnusedTokens" ItemName="Unused"/> /// </MSBuild.ExtensionPack.FileSystem.Detokenise> /// <Message Text="Unused Token - %(Unused.Identity)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class Detokenise : BaseTask { private const string AnalyseTaskAction = "Analyse"; private const string DetokeniseTaskAction = "Detokenise"; private const string ReportTaskAction = "Report"; private string tokenExtractionPattern = @"(?<=\$\()[0-9a-zA-Z-._]+(?=\))"; private string tokenPattern = @"\$\([0-9a-zA-Z-._]+\)"; private Project project; private Encoding fileEncoding = Encoding.UTF8; private Regex parseRegex; private bool analyseOnly, report; private string separator = "#~#"; private Dictionary<string, string> commandLineDictionary; private SortedDictionary<string, string> tokenDictionary; private SortedDictionary<string, string> unusedTokens; private string activeFile; // this bool is used to indicate what mode we are in. // if true, then the task has been configured to use a passed in collection // to use as replacement tokens. If false, then it will use the msbuild // proj file for replacement tokens private bool collectionMode = true; // this bool is used to track whether the file needs to be re-written. private bool tokenMatched; /// <summary> /// Set to true for files being processed to be output to the console. /// </summary> public bool DisplayFiles { get; set; } /// <summary> /// Specifies the regular expression format of the token to look for. The default pattern is \$\([0-9a-zA-Z-._]+\) which equates to $(token) /// </summary> public string TokenPattern { get { return this.tokenPattern; } set { this.tokenPattern = value; } } /// <summary> /// Specifies the regular expression to use to extract the token name from the TokenPattern provided. The default pattern is (?&lt;=\$\()[0-9a-zA-Z-._]+(?=\)), i.e it will extract token from $(token) /// </summary> public string TokenExtractionPattern { get { return this.tokenExtractionPattern; } set { this.tokenExtractionPattern = value; } } /// <summary> /// Sets the replacement values. /// </summary> public ITaskItem[] ReplacementValues { get; set; } /// <summary> /// Sets the replacement values provided via the command line. The format is token1=value1#~#token2=value2 etc. /// </summary> public string CommandLineValues { get; set; } /// <summary> /// Sets the separator to use to split the CommandLineValues. The default is #~# /// </summary> public string Separator { get { return this.separator; } set { this.separator = value; } } /// <summary> /// Sets the MSBuild file to load for token matching. Defaults to BuildEngine.ProjectFileOfTaskNode /// </summary> public ITaskItem ProjectFile { get; set; } /// <summary> /// If this is set to true, then the file is re-written, even if no tokens are matched. /// this may be used in the case when the user wants to ensure all file are written /// with the same encoding. /// </summary> public bool ForceWrite { get; set; } /// <summary> /// Specifies whether to search in the ReplacementValues, CommandLineValues and the ProjectFile for token values. Default is false. /// </summary> public bool SearchAllStores { get; set; } /// <summary> /// Specifies whether to ignore tokens which are not matched. Default is false. /// </summary> public bool IgnoreUnknownTokens { get; set; } /// <summary> /// Sets the TargetPath. /// </summary> public string TargetPath { get; set; } /// <summary> /// Sets the TargetFiles. /// </summary> public ITaskItem[] TargetFiles { get; set; } /// <summary> /// The file encoding to write the new file in. The task will attempt to default to the current file encoding. If TargetFiles is specified, individual encodings can be specified by providing an Encoding metadata value. /// </summary> public string TextEncoding { get; set; } /// <summary> /// Gets the files processed count. [Output] /// </summary> [Output] public int FilesProcessed { get; set; } /// <summary> /// Gets the files detokenised count. [Output] /// </summary> [Output] public int FilesDetokenised { get; set; } /// <summary> /// ItemGroup containing the Tokens (Identity) and Files metadata containing all the files in which the token can be found. /// </summary> [Output] public ITaskItem[] TokenReport { get; set; } /// <summary> /// Itemgroup containing the tokens which have been provided but not found in the files scanned. ReportUnusedTokens must be set to true to use this. /// </summary> [Output] public ITaskItem[] UnusedTokens { get; set; } /// <summary> /// Set to true when running a Report to see which tokens are not used in any files scanned. Default is false. /// </summary> public bool ReportUnusedTokens { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } switch (this.TaskAction) { case AnalyseTaskAction: this.analyseOnly = true; break; case DetokeniseTaskAction: break; case ReportTaskAction: this.analyseOnly = true; this.report = true; break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } this.tokenDictionary = new SortedDictionary<string, string>(); this.DoDetokenise(); if (this.tokenDictionary.Count > 0 && this.report) { this.TokenReport = new TaskItem[this.tokenDictionary.Count]; int i = 0; foreach (var s in this.tokenDictionary) { ITaskItem t = new TaskItem(s.Key); t.SetMetadata("Files", s.Value); this.TokenReport[i] = t; i++; } if (this.ReportUnusedTokens) { this.unusedTokens = new SortedDictionary<string, string>(); // Find unused tokens. if (this.collectionMode) { if (this.ReplacementValues != null) { // we need to look in the ReplacementValues for a match foreach (ITaskItem token in this.ReplacementValues) { if (!this.tokenDictionary.ContainsKey(token.ToString()) && !this.unusedTokens.ContainsKey(token.ToString())) { this.unusedTokens.Add(token.ToString(), string.Empty); } } } if (this.commandLineDictionary != null) { foreach (string s in this.commandLineDictionary.Keys) { if (!this.tokenDictionary.ContainsKey(s) && !this.unusedTokens.ContainsKey(s)) { this.unusedTokens.Add(s, string.Empty); } } } } else { foreach (ProjectProperty pp in this.project.Properties) { if (!this.tokenDictionary.ContainsKey(pp.Name) && !this.unusedTokens.ContainsKey(pp.Name)) { this.unusedTokens.Add(pp.Name, string.Empty); } } } this.UnusedTokens = new TaskItem[this.unusedTokens.Count]; i = 0; foreach (var s in this.unusedTokens) { ITaskItem t = new TaskItem(s.Key); this.UnusedTokens[i] = t; i++; } } } } private static Encoding GetTextEncoding(string enc) { switch (enc) { case "DEFAULT": return Encoding.Default; case "ASCII": return Encoding.ASCII; case "Unicode": return Encoding.Unicode; case "UTF7": return Encoding.UTF7; case "UTF8": return Encoding.UTF8; case "UTF32": return Encoding.UTF32; case "BigEndianUnicode": return Encoding.BigEndianUnicode; default: return !string.IsNullOrEmpty(enc) ? Encoding.GetEncoding(enc) : null; } } private void DoDetokenise() { try { this.LogTaskMessage("Detokenise Task Execution Started [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]"); // if the ReplacementValues collection and the CommandLineValues are null, then we need to load // the project file that called this task to get it's properties. if (this.ReplacementValues == null && string.IsNullOrEmpty(this.CommandLineValues)) { this.collectionMode = false; } else if (!string.IsNullOrEmpty(this.CommandLineValues)) { string[] commandLineValuesArray = this.CommandLineValues.Split(new[] { this.Separator }, StringSplitOptions.RemoveEmptyEntries); this.commandLineDictionary = new Dictionary<string, string>(); foreach (string s in commandLineValuesArray) { string[] temp = s.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); this.commandLineDictionary.Add(temp[0], temp[1]); } } if (this.project == null && (!this.collectionMode || this.SearchAllStores)) { // Read the project file to get the tokens string projectFile = this.ProjectFile == null ? this.BuildEngine.ProjectFileOfTaskNode : this.ProjectFile.ItemSpec; this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Loading Project: {0}", projectFile)); this.project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(projectFile).FirstOrDefault(); if (this.project == null) { ProjectCollection.GlobalProjectCollection.LoadProject(projectFile); this.project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(projectFile).FirstOrDefault(); } } if (!string.IsNullOrEmpty(this.TextEncoding)) { try { this.fileEncoding = GetTextEncoding(this.TextEncoding); } catch (ArgumentException) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Error, {0} is not a supported encoding name.", this.TextEncoding)); return; } } // Load the regex to use this.parseRegex = new Regex(this.TokenPattern, RegexOptions.Compiled); // Check to see if we are processing a file collection or a path if (string.IsNullOrEmpty(this.TargetPath) != true) { // we need to process a path this.ProcessPath(); } else { // we need to process a collection this.ProcessCollection(); } } finally { this.LogTaskMessage("Detokenise Task Execution Completed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]"); } } private void ProcessPath() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Detokenising Path: {0}", this.TargetPath)); string originalPath = this.TargetPath; string rootPath = originalPath.Replace("*", string.Empty); // Check if we need to do a recursive search if (originalPath.Contains("*")) { // Need to do a recursive search DirectoryInfo dir = new DirectoryInfo(rootPath); if (!dir.Exists) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The directory does not exist: {0}", rootPath)); throw new ArgumentException("Review error log"); } FileSystemInfo[] infos = dir.GetFileSystemInfos("*"); this.ProcessFolder(infos); } else { // Only need to process the files in the folder provided DirectoryInfo dir = new DirectoryInfo(originalPath); if (!dir.Exists) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The directory does not exist: {0}", rootPath)); throw new ArgumentException("Review error log"); } FileInfo[] fileInfo = dir.GetFiles(); foreach (FileInfo f in fileInfo) { this.tokenMatched = false; this.DetokeniseFileProvided(f.FullName, false, null); } } } private void ProcessFolder(IEnumerable<FileSystemInfo> fileSysInfo) { // Iterate through each item. foreach (FileSystemInfo i in fileSysInfo) { // Check to see if this is a DirectoryInfo object. var info = i as DirectoryInfo; if (info != null) { // Cast the object to a DirectoryInfo object. DirectoryInfo dirInfo = info; // Iterate through all sub-directories. this.ProcessFolder(dirInfo.GetFileSystemInfos("*")); } else if (i is FileInfo) { this.tokenMatched = false; this.DetokeniseFileProvided(i.FullName, false, null); } } } private void ProcessCollection() { if (this.TargetFiles == null) { Log.LogError("The collection passed to TargetFiles is empty"); throw new ArgumentException("Review error log"); } this.LogTaskMessage(this.analyseOnly ? string.Format(CultureInfo.CurrentCulture, "Analysing Collection: {0} files", this.TargetFiles.Length) : string.Format(CultureInfo.CurrentCulture, "Detokenising Collection: {0} files", this.TargetFiles.Length)); foreach (ITaskItem file in this.TargetFiles) { this.tokenMatched = false; this.DetokeniseFileProvided(file.ItemSpec, true, GetTextEncoding(file.GetMetadata("Encoding"))); } } private void DetokeniseFileProvided(string file, bool checkExists, Encoding enc) { this.FilesProcessed++; this.activeFile = file; if (this.DisplayFiles) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Detokenising File: {0}", file)); } Encoding finalEncoding; // See if the file exists if (checkExists && System.IO.File.Exists(file) == false) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "File not found: {0}", file)); throw new ArgumentException("Review error log"); } // Open the file and attempt to read the encoding from the BOM string fileContent; using (StreamReader streamReader = new StreamReader(file, this.fileEncoding, true)) { // Read the file. fileContent = streamReader.ReadToEnd(); finalEncoding = enc ?? (string.IsNullOrEmpty(this.TextEncoding) ? streamReader.CurrentEncoding : this.fileEncoding); } // Parse the file. MatchEvaluator matchEvaluator = this.FindReplacement; string newFile = this.parseRegex.Replace(fileContent, matchEvaluator); // Only write out new content if a replacement was done or ForceWrite has been set if ((this.tokenMatched || this.ForceWrite) && !this.analyseOnly) { // First make sure the file is writable. bool changedAttribute = false; FileAttributes fileAttributes = System.IO.File.GetAttributes(file); // If readonly attribute is set, reset it. if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { this.LogTaskMessage(MessageImportance.Low, "Making file writable"); System.IO.File.SetAttributes(file, fileAttributes ^ FileAttributes.ReadOnly); changedAttribute = true; } // Write out the new file. using (StreamWriter streamWriter = new StreamWriter(file, false, finalEncoding)) { if (this.DisplayFiles) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Re-writing file content: {0}", file)); } streamWriter.Write(newFile); this.FilesDetokenised++; } if (changedAttribute) { this.LogTaskMessage(MessageImportance.Low, "Making file readonly"); System.IO.File.SetAttributes(file, FileAttributes.ReadOnly); } } } private string FindReplacement(Group regexMatch) { // Get the match. string propertyFound = regexMatch.Captures[0].ToString(); // Extract the keyword from the match. string extractedProperty = Regex.Match(propertyFound, this.TokenExtractionPattern).Captures[0].ToString(); // Find the replacement property if (this.collectionMode) { if (this.ReplacementValues != null) { // we need to look in the ReplacementValues for a match foreach (ITaskItem token in this.ReplacementValues) { if (token.ToString() == extractedProperty) { // set the bool so we can write the new file content this.tokenMatched = true; if (this.report) { this.UpdateTokenDictionary(extractedProperty); } return token.GetMetadata("Replacement"); } } if (!this.report && !this.SearchAllStores && !this.IgnoreUnknownTokens) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Property not found: {0}", extractedProperty)); throw new ArgumentException("Review error log"); } } // we need to look in the CommandLineValues if (this.commandLineDictionary != null) { try { string replacement = this.commandLineDictionary[extractedProperty]; // set the bool so we can write the new file content this.tokenMatched = true; if (this.report) { this.UpdateTokenDictionary(extractedProperty); } return replacement; } catch { if (!this.report && !this.SearchAllStores && !this.IgnoreUnknownTokens) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Property not found: {0}", extractedProperty)); throw new ArgumentException("Review error log"); } } } } // we need to look in the calling project's properties collection if (this.project == null || this.project.GetProperty(extractedProperty) == null) { if (!this.report && !this.IgnoreUnknownTokens) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Property not found: {0}", extractedProperty)); throw new ArgumentException("Review error log"); } if (this.IgnoreUnknownTokens) { return string.Format(CultureInfo.InvariantCulture, "$({0})", extractedProperty); } } // set the bool so we can write the new file content this.tokenMatched = true; if (this.report) { this.UpdateTokenDictionary(extractedProperty); } return this.report ? string.Empty : (from p in this.project.Properties where string.Equals(p.Name, extractedProperty, StringComparison.OrdinalIgnoreCase) select p.EvaluatedValue).FirstOrDefault(); } private void UpdateTokenDictionary(string extractedProperty) { if (this.tokenDictionary.ContainsKey(extractedProperty)) { if (!this.tokenDictionary[extractedProperty].Contains(this.activeFile)) { this.tokenDictionary[extractedProperty] += this.activeFile + ";"; } return; } this.tokenDictionary.Add(extractedProperty, this.activeFile + ";"); } } }