context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using IdentityModel; using IdentityServer4; using IdentityServer4.Events; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace IdentityServerHost.Quickstart.UI { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IEventService _events; private readonly ILogger<ExternalController> _logger; public ExternalController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, ILogger<ExternalController> logger) { _userManager = userManager; _signInManager = signInManager; _interaction = interaction; _clientStore = clientStore; _events = events; _logger = logger; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public IActionResult Challenge(string scheme, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", scheme }, } }; return Challenge(props, scheme); } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } if (_logger.IsEnabled(LogLevel.Debug)) { var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}"); _logger.LogDebug("External claims: {@claims}", externalClaims); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = await AutoProvisionUserAsync(provider, providerUserId, claims); } // this allows us to collect any additional claims or properties // for the specific protocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallback(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user // we must issue the cookie maually, and can't use the SignInManager because // it doesn't expose an API to issue additional claims from the login workflow var principal = await _signInManager.CreateUserPrincipalAsync(user); additionalLocalClaims.AddRange(principal.Claims); var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id; var isuser = new IdentityServerUser(user.Id) { DisplayName = name, IdentityProvider = provider, AdditionalClaims = additionalLocalClaims }; await HttpContext.SignInAsync(isuser, localSignInProps); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, name, true, context?.Client.ClientId)); if (context != null) { if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return this.LoadingPage("Redirect", returnUrl); } } return Redirect(returnUrl); } private async Task<(ApplicationUser user, string provider, string providerUserId, IEnumerable<Claim> claims)> FindUserFromExternalProviderAsync(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = await _userManager.FindByLoginAsync(provider, providerUserId); return (user, provider, providerUserId, claims); } private async Task<ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable<Claim> claims) { // create a list of claims that we want to transfer into our store var filtered = new List<Claim>(); // user's display name var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; if (name != null) { filtered.Add(new Claim(JwtClaimTypes.Name, name)); } else { var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value; var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value; if (first != null && last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last)); } else if (first != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first)); } else if (last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, last)); } } // email var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; if (email != null) { filtered.Add(new Claim(JwtClaimTypes.Email, email)); } var user = new ApplicationUser { UserName = Guid.NewGuid().ToString(), }; var identityResult = await _userManager.CreateAsync(user); if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description); if (filtered.Any()) { identityResult = await _userManager.AddClaimsAsync(user, filtered); if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description); } identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider)); if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description); return user; } // if the external login is OIDC-based, there are certain things we need to preserve to make logout work // this will be different for WS-Fed, SAML2p or other protocols private void ProcessLoginCallback(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var idToken = externalResult.Properties.GetTokenValue("id_token"); if (idToken != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = idToken } }); } } } }
using ATL.Logging; using System; using System.IO; using static ATL.AudioData.AudioDataManager; using static ATL.ChannelsArrangements; namespace ATL.AudioData.IO { /// <summary> /// Class for Monkey's Audio file manipulation (extension : .APE) /// </summary> class APE : IAudioDataIO { // Compression level codes public const int MONKEY_COMPRESSION_FAST = 1000; // Fast (poor) public const int MONKEY_COMPRESSION_NORMAL = 2000; // Normal (good) public const int MONKEY_COMPRESSION_HIGH = 3000; // High (very good) public const int MONKEY_COMPRESSION_EXTRA_HIGH = 4000; // Extra high (best) public const int MONKEY_COMPRESSION_INSANE = 5000; // Insane public const int MONKEY_COMPRESSION_BRAINDEAD = 6000; // BrainDead // Compression level names public static readonly string[] MONKEY_COMPRESSION = new string[7] { "Unknown", "Fast", "Normal", "High", "Extra High", "Insane", "BrainDead" }; // Format flags, only for Monkey's Audio <= 3.97 public const byte MONKEY_FLAG_8_BIT = 1; // Audio 8-bit public const byte MONKEY_FLAG_CRC = 2; // New CRC32 error detection public const byte MONKEY_FLAG_PEAK_LEVEL = 4; // Peak level stored public const byte MONKEY_FLAG_24_BIT = 8; // Audio 24-bit public const byte MONKEY_FLAG_SEEK_ELEMENTS = 16; // Number of seek elements stored public const byte MONKEY_FLAG_WAV_NOT_STORED = 32; // WAV header not stored // Channel mode names public static readonly string[] MONKEY_MODE = new string[3] { "Unknown", "Mono", "Stereo" }; ApeHeader header = new ApeHeader(); // common header // Stuff loaded from the header: private int version; private string versionStr; private ChannelsArrangement channelsArrangement; private int sampleRate; private int bits; private uint peakLevel; private double peakLevelRatio; private long totalSamples; private int compressionMode; private string compressionModeStr; // FormatFlags, only used with Monkey's <= 3.97 private int formatFlags; private bool hasPeakLevel; private bool hasSeekElements; private bool wavNotStored; private double bitrate; private double duration; private bool isValid; private AudioDataManager.SizeInfo sizeInfo; private string filePath; // Real structure of Monkey's Audio header // common header for all versions private class ApeHeader { public char[] cID = new char[4]; // should equal 'MAC ' public ushort nVersion; // version number * 1000 (3.81 = 3810) } // old header for <= 3.97 private struct ApeHeaderOld { public ushort nCompressionLevel; // the compression level public ushort nFormatFlags; // any format flags (for future use) public ushort nChannels; // the number of channels (1 or 2) public uint nSampleRate; // the sample rate (typically 44100) public uint nHeaderBytes; // the bytes after the MAC header that compose the WAV header public uint nTerminatingBytes; // the bytes after that raw data (for extended info) public uint nTotalFrames; // the number of frames in the file public uint nFinalFrameBlocks; // the number of samples in the final frame public int nInt; } // new header for >= 3.98 private struct ApeHeaderNew { public ushort nCompressionLevel; // the compression level (see defines I.E. COMPRESSION_LEVEL_FAST) public ushort nFormatFlags; // any format flags (for future use) Note: NOT the same flags as the old header! public uint nBlocksPerFrame; // the number of audio blocks in one frame public uint nFinalFrameBlocks; // the number of audio blocks in the final frame public uint nTotalFrames; // the total number of frames public ushort nBitsPerSample; // the bits per sample (typically 16) public ushort nChannels; // the number of channels (1 or 2) public uint nSampleRate; // the sample rate (typically 44100) } // data descriptor for >= 3.98 private class ApeDescriptor { public ushort padded; // padding/reserved (always empty) public uint nDescriptorBytes; // the number of descriptor bytes (allows later expansion of this header) public uint nHeaderBytes; // the number of header APE_HEADER bytes public uint nSeekTableBytes; // the number of bytes of the seek table public uint nHeaderDataBytes; // the number of header data bytes (from original file) public uint nAPEFrameDataBytes; // the number of bytes of APE frame data public uint nAPEFrameDataBytesHigh; // the high order number of APE frame data bytes public uint nTerminatingDataBytes; // the terminating data of the file (not including tag data) public byte[] cFileMD5 = new byte[16]; // the MD5 hash of the file (see notes for usage... it's a littly tricky) } public int Version { get { return this.version; } } public string VersionStr { get { return this.versionStr; } } public ChannelsArrangement ChannelsArrangement { get { return channelsArrangement; } } public int Bits { get { return this.bits; } } public uint PeakLevel { get { return this.peakLevel; } } public double PeakLevelRatio { get { return this.peakLevelRatio; } } public long TotalSamples { get { return this.totalSamples; } } public int CompressionMode { get { return this.compressionMode; } } public string CompressionModeStr { get { return this.compressionModeStr; } } // FormatFlags, only used with Monkey's <= 3.97 public int FormatFlags { get { return this.formatFlags; } } public bool HasPeakLevel { get { return this.hasPeakLevel; } } public bool HasSeekElements { get { return this.hasSeekElements; } } public bool WavNotStored { get { return this.wavNotStored; } } // ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES public int SampleRate { get { return this.sampleRate; } } public bool IsVBR { get { return false; } } public int CodecFamily { get { return AudioDataIOFactory.CF_LOSSLESS; } } public string FileName { get { return filePath; } } public double BitRate { get { return bitrate; } } public double Duration { get { return duration; } } public bool IsMetaSupported(int metaDataType) { return (metaDataType == MetaDataIOFactory.TAG_APE) || (metaDataType == MetaDataIOFactory.TAG_ID3V1) || (metaDataType == MetaDataIOFactory.TAG_ID3V2); } // ---------- CONSTRUCTORS & INITIALIZERS protected void resetData() { // Reset data isValid = false; version = 0; versionStr = ""; sampleRate = 0; bits = 0; peakLevel = 0; peakLevelRatio = 0.0; totalSamples = 0; compressionMode = 0; compressionModeStr = ""; formatFlags = 0; hasPeakLevel = false; hasSeekElements = false; wavNotStored = false; bitrate = 0; duration = 0; } public APE(string filePath) { this.filePath = filePath; resetData(); } // ---------- SUPPORT METHODS private void readCommonHeader(BinaryReader source) { source.BaseStream.Seek(sizeInfo.ID3v2Size, SeekOrigin.Begin); header.cID = source.ReadChars(4); header.nVersion = source.ReadUInt16(); } public bool Read(BinaryReader source, SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams) { ApeHeaderOld APE_OLD = new ApeHeaderOld(); // old header <= 3.97 ApeHeaderNew APE_NEW = new ApeHeaderNew(); // new header >= 3.98 ApeDescriptor APE_DESC = new ApeDescriptor(); // extra header >= 3.98 int BlocksPerFrame; bool LoadSuccess; bool result = false; this.sizeInfo = sizeInfo; resetData(); // reading data from file LoadSuccess = false; readCommonHeader(source); if (StreamUtils.StringEqualsArr("MAC ", header.cID)) { isValid = true; version = header.nVersion; versionStr = ((double)version / 1000).ToString().Substring(0, 4); //Str(FVersion / 1000 : 4 : 2, FVersionStr); // Load New Monkey's Audio Header for version >= 3.98 if (header.nVersion >= 3980) { APE_DESC.padded = 0; APE_DESC.nDescriptorBytes = 0; APE_DESC.nHeaderBytes = 0; APE_DESC.nSeekTableBytes = 0; APE_DESC.nHeaderDataBytes = 0; APE_DESC.nAPEFrameDataBytes = 0; APE_DESC.nAPEFrameDataBytesHigh = 0; APE_DESC.nTerminatingDataBytes = 0; Array.Clear(APE_DESC.cFileMD5, 0, APE_DESC.cFileMD5.Length); APE_DESC.padded = source.ReadUInt16(); APE_DESC.nDescriptorBytes = source.ReadUInt32(); APE_DESC.nHeaderBytes = source.ReadUInt32(); APE_DESC.nSeekTableBytes = source.ReadUInt32(); APE_DESC.nHeaderDataBytes = source.ReadUInt32(); APE_DESC.nAPEFrameDataBytes = source.ReadUInt32(); APE_DESC.nAPEFrameDataBytesHigh = source.ReadUInt32(); APE_DESC.nTerminatingDataBytes = source.ReadUInt32(); APE_DESC.cFileMD5 = source.ReadBytes(16); // seek past description header if (APE_DESC.nDescriptorBytes != 52) source.BaseStream.Seek(APE_DESC.nDescriptorBytes - 52, SeekOrigin.Current); // load new ape_header if (APE_DESC.nHeaderBytes > 24/*sizeof(APE_NEW)*/) APE_DESC.nHeaderBytes = 24/*sizeof(APE_NEW)*/; APE_NEW.nCompressionLevel = 0; APE_NEW.nFormatFlags = 0; APE_NEW.nBlocksPerFrame = 0; APE_NEW.nFinalFrameBlocks = 0; APE_NEW.nTotalFrames = 0; APE_NEW.nBitsPerSample = 0; APE_NEW.nChannels = 0; APE_NEW.nSampleRate = 0; APE_NEW.nCompressionLevel = source.ReadUInt16(); APE_NEW.nFormatFlags = source.ReadUInt16(); APE_NEW.nBlocksPerFrame = source.ReadUInt32(); APE_NEW.nFinalFrameBlocks = source.ReadUInt32(); APE_NEW.nTotalFrames = source.ReadUInt32(); APE_NEW.nBitsPerSample = source.ReadUInt16(); APE_NEW.nChannels = source.ReadUInt16(); APE_NEW.nSampleRate = source.ReadUInt32(); // based on MAC SDK 3.98a1 (APEinfo.h) sampleRate = (int)APE_NEW.nSampleRate; channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(APE_NEW.nChannels); formatFlags = APE_NEW.nFormatFlags; bits = APE_NEW.nBitsPerSample; compressionMode = APE_NEW.nCompressionLevel; // calculate total uncompressed samples if (APE_NEW.nTotalFrames > 0) { totalSamples = (long)(APE_NEW.nBlocksPerFrame) * (long)(APE_NEW.nTotalFrames - 1) + (long)(APE_NEW.nFinalFrameBlocks); } LoadSuccess = true; } else { // Old Monkey <= 3.97 APE_OLD.nCompressionLevel = 0; APE_OLD.nFormatFlags = 0; APE_OLD.nChannels = 0; APE_OLD.nSampleRate = 0; APE_OLD.nHeaderBytes = 0; APE_OLD.nTerminatingBytes = 0; APE_OLD.nTotalFrames = 0; APE_OLD.nFinalFrameBlocks = 0; APE_OLD.nInt = 0; APE_OLD.nCompressionLevel = source.ReadUInt16(); APE_OLD.nFormatFlags = source.ReadUInt16(); APE_OLD.nChannels = source.ReadUInt16(); APE_OLD.nSampleRate = source.ReadUInt32(); APE_OLD.nHeaderBytes = source.ReadUInt32(); APE_OLD.nTerminatingBytes = source.ReadUInt32(); APE_OLD.nTotalFrames = source.ReadUInt32(); APE_OLD.nFinalFrameBlocks = source.ReadUInt32(); APE_OLD.nInt = source.ReadInt32(); compressionMode = APE_OLD.nCompressionLevel; sampleRate = (int)APE_OLD.nSampleRate; channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(APE_OLD.nChannels); formatFlags = APE_OLD.nFormatFlags; bits = 16; if ((APE_OLD.nFormatFlags & MONKEY_FLAG_8_BIT) != 0) bits = 8; if ((APE_OLD.nFormatFlags & MONKEY_FLAG_24_BIT) != 0) bits = 24; hasSeekElements = ((APE_OLD.nFormatFlags & MONKEY_FLAG_PEAK_LEVEL) != 0); wavNotStored = ((APE_OLD.nFormatFlags & MONKEY_FLAG_SEEK_ELEMENTS) != 0); hasPeakLevel = ((APE_OLD.nFormatFlags & MONKEY_FLAG_WAV_NOT_STORED) != 0); if (hasPeakLevel) { peakLevel = (uint)APE_OLD.nInt; peakLevelRatio = (peakLevel / (1 << bits) / 2.0) * 100.0; } // based on MAC_SDK_397 (APEinfo.cpp) if (version >= 3950) BlocksPerFrame = 73728 * 4; else if ((version >= 3900) || ((version >= 3800) && (MONKEY_COMPRESSION_EXTRA_HIGH == APE_OLD.nCompressionLevel))) BlocksPerFrame = 73728; else BlocksPerFrame = 9216; // calculate total uncompressed samples if (APE_OLD.nTotalFrames > 0) { totalSamples = (long)(APE_OLD.nTotalFrames - 1) * (long)(BlocksPerFrame) + (long)(APE_OLD.nFinalFrameBlocks); } LoadSuccess = true; } if (LoadSuccess) { // compression profile name if ((0 == (compressionMode % 1000)) && (compressionMode <= 6000)) { compressionModeStr = MONKEY_COMPRESSION[compressionMode / 1000]; // int division } else { compressionModeStr = compressionMode.ToString(); } // length if (sampleRate > 0) duration = ((double)totalSamples * 1000.0 / sampleRate); // average bitrate if (duration > 0) bitrate = 8 * (sizeInfo.FileSize - sizeInfo.TotalTagSize) / (duration); // some extra sanity checks isValid = ((bits > 0) && (sampleRate > 0) && (totalSamples > 0) && (channelsArrangement.NbChannels > 0)); result = isValid; } } return result; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.Analyst3D; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Carto; namespace MultiPatchExamples { public partial class MultiPatchExamples : Form { private object _missing = Type.Missing; private IGraphicsContainer3D _axesGraphicsContainer3D; private IGraphicsContainer3D _outlineGraphicsContainer3D; private IGraphicsContainer3D _multiPatchGraphicsContainer3D; public MultiPatchExamples() { InitializeComponent(); Initialize(); } private void Initialize() { _axesGraphicsContainer3D = GraphicsLayer3DUtilities.ConstructGraphicsLayer3D("Axes"); _multiPatchGraphicsContainer3D = GraphicsLayer3DUtilities.ConstructGraphicsLayer3D("MultiPatch"); _outlineGraphicsContainer3D = GraphicsLayer3DUtilities.ConstructGraphicsLayer3D("Outline"); GraphicsLayer3DUtilities.DisableLighting(_multiPatchGraphicsContainer3D); axSceneControl.Scene.AddLayer(_axesGraphicsContainer3D as ILayer, true); axSceneControl.Scene.AddLayer(_multiPatchGraphicsContainer3D as ILayer, true); axSceneControl.Scene.AddLayer(_outlineGraphicsContainer3D as ILayer, true); DrawUtilities.DrawAxes(_axesGraphicsContainer3D); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleStrip1Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleStripExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleStrip2Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleStripExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleStrip3Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleStripExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleStrip4Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleStripExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleStrip5Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleStripExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleFan1Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleFanExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleFan2Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleFanExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleFan3Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleFanExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleFan4Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleFanExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleFan5Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleFanExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangleFan6Button_Click(object sender, EventArgs e) { IGeometry geometry = TriangleFanExamples.GetExample6(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangles1Button_Click(object sender, EventArgs e) { IGeometry geometry = TrianglesExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangles2Button_Click(object sender, EventArgs e) { IGeometry geometry = TrianglesExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangles3Button_Click(object sender, EventArgs e) { IGeometry geometry = TrianglesExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangles4Button_Click(object sender, EventArgs e) { IGeometry geometry = TrianglesExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangles5Button_Click(object sender, EventArgs e) { IGeometry geometry = TrianglesExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void triangles6Button_Click(object sender, EventArgs e) { IGeometry geometry = TrianglesExamples.GetExample6(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ring1Button_Click(object sender, EventArgs e) { IGeometry geometry = RingExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ring2Button_Click(object sender, EventArgs e) { IGeometry geometry = RingExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ring3Button_Click(object sender, EventArgs e) { IGeometry geometry = RingExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ring4Button_Click(object sender, EventArgs e) { IGeometry geometry = RingExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ring5Button_Click(object sender, EventArgs e) { IGeometry geometry = RingExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void vector3D1Button_Click(object sender, EventArgs e) { IGeometry geometry = Vector3DExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void vector3D2Button_Click(object sender, EventArgs e) { IGeometry geometry = Vector3DExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void vector3D3Button_Click(object sender, EventArgs e) { IGeometry geometry = Vector3DExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void transform3D1Button_Click(object sender, EventArgs e) { IGeometry geometry = Transform3DExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void transform3D2Button_Click(object sender, EventArgs e) { IGeometry geometry = Transform3DExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void transform3D3Button_Click(object sender, EventArgs e) { IGeometry geometry = Transform3DExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void transform3D4Button_Click(object sender, EventArgs e) { IGeometry geometry = Transform3DExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion1Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion2Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion3Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion4Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion5Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion6Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample6(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion7Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample7(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ringGroup1Button_Click(object sender, EventArgs e) { IGeometry geometry = RingGroupExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ringGroup2Button_Click(object sender, EventArgs e) { IGeometry geometry = RingGroupExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ringGroup3Button_Click(object sender, EventArgs e) { IGeometry geometry = RingGroupExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ringGroup4Button_Click(object sender, EventArgs e) { IGeometry geometry = RingGroupExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void ringGroup5Button_Click(object sender, EventArgs e) { IGeometry geometry = RingGroupExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion8Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample8(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusionButton9_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample9(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion10Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample10(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion11Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample11(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion12Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample12(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion13Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample13(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void vector3D4Button_Click(object sender, EventArgs e) { IGeometry geometry = Vector3DExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void vector3D5Button_Click(object sender, EventArgs e) { IGeometry geometry = Vector3DExamples.GetExample5(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void composite1Button_Click(object sender, EventArgs e) { IGeometry geometry = CompositeExamples.GetExample1(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void composite2Button_Click(object sender, EventArgs e) { IGeometry geometry = CompositeExamples.GetExample2(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void composite3Button_Click(object sender, EventArgs e) { IGeometry geometry = CompositeExamples.GetExample3(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void composite4Button_Click(object sender, EventArgs e) { IGeometry geometry = CompositeExamples.GetExample4(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion14Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample14(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } private void extrusion15Button_Click(object sender, EventArgs e) { IGeometry geometry = ExtrusionExamples.GetExample15(); DrawUtilities.DrawMultiPatch(_multiPatchGraphicsContainer3D, geometry); DrawUtilities.DrawOutline(_outlineGraphicsContainer3D, geometry); axSceneControl.SceneGraph.RefreshViewers(); } } }
//Copyright (C) 2006 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the CountedSet.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: //Copyright (C) 2003 Thomas Morton // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace OpenNLP.Tools.Util { /// <summary> /// Set which counts the number of times a values are added to it. /// This value can be accessed with the GetCount method. /// </summary> public class CountedSet<T> : ICollection<T> { private readonly IDictionary<T, int> mCountedSet; /// <summary> Creates a new counted set.</summary> public CountedSet() { mCountedSet = new Dictionary<T, int>(); } /// <summary> /// Creates a new counted set of the specified initial size. /// </summary> /// <param name="size"> /// The initial size of this set. /// </param> public CountedSet(int size) { mCountedSet = new Dictionary<T, int>(size); } #region ICollection<T> Members public void Add(T item) { if (mCountedSet.ContainsKey(item)) { mCountedSet[item]++; } else { mCountedSet.Add(item, 1); } } public void Clear() { mCountedSet.Clear(); } public bool Contains(T item) { return mCountedSet.ContainsKey(item); } public void CopyTo(T[] array, int arrayIndex) { throw new NotSupportedException("The method or operation is not implemented."); } public int Count { get { return mCountedSet.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { if (mCountedSet.ContainsKey(item)) { mCountedSet.Remove(item); return true; } return false; } #endregion /// <summary> /// Reduces the count associated with this object by 1. If this causes the count /// to become 0, then the object is removed form the set. /// </summary> /// <param name="item">The item whose count is being reduced. /// </param> public virtual void Subtract(T item) { if (mCountedSet.ContainsKey(item)) { if (mCountedSet[item] > 1) { mCountedSet[item]--; } else { mCountedSet.Remove(item); } } } /// <summary> /// Assigns the specified object the specified count in the set. /// </summary> /// <param name="item"> /// The item to be added or updated in the set. /// </param> /// <param name="count"> /// The count of the specified item. /// </param> public virtual void SetCount(T item, int count) { if (mCountedSet.ContainsKey(item)) { mCountedSet[item] = count; } else { mCountedSet.Add(item, count); } } /// <summary> Return the count of the specified object.</summary> /// <param name="item">the object whose count needs to be determined. /// </param> /// <returns> the count of the specified object. /// </returns> public virtual int GetCount(T item) { if (!mCountedSet.ContainsKey(item)) { return 0; } else { return mCountedSet[item]; } } #region Write methods public virtual void Write(string fileName, int countCutoff) { Write(fileName, countCutoff, " "); } public virtual void Write(string fileName, int countCutoff, string delim) { using (var streamWriter = new StreamWriter(fileName, false)) { foreach (T key in mCountedSet.Keys) { int count = this.GetCount(key); if (count >= countCutoff) { streamWriter.WriteLine(count + delim + key); } } } } public virtual void Write(string fileName, int countCutoff, string delim, System.Text.Encoding encoding) { using (var streamWriter = new StreamWriter(fileName, false, encoding)) { foreach (T key in mCountedSet.Keys) { int count = this.GetCount(key); if (count >= countCutoff) { streamWriter.WriteLine(count + delim + key); } } } } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return new List<T>(mCountedSet.Keys).GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new ArrayList((ICollection) mCountedSet.Keys).GetEnumerator(); } #endregion //public virtual System.Boolean AddAll(System.Collections.ICollection c) //{ // bool changed = false; // //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" // for (System.Collections.IEnumerator ci = c.GetEnumerator(); ci.MoveNext(); ) // { // //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" // changed = changed || Add(ci.Current); // } // return changed; //} ///// <summary> ///// Adds all the elements contained in the specified collection. ///// </summary> ///// <param name="collection"> ///// The collection used to extract the elements that will be added. ///// </param> ///// <returns> ///// Returns true if all the elements were successfuly added. Otherwise returns false. ///// </returns> //public virtual bool AddAll(ICollection<T> collection) //{ // bool result = false; // if (collection != null) // { // foreach (T item in collection) // { // result = this.Add(item); // } // } // return result; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.containsAll' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool containsAll(System.Collections.ICollection c) //{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // return SupportClass.ICollectionSupport.ContainsAll(new HashSet<T>(mCountedSet.Keys), c); //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.isEmpty' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool isEmpty() //{ // return (mCountedSet.Count == 0); //} ////UPGRADE_ISSUE: The equivalent in .NET for method 'java.util.Set.iterator' returns a different type. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1224'" ////GetEnumerator is not virtual in the List<T>, which is the eventual base class ////public override List<T>.Enumerator GetEnumerator() ////{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" //// return new HashSet<T>(cset.Keys).GetEnumerator(); ////} ////UPGRADE_ISSUE: The equivalent in .NET for method 'java.util.Set.remove' returns a different type. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1224'" //public override bool Remove(T o) //{ // if (mCountedSet.ContainsKey(o)) // { // mCountedSet.Remove(o); // return true; // } // return false; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.removeAll' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool removeAll(ICollection<T> c) //{ // bool changed = false; // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" // for (System.Collections.IEnumerator ki = new HashSet<T>(mCountedSet.Keys).GetEnumerator(); ki.MoveNext(); ) // { // System.Object tempObject; // //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" // tempObject = mCountedSet[ki.Current]; // mCountedSet.Remove(ki.Current); // changed = changed || (tempObject != null); // } // return changed; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.retainAll' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool retainAll(System.Collections.ICollection c) //{ // bool changed = false; // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" // for (System.Collections.IEnumerator ki = new SupportClass.HashSetSupport(mCountedSet.Keys).GetEnumerator(); ki.MoveNext(); ) // { // //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" // System.Object key = ki.Current; // if (!SupportClass.ICollectionSupport.Contains(c, key)) // { // mCountedSet.Remove(key); // changed = true; // } // } // return changed; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.toArray' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual System.Object[] toArray() //{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // return SupportClass.ICollectionSupport.ToArray(new SupportClass.HashSetSupport(mCountedSet.Keys)); //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.toArray' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual System.Object[] toArray(System.Object[] arg0) //{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // return SupportClass.ICollectionSupport.ToArray(new SupportClass.HashSetSupport(mCountedSet.Keys), arg0); //} } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace GreyhoundRacing.WebAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.Test; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test { public class UserStoreWithGenericsTest : IdentitySpecificationTestBase<IdentityUserWithGenerics, MyIdentityRole, string>, IClassFixture<ScratchDatabaseFixture> { private readonly ScratchDatabaseFixture _fixture; public UserStoreWithGenericsTest(ScratchDatabaseFixture fixture) { _fixture = fixture; } private ContextWithGenerics CreateContext() { var db = DbUtil.Create<ContextWithGenerics>(_fixture.Connection); db.Database.EnsureCreated(); return db; } protected override object CreateTestContext() { return CreateContext(); } protected override void AddUserStore(IServiceCollection services, object context = null) { services.AddSingleton<IUserStore<IdentityUserWithGenerics>>(new UserStoreWithGenerics((ContextWithGenerics)context, "TestContext")); } protected override void AddRoleStore(IServiceCollection services, object context = null) { services.AddSingleton<IRoleStore<MyIdentityRole>>(new RoleStoreWithGenerics((ContextWithGenerics)context, "TestContext")); } protected override IdentityUserWithGenerics CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "", bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false) { return new IdentityUserWithGenerics { UserName = useNamePrefixAsUserName ? namePrefix : string.Format(CultureInfo.InvariantCulture, "{0}{1}", namePrefix, Guid.NewGuid()), Email = email, PhoneNumber = phoneNumber, LockoutEnabled = lockoutEnabled, LockoutEnd = lockoutEnd }; } protected override MyIdentityRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false) { var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format(CultureInfo.InvariantCulture, "{0}{1}", roleNamePrefix, Guid.NewGuid()); return new MyIdentityRole(roleName); } protected override void SetUserPasswordHash(IdentityUserWithGenerics user, string hashedPassword) { user.PasswordHash = hashedPassword; } protected override Expression<Func<IdentityUserWithGenerics, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName; protected override Expression<Func<MyIdentityRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName; #pragma warning disable CA1310 // Specify StringComparison for correctness protected override Expression<Func<IdentityUserWithGenerics, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName); protected override Expression<Func<MyIdentityRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName); #pragma warning restore CA1310 // Specify StringComparison for correctness [Fact] public void AddEntityFrameworkStoresWithInvalidUserThrows() { var services = new ServiceCollection(); var builder = services.AddIdentity<object, IdentityRole>(); var e = Assert.Throws<InvalidOperationException>(() => builder.AddEntityFrameworkStores<ContextWithGenerics>()); Assert.Contains("AddEntityFrameworkStores", e.Message); } [Fact] public void AddEntityFrameworkStoresWithInvalidRoleThrows() { var services = new ServiceCollection(); var builder = services.AddIdentity<IdentityUser, object>(); var e = Assert.Throws<InvalidOperationException>(() => builder.AddEntityFrameworkStores<ContextWithGenerics>()); Assert.Contains("AddEntityFrameworkStores", e.Message); } [Fact] public async Task CanAddRemoveUserClaimWithIssuer() { var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Claim[] claims = { new Claim("c1", "v1", null, "i1"), new Claim("c2", "v2", null, "i2"), new Claim("c2", "v3", null, "i3") }; foreach (Claim c in claims) { IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c)); } var userId = await manager.GetUserIdAsync(user); var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(3, userClaims.Count); Assert.Equal(3, userClaims.Intersect(claims, ClaimEqualityComparer.Default).Count()); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[0])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(2, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[1])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[2])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(0, userClaims.Count); } [Fact] public async Task RemoveClaimWithIssuerOnlyAffectsUser() { var manager = CreateManager(); var user = CreateTestUser(); var user2 = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user2)); Claim[] claims = { new Claim("c", "v", null, "i1"), new Claim("c2", "v2", null, "i2"), new Claim("c2", "v3", null, "i3") }; foreach (Claim c in claims) { IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user2, c)); } var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(3, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[0])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(2, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[1])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[2])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(0, userClaims.Count); var userClaims2 = await manager.GetClaimsAsync(user2); Assert.Equal(3, userClaims2.Count); } [Fact] public async Task CanReplaceUserClaimWithIssuer() { var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, new Claim("c", "a", "i"))); var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); Claim claim = new Claim("c", "b", "i"); Claim oldClaim = userClaims.FirstOrDefault(); IdentityResultAssert.IsSuccess(await manager.ReplaceClaimAsync(user, oldClaim, claim)); var newUserClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, newUserClaims.Count); Claim newClaim = newUserClaims.FirstOrDefault(); Assert.Equal(claim.Type, newClaim.Type); Assert.Equal(claim.Value, newClaim.Value); Assert.Equal(claim.Issuer, newClaim.Issuer); } } public class ClaimEqualityComparer : IEqualityComparer<Claim> { public static IEqualityComparer<Claim> Default = new ClaimEqualityComparer(); public bool Equals(Claim x, Claim y) { return x.Value == y.Value && x.Type == y.Type && x.Issuer == y.Issuer; } public int GetHashCode(Claim obj) { return 1; } } #region Generic Type defintions public class IdentityUserWithGenerics : IdentityUser<string> { public IdentityUserWithGenerics() { Id = Guid.NewGuid().ToString(); } } public class UserStoreWithGenerics : UserStore<IdentityUserWithGenerics, MyIdentityRole, ContextWithGenerics, string, IdentityUserClaimWithIssuer, IdentityUserRoleWithDate, IdentityUserLoginWithContext, IdentityUserTokenWithStuff, IdentityRoleClaimWithIssuer> { public string LoginContext { get; set; } public UserStoreWithGenerics(ContextWithGenerics context, string loginContext) : base(context) { LoginContext = loginContext; } protected override IdentityUserRoleWithDate CreateUserRole(IdentityUserWithGenerics user, MyIdentityRole role) { return new IdentityUserRoleWithDate() { RoleId = role.Id, UserId = user.Id, Created = DateTime.UtcNow }; } protected override IdentityUserClaimWithIssuer CreateUserClaim(IdentityUserWithGenerics user, Claim claim) { return new IdentityUserClaimWithIssuer { UserId = user.Id, ClaimType = claim.Type, ClaimValue = claim.Value, Issuer = claim.Issuer }; } protected override IdentityUserLoginWithContext CreateUserLogin(IdentityUserWithGenerics user, UserLoginInfo login) { return new IdentityUserLoginWithContext { UserId = user.Id, ProviderKey = login.ProviderKey, LoginProvider = login.LoginProvider, ProviderDisplayName = login.ProviderDisplayName, Context = LoginContext }; } protected override IdentityUserTokenWithStuff CreateUserToken(IdentityUserWithGenerics user, string loginProvider, string name, string value) { return new IdentityUserTokenWithStuff { UserId = user.Id, LoginProvider = loginProvider, Name = name, Value = value, Stuff = "stuff" }; } } public class RoleStoreWithGenerics : RoleStore<MyIdentityRole, ContextWithGenerics, string, IdentityUserRoleWithDate, IdentityRoleClaimWithIssuer> { private string _loginContext; public RoleStoreWithGenerics(ContextWithGenerics context, string loginContext) : base(context) { _loginContext = loginContext; } protected override IdentityRoleClaimWithIssuer CreateRoleClaim(MyIdentityRole role, Claim claim) { return new IdentityRoleClaimWithIssuer { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value, Issuer = claim.Issuer }; } } public class IdentityUserClaimWithIssuer : IdentityUserClaim<string> { public string Issuer { get; set; } public override Claim ToClaim() { return new Claim(ClaimType, ClaimValue, null, Issuer); } public override void InitializeFromClaim(Claim other) { ClaimValue = other.Value; ClaimType = other.Type; Issuer = other.Issuer; } } public class IdentityRoleClaimWithIssuer : IdentityRoleClaim<string> { public string Issuer { get; set; } public override Claim ToClaim() { return new Claim(ClaimType, ClaimValue, null, Issuer); } public override void InitializeFromClaim(Claim other) { ClaimValue = other.Value; ClaimType = other.Type; Issuer = other.Issuer; } } public class IdentityUserRoleWithDate : IdentityUserRole<string> { public DateTime Created { get; set; } } public class MyIdentityRole : IdentityRole<string> { public MyIdentityRole() : base() { Id = Guid.NewGuid().ToString(); } public MyIdentityRole(string roleName) : this() { Name = roleName; } } public class IdentityUserTokenWithStuff : IdentityUserToken<string> { public string Stuff { get; set; } } public class IdentityUserLoginWithContext : IdentityUserLogin<string> { public string Context { get; set; } } public class ContextWithGenerics : IdentityDbContext<IdentityUserWithGenerics, MyIdentityRole, string, IdentityUserClaimWithIssuer, IdentityUserRoleWithDate, IdentityUserLoginWithContext, IdentityRoleClaimWithIssuer, IdentityUserTokenWithStuff> { public ContextWithGenerics(DbContextOptions options) : base(options) { } } #endregion }
#region Header /* * The authors disclaim copyright to this source code. * For more details, see the COPYING file included with this distribution. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Linq; namespace LitJson { internal struct PropertyMetadata { public Type Type { get; set; } public MemberInfo Info { get; set; } public JsonIgnoreWhen Ignore { get; set; } public string Alias { get; set; } public bool IsField { get; set; } public bool Include { get; set; } } internal struct ArrayMetadata { public bool IsArray { get; set; } public bool IsList { get; set; } private Type elemType; public Type ElementType { get { if (elemType == null) { elemType = typeof(JsonData); } return elemType; } set { elemType = value; } } } internal struct ObjectMetadata { public IDictionary<string, PropertyMetadata> Properties { get; set; } public bool IsDictionary { get; set; } private Type elemType; public Type ElementType { get { if (elemType == null) { elemType = typeof(JsonData); } return elemType; } set { elemType = value; } } } internal delegate void ExporterFunc(object obj, JsonWriter writer); public delegate void ExporterFunc<T>(T obj, JsonWriter writer); internal delegate object ImporterFunc(object input); public delegate TValue ImporterFunc<TJson, TValue>(TJson input); internal delegate object FactoryFunc(); public delegate T FactoryFunc<T>(); public delegate IJsonWrapper WrapperFactory(); /// <summary> /// JSON to .Net object and object to JSON conversions. /// </summary> public class JsonMapper { private static readonly int maxNestingDepth; private static readonly IFormatProvider datetimeFormat; private static readonly IDictionary<Type, ExporterFunc> baseExportTable; private static readonly IDictionary<Type, ExporterFunc> customExportTable; private static readonly IDictionary<Type, IDictionary<Type, ImporterFunc>> baseImportTable; private static readonly IDictionary<Type, IDictionary<Type, ImporterFunc>> customImportTable; private static readonly IDictionary<Type, FactoryFunc> customFactoryTable; private static readonly IDictionary<Type, ArrayMetadata> arrayMetadata; private static readonly IDictionary<Type, IDictionary<Type, MethodInfo>> convOps; private static readonly IDictionary<Type, ObjectMetadata> objectMetadata; static JsonMapper() { maxNestingDepth = 100; datetimeFormat = DateTimeFormatInfo.InvariantInfo; arrayMetadata = new Dictionary<Type, ArrayMetadata>(); objectMetadata = new Dictionary<Type, ObjectMetadata>(); convOps = new Dictionary<Type, IDictionary<Type, MethodInfo>>(); baseExportTable = new Dictionary<Type, ExporterFunc>(); customExportTable = new Dictionary<Type, ExporterFunc>(); baseImportTable = new Dictionary<Type, IDictionary<Type, ImporterFunc>>(); customImportTable = new Dictionary<Type, IDictionary<Type, ImporterFunc>>(); customFactoryTable = new Dictionary<Type, FactoryFunc>(); RegisterBaseExporters(); RegisterBaseImporters(); } private static ArrayMetadata AddArrayMetadata(Type type) { if (arrayMetadata.ContainsKey(type)) { return arrayMetadata[type]; } ArrayMetadata data = new ArrayMetadata(); data.IsArray = type.IsArray; if (type.GetInterface("System.Collections.IList") != null) { data.IsList = true; } foreach (PropertyInfo pinfo in type.GetProperties()) { if (pinfo.Name != "Item") { continue; } ParameterInfo[] parameters = pinfo.GetIndexParameters(); if (parameters.Length != 1) { continue; } if (parameters[0].ParameterType == typeof(int)) { data.ElementType = pinfo.PropertyType; } } arrayMetadata[type] = data; return data; } private static ObjectMetadata AddObjectMetadata(Type type) { if (objectMetadata.ContainsKey(type)) { return objectMetadata[type]; } ObjectMetadata data = new ObjectMetadata(); if (type.GetInterface("System.Collections.IDictionary") != null) { data.IsDictionary = true; } data.Properties = new Dictionary<string, PropertyMetadata>(); HashSet<string> ignoredMembers = new HashSet<string>(); object[] memberAttrs = type.GetCustomAttributes(typeof(JsonIgnoreMember), true); foreach (JsonIgnoreMember memberAttr in memberAttrs) { ignoredMembers.UnionWith(memberAttr.Members); } // Get all kinds of declared properties BindingFlags pflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; foreach (PropertyInfo pinfo in type.GetProperties(pflags)) { if (pinfo.Name == "Item") { ParameterInfo[] parameters = pinfo.GetIndexParameters(); if (parameters.Length != 1) { continue; } if (parameters[0].ParameterType == typeof(string)) { data.ElementType = pinfo.PropertyType; } continue; } // Include properties automatically that have at least one public accessor bool autoInclude = (pinfo.GetGetMethod() != null && pinfo.GetGetMethod().IsPublic) || (pinfo.GetSetMethod() != null && pinfo.GetSetMethod().IsPublic); // If neither accessor is public and we don't have a [JsonInclude] attribute, skip it if (!autoInclude && pinfo.GetCustomAttributes(typeof(JsonInclude), true).Count() == 0) { continue; } PropertyMetadata pdata = new PropertyMetadata(); pdata.Info = pinfo; pdata.Type = pinfo.PropertyType; object[] ignoreAttrs = pinfo.GetCustomAttributes(typeof(JsonIgnore), true).ToArray(); if (ignoreAttrs.Length > 0) { pdata.Ignore = ((JsonIgnore)ignoreAttrs[0]).Usage; } else if (ignoredMembers.Contains(pinfo.Name)) { pdata.Ignore = JsonIgnoreWhen.Serializing | JsonIgnoreWhen.Deserializing; } object[] aliasAttrs = pinfo.GetCustomAttributes(typeof(JsonAlias), true).ToArray(); if (aliasAttrs.Length > 0) { JsonAlias aliasAttr = (JsonAlias)aliasAttrs[0]; if (aliasAttr.Alias == pinfo.Name) { throw new JsonException(string.Format("Alias name '{0}' must be different from the property it represents for type '{1}'", pinfo.Name, type)); } if (data.Properties.ContainsKey(aliasAttr.Alias)) { throw new JsonException(string.Format("'{0}' already contains the property or alias name '{1}'", type, aliasAttr.Alias)); } pdata.Alias = aliasAttr.Alias; if (aliasAttr.AcceptOriginal) { data.Properties.Add(pinfo.Name, pdata); } } if (pdata.Alias != null) { data.Properties.Add(pdata.Alias, pdata); } else { if (data.Properties.ContainsKey(pinfo.Name)) { throw new JsonException(string.Format("'{0}' already contains the property or alias name '{1}'", type, pinfo.Name)); } data.Properties.Add(pinfo.Name, pdata); } } // Get all kinds of declared fields BindingFlags fflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; foreach (FieldInfo finfo in type.GetFields(fflags)) { // If the field isn't public and doesn't have an [Include] attribute, skip it if (!finfo.IsPublic && finfo.GetCustomAttributes(typeof(JsonInclude), true).Count() == 0) { continue; } PropertyMetadata pdata = new PropertyMetadata(); pdata.Info = finfo; pdata.IsField = true; pdata.Type = finfo.FieldType; object[] ignoreAttrs = finfo.GetCustomAttributes(typeof(JsonIgnore), true).ToArray(); if (ignoreAttrs.Length > 0) { pdata.Ignore = ((JsonIgnore)ignoreAttrs[0]).Usage; } else if (ignoredMembers.Contains(finfo.Name)) { pdata.Ignore = JsonIgnoreWhen.Serializing | JsonIgnoreWhen.Deserializing; } object[] aliasAttrs = finfo.GetCustomAttributes(typeof(JsonAlias), true).ToArray(); if (aliasAttrs.Length > 0) { JsonAlias aliasAttr = (JsonAlias)aliasAttrs[0]; if (aliasAttr.Alias == finfo.Name) { throw new JsonException(string.Format("Alias name '{0}' must be different from the field it represents for type '{1}'", finfo.Name, type)); } if (data.Properties.ContainsKey(aliasAttr.Alias)) { throw new JsonException(string.Format("'{0}' already contains the field or alias name '{1}'", type, aliasAttr.Alias)); } pdata.Alias = aliasAttr.Alias; if (aliasAttr.AcceptOriginal) { data.Properties.Add(finfo.Name, pdata); } } if (pdata.Alias != null) { data.Properties.Add(pdata.Alias, pdata); } else { if (data.Properties.ContainsKey(finfo.Name)) { throw new JsonException(string.Format("'{0}' already contains the field or alias name '{1}'", type, finfo.Name)); } data.Properties.Add(finfo.Name, pdata); } } objectMetadata.Add(type, data); return data; } private static object CreateInstance(Type type) { FactoryFunc factory; if (customFactoryTable.TryGetValue(type, out factory)) { return factory(); } // construct the new instance with the default constructor (if present), handles structs as well BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; ConstructorInfo constructor = type.GetConstructor(flags, null, new Type[0], null); if (constructor != null) { constructor.Invoke(null); } return Activator.CreateInstance(type); } private static MethodInfo GetConvOp(Type t1, Type t2) { if (!convOps.ContainsKey(t1)) { convOps.Add(t1, new Dictionary<Type, MethodInfo>()); } if (convOps[t1].ContainsKey(t2)) { return convOps[t1][t2]; } MethodInfo op = t1.GetMethod("op_Implicit", new Type[]{t2}); convOps[t1][t2] = op; return op; } private static ImporterFunc GetImporter(Type jsonType, Type valueType) { if (customImportTable.ContainsKey(jsonType) && customImportTable[jsonType].ContainsKey(valueType)) { return customImportTable[jsonType][valueType]; } if (baseImportTable.ContainsKey(jsonType) && baseImportTable[jsonType].ContainsKey(valueType)) { return baseImportTable[jsonType][valueType]; } return null; } private static ExporterFunc GetExporter(Type valueType) { if (customExportTable.ContainsKey(valueType)) { return customExportTable[valueType]; } if (baseExportTable.ContainsKey(valueType)) { return baseExportTable[valueType]; } return null; } private static object ReadValue(Type instType, JsonReader reader) { reader.Read(); if (reader.Token == JsonToken.ArrayEnd) { return null; } Type underlyingType = Nullable.GetUnderlyingType(instType); Type valueType = underlyingType ?? instType; if (reader.Token == JsonToken.Null) { #if JSON_WINRT || (UNITY_METRO && !UNITY_EDITOR) /* IsClass is made a getter here as a comparability patch for WinRT build targets, see Platform.cs */ if (instType.IsClass() || underlyingType != null) { #else if (instType.IsClass || underlyingType != null) { #endif return null; } throw new JsonException(string.Format("Can't assign null to an instance of type {0}", instType)); } if (reader.Token == JsonToken.Real || reader.Token == JsonToken.Natural || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type jsonType = reader.Value.GetType(); if (valueType.IsAssignableFrom(jsonType)) { return reader.Value; } // Try to find a custom or base importer ImporterFunc importer = GetImporter(jsonType, valueType); if (importer != null) { return importer(reader.Value); } // Maybe it's an enum #if JSON_WINRT || (UNITY_METRO && !UNITY_EDITOR) /* IsClass is made a getter here as a comparability patch for WinRT build targets, see Platform.cs */ if (valueType.IsEnum()) { #else if (valueType.IsEnum) { #endif return Enum.ToObject(valueType, reader.Value); } // Try using an implicit conversion operator MethodInfo convOp = GetConvOp(valueType, jsonType); if (convOp != null) { return convOp.Invoke(null, new object[]{reader.Value}); } // No luck throw new JsonException(string.Format("Can't assign value '{0}' (type {1}) to type {2}", reader.Value, jsonType, instType)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { // If there's a custom importer that fits, use it ImporterFunc importer = GetImporter(typeof(JsonData), instType); if (importer != null) { instType = typeof(JsonData); } AddArrayMetadata(instType); ArrayMetadata tdata = arrayMetadata[instType]; if (!tdata.IsArray && !tdata.IsList) { throw new JsonException(string.Format("Type {0} can't act as an array", instType)); } IList list; Type elemType; if (!tdata.IsArray) { list = (IList)CreateInstance(instType); elemType = tdata.ElementType; } else { //list = new ArrayList(); list = new List<object>(); elemType = instType.GetElementType(); } while (true) { object item = ReadValue(elemType, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) { break; } list.Add(item); } if (tdata.IsArray) { int n = list.Count; instance = Array.CreateInstance(elemType, n); for (int i = 0; i < n; i++) { ((Array)instance).SetValue (list[i], i); } } else { instance = list; } if (importer != null) { instance = importer(instance); } } else if (reader.Token == JsonToken.ObjectStart) { bool done = false; string property = null; reader.Read(); if (reader.Token == JsonToken.ObjectEnd) { done = true; } else { property = (string)reader.Value; if (reader.TypeHinting && property == reader.HintTypeName) { reader.Read(); string typeName = (string)reader.Value; reader.Read(); if ((string)reader.Value == reader.HintValueName) { valueType = Type.GetType(typeName); object value = ReadValue(valueType, reader); reader.Read(); if (reader.Token != JsonToken.ObjectEnd) { throw new JsonException(string.Format("Invalid type hinting object, has too many properties: {0}...", reader.Token)); } return value; } else { throw new JsonException(string.Format("Expected \"{0}\" property for type hinting but instead got \"{1}\"", reader.HintValueName, reader.Value)); } } } // If there's a custom importer that fits, use to create a JsonData type instead. // Once the object is deserialzied, it will be invoked to create the actual converted object. ImporterFunc importer = GetImporter(typeof(JsonData), valueType); if (importer != null) { valueType = typeof(JsonData); } ObjectMetadata tdata = AddObjectMetadata(valueType); instance = CreateInstance(valueType); bool firstRun = true; while (!done) { if (firstRun) { firstRun = false; } else { reader.Read(); if (reader.Token == JsonToken.ObjectEnd) { break; } property = (string)reader.Value; } PropertyMetadata pdata; if (tdata.Properties.TryGetValue(property, out pdata)) { // Don't deserialize a field or property that has a JsonIgnore attribute with deserialization usage. if ((pdata.Ignore & JsonIgnoreWhen.Deserializing) > 0) { ReadSkip(reader); continue; } if (pdata.IsField) { ((FieldInfo)pdata.Info).SetValue(instance, ReadValue(pdata.Type, reader)); } else { PropertyInfo pinfo = (PropertyInfo)pdata.Info; if (pinfo.CanWrite) { pinfo.SetValue(instance, ReadValue(pdata.Type, reader), null); } else { ReadValue(pdata.Type, reader); } } } else { if (!tdata.IsDictionary) { if (!reader.SkipNonMembers) { throw new JsonException(string.Format("The type {0} doesn't have the property '{1}'", instType, property)); } else { ReadSkip(reader); continue; } } ((IDictionary)instance).Add(property, ReadValue(tdata.ElementType, reader)); } } if (importer != null) { instance = importer(instance); } } return instance; } private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader) { reader.Read(); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) { return null; } IJsonWrapper instance = factory(); if (reader.Token == JsonToken.String) { instance.SetString((string)reader.Value); return instance; } if (reader.Token == JsonToken.Real) { instance.SetReal((double)reader.Value); return instance; } if (reader.Token == JsonToken.Natural) { instance.SetNatural((long)reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean((bool)reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType(JsonType.Array); while (true) { IJsonWrapper item = ReadValue(factory, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) { break; } ((IList)instance).Add(item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType(JsonType.Object); while (true) { reader.Read(); if (reader.Token == JsonToken.ObjectEnd) { break; } string property = (string)reader.Value; ((IDictionary)instance)[property] = ReadValue(factory, reader); } } return instance; } private static void ReadSkip(JsonReader reader) { ToWrapper(delegate { return new JsonMockWrapper(); }, reader); } private static void RegisterBaseExporters() { baseExportTable[typeof(sbyte)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt64((sbyte)obj)); }; baseExportTable[typeof(byte)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt64((byte)obj)); }; baseExportTable[typeof(char)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToString((char)obj)); }; baseExportTable[typeof(short)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt64((short)obj)); }; baseExportTable[typeof(ushort)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt64((ushort)obj)); }; baseExportTable[typeof(int)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt64((int)obj)); }; baseExportTable[typeof(uint)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToInt64((uint)obj)); }; baseExportTable[typeof(ulong)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToUInt64((ulong)obj)); }; baseExportTable[typeof(float)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToDouble((float)obj)); }; baseExportTable[typeof(decimal)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToDecimal((decimal)obj)); }; baseExportTable[typeof(DateTime)] = delegate(object obj, JsonWriter writer) { writer.Write(Convert.ToString((DateTime)obj, datetimeFormat)); }; } private static void RegisterBaseImporters() { RegisterImporter(baseImportTable, typeof(long), typeof(sbyte), delegate(object input) { return Convert.ToSByte((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(byte), delegate(object input) { return Convert.ToByte((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(short), delegate(object input) { return Convert.ToInt16((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(ushort), delegate(object input) { return Convert.ToUInt16((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(int), delegate(object input) { return Convert.ToInt32((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(uint), delegate(object input) { return Convert.ToUInt32((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(ulong), delegate(object input) { return Convert.ToUInt64((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(float), delegate(object input) { return Convert.ToSingle((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(double), delegate(object input) { return Convert.ToDouble((long)input); }); RegisterImporter(baseImportTable, typeof(long), typeof(decimal), delegate(object input) { return Convert.ToDecimal((long)input); }); RegisterImporter(baseImportTable, typeof(double), typeof(float), delegate(object input) { return Convert.ToSingle((double)input); }); RegisterImporter(baseImportTable, typeof(double), typeof(decimal), delegate(object input) { return Convert.ToDecimal((double)input); }); RegisterImporter(baseImportTable, typeof(string), typeof(char), delegate(object input) { return Convert.ToChar((string)input); }); RegisterImporter(baseImportTable, typeof(string), typeof(DateTime), delegate(object input) { return Convert.ToDateTime((string)input, datetimeFormat); }); } private static void RegisterImporter(IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type jsonType, Type valueType, ImporterFunc importer) { if (!table.ContainsKey(jsonType)) { table.Add(jsonType, new Dictionary<Type, ImporterFunc>()); } table[jsonType][valueType] = importer; } private static void WriteValue(object obj, JsonWriter writer, bool privateWriter, int depth) { if (depth > maxNestingDepth) { throw new JsonException(string.Format("Max allowed object depth reached while trying to export from type {0}", obj.GetType())); } if (obj == null) { writer.Write(null); return; } if (obj is IJsonWrapper) { if (privateWriter) { writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); } else { ((IJsonWrapper)obj).ToJson(writer); } return; } if (obj is string) { writer.Write((string)obj); return; } if (obj is double) { writer.Write((double)obj); return; } if (obj is long) { writer.Write((long)obj); return; } if (obj is bool) { writer.Write((bool)obj); return; } if (obj is Array) { writer.WriteArrayStart(); Array arr = (Array)obj; Type elemType = arr.GetType().GetElementType(); foreach (object elem in arr) { // if the collection contains polymorphic elements, we need to include type information for deserialization if (writer.TypeHinting && elem != null & elem.GetType() != elemType) { writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(elem.GetType().FullName); writer.WritePropertyName(writer.HintValueName); WriteValue(elem, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(elem, writer, privateWriter, depth + 1); } } writer.WriteArrayEnd(); return; } if (obj is IList) { writer.WriteArrayStart(); IList list = (IList)obj; // collection might be non-generic type like Arraylist Type elemType = typeof(object); if (list.GetType().GetGenericArguments().Length > 0) { // collection is a generic type like List<T> elemType = list.GetType().GetGenericArguments()[0]; } foreach (object elem in list) { // if the collection contains polymorphic elements, we need to include type information for deserialization if (writer.TypeHinting && elem != null && elem.GetType() != elemType) { writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(elem.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(elem, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(elem, writer, privateWriter, depth + 1); } } writer.WriteArrayEnd(); return; } if (obj is IDictionary) { writer.WriteObjectStart(); IDictionary dict = (IDictionary)obj; // collection might be non-generic type like Hashtable Type elemType = typeof(object); if (dict.GetType().GetGenericArguments().Length > 1) { // collection is a generic type like Dictionary<T, V> elemType = dict.GetType().GetGenericArguments()[1]; } foreach (DictionaryEntry entry in dict) { writer.WritePropertyName((string)entry.Key); // if the collection contains polymorphic elements, we need to include type information for deserialization if (writer.TypeHinting && entry.Value != null && entry.Value.GetType() != elemType) { writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(entry.Value.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(entry.Value, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(entry.Value, writer, privateWriter, depth + 1); } } writer.WriteObjectEnd(); return; } Type objType = obj.GetType(); // Try a base or custom importer if one exists ExporterFunc exporter = GetExporter(objType); if (exporter != null) { exporter(obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type enumType = Enum.GetUnderlyingType(objType); if (enumType == typeof(long)) { writer.Write((long)obj); } else { ExporterFunc enumConverter = GetExporter(enumType); if (enumConverter != null) { enumConverter(obj, writer); } } return; } // What if it's a Guid? if (obj is System.Guid) { writer.Write(((System.Guid)obj).ToString()); return; } // Okay, it looks like the input should be exported as an object ObjectMetadata tdata = AddObjectMetadata(objType); writer.WriteObjectStart(); foreach (string property in tdata.Properties.Keys) { PropertyMetadata pdata = tdata.Properties[property]; // Don't serialize soft aliases (which get added to ObjectMetadata.Properties twice). if (pdata.Alias != null && property != pdata.Info.Name && tdata.Properties.ContainsKey(pdata.Info.Name)) { continue; } // Don't serialize a field or property with the JsonIgnore attribute with serialization usage if ((pdata.Ignore & JsonIgnoreWhen.Serializing) > 0) { continue; } if (pdata.IsField) { FieldInfo info = (FieldInfo)pdata.Info; if (pdata.Alias != null) { writer.WritePropertyName(pdata.Alias); } else { writer.WritePropertyName(info.Name); } object value = info.GetValue(obj); if (writer.TypeHinting && value != null && info.FieldType != value.GetType()) { // the object stored in the field might be a different type that what was declared, need type hinting writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(value.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(value, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(value, writer, privateWriter, depth + 1); } } else { PropertyInfo info = (PropertyInfo)pdata.Info; if (info.CanRead) { if (pdata.Alias != null) { writer.WritePropertyName(pdata.Alias); } else { writer.WritePropertyName(info.Name); } object value = info.GetValue(obj, null); if (writer.TypeHinting && value != null && info.PropertyType != value.GetType()) { // the object stored in the property might be a different type that what was declared, need type hinting writer.WriteObjectStart(); writer.WritePropertyName(writer.HintTypeName); writer.Write(value.GetType().AssemblyQualifiedName); writer.WritePropertyName(writer.HintValueName); WriteValue(value, writer, privateWriter, depth + 1); writer.WriteObjectEnd(); } else { WriteValue(value, writer, privateWriter, depth + 1); } } } } writer.WriteObjectEnd(); } public static string ToJson(object obj) { JsonWriter writer = new JsonWriter(); WriteValue(obj, writer, true, 0); return writer.ToString(); } public static void ToJson(object obj, JsonWriter writer) { WriteValue(obj, writer, false, 0); } public static JsonData ToObject(JsonReader reader) { return (JsonData)ToWrapper(delegate { return new JsonData(); }, reader); } public static JsonData ToObject(TextReader reader) { JsonReader jsonReader = new JsonReader(reader); return (JsonData)ToWrapper(delegate { return new JsonData(); }, jsonReader); } public static JsonData ToObject(string json) { return (JsonData)ToWrapper(delegate { return new JsonData(); }, json); } public static T ToObject<T>(JsonReader reader) { return (T)ReadValue(typeof(T), reader); } public static T ToObject<T>(TextReader reader) { JsonReader jsonReader = new JsonReader(reader); return (T)ReadValue(typeof(T), jsonReader); } public static T ToObject<T>(string json) { JsonReader reader = new JsonReader(json); return (T)ReadValue(typeof(T), reader); } public static IJsonWrapper ToWrapper(WrapperFactory factory, JsonReader reader) { return ReadValue(factory, reader); } public static IJsonWrapper ToWrapper(WrapperFactory factory, string json) { JsonReader reader = new JsonReader(json); return ReadValue(factory, reader); } public static void RegisterExporter<T>(ExporterFunc<T> exporter) { ExporterFunc wrapper = delegate(object obj, JsonWriter writer) { exporter((T)obj, writer); }; customExportTable[typeof(T)] = wrapper; } public static void RegisterImporter<TJson, TValue>(ImporterFunc<TJson, TValue> importer) { ImporterFunc wrapper = delegate(object input) { return importer((TJson)input); }; RegisterImporter(customImportTable, typeof(TJson), typeof(TValue), wrapper); } public static void RegisterFactory<T>(FactoryFunc<T> factory) { FactoryFunc factoryWrapper = delegate { return factory(); }; customFactoryTable[typeof(T)] = factoryWrapper; } public static void UnregisterFactories() { customFactoryTable.Clear(); } public static void UnregisterExporters() { customExportTable.Clear(); } public static void UnregisterImporters() { customImportTable.Clear(); } } }
/** Copyright 2012 Useless Random Thought Software 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.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Timers; using System.Media; using System.Threading; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; namespace ToddlerTyper { public partial class MainWindow : Form { //*****************************************************************************************/ // setting up unmanaged code path // Structure contain information about low-level keyboard input event [StructLayout(LayoutKind.Sequential)] private struct KBDLLHOOKSTRUCT { public Keys key; public int scanCode; public int flags; public int time; public IntPtr extra; } //System level functions to be used for hook and unhook keyboard input private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool UnhookWindowsHookEx(IntPtr hook); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string name); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern short GetAsyncKeyState(Keys key); //Declaring Global objects private IntPtr ptrHook; private LowLevelKeyboardProc objKeyboardProcess; /* * Setting up special key interceptor */ private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp) { if (nCode >= 0) { KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT)); if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin) // Disabling Windows keys { return (IntPtr)1; } } return CallNextHookEx(ptrHook, nCode, wp, lp); } //*****************************************************************************************/ /** * Constructor * */ public MainWindow() { ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule; //Get Current Module objKeyboardProcess = new LowLevelKeyboardProc(captureKey); //Assign callback function each time keyboard process ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0); //Setting Hook of Keyboard Process for current module InitializeComponent(); Init(); } //*****************************************************************************************/ // manager singleton objects private ElementAssetManager elementAssetManager = new ElementAssetManager(); private SoundManager soundManager = new SoundManager(); private DrawElementManager drawElementManager = new DrawElementManager(); //*****************************************************************************************/ private void Init() { // setup timer frameRefreshTimer = new System.Timers.Timer(); frameRefreshTimer.Elapsed += new ElapsedEventHandler(OnRefreshEvent); frameRefreshTimer.Interval = 68; frameRefreshTimer.Enabled = true; frameRefreshTimer.Start(); frameRateTimer = new System.Timers.Timer(); frameRateTimer.Elapsed += new ElapsedEventHandler(OnFrameRateCheck); frameRateTimer.Interval = 2000; frameRateTimer.Enabled = true; frameRateTimer.Start(); } //*****************************************************************************************/ private void OnFrameRateCheck(object sender, ElapsedEventArgs e) { int elementCount = 0; LinkedList<DrawElement> elements = drawElementManager.getElements(); lock (elements) { elementCount = elements.Count; } GC.Collect(); frameRate = frameCount / 2; frameCount = 0; } private void OnRefreshEvent(object sender, ElapsedEventArgs e) { // The force the window to redraw drawElementManager.nextFrame(); Invalidate(); } //*****************************************************************************************/ private System.Timers.Timer frameRefreshTimer; private System.Timers.Timer frameRateTimer; private int lastKey = 0; private int frameCount = 0; private float frameRate = 0; private long frameTotal = 0; //*****************************************************************************************/ // System Events private void MainWindow_Paint(object sender, PaintEventArgs e) { // wipe the screen e.Graphics.Clear(Color.White); // draw the instructions Font drawFont = new Font("Arial", 12); SolidBrush drawBrush = new SolidBrush(Color.Black); // Set format of string. StringFormat drawFormat = new StringFormat(); drawFormat.FormatFlags = StringFormatFlags.DirectionVertical; // draw string e.Graphics.DrawString(Properties.Resources.instructions, drawFont, drawBrush, 0, 0, drawFormat); if (frameTotal < 20 || (frameTotal < 600 && lastKey == 0)) { e.Graphics.DrawString(Properties.Resources.copyright, drawFont, drawBrush, 100, 200); } // paint each element LinkedList<DrawElement> elements = drawElementManager.getElements(); lock (elements) { foreach (DrawElement element in elements) { element.draw(e.Graphics); } } // display debugging info frameCount++; frameTotal++; //#if DEBUG // string drawString = "Element Count: " + elements.Count + " Frame Rate: " + frameRate + " Last Key: " + lastKey; // // Draw string to screen. // e.Graphics.DrawString(drawString, drawFont, drawBrush, 30, 0, drawFormat); //#endif } private void MainWindow_Load(object sender, EventArgs e) { Cursor.Hide(); drawElementManager.setScreenHeight(this.Height); drawElementManager.setScreenWidth(this.Width); } private void MainWindow_ResizeEnd(object sender, EventArgs e) { drawElementManager.setScreenHeight(this.Height); drawElementManager.setScreenWidth(this.Width); } private void MainWindow_FormClosing(object sender, FormClosingEventArgs e) { soundManager.Shutdown(); drawElementManager.Shutdown(); } protected override void OnPaintBackground(PaintEventArgs pevent) { //NOTE: overriding to prevent tearing and other nasty graphical stuffs... // and yes... we really are doing NOTHING here. } /* * * We only want one event per key press. We dedupe the "down" events * by only counting them once. * */ private bool keyDown = false; private void MainWindow_KeyDown(object sender, KeyEventArgs e) { if (keyDown) return; lastKey = e.KeyValue; RunEvent(e.KeyValue); keyDown = true; } private void MainWindow_KeyUp(object sender, KeyEventArgs e) { keyDown = false; } private void MainWindow_Leave(object sender, EventArgs e) { // Get the window to the front. this.TopMost = true; this.TopMost = false; // 'Steal' the focus. this.Activate(); } private void MainWindow_MouseDown(object sender, MouseEventArgs e) { RunEvent(0, e.X, e.Y); } //*****************************************************************************************/ // Element Randomizer private void RunEvent(int key) { RunEvent(key, -1, -1); } private void RunEvent(int key, int posX, int posY) { // notify the element manager of current screen size drawElementManager.setScreenHeight(this.Height); drawElementManager.setScreenWidth(this.Width); // grab an element asset ElementAsset asset = elementAssetManager.getElementAsset(key); if (asset.getImageFileName() == null) { // elements with no images are useless return; } DrawElementRequest request = new DrawElementRequest(asset, posX, posY, this.Height, this.Width); drawElementManager.addRandomDrawElement(request); // play sound if (asset.getSoundFileName() != null) { soundManager.playSound(new SoundEvent(asset.getSoundFileName())); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Container.V1 { /// <summary> /// Google Container Engine Cluster Manager v1 /// </summary> public static class ClusterManager { static readonly string __ServiceName = "google.container.v1.ClusterManager"; static readonly Marshaller<global::Google.Container.V1.ListClustersRequest> __Marshaller_ListClustersRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ListClustersRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.ListClustersResponse> __Marshaller_ListClustersResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ListClustersResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.GetClusterRequest> __Marshaller_GetClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.GetClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.Cluster> __Marshaller_Cluster = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.Cluster.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.CreateClusterRequest> __Marshaller_CreateClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.CreateClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.Operation> __Marshaller_Operation = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.Operation.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.UpdateClusterRequest> __Marshaller_UpdateClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.UpdateClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.DeleteClusterRequest> __Marshaller_DeleteClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.DeleteClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.ListOperationsRequest> __Marshaller_ListOperationsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ListOperationsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.ListOperationsResponse> __Marshaller_ListOperationsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ListOperationsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.GetOperationRequest> __Marshaller_GetOperationRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.GetOperationRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.CancelOperationRequest> __Marshaller_CancelOperationRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.CancelOperationRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.GetServerConfigRequest> __Marshaller_GetServerConfigRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.GetServerConfigRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.ServerConfig> __Marshaller_ServerConfig = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ServerConfig.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.ListNodePoolsRequest> __Marshaller_ListNodePoolsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ListNodePoolsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.ListNodePoolsResponse> __Marshaller_ListNodePoolsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.ListNodePoolsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.GetNodePoolRequest> __Marshaller_GetNodePoolRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.GetNodePoolRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.NodePool> __Marshaller_NodePool = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.NodePool.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.CreateNodePoolRequest> __Marshaller_CreateNodePoolRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.CreateNodePoolRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.DeleteNodePoolRequest> __Marshaller_DeleteNodePoolRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.DeleteNodePoolRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.RollbackNodePoolUpgradeRequest> __Marshaller_RollbackNodePoolUpgradeRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.RollbackNodePoolUpgradeRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Container.V1.SetNodePoolManagementRequest> __Marshaller_SetNodePoolManagementRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Container.V1.SetNodePoolManagementRequest.Parser.ParseFrom); static readonly Method<global::Google.Container.V1.ListClustersRequest, global::Google.Container.V1.ListClustersResponse> __Method_ListClusters = new Method<global::Google.Container.V1.ListClustersRequest, global::Google.Container.V1.ListClustersResponse>( MethodType.Unary, __ServiceName, "ListClusters", __Marshaller_ListClustersRequest, __Marshaller_ListClustersResponse); static readonly Method<global::Google.Container.V1.GetClusterRequest, global::Google.Container.V1.Cluster> __Method_GetCluster = new Method<global::Google.Container.V1.GetClusterRequest, global::Google.Container.V1.Cluster>( MethodType.Unary, __ServiceName, "GetCluster", __Marshaller_GetClusterRequest, __Marshaller_Cluster); static readonly Method<global::Google.Container.V1.CreateClusterRequest, global::Google.Container.V1.Operation> __Method_CreateCluster = new Method<global::Google.Container.V1.CreateClusterRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "CreateCluster", __Marshaller_CreateClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.UpdateClusterRequest, global::Google.Container.V1.Operation> __Method_UpdateCluster = new Method<global::Google.Container.V1.UpdateClusterRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "UpdateCluster", __Marshaller_UpdateClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.DeleteClusterRequest, global::Google.Container.V1.Operation> __Method_DeleteCluster = new Method<global::Google.Container.V1.DeleteClusterRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "DeleteCluster", __Marshaller_DeleteClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.ListOperationsRequest, global::Google.Container.V1.ListOperationsResponse> __Method_ListOperations = new Method<global::Google.Container.V1.ListOperationsRequest, global::Google.Container.V1.ListOperationsResponse>( MethodType.Unary, __ServiceName, "ListOperations", __Marshaller_ListOperationsRequest, __Marshaller_ListOperationsResponse); static readonly Method<global::Google.Container.V1.GetOperationRequest, global::Google.Container.V1.Operation> __Method_GetOperation = new Method<global::Google.Container.V1.GetOperationRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "GetOperation", __Marshaller_GetOperationRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.CancelOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CancelOperation = new Method<global::Google.Container.V1.CancelOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "CancelOperation", __Marshaller_CancelOperationRequest, __Marshaller_Empty); static readonly Method<global::Google.Container.V1.GetServerConfigRequest, global::Google.Container.V1.ServerConfig> __Method_GetServerConfig = new Method<global::Google.Container.V1.GetServerConfigRequest, global::Google.Container.V1.ServerConfig>( MethodType.Unary, __ServiceName, "GetServerConfig", __Marshaller_GetServerConfigRequest, __Marshaller_ServerConfig); static readonly Method<global::Google.Container.V1.ListNodePoolsRequest, global::Google.Container.V1.ListNodePoolsResponse> __Method_ListNodePools = new Method<global::Google.Container.V1.ListNodePoolsRequest, global::Google.Container.V1.ListNodePoolsResponse>( MethodType.Unary, __ServiceName, "ListNodePools", __Marshaller_ListNodePoolsRequest, __Marshaller_ListNodePoolsResponse); static readonly Method<global::Google.Container.V1.GetNodePoolRequest, global::Google.Container.V1.NodePool> __Method_GetNodePool = new Method<global::Google.Container.V1.GetNodePoolRequest, global::Google.Container.V1.NodePool>( MethodType.Unary, __ServiceName, "GetNodePool", __Marshaller_GetNodePoolRequest, __Marshaller_NodePool); static readonly Method<global::Google.Container.V1.CreateNodePoolRequest, global::Google.Container.V1.Operation> __Method_CreateNodePool = new Method<global::Google.Container.V1.CreateNodePoolRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "CreateNodePool", __Marshaller_CreateNodePoolRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.DeleteNodePoolRequest, global::Google.Container.V1.Operation> __Method_DeleteNodePool = new Method<global::Google.Container.V1.DeleteNodePoolRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "DeleteNodePool", __Marshaller_DeleteNodePoolRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.RollbackNodePoolUpgradeRequest, global::Google.Container.V1.Operation> __Method_RollbackNodePoolUpgrade = new Method<global::Google.Container.V1.RollbackNodePoolUpgradeRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "RollbackNodePoolUpgrade", __Marshaller_RollbackNodePoolUpgradeRequest, __Marshaller_Operation); static readonly Method<global::Google.Container.V1.SetNodePoolManagementRequest, global::Google.Container.V1.Operation> __Method_SetNodePoolManagement = new Method<global::Google.Container.V1.SetNodePoolManagementRequest, global::Google.Container.V1.Operation>( MethodType.Unary, __ServiceName, "SetNodePoolManagement", __Marshaller_SetNodePoolManagementRequest, __Marshaller_Operation); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Container.V1.ClusterServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of ClusterManager</summary> public abstract class ClusterManagerBase { /// <summary> /// Lists all clusters owned by a project in either the specified zone or all /// zones. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.ListClustersResponse> ListClusters(global::Google.Container.V1.ListClustersRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets the details of a specific cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Cluster> GetCluster(global::Google.Container.V1.GetClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a cluster, consisting of the specified number and type of Google /// Compute Engine instances. /// /// By default, the cluster is created in the project's /// [default network](/compute/docs/networks-and-firewalls#networks). /// /// One firewall is added for the cluster. After cluster creation, /// the cluster creates routes for each node to allow the containers /// on that node to communicate with all other instances in the /// cluster. /// /// Finally, an entry is added to the project's global metadata indicating /// which CIDR range is being used by the cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> CreateCluster(global::Google.Container.V1.CreateClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Updates the settings of a specific cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> UpdateCluster(global::Google.Container.V1.UpdateClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes the cluster, including the Kubernetes endpoint and all worker /// nodes. /// /// Firewalls and routes that were configured during cluster creation /// are also deleted. /// /// Other Google Compute Engine resources that might be in use by the cluster /// (e.g. load balancer resources) will not be deleted if they weren't present /// at the initial create time. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> DeleteCluster(global::Google.Container.V1.DeleteClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists all operations in a project in a specific zone or all zones. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.ListOperationsResponse> ListOperations(global::Google.Container.V1.ListOperationsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets the specified operation. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> GetOperation(global::Google.Container.V1.GetOperationRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Cancels the specified operation. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CancelOperation(global::Google.Container.V1.CancelOperationRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Returns configuration info about the Container Engine service. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.ServerConfig> GetServerConfig(global::Google.Container.V1.GetServerConfigRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists the node pools for a cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.ListNodePoolsResponse> ListNodePools(global::Google.Container.V1.ListNodePoolsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Retrieves the node pool requested. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.NodePool> GetNodePool(global::Google.Container.V1.GetNodePoolRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a node pool for a cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> CreateNodePool(global::Google.Container.V1.CreateNodePoolRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a node pool from a cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> DeleteNodePool(global::Google.Container.V1.DeleteNodePoolRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Roll back the previously Aborted or Failed NodePool upgrade. /// This will be an no-op if the last upgrade successfully completed. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> RollbackNodePoolUpgrade(global::Google.Container.V1.RollbackNodePoolUpgradeRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Sets the NodeManagement options for a node pool. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Container.V1.Operation> SetNodePoolManagement(global::Google.Container.V1.SetNodePoolManagementRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for ClusterManager</summary> public class ClusterManagerClient : ClientBase<ClusterManagerClient> { /// <summary>Creates a new client for ClusterManager</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ClusterManagerClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for ClusterManager that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ClusterManagerClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ClusterManagerClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ClusterManagerClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists all clusters owned by a project in either the specified zone or all /// zones. /// </summary> public virtual global::Google.Container.V1.ListClustersResponse ListClusters(global::Google.Container.V1.ListClustersRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListClusters(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists all clusters owned by a project in either the specified zone or all /// zones. /// </summary> public virtual global::Google.Container.V1.ListClustersResponse ListClusters(global::Google.Container.V1.ListClustersRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListClusters, null, options, request); } /// <summary> /// Lists all clusters owned by a project in either the specified zone or all /// zones. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ListClustersResponse> ListClustersAsync(global::Google.Container.V1.ListClustersRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListClustersAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists all clusters owned by a project in either the specified zone or all /// zones. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ListClustersResponse> ListClustersAsync(global::Google.Container.V1.ListClustersRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListClusters, null, options, request); } /// <summary> /// Gets the details of a specific cluster. /// </summary> public virtual global::Google.Container.V1.Cluster GetCluster(global::Google.Container.V1.GetClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the details of a specific cluster. /// </summary> public virtual global::Google.Container.V1.Cluster GetCluster(global::Google.Container.V1.GetClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetCluster, null, options, request); } /// <summary> /// Gets the details of a specific cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Cluster> GetClusterAsync(global::Google.Container.V1.GetClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the details of a specific cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Cluster> GetClusterAsync(global::Google.Container.V1.GetClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetCluster, null, options, request); } /// <summary> /// Creates a cluster, consisting of the specified number and type of Google /// Compute Engine instances. /// /// By default, the cluster is created in the project's /// [default network](/compute/docs/networks-and-firewalls#networks). /// /// One firewall is added for the cluster. After cluster creation, /// the cluster creates routes for each node to allow the containers /// on that node to communicate with all other instances in the /// cluster. /// /// Finally, an entry is added to the project's global metadata indicating /// which CIDR range is being used by the cluster. /// </summary> public virtual global::Google.Container.V1.Operation CreateCluster(global::Google.Container.V1.CreateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a cluster, consisting of the specified number and type of Google /// Compute Engine instances. /// /// By default, the cluster is created in the project's /// [default network](/compute/docs/networks-and-firewalls#networks). /// /// One firewall is added for the cluster. After cluster creation, /// the cluster creates routes for each node to allow the containers /// on that node to communicate with all other instances in the /// cluster. /// /// Finally, an entry is added to the project's global metadata indicating /// which CIDR range is being used by the cluster. /// </summary> public virtual global::Google.Container.V1.Operation CreateCluster(global::Google.Container.V1.CreateClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateCluster, null, options, request); } /// <summary> /// Creates a cluster, consisting of the specified number and type of Google /// Compute Engine instances. /// /// By default, the cluster is created in the project's /// [default network](/compute/docs/networks-and-firewalls#networks). /// /// One firewall is added for the cluster. After cluster creation, /// the cluster creates routes for each node to allow the containers /// on that node to communicate with all other instances in the /// cluster. /// /// Finally, an entry is added to the project's global metadata indicating /// which CIDR range is being used by the cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> CreateClusterAsync(global::Google.Container.V1.CreateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a cluster, consisting of the specified number and type of Google /// Compute Engine instances. /// /// By default, the cluster is created in the project's /// [default network](/compute/docs/networks-and-firewalls#networks). /// /// One firewall is added for the cluster. After cluster creation, /// the cluster creates routes for each node to allow the containers /// on that node to communicate with all other instances in the /// cluster. /// /// Finally, an entry is added to the project's global metadata indicating /// which CIDR range is being used by the cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> CreateClusterAsync(global::Google.Container.V1.CreateClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateCluster, null, options, request); } /// <summary> /// Updates the settings of a specific cluster. /// </summary> public virtual global::Google.Container.V1.Operation UpdateCluster(global::Google.Container.V1.UpdateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates the settings of a specific cluster. /// </summary> public virtual global::Google.Container.V1.Operation UpdateCluster(global::Google.Container.V1.UpdateClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateCluster, null, options, request); } /// <summary> /// Updates the settings of a specific cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> UpdateClusterAsync(global::Google.Container.V1.UpdateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates the settings of a specific cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> UpdateClusterAsync(global::Google.Container.V1.UpdateClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateCluster, null, options, request); } /// <summary> /// Deletes the cluster, including the Kubernetes endpoint and all worker /// nodes. /// /// Firewalls and routes that were configured during cluster creation /// are also deleted. /// /// Other Google Compute Engine resources that might be in use by the cluster /// (e.g. load balancer resources) will not be deleted if they weren't present /// at the initial create time. /// </summary> public virtual global::Google.Container.V1.Operation DeleteCluster(global::Google.Container.V1.DeleteClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the cluster, including the Kubernetes endpoint and all worker /// nodes. /// /// Firewalls and routes that were configured during cluster creation /// are also deleted. /// /// Other Google Compute Engine resources that might be in use by the cluster /// (e.g. load balancer resources) will not be deleted if they weren't present /// at the initial create time. /// </summary> public virtual global::Google.Container.V1.Operation DeleteCluster(global::Google.Container.V1.DeleteClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteCluster, null, options, request); } /// <summary> /// Deletes the cluster, including the Kubernetes endpoint and all worker /// nodes. /// /// Firewalls and routes that were configured during cluster creation /// are also deleted. /// /// Other Google Compute Engine resources that might be in use by the cluster /// (e.g. load balancer resources) will not be deleted if they weren't present /// at the initial create time. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> DeleteClusterAsync(global::Google.Container.V1.DeleteClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the cluster, including the Kubernetes endpoint and all worker /// nodes. /// /// Firewalls and routes that were configured during cluster creation /// are also deleted. /// /// Other Google Compute Engine resources that might be in use by the cluster /// (e.g. load balancer resources) will not be deleted if they weren't present /// at the initial create time. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> DeleteClusterAsync(global::Google.Container.V1.DeleteClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteCluster, null, options, request); } /// <summary> /// Lists all operations in a project in a specific zone or all zones. /// </summary> public virtual global::Google.Container.V1.ListOperationsResponse ListOperations(global::Google.Container.V1.ListOperationsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListOperations(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists all operations in a project in a specific zone or all zones. /// </summary> public virtual global::Google.Container.V1.ListOperationsResponse ListOperations(global::Google.Container.V1.ListOperationsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListOperations, null, options, request); } /// <summary> /// Lists all operations in a project in a specific zone or all zones. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ListOperationsResponse> ListOperationsAsync(global::Google.Container.V1.ListOperationsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListOperationsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists all operations in a project in a specific zone or all zones. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ListOperationsResponse> ListOperationsAsync(global::Google.Container.V1.ListOperationsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListOperations, null, options, request); } /// <summary> /// Gets the specified operation. /// </summary> public virtual global::Google.Container.V1.Operation GetOperation(global::Google.Container.V1.GetOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOperation(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the specified operation. /// </summary> public virtual global::Google.Container.V1.Operation GetOperation(global::Google.Container.V1.GetOperationRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetOperation, null, options, request); } /// <summary> /// Gets the specified operation. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> GetOperationAsync(global::Google.Container.V1.GetOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOperationAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the specified operation. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> GetOperationAsync(global::Google.Container.V1.GetOperationRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetOperation, null, options, request); } /// <summary> /// Cancels the specified operation. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelOperation(global::Google.Container.V1.CancelOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelOperation(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Cancels the specified operation. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelOperation(global::Google.Container.V1.CancelOperationRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CancelOperation, null, options, request); } /// <summary> /// Cancels the specified operation. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelOperationAsync(global::Google.Container.V1.CancelOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelOperationAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Cancels the specified operation. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelOperationAsync(global::Google.Container.V1.CancelOperationRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CancelOperation, null, options, request); } /// <summary> /// Returns configuration info about the Container Engine service. /// </summary> public virtual global::Google.Container.V1.ServerConfig GetServerConfig(global::Google.Container.V1.GetServerConfigRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetServerConfig(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns configuration info about the Container Engine service. /// </summary> public virtual global::Google.Container.V1.ServerConfig GetServerConfig(global::Google.Container.V1.GetServerConfigRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetServerConfig, null, options, request); } /// <summary> /// Returns configuration info about the Container Engine service. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ServerConfig> GetServerConfigAsync(global::Google.Container.V1.GetServerConfigRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetServerConfigAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns configuration info about the Container Engine service. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ServerConfig> GetServerConfigAsync(global::Google.Container.V1.GetServerConfigRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetServerConfig, null, options, request); } /// <summary> /// Lists the node pools for a cluster. /// </summary> public virtual global::Google.Container.V1.ListNodePoolsResponse ListNodePools(global::Google.Container.V1.ListNodePoolsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListNodePools(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the node pools for a cluster. /// </summary> public virtual global::Google.Container.V1.ListNodePoolsResponse ListNodePools(global::Google.Container.V1.ListNodePoolsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListNodePools, null, options, request); } /// <summary> /// Lists the node pools for a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ListNodePoolsResponse> ListNodePoolsAsync(global::Google.Container.V1.ListNodePoolsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListNodePoolsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the node pools for a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.ListNodePoolsResponse> ListNodePoolsAsync(global::Google.Container.V1.ListNodePoolsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListNodePools, null, options, request); } /// <summary> /// Retrieves the node pool requested. /// </summary> public virtual global::Google.Container.V1.NodePool GetNodePool(global::Google.Container.V1.GetNodePoolRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetNodePool(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Retrieves the node pool requested. /// </summary> public virtual global::Google.Container.V1.NodePool GetNodePool(global::Google.Container.V1.GetNodePoolRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetNodePool, null, options, request); } /// <summary> /// Retrieves the node pool requested. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.NodePool> GetNodePoolAsync(global::Google.Container.V1.GetNodePoolRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetNodePoolAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Retrieves the node pool requested. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.NodePool> GetNodePoolAsync(global::Google.Container.V1.GetNodePoolRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetNodePool, null, options, request); } /// <summary> /// Creates a node pool for a cluster. /// </summary> public virtual global::Google.Container.V1.Operation CreateNodePool(global::Google.Container.V1.CreateNodePoolRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateNodePool(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a node pool for a cluster. /// </summary> public virtual global::Google.Container.V1.Operation CreateNodePool(global::Google.Container.V1.CreateNodePoolRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateNodePool, null, options, request); } /// <summary> /// Creates a node pool for a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> CreateNodePoolAsync(global::Google.Container.V1.CreateNodePoolRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateNodePoolAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a node pool for a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> CreateNodePoolAsync(global::Google.Container.V1.CreateNodePoolRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateNodePool, null, options, request); } /// <summary> /// Deletes a node pool from a cluster. /// </summary> public virtual global::Google.Container.V1.Operation DeleteNodePool(global::Google.Container.V1.DeleteNodePoolRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteNodePool(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a node pool from a cluster. /// </summary> public virtual global::Google.Container.V1.Operation DeleteNodePool(global::Google.Container.V1.DeleteNodePoolRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteNodePool, null, options, request); } /// <summary> /// Deletes a node pool from a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> DeleteNodePoolAsync(global::Google.Container.V1.DeleteNodePoolRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteNodePoolAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a node pool from a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> DeleteNodePoolAsync(global::Google.Container.V1.DeleteNodePoolRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteNodePool, null, options, request); } /// <summary> /// Roll back the previously Aborted or Failed NodePool upgrade. /// This will be an no-op if the last upgrade successfully completed. /// </summary> public virtual global::Google.Container.V1.Operation RollbackNodePoolUpgrade(global::Google.Container.V1.RollbackNodePoolUpgradeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RollbackNodePoolUpgrade(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Roll back the previously Aborted or Failed NodePool upgrade. /// This will be an no-op if the last upgrade successfully completed. /// </summary> public virtual global::Google.Container.V1.Operation RollbackNodePoolUpgrade(global::Google.Container.V1.RollbackNodePoolUpgradeRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_RollbackNodePoolUpgrade, null, options, request); } /// <summary> /// Roll back the previously Aborted or Failed NodePool upgrade. /// This will be an no-op if the last upgrade successfully completed. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> RollbackNodePoolUpgradeAsync(global::Google.Container.V1.RollbackNodePoolUpgradeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RollbackNodePoolUpgradeAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Roll back the previously Aborted or Failed NodePool upgrade. /// This will be an no-op if the last upgrade successfully completed. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> RollbackNodePoolUpgradeAsync(global::Google.Container.V1.RollbackNodePoolUpgradeRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_RollbackNodePoolUpgrade, null, options, request); } /// <summary> /// Sets the NodeManagement options for a node pool. /// </summary> public virtual global::Google.Container.V1.Operation SetNodePoolManagement(global::Google.Container.V1.SetNodePoolManagementRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SetNodePoolManagement(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Sets the NodeManagement options for a node pool. /// </summary> public virtual global::Google.Container.V1.Operation SetNodePoolManagement(global::Google.Container.V1.SetNodePoolManagementRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SetNodePoolManagement, null, options, request); } /// <summary> /// Sets the NodeManagement options for a node pool. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> SetNodePoolManagementAsync(global::Google.Container.V1.SetNodePoolManagementRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SetNodePoolManagementAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Sets the NodeManagement options for a node pool. /// </summary> public virtual AsyncUnaryCall<global::Google.Container.V1.Operation> SetNodePoolManagementAsync(global::Google.Container.V1.SetNodePoolManagementRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SetNodePoolManagement, null, options, request); } protected override ClusterManagerClient NewInstance(ClientBaseConfiguration configuration) { return new ClusterManagerClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(ClusterManagerBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListClusters, serviceImpl.ListClusters) .AddMethod(__Method_GetCluster, serviceImpl.GetCluster) .AddMethod(__Method_CreateCluster, serviceImpl.CreateCluster) .AddMethod(__Method_UpdateCluster, serviceImpl.UpdateCluster) .AddMethod(__Method_DeleteCluster, serviceImpl.DeleteCluster) .AddMethod(__Method_ListOperations, serviceImpl.ListOperations) .AddMethod(__Method_GetOperation, serviceImpl.GetOperation) .AddMethod(__Method_CancelOperation, serviceImpl.CancelOperation) .AddMethod(__Method_GetServerConfig, serviceImpl.GetServerConfig) .AddMethod(__Method_ListNodePools, serviceImpl.ListNodePools) .AddMethod(__Method_GetNodePool, serviceImpl.GetNodePool) .AddMethod(__Method_CreateNodePool, serviceImpl.CreateNodePool) .AddMethod(__Method_DeleteNodePool, serviceImpl.DeleteNodePool) .AddMethod(__Method_RollbackNodePoolUpgrade, serviceImpl.RollbackNodePoolUpgrade) .AddMethod(__Method_SetNodePoolManagement, serviceImpl.SetNodePoolManagement).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; namespace System.Data.Odbc { internal struct SQLLEN { private IntPtr _value; internal SQLLEN(int value) { _value = new IntPtr(value); } internal SQLLEN(long value) { #if WIN32 _value = new IntPtr(checked((int)value)); #else _value = new IntPtr(value); #endif } internal SQLLEN(IntPtr value) { _value = value; } public static implicit operator SQLLEN(int value) { // return new SQLLEN(value); } public static explicit operator SQLLEN(long value) { return new SQLLEN(value); } public unsafe static implicit operator int (SQLLEN value) { // #if WIN32 return (int)value._value.ToInt32(); #else long l = (long)value._value.ToInt64(); return checked((int)l); #endif } public unsafe static explicit operator long (SQLLEN value) { return value._value.ToInt64(); } public unsafe long ToInt64() { return _value.ToInt64(); } } internal sealed class OdbcStatementHandle : OdbcHandle { internal OdbcStatementHandle(OdbcConnectionHandle connectionHandle) : base(ODBC32.SQL_HANDLE.STMT, connectionHandle) { } internal ODBC32.RetCode BindColumn2(int columnNumber, ODBC32.SQL_C targetType, HandleRef buffer, IntPtr length, IntPtr srLen_or_Ind) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLBindCol(this, checked((ushort)columnNumber), targetType, buffer, length, srLen_or_Ind); ODBC.TraceODBC(3, "SQLBindCol", retcode); return retcode; } internal ODBC32.RetCode BindColumn3(int columnNumber, ODBC32.SQL_C targetType, IntPtr srLen_or_Ind) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLBindCol(this, checked((ushort)columnNumber), targetType, ADP.PtrZero, ADP.PtrZero, srLen_or_Ind); ODBC.TraceODBC(3, "SQLBindCol", retcode); return retcode; } internal ODBC32.RetCode BindParameter(short ordinal, short parameterDirection, ODBC32.SQL_C sqlctype, ODBC32.SQL_TYPE sqltype, IntPtr cchSize, IntPtr scale, HandleRef buffer, IntPtr bufferLength, HandleRef intbuffer) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLBindParameter(this, checked((ushort)ordinal), // Parameter Number parameterDirection, // InputOutputType sqlctype, // ValueType checked((short)sqltype), // ParameterType cchSize, // ColumnSize scale, // DecimalDigits buffer, // ParameterValuePtr bufferLength, // BufferLength intbuffer); // StrLen_or_IndPtr ODBC.TraceODBC(3, "SQLBindParameter", retcode); return retcode; } internal ODBC32.RetCode Cancel() { // In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all // (ODBC Programmer's Reference ...) ODBC32.RetCode retcode = UnsafeNativeMethods.SQLCancel(this); ODBC.TraceODBC(3, "SQLCancel", retcode); return retcode; } internal ODBC32.RetCode CloseCursor() { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLCloseCursor(this); ODBC.TraceODBC(3, "SQLCloseCursor", retcode); return retcode; } internal ODBC32.RetCode ColumnAttribute(int columnNumber, short fieldIdentifier, CNativeBuffer characterAttribute, out short stringLength, out SQLLEN numericAttribute) { IntPtr result; ODBC32.RetCode retcode = UnsafeNativeMethods.SQLColAttributeW(this, checked((short)columnNumber), fieldIdentifier, characterAttribute, characterAttribute.ShortLength, out stringLength, out result); numericAttribute = new SQLLEN(result); ODBC.TraceODBC(3, "SQLColAttributeW", retcode); return retcode; } internal ODBC32.RetCode Columns(string tableCatalog, string tableSchema, string tableName, string columnName) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLColumnsW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), columnName, ODBC.ShortStringLength(columnName)); ODBC.TraceODBC(3, "SQLColumnsW", retcode); return retcode; } internal ODBC32.RetCode Execute() { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLExecute(this); ODBC.TraceODBC(3, "SQLExecute", retcode); return retcode; } internal ODBC32.RetCode ExecuteDirect(string commandText) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLExecDirectW(this, commandText, ODBC32.SQL_NTS); ODBC.TraceODBC(3, "SQLExecDirectW", retcode); return retcode; } internal ODBC32.RetCode Fetch() { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLFetch(this); ODBC.TraceODBC(3, "SQLFetch", retcode); return retcode; } internal ODBC32.RetCode FreeStatement(ODBC32.STMT stmt) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLFreeStmt(this, stmt); ODBC.TraceODBC(3, "SQLFreeStmt", retcode); return retcode; } internal ODBC32.RetCode GetData(int index, ODBC32.SQL_C sqlctype, CNativeBuffer buffer, int cb, out IntPtr cbActual) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetData(this, checked((ushort)index), sqlctype, buffer, new IntPtr(cb), out cbActual); ODBC.TraceODBC(3, "SQLGetData", retcode); return retcode; } internal ODBC32.RetCode GetStatementAttribute(ODBC32.SQL_ATTR attribute, out IntPtr value, out int stringLength) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetStmtAttrW(this, attribute, out value, ADP.PtrSize, out stringLength); ODBC.TraceODBC(3, "SQLGetStmtAttrW", retcode); return retcode; } internal ODBC32.RetCode GetTypeInfo(Int16 fSqlType) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetTypeInfo(this, fSqlType); ODBC.TraceODBC(3, "SQLGetTypeInfo", retcode); return retcode; } internal ODBC32.RetCode MoreResults() { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLMoreResults(this); ODBC.TraceODBC(3, "SQLMoreResults", retcode); return retcode; } internal ODBC32.RetCode NumberOfResultColumns(out short columnsAffected) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLNumResultCols(this, out columnsAffected); ODBC.TraceODBC(3, "SQLNumResultCols", retcode); return retcode; } internal ODBC32.RetCode Prepare(string commandText) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLPrepareW(this, commandText, ODBC32.SQL_NTS); ODBC.TraceODBC(3, "SQLPrepareW", retcode); return retcode; } internal ODBC32.RetCode PrimaryKeys(string catalogName, string schemaName, string tableName) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLPrimaryKeysW(this, catalogName, ODBC.ShortStringLength(catalogName), // CatalogName schemaName, ODBC.ShortStringLength(schemaName), // SchemaName tableName, ODBC.ShortStringLength(tableName) // TableName ); ODBC.TraceODBC(3, "SQLPrimaryKeysW", retcode); return retcode; } internal ODBC32.RetCode Procedures(string procedureCatalog, string procedureSchema, string procedureName) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLProceduresW(this, procedureCatalog, ODBC.ShortStringLength(procedureCatalog), procedureSchema, ODBC.ShortStringLength(procedureSchema), procedureName, ODBC.ShortStringLength(procedureName)); ODBC.TraceODBC(3, "SQLProceduresW", retcode); return retcode; } internal ODBC32.RetCode ProcedureColumns(string procedureCatalog, string procedureSchema, string procedureName, string columnName) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLProcedureColumnsW(this, procedureCatalog, ODBC.ShortStringLength(procedureCatalog), procedureSchema, ODBC.ShortStringLength(procedureSchema), procedureName, ODBC.ShortStringLength(procedureName), columnName, ODBC.ShortStringLength(columnName)); ODBC.TraceODBC(3, "SQLProcedureColumnsW", retcode); return retcode; } internal ODBC32.RetCode RowCount(out SQLLEN rowCount) { IntPtr result; ODBC32.RetCode retcode = UnsafeNativeMethods.SQLRowCount(this, out result); rowCount = new SQLLEN(result); ODBC.TraceODBC(3, "SQLRowCount", retcode); return retcode; } internal ODBC32.RetCode SetStatementAttribute(ODBC32.SQL_ATTR attribute, IntPtr value, ODBC32.SQL_IS stringLength) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetStmtAttrW(this, (int)attribute, value, (int)stringLength); ODBC.TraceODBC(3, "SQLSetStmtAttrW", retcode); return retcode; } internal ODBC32.RetCode SpecialColumns(string quotedTable) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSpecialColumnsW(this, ODBC32.SQL_SPECIALCOLS.ROWVER, null, 0, null, 0, quotedTable, ODBC.ShortStringLength(quotedTable), ODBC32.SQL_SCOPE.SESSION, ODBC32.SQL_NULLABILITY.NO_NULLS); ODBC.TraceODBC(3, "SQLSpecialColumnsW", retcode); return retcode; } internal ODBC32.RetCode Statistics(string tableCatalog, string tableSchema, string tableName, Int16 unique, Int16 accuracy) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLStatisticsW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), unique, accuracy); ODBC.TraceODBC(3, "SQLStatisticsW", retcode); return retcode; } internal ODBC32.RetCode Statistics(string tableName) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLStatisticsW(this, null, 0, null, 0, tableName, ODBC.ShortStringLength(tableName), (Int16)ODBC32.SQL_INDEX.UNIQUE, (Int16)ODBC32.SQL_STATISTICS_RESERVED.ENSURE); ODBC.TraceODBC(3, "SQLStatisticsW", retcode); return retcode; } internal ODBC32.RetCode Tables(string tableCatalog, string tableSchema, string tableName, string tableType) { ODBC32.RetCode retcode = UnsafeNativeMethods.SQLTablesW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), tableType, ODBC.ShortStringLength(tableType)); ODBC.TraceODBC(3, "SQLTablesW", retcode); return retcode; } } }
// --------------------------------------------------------------------------- // <copyright company="Microsoft Corporation" file="XmlDiffViewDocumentType.cs"> // Copyright (c) Microsoft Corporation 2005 // </copyright> // <project> // XmlDiffView // </project> // <summary> // Generate output data for differences in /// the DOCTYPE declaration (DTD) nodes. This /// does not drill down into the components of /// the DTD's internal subset. // </summary> // <history> // [barryw] 03MAR05 Created // </history> // --------------------------------------------------------------------------- namespace Microsoft.XmlDiffPatch { #region Using directives using System; using System.Xml; using System.IO; using System.Diagnostics; #endregion /// <summary> /// Class to generate output data for differences in /// the DOCTYPE declaration (DTD) nodes. /// </summary> /// <remarks>Programmer notes for future code /// enhancements: The PublicLiteral /// and the SystemLiteral are considered attributes. /// The attribute names are PUBLIC and SYSTEM. /// To retrieve the content of the attribute, use /// GetAttribute or another attribute accessing /// method.</remarks> internal class XmlDiffViewDocumentType : XmlDiffViewNode { #region Member variables section /// <summary> /// Name given to the DOCTYPE declaration (DTD). /// </summary> private string nameStore; private string systemIdStore; private string publicIdStore; private string internalDtdSubset; #endregion #region Constructors section /// <summary> /// Constructor /// </summary> /// <param name="name">declaration name</param> /// <param name="publicId">value of the PUBLIC declaration 'attribute'</param> /// <param name="systemId">value of the SYSTEM declaration 'attribute'</param> /// <param name="documentTypeSubset">The inner declaration data</param> public XmlDiffViewDocumentType(string name, string publicId, string systemId, string documentTypeSubset) : base(XmlNodeType.DocumentType) { this.Name = name; this.PublicId = (publicId == null) ? string.Empty : publicId; this.SystemId = (systemId == null) ? string.Empty : systemId; this.Subset = documentTypeSubset; } #endregion #region Properties section /// <summary> /// Gets and sets the value of the SYSTEM declaration 'attribute' /// </summary> public string SystemId { get { return this.systemIdStore; } set { this.systemIdStore = value; } } /// <summary> /// Gets and sets the declaration name /// </summary> public string Name { get { return this.nameStore; } set { this.nameStore = value; } } /// <summary> /// Gets and sets the value of the PUBLIC declaration 'attribute' /// </summary> public string PublicId { get { return this.publicIdStore; } set { this.publicIdStore = value; } } /// <summary> /// Gets and sets the inner data for the declaration /// </summary> public string Subset { get { return this.internalDtdSubset; } set { this.internalDtdSubset = value; } } /// <summary> /// Returns the complete declaration /// </summary> public override string OuterXml { get { string dtd = "<!DOCTYPE " + this.Name + " "; if (this.PublicId != string.Empty) { dtd += Tags.DtdPublic + "\"" + this.PublicId + "\" "; } else if (this.SystemId != string.Empty) { dtd += Tags.DtdSystem + "\"" + this.SystemId + "\" "; } if (this.Subset != string.Empty) { dtd += "[" + this.Subset + "]"; } dtd += ">"; return dtd; } } #endregion #region Methods section /// <summary> /// Creates a complete copy of the current node. /// </summary> /// <param name="deep">deprecated</param> /// <returns>Exception: Clone method should /// never be called on a document type /// node.</returns> [Obsolete("Clone method should never be called on document type node.", true)] internal override XmlDiffViewNode Clone(bool deep) { Debug.Assert(false, "Clone method should never be called on document type node."); return null; } /// <summary> /// Generates output data in html form /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> internal override void DrawHtml(XmlWriter writer, int indent) { if (Operation == XmlDiffViewOperation.Change) { XmlDiffView.HtmlStartRow(writer); this.DrawLinkNode(writer); for (int i = 0; i < 2; i++) { XmlDiffView.HtmlStartCell(writer, indent); // name XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, Tags.XmlDocumentTypeBegin); if (i == 0) { XmlDiffView.HtmlWriteString( writer, (this.Name == ChangeInformation.LocalName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, this.Name); } else { XmlDiffView.HtmlWriteString( writer, (this.Name == ChangeInformation.LocalName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, ChangeInformation.LocalName); } XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, " "); string systemString = "SYSTEM "; // public id if (this.PublicId == ChangeInformation.Prefix) { // match if (this.PublicId != string.Empty) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, Tags.DtdPublic + "\"" + this.PublicId + "\" "); systemString = string.Empty; } } else { // add if (this.PublicId == string.Empty) { if (i == 1) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Add, Tags.DtdPublic + "\"" + ChangeInformation.Prefix + "\" "); systemString = string.Empty; } } // remove else if (ChangeInformation.Prefix == string.Empty) { if (i == 0) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Remove, Tags.DtdPublic + "\"" + this.PublicId + "\" "); systemString = string.Empty; } } // change else { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, Tags.DtdPublic + "\"" + ((i == 0) ? this.PublicId : ChangeInformation.Prefix) + "\""); systemString = string.Empty; } } // system id if (this.SystemId == ChangeInformation.NamespaceUri) { if (this.SystemId != string.Empty) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, systemString + "\"" + this.SystemId + "\" "); } } else { // add if (this.SystemId == string.Empty) { if (i == 1) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Add, systemString + "\"" + ChangeInformation.NamespaceUri + "\" "); } } // remove else if (ChangeInformation.Prefix == string.Empty) { if (i == 0) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Remove, systemString + "\"" + this.SystemId + "\""); } } // change else { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, systemString + "\"" + ((i == 0) ? this.SystemId : ChangeInformation.NamespaceUri) + "\" "); } } // internal subset if (this.Subset == ChangeInformation.Subset) { if (this.Subset != string.Empty) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, "[" + this.Subset + "]"); } } else { // add if (this.Subset == string.Empty) { if (i == 1) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Add, "[" + ChangeInformation.Subset + "]"); } } // remove else if (ChangeInformation.Subset == string.Empty) { if (i == 0) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Remove, "[" + this.Subset + "]"); } } // change else { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, "[" + ((i == 0) ? this.Subset : ChangeInformation.Subset) + "]"); } } // close start tag XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, Tags.XmlDocumentTypeEnd); XmlDiffView.HtmlEndCell(writer); } XmlDiffView.HtmlEndRow(writer); } else { DrawHtmlNoChange(writer, indent); } } /// <summary> /// Add the DocumentType data to the output. /// </summary> /// <param name="writer">Output data stream</param> /// <param name="indent">current size of text indentation</param> /// <remarks>If the DOCTYPE declaration includes /// declarations that are to be combined with /// external files or the external subset, it /// uses the following syntax. /// DOCTYPE rootElement SYSTEM "URIreference" /// [declarations] /// or /// DOCTYPE rootElement PUBLIC "PublicIdentifier" "URIreference" /// [declarations] /// </remarks> internal override void DrawText(TextWriter writer, int indent) { Debug.Assert(NodeType == XmlNodeType.DocumentType); // indent the text. writer.Write(XmlDiffView.IndentText(indent)); switch (Operation) { case XmlDiffViewOperation.Add: this.DrawTextAdd(writer, indent); break; case XmlDiffViewOperation.Change: this.DrawTextChange(writer, indent); break; case XmlDiffViewOperation.Ignore: case XmlDiffViewOperation.MoveFrom: this.DrawTextMoveFrom(writer, indent); break; case XmlDiffViewOperation.MoveTo: this.DrawTextMoveTo(writer, indent); break; case XmlDiffViewOperation.Match: // for 'Ignore' and match operations // write out the baseline data this.DrawTextNoChange(writer, indent); break; case XmlDiffViewOperation.Remove: this.DrawTextRemove(writer, indent); break; default: Debug.Assert(false); break; } writer.Write(writer.NewLine); } /// <summary> /// Generates the original document type sudo-attribute /// </summary> /// <returns>document type sudo-attribute</returns> private string DocumentTypeSudoAttributes() { string systemString = "SYSTEM "; const string publicString = "PUBLIC "; string attributes = " "; switch (Operation) { case XmlDiffViewOperation.Add: case XmlDiffViewOperation.Remove: case XmlDiffViewOperation.MoveFrom: case XmlDiffViewOperation.Match: // for 'add'/'remove'/'move from' differences and // match the values are in the regular properties, // not the changed information object if ((null != this.PublicId) && (this.PublicId != string.Empty)) { attributes += publicString + "\"" + this.PublicId + "\" "; } else if ((null != this.SystemId) && (this.SystemId != string.Empty)) { attributes += systemString + "\"" + this.SystemId + "\" "; } else if (null != ChangeInformation) { if ((null != ChangeInformation.Prefix) && (ChangeInformation.Prefix != string.Empty)) { Debug.Assert( false, "Unexpected value ", publicString + "\"" + ChangeInformation.Prefix + "\" "); } else if ((null != ChangeInformation.NamespaceUri) && (ChangeInformation.NamespaceUri != string.Empty)) { Debug.Assert( false, "Unexpected value ", systemString + "\"" + ChangeInformation.NamespaceUri + "\" "); } } break; case XmlDiffViewOperation.MoveTo: // for ''move to' differences the values // are in the changed information object if ((null != ChangeInformation.Prefix) && (ChangeInformation.Prefix != string.Empty)) { attributes += publicString + "\"" + ChangeInformation.Prefix + "\" "; } else if ((null != ChangeInformation.NamespaceUri) && (ChangeInformation.NamespaceUri != string.Empty)) { attributes += systemString + "\"" + ChangeInformation.NamespaceUri + "\" "; } else if ((null != this.PublicId) && (this.PublicId != string.Empty)) { Debug.Assert( false, "Unexpected value ", publicString + "\"" + this.PublicId + "\" "); } else if ((null != this.SystemId) && (this.SystemId != string.Empty)) { Debug.Assert( false, "Unexpected value ", systemString + "\"" + this.SystemId + "\" "); } break; case XmlDiffViewOperation.Ignore: attributes = string.Empty; break; case XmlDiffViewOperation.Change: attributes = " "; // check for changes in the public "attribute" value if (((null != this.PublicId) || (null != ChangeInformation.Prefix)) && (this.PublicId == ChangeInformation.Prefix)) { // match if (string.Empty != this.PublicId) { attributes += Tags.DtdPublic + "\"" + this.PublicId + "\" "; systemString = string.Empty; } } else { if ((string.Empty == this.PublicId) && (string.Empty != ChangeInformation.Prefix)) { // add attributes += Difference.Tag + Difference.DocumentTypeAdded; attributes += " " + Tags.DtdPublic + "\"" + ChangeInformation.Prefix + "\" "; systemString = string.Empty; } else if ((string.Empty == ChangeInformation.Prefix) && (string.Empty != this.PublicId)) { // remove attributes += Difference.Tag + Difference.DocumentTypeDeleted; attributes += Tags.DtdPublic + "\"" + this.PublicId + "\" "; systemString = string.Empty; } else { // if both have values, they must be different if ((string.Empty != ChangeInformation.Prefix) && (string.Empty != this.PublicId)) { // change attributes += Difference.Tag + "=" + Difference.ChangeBegin + Tags.DtdPublic + "\"" + this.PublicId + "\" " + Difference.ChangeTo + Tags.DtdPublic + "\"" + ChangeInformation.Prefix + "\" " + Difference.ChangeEnd; systemString = string.Empty; } } } // system id if (((null != this.SystemId) || (null != ChangeInformation.NamespaceUri)) && (this.SystemId == ChangeInformation.NamespaceUri)) { // match if (this.SystemId != string.Empty) { attributes += systemString + "\"" + this.SystemId + "\" "; } } else { if ((string.Empty == this.SystemId) && (string.Empty != ChangeInformation.NamespaceUri)) { // add attributes += Difference.Tag + Difference.DocumentTypeAdded; attributes += systemString + "\"" + ChangeInformation.NamespaceUri + "\" "; } // remove else if ((ChangeInformation.Prefix == string.Empty) && (string.Empty != this.SystemId)) { attributes += Difference.Tag + Difference.DocumentTypeDeleted; attributes += systemString + "\"" + this.SystemId + "\" "; } // change else { // if both have values, they must be different if ((string.Empty != ChangeInformation.NamespaceUri) && (string.Empty != this.SystemId)) { // change attributes += Difference.Tag + "=" + Difference.ChangeBegin + systemString + "\"" + this.SystemId + "\" " + Difference.ChangeTo + systemString + "\"" + ChangeInformation.NamespaceUri + "\" " + Difference.ChangeEnd; } } } break; default: Trace.WriteLine("This differencing operation is not recognized"); throw new ArgumentOutOfRangeException( "Operation", Operation, "This differencing operation is not recognized"); } return attributes; } /// <summary> /// Generates output data in text form for differences /// due to adding data /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private void DrawTextAdd( TextWriter writer, int indent) { writer.Write(Tags.XmlDocumentTypeBegin + this.Name + this.DocumentTypeSudoAttributes() + "[" + writer.NewLine + XmlDiffView.IndentText(indent + indent) + Tags.XmlCommentOldStyleBegin + " " + Difference.Tag + Difference.DocumentTypeAdded + " " + Tags.XmlCommentOldStyleEnd + writer.NewLine + this.internalDtdSubset + writer.NewLine + "]" + Tags.XmlDocumentTypeEnd); } /// <summary> /// Generates output data in text form for differences /// due to moving data from a location /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private void DrawTextMoveFrom( TextWriter writer, int indent) { // generate the dtd name and sudo-attributes writer.Write(Tags.XmlDocumentTypeBegin + this.Name + this.DocumentTypeSudoAttributes() + "[" + writer.NewLine); // generate the main body of the dtd. writer.Write(XmlDiffView.IndentText(indent + indent) + writer.NewLine); // include a comment about the difference. writer.Write(Tags.XmlCommentOldStyleBegin + " " + Difference.Tag + Difference.DocumentTypeMovedFromBegin + OperationId + Difference.DocumentTypeMovedFromEnd + " " + Tags.XmlCommentOldStyleEnd + writer.NewLine); // include main body and closing tags writer.Write(XmlDiffView.IndentText(indent + indent) + this.internalDtdSubset + writer.NewLine + "]" + Tags.XmlDocumentTypeEnd); } /// <summary> /// Generates output data in text form for differences /// due to moving data to a new location /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private void DrawTextMoveTo( TextWriter writer, int indent) { // generate the dtd name and sudo-attributes writer.Write(Tags.XmlDocumentTypeBegin + this.Name + this.DocumentTypeSudoAttributes() + "[" + writer.NewLine); // generate the main body of the dtd. writer.Write(XmlDiffView.IndentText(indent + indent) + writer.NewLine); // include a comment about the difference. writer.Write(Tags.XmlCommentOldStyleBegin + " " + Difference.Tag + Difference.DocumentTypeMovedToBegin + OperationId + Difference.DocumentTypeMovedToEnd + " " + Tags.XmlCommentOldStyleEnd + writer.NewLine); // include main body and closing tags writer.Write(XmlDiffView.IndentText(indent + indent) + this.internalDtdSubset + writer.NewLine + "]" + Tags.XmlDocumentTypeEnd); } /// <summary> /// Generates output data in text form for differences /// due to removing data /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private void DrawTextRemove( TextWriter writer, int indent) { // generate the dtd name and sudo-attributes writer.Write(Tags.XmlDocumentTypeBegin + this.Name + this.DocumentTypeSudoAttributes() + "[" + writer.NewLine); // generate the main body of the dtd. writer.Write(XmlDiffView.IndentText(indent + indent)); // include a comment about the difference. writer.Write(Tags.XmlCommentOldStyleBegin + " " + Difference.Tag + Difference.DocumentTypeDeleted + " " + Tags.XmlCommentOldStyleEnd + writer.NewLine); // include main body and closing tags writer.Write(XmlDiffView.IndentText(indent + indent) + this.internalDtdSubset + writer.NewLine + XmlDiffView.IndentText(indent + indent) + "]" + Tags.XmlDocumentTypeEnd); } /// <summary> /// Generates output data in text form for differences /// due to changing data /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private void DrawTextChange( TextWriter writer, int indent) { // generate the dtd name and sudo-attributes writer.Write(Tags.XmlDocumentTypeBegin + this.Name + this.DocumentTypeSudoAttributes() + "[" + writer.NewLine); // generate the main body of the dtd. writer.Write(XmlDiffView.IndentText(indent + indent) + writer.NewLine); // include a comment about the difference showing the old subset data. writer.Write(Tags.XmlCommentOldStyleBegin + writer.NewLine + " " + Difference.Tag + Difference.ChangeBegin + this.internalDtdSubset + Difference.ChangeEnd + writer.NewLine + " " + Tags.XmlCommentOldStyleEnd + writer.NewLine); // include main body and closing tags writer.Write(XmlDiffView.IndentText(indent + indent) + changeInfo.Subset + writer.NewLine + "]" + Tags.XmlDocumentTypeEnd); } /// <summary> /// Generates output data in text form for differences /// due to changing existing data /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private new void DrawTextNoChange( TextWriter writer, int indent) { string dtd = Tags.XmlDocumentTypeBegin + this.Name + this.DocumentTypeSudoAttributes() + this.internalDtdSubset + Tags.XmlDocumentTypeEnd; } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // 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.Globalization; using NUnit.Framework.Constraints; namespace NUnit.Framework.Internal { /// <summary> /// TextMessageWriter writes constraint descriptions and messages /// in displayable form as a text stream. It tailors the display /// of individual message components to form the standard message /// format of NUnit assertion failure messages. /// </summary> public class TextMessageWriter : MessageWriter { #region Message Formats and Constants private static readonly int DEFAULT_LINE_LENGTH = 78; // Prefixes used in all failure messages. All must be the same // length, which is held in the PrefixLength field. Should not // contain any tabs or newline characters. /// <summary> /// Prefix used for the expected value line of a message /// </summary> public static readonly string Pfx_Expected = " Expected: "; /// <summary> /// Prefix used for the actual value line of a message /// </summary> public static readonly string Pfx_Actual = " But was: "; /// <summary> /// Length of a message prefix /// </summary> public static readonly int PrefixLength = Pfx_Expected.Length; #endregion #region Instance Fields private int maxLineLength = DEFAULT_LINE_LENGTH; private bool _sameValDiffTypes = false; private string _expectedType, _actualType; #endregion #region Constructors /// <summary> /// Construct a TextMessageWriter /// </summary> public TextMessageWriter() { } /// <summary> /// Construct a TextMessageWriter, specifying a user message /// and optional formatting arguments. /// </summary> /// <param name="userMessage"></param> /// <param name="args"></param> public TextMessageWriter(string userMessage, params object[] args) { if ( userMessage != null && userMessage != string.Empty) this.WriteMessageLine(userMessage, args); } #endregion #region Properties /// <summary> /// Gets or sets the maximum line length for this writer /// </summary> public override int MaxLineLength { get { return maxLineLength; } set { maxLineLength = value; } } #endregion #region Public Methods - High Level /// <summary> /// Method to write single line message with optional args, usually /// written to precede the general failure message, at a given /// indentation level. /// </summary> /// <param name="level">The indentation level of the message</param> /// <param name="message">The message to be written</param> /// <param name="args">Any arguments used in formatting the message</param> public override void WriteMessageLine(int level, string message, params object[] args) { if (message != null) { while (level-- >= 0) Write(" "); if (args != null && args.Length > 0) message = string.Format(message, args); WriteLine(MsgUtils.EscapeNullCharacters(message)); } } /// <summary> /// Display Expected and Actual lines for a constraint. This /// is called by MessageWriter's default implementation of /// WriteMessageTo and provides the generic two-line display. /// </summary> /// <param name="result">The result of the constraint that failed</param> public override void DisplayDifferences(ConstraintResult result) { WriteExpectedLine(result); WriteActualLine(result); } /// <summary> /// Gets the unique type name between expected and actual. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="expectedType">Output of the unique type name for expected</param> /// <param name="actualType">Output of the unique type name for actual</param> private void ResolveTypeNameDifference(object expected, object actual, out string expectedType, out string actualType) { TypeNameDifferenceResolver resolver = new TypeNameDifferenceResolver(); resolver.ResolveTypeNameDifference(expected, actual, out expectedType, out actualType); expectedType = $" ({expectedType})"; actualType = $" ({actualType})"; } /// <summary> /// Display Expected and Actual lines for given values. This /// method may be called by constraints that need more control over /// the display of actual and expected values than is provided /// by the default implementation. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> public override void DisplayDifferences(object expected, object actual) { DisplayDifferences(expected, actual,null); } /// <summary> /// Display Expected and Actual lines for given values, including /// a tolerance value on the expected line. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="tolerance">The tolerance within which the test was made</param> public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) { if (expected != null && actual != null && expected.GetType() != actual.GetType() && MsgUtils.FormatValue(expected) == MsgUtils.FormatValue(actual) ) { _sameValDiffTypes = true; ResolveTypeNameDifference(expected, actual, out _expectedType, out _actualType); } WriteExpectedLine(expected, tolerance); WriteActualLine(actual); } /// <summary> /// Display the expected and actual string values on separate lines. /// If the mismatch parameter is >=0, an additional line is displayed /// line containing a caret that points to the mismatch point. /// </summary> /// <param name="expected">The expected string value</param> /// <param name="actual">The actual string value</param> /// <param name="mismatch">The point at which the strings don't match or -1</param> /// <param name="ignoreCase">If true, case is ignored in string comparisons</param> /// <param name="clipping">If true, clip the strings to fit the max line length</param> public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) { // Maximum string we can display without truncating int maxDisplayLength = MaxLineLength - PrefixLength // Allow for prefix - 2; // 2 quotation marks if ( clipping ) MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); expected = MsgUtils.EscapeControlChars(expected); actual = MsgUtils.EscapeControlChars(actual); // The mismatch position may have changed due to clipping or white space conversion mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); Write( Pfx_Expected ); Write( MsgUtils.FormatValue(expected) ); if ( ignoreCase ) Write( ", ignoring case" ); WriteLine(); WriteActualLine( actual ); //DisplayDifferences(expected, actual); if (mismatch >= 0) WriteCaretLine(mismatch); } #endregion #region Public Methods - Low Level /// <summary> /// Writes the text for an actual value. /// </summary> /// <param name="actual">The actual value.</param> public override void WriteActualValue(object actual) { WriteValue(actual); } /// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> public override void WriteValue(object val) { Write(MsgUtils.FormatValue(val)); } /// <summary> /// Writes the text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public override void WriteCollectionElements(IEnumerable collection, long start, int max) { Write(MsgUtils.FormatCollection(collection, start, max)); } #endregion #region Helper Methods /// <summary> /// Write the generic 'Expected' line for a constraint /// </summary> /// <param name="result">The constraint that failed</param> private void WriteExpectedLine(ConstraintResult result) { Write(Pfx_Expected); WriteLine(result.Description); } /// <summary> /// Write the generic 'Expected' line for a given value /// </summary> /// <param name="expected">The expected value</param> private void WriteExpectedLine(object expected) { WriteExpectedLine(expected, null); } /// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); Write(MsgUtils.FormatValue(expected)); if (_sameValDiffTypes) { Write(_expectedType); } if (tolerance != null && !tolerance.IsUnsetOrDefault) { Write(" +/- "); Write(MsgUtils.FormatValue(tolerance.Amount)); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); } WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a constraint /// </summary> /// <param name="result">The ConstraintResult for which the actual value is to be written</param> private void WriteActualLine(ConstraintResult result) { Write(Pfx_Actual); result.WriteActualValueTo(this); WriteLine(); //WriteLine(MsgUtils.FormatValue(result.ActualValue)); } /// <summary> /// Write the generic 'Actual' line for a given value /// </summary> /// <param name="actual">The actual value causing a failure</param> private void WriteActualLine(object actual) { Write(Pfx_Actual); WriteActualValue(actual); if (_sameValDiffTypes) { Write(_actualType); } WriteLine(); } private void WriteCaretLine(int mismatch) { // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Security; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; namespace System.IO { public static partial class Directory { public static DirectoryInfo GetParent(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); String s = Path.GetDirectoryName(fullPath); if (s == null) return null; return new DirectoryInfo(s); } [System.Security.SecuritySafeCritical] public static DirectoryInfo CreateDirectory(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); FileSystem.Current.CreateDirectory(fullPath); return new DirectoryInfo(fullPath, null); } // Input to this method should already be fullpath. This method will ensure that we append // the trailing slash only when appropriate. internal static String EnsureTrailingDirectorySeparator(string fullPath) { String fullPathWithTrailingDirectorySeparator; if (!PathHelpers.EndsInDirectorySeparator(fullPath)) fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString; else fullPathWithTrailingDirectorySeparator = fullPath; return fullPathWithTrailingDirectorySeparator; } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // [System.Security.SecuritySafeCritical] // auto-generated public static bool Exists(String path) { try { if (path == null) return false; if (path.Length == 0) return false; String fullPath = Path.GetFullPath(path); return FileSystem.Current.DirectoryExists(fullPath); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } public static void SetCreationTime(String path, DateTime creationTime) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true); } public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true); } public static DateTime GetCreationTime(String path) { return File.GetCreationTime(path); } public static DateTime GetCreationTimeUtc(String path) { return File.GetCreationTimeUtc(path); } public static void SetLastWriteTime(String path, DateTime lastWriteTime) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true); } public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true); } public static DateTime GetLastWriteTime(String path) { return File.GetLastWriteTime(path); } public static DateTime GetLastWriteTimeUtc(String path) { return File.GetLastWriteTimeUtc(path); } public static void SetLastAccessTime(String path, DateTime lastAccessTime) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true); } public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true); } public static DateTime GetLastAccessTime(String path) { return File.GetLastAccessTime(path); } public static DateTime GetLastAccessTimeUtc(String path) { return File.GetLastAccessTimeUtc(path); } // Returns an array of filenames in the DirectoryInfo specified by path public static String[] GetFiles(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (i.e. "*.txt"). public static String[] GetFiles(String path, String searchPattern) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (i.e. "*.txt") and search option public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (i.e. "*.txt") and search option private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption); } // Returns an array of Directories in the current directory. public static String[] GetDirectories(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public static String[] GetDirectories(String path, String searchPattern) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<String[]>() != null); return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path public static String[] GetFileSystemEntries(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). We disallow .. as a part of the search criteria public static String[] GetFileSystemEntries(String path, String searchPattern) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). We disallow .. as a part of the search criteria public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, searchPattern, searchOption); } private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption); } // Returns fully qualified user path of dirs/files that matches the search parameters. // For recursive search this method will search through all the sub dirs and execute // the given search criteria against every dir. // For all the dirs/files returned, it will then demand path discovery permission for // their parent folders (it will avoid duplicate permission checks) internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(userPathOriginal != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption, (includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0)); return EnumerableHelpers.ToArray(enumerable); } public static IEnumerable<String> EnumerateDirectories(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true); } public static IEnumerable<String> EnumerateFiles(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFiles(String path, String searchPattern) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false); } public static IEnumerable<String> EnumerateFileSystemEntries(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException(nameof(path)); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true); } private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption, bool includeFiles, bool includeDirs) { Debug.Assert(path != null); Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption, (includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0)); } [System.Security.SecuritySafeCritical] public static String GetDirectoryRoot(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); return root; } internal static String InternalGetDirectoryRoot(String path) { if (path == null) return null; return path.Substring(0, PathInternal.GetRootLength(path)); } /*===============================CurrentDirectory=============================== **Action: Provides a getter and setter for the current directory. The original ** current DirectoryInfo is the one from which the process was started. **Returns: The current DirectoryInfo (from the getter). Void from the setter. **Arguments: The current DirectoryInfo to which to switch to the setter. **Exceptions: ==============================================================================*/ [System.Security.SecuritySafeCritical] public static String GetCurrentDirectory() { return FileSystem.Current.GetCurrentDirectory(); } [System.Security.SecurityCritical] // auto-generated public static void SetCurrentDirectory(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); Contract.EndContractBlock(); if (PathInternal.IsPathTooLong(path)) throw new PathTooLongException(SR.IO_PathTooLong); String fulldestDirName = Path.GetFullPath(path); FileSystem.Current.SetCurrentDirectory(fulldestDirName); } [System.Security.SecuritySafeCritical] public static void Move(String sourceDirName, String destDirName) { if (sourceDirName == null) throw new ArgumentNullException(nameof(sourceDirName)); if (sourceDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceDirName)); if (destDirName == null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); Contract.EndContractBlock(); String fullsourceDirName = Path.GetFullPath(sourceDirName); String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName); if (PathInternal.IsDirectoryTooLong(sourcePath)) throw new PathTooLongException(SR.IO_PathTooLong); String fulldestDirName = Path.GetFullPath(destDirName); String destPath = EnsureTrailingDirectorySeparator(fulldestDirName); if (PathInternal.IsDirectoryTooLong(destPath)) throw new PathTooLongException(SR.IO_PathTooLong); StringComparison pathComparison = PathInternal.StringComparison; if (String.Equals(sourcePath, destPath, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(sourcePath); String destinationRoot = Path.GetPathRoot(destPath); if (!String.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); if (!FileSystem.Current.DirectoryExists(fullsourceDirName)) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, fullsourceDirName)); if (FileSystem.Current.DirectoryExists(fulldestDirName)) throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, fulldestDirName)); FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName); } [System.Security.SecuritySafeCritical] public static void Delete(String path) { String fullPath = Path.GetFullPath(path); FileSystem.Current.RemoveDirectory(fullPath, false); } [System.Security.SecuritySafeCritical] public static void Delete(String path, bool recursive) { String fullPath = Path.GetFullPath(path); FileSystem.Current.RemoveDirectory(fullPath, recursive); } public static string[] GetLogicalDrives() { return FileSystem.Current.GetLogicalDrives(); } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet * The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangRussianModel.cpp * and adjusted to language specific support. */ namespace UtfUnknown.Core.Models.SingleByte.Russian; internal class Ibm855_RussianModel : RussianModel { private static readonly byte[] BYTE_TO_ORDER_MAP = { CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, RET, CTR, CTR, RET, CTR, CTR, //00 CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, //10 SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, //20 NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, SYM, SYM, SYM, SYM, SYM, SYM, //30 SYM, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 74, 153, 75, 154, //40 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, SYM, SYM, SYM, SYM, SYM, //50 SYM, 71, 172, 66, 173, 65, 174, 76, 175, 64, 176, 177, 77, 72, 178, 69, //60 67, 179, 78, 73, 180, 181, 79, 182, 183, 184, 185, SYM, SYM, SYM, SYM, SYM, //70 191, 192, 193, 194, 68, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 27, 59, 54, 70, 3, 37, 21, 44, 28, 58, 13, 41, 2, 48, 39, 53, 19, 46, 218, 219, 220, 221, 222, 223, 224, 26, 55, 4, 42, 225, 226, 227, 228, 23, 60, 229, 230, 231, 232, 233, 234, 235, 11, 36, 236, 237, 238, 239, 240, 241, 242, 243, 8, 49, 12, 38, 5, 31, 1, 34, 15, 244, 245, 246, 247, 35, 16, 248, 43, 9, 45, 7, 32, 6, 40, 14, 52, 24, 56, 10, 33, 17, 61, 249, 250, 18, 62, 20, 51, 25, 57, 30, 47, 29, 63, 22, 50, 251, NUM, CTR }; public Ibm855_RussianModel() : base( BYTE_TO_ORDER_MAP, CodepageName.IBM855) { } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace Microsoft.Tools.ServiceModel.ComSvcConfig { using System; using System.ServiceModel.Channels; using System.Diagnostics; using System.Configuration; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel; using System.ServiceModel.Configuration; using System.ServiceModel.Description; using Microsoft.Tools.ServiceModel; using Microsoft.Tools.ServiceModel.SvcUtil; using System.Transactions; class ComplusEndpointConfigContainer : EndpointConfigContainer { ComAdminAppInfo appInfo; bool closed; // if this container has not yet been asked to commit or abort, operations are still allowed string appDir; bool mustGenerateAppDir; AtomicFile manifestFile; AtomicFile configFile; bool listenerComponentExists; bool hasServices; TransactionScope scope; bool modified = false; ComplusEndpointConfigContainer(ComAdminAppInfo appInfo) { this.appInfo = appInfo; this.scope = null; if (appInfo.ApplicationDirectory != null && appInfo.ApplicationDirectory.Length > 0) { this.appDir = appInfo.ApplicationDirectory; this.mustGenerateAppDir = false; if (!Directory.Exists(this.appDir)) { // We will not tolerate misconfigured COM+ apps (i.e. we wont create the dir for you, which is consistent with what COM+ does throw Tool.CreateException(SR.GetString(SR.ApplicationDirectoryDoesNotExist, appDir), null); } } else { this.appDir = GeneratedAppDirectoryName(); if (!Directory.Exists(this.appDir)) this.mustGenerateAppDir = true; } this.configFile = new AtomicFile(Path.Combine(this.appDir, "application.config")); this.manifestFile = new AtomicFile(Path.Combine(this.appDir, "application.manifest")); this.listenerComponentExists = appInfo.ListenerExists; this.hasServices = listenerComponentExists; // notice how we initialize this } public override bool WasModified { get { return this.modified; } set { this.modified = value; } } internal AtomicFile ConfigFile { get { return this.configFile; } } internal bool ListenerComponentExists { get { return this.listenerComponentExists; } } public override void AbortChanges() { this.closed = true; this.manifestFile.Abort(); this.configFile.Abort(); if (this.mustGenerateAppDir) { // Delete the directory if it exists if (Directory.Exists(this.appDir)) { Directory.Delete(this.appDir); } } if (scope != null) { try { Transaction.Current.Rollback(); scope.Complete(); scope.Dispose(); } catch (Exception ex) { if (ex is NullReferenceException || ex is SEHException) { throw; } ToolConsole.WriteWarning(SR.GetString(SR.FailedToAbortTransactionWithError, ex.Message)); } } } public override void Add(IList<EndpointConfig> endpointConfigs) { ThrowIfClosed(); Configuration config = GetConfiguration(false); // not read only Debug.Assert(config != null, "config != null"); bool anyAdded = false; foreach (EndpointConfig endpointConfig in endpointConfigs) { Debug.Assert(endpointConfig.Appid == this.appInfo.ID, "can't add endpoint for a different application"); bool added = this.BaseAddEndpointConfig(config, endpointConfig); if (added) { anyAdded = true; // the metadata exchange endpoint is not displayed as a regular endpoint if (endpointConfig.Iid == typeof(IMetadataExchange).GUID) { ToolConsole.WriteLine(SR.GetString(SR.MexEndpointAdded)); continue; } if (!Tool.Options.ShowGuids) { ToolConsole.WriteLine(SR.GetString(SR.InterfaceAdded, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); } else { ToolConsole.WriteLine(SR.GetString(SR.InterfaceAdded, endpointConfig.Clsid, endpointConfig.Iid)); } } else { // the metadata exchange endpoint is not displayed as a regular endpoint if (endpointConfig.Iid == typeof(IMetadataExchange).GUID) { if (!Tool.Options.ShowGuids) ToolConsole.WriteWarning(SR.GetString(SR.MexEndpointAlreadyExposed, endpointConfig.ComponentProgID)); else ToolConsole.WriteWarning(SR.GetString(SR.MexEndpointAlreadyExposed, endpointConfig.Clsid)); } else { if (!Tool.Options.ShowGuids) ToolConsole.WriteWarning(SR.GetString(SR.InterfaceAlreadyExposed, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); else ToolConsole.WriteWarning(SR.GetString(SR.InterfaceAlreadyExposed, endpointConfig.Clsid, endpointConfig.Iid)); } } } if (anyAdded) { WasModified = true; config.Save(); } this.hasServices = true; } const string defaultBindingType = "netNamedPipeBinding"; const string defaultTransactionBindingType = "netNamedPipeBinding"; const string defaultMexBindingType = "mexNamedPipeBinding"; const string defaultBindingName = "comNonTransactionalBinding"; const string defaultTransactionalBindingName = "comTransactionalBinding"; public override string DefaultBindingType { get { return defaultBindingType; } } public override string DefaultBindingName { get { return defaultBindingName; } } public override string DefaultTransactionalBindingType { get { return defaultTransactionBindingType; } } public override string DefaultTransactionalBindingName { get { return defaultTransactionalBindingName; } } public override string DefaultMexBindingType { get { return defaultMexBindingType; } } public override string DefaultMexBindingName { get { return null; } } void EnsureNetProfileNamedPipeBindingElementBinding(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (!sg.Bindings.NetNamedPipeBinding.Bindings.ContainsKey(this.DefaultBindingName)) { NetNamedPipeBindingElement bindingConfig; bindingConfig = new NetNamedPipeBindingElement(this.DefaultBindingName); sg.Bindings.NetNamedPipeBinding.Bindings.Add(bindingConfig); } if (!sg.Bindings.NetNamedPipeBinding.Bindings.ContainsKey(this.DefaultTransactionalBindingName)) { NetNamedPipeBindingElement bindingConfig; bindingConfig = new NetNamedPipeBindingElement(this.DefaultTransactionalBindingName); bindingConfig.TransactionFlow = true; sg.Bindings.NetNamedPipeBinding.Bindings.Add(bindingConfig); } } protected override void AddBinding(Configuration config) { EnsureNetProfileNamedPipeBindingElementBinding(config); } void EnsureBindingRemoved(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (sg.Bindings.NetNamedPipeBinding.Bindings.ContainsKey(this.DefaultBindingName)) { NetNamedPipeBindingElement element = sg.Bindings.NetNamedPipeBinding.Bindings[this.DefaultBindingName]; sg.Bindings.NetNamedPipeBinding.Bindings.Remove(element); } if (sg.Bindings.NetNamedPipeBinding.Bindings.ContainsKey(this.DefaultTransactionalBindingName)) { NetNamedPipeBindingElement element = sg.Bindings.NetNamedPipeBinding.Bindings[this.DefaultTransactionalBindingName]; sg.Bindings.NetNamedPipeBinding.Bindings.Remove(element); } } protected override void RemoveBinding(Configuration config) { EnsureBindingRemoved(config); } public override void CommitChanges() { this.manifestFile.Commit(); this.configFile.Commit(); if (scope != null) { try { scope.Complete(); scope.Dispose(); } catch (Exception ex) { if (ex is NullReferenceException || ex is SEHException) { throw; } Tool.CreateException(SR.GetString(SR.FailedToCommitChangesToCatalog), ex); } } } public override void PrepareChanges() { this.closed = true; bool workDone = this.configFile.HasBeenModified() && WasModified; TransactionOptions opts = new TransactionOptions(); opts.Timeout = TimeSpan.FromMinutes(5); opts.IsolationLevel = IsolationLevel.Serializable; scope = new TransactionScope(TransactionScopeOption.Required, opts, EnterpriseServicesInteropOption.Full); if (workDone) { // if appDir doesnt exist, we must create it before we prepare the config files below if (this.mustGenerateAppDir) { // create it Directory.CreateDirectory(this.appDir); ToolConsole.WriteLine(SR.GetString(SR.DirectoryCreated, this.appDir)); } // set the COM+ app property ComAdminWrapper.SetAppDir(this.appInfo.ID.ToString("B"), this.appDir); } this.configFile.Prepare(); if (workDone) { ToolConsole.WriteLine(SR.GetString((this.configFile.OriginalFileExists ? SR.FileUpdated : SR.FileCreated), configFile.OriginalFileName)); } if (workDone && !this.manifestFile.CurrentExists() && this.hasServices) { string fileName = this.manifestFile.GetCurrentFileName(false); // for update CreateManifestFile(this.manifestFile.GetCurrentFileName(false)); ToolConsole.WriteLine(SR.GetString(SR.FileCreated, this.manifestFile.OriginalFileName)); } this.manifestFile.Prepare(); if (workDone) { // Now, install the Listener if it isnt already there if (this.hasServices && !this.listenerComponentExists) { ComAdminWrapper.InstallListener(this.appInfo.ID, this.appDir, this.appInfo.RuntimeVersion); } else if (!this.hasServices && this.listenerComponentExists) { ComAdminWrapper.RemoveListener(this.appInfo.ID); } if (this.appInfo.IsServerActivated) { ToolConsole.WriteWarning(SR.GetString(SR.ShouldRestartApp, this.appInfo.Name)); } } } void CreateManifestFile(string fileName) { using (StreamWriter sw = File.CreateText(fileName)) { sw.WriteLine("<assembly manifestVersion=\"1.0\" xmlns=\"urn:schemas-microsoft-com:asm.v1\"><assemblyIdentity name=\"" + this.appInfo.ID.ToString("B") + "\" version=\"1.0.0.0\" type=\"win32\"/></assembly>"); } } //returns the properly formatted partiton id iff the app is not in the default partition string GetPartitionId(Guid appId) { string partitionId = null; partitionId = ComAdminWrapper.GetPartitionIdForApplication(appId); if ((!String.IsNullOrEmpty(partitionId)) && partitionId != ComAdminWrapper.GetGlobalPartitionID()) { //convert guid to representation without {} Guid partitionGuid = new Guid(partitionId); partitionId = partitionGuid.ToString(); partitionId = partitionId + "/"; } else partitionId = ""; return partitionId; } public override string DefaultEndpointAddress(Guid appId, Guid clsid, Guid iid) { ComAdminAppInfo adminAppInfo = ComAdminWrapper.GetAppInfo(appId.ToString("B")); if (null == adminAppInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindAppInfo, appId.ToString("B")), null); } ComAdminClassInfo adminClassInfo = adminAppInfo.FindClass(clsid.ToString("B")); if (null == adminClassInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindClassInfo, clsid.ToString("B")), null); } ComAdminInterfaceInfo adminInterfaceInfo = adminClassInfo.FindInterface(iid.ToString("B")); if (null == adminInterfaceInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindInterfaceInfo, iid.ToString("B")), null); } string uri = Uri.EscapeUriString(adminInterfaceInfo.Name); if (Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute)) return uri; return iid.ToString().ToUpperInvariant(); } public override string DefaultMexAddress(Guid appId, Guid clsid) { return EndpointConfig.MexEndpointSuffix; } public override string BaseServiceAddress(Guid appId, Guid clsid, Guid iid) { ComAdminAppInfo adminAppInfo = ComAdminWrapper.GetAppInfo(appId.ToString("B")); if (null == adminAppInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindAppInfo, appId.ToString("B")), null); } ComAdminClassInfo adminClassInfo = adminAppInfo.FindClass(clsid.ToString("B")); if (null == adminClassInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindClassInfo, clsid.ToString("B")), null); } string uri = Uri.EscapeUriString("net.pipe://localhost/" + adminAppInfo.Name + "/" + GetPartitionId(appId) + adminClassInfo.Name); if (Uri.IsWellFormedUriString(uri, UriKind.Absolute)) return uri; return "net.pipe://localhost/" + (appId.ToString() + "/" + clsid.ToString()); } // Just like COM+ Import, we create the following directory "%ProgramFiles%\ComPlus Applications\{appid}" string GeneratedAppDirectoryName() { string programFiles; if (ComAdminWrapper.IsApplicationWow(appInfo.ID)) programFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); else programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); return programFiles + "\\ComPlus Applications\\" + this.appInfo.ID.ToString("B") + "\\"; } public static List<ComplusEndpointConfigContainer> Get() { List<ComplusEndpointConfigContainer> containers = new List<ComplusEndpointConfigContainer>(); Guid[] ids = ComAdminWrapper.GetApplicationIds(); foreach (Guid id in ids) { ComplusEndpointConfigContainer container = ComplusEndpointConfigContainer.Get(id.ToString("B")); if (container != null) containers.Add(container); } return containers; } public static ComplusEndpointConfigContainer Get(string appIdOrName) { return Get(appIdOrName, false); } public static ComplusEndpointConfigContainer Get(string appIdOrName, bool rethrow) { ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(appIdOrName); if (appInfo == null) { return null; } try { ComplusEndpointConfigContainer container = new ComplusEndpointConfigContainer(appInfo); return container; } catch (Exception ex) { if (ex is NullReferenceException || ex is SEHException) { throw; } if (rethrow) throw; else ToolConsole.WriteWarning(SR.GetString(SR.FailedToLoadConfigForApplicationIgnoring, appInfo.Name, ex.Message)); } return null; } public override Configuration GetConfiguration(bool readOnly) { string fileName = this.configFile.GetCurrentFileName(readOnly); if (string.IsNullOrEmpty(fileName)) { return null; } return GetConfigurationFromFile(fileName); } public override List<string> GetBaseAddresses(EndpointConfig config) { List<string> ret = new List<string>(); Configuration svcconfig = GetConfiguration(true); ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(svcconfig); ServiceElementCollection serviceColl = sg.Services.Services; ServiceElement serviceElement = null; // Find serviceElement foreach (ServiceElement el in serviceColl) { if (config.MatchServiceType(el.Name)) { serviceElement = el; break; } } if (null == serviceElement) return ret; foreach (BaseAddressElement element in serviceElement.Host.BaseAddresses) ret.Add(element.BaseAddress); return ret; } public override List<EndpointConfig> GetEndpointConfigs() { ThrowIfClosed(); Configuration config = GetConfiguration(true); // readonly if (config == null) { // null config means there is no config to read, return an empty list return new List<EndpointConfig>(); } Dictionary<string, List<EndpointConfig>> endpointConfigs = BaseGetEndpointsFromConfiguration(config); List<EndpointConfig> list = new List<EndpointConfig>(); // now, fix up the appid for all the endpoints foreach (List<EndpointConfig> endpoints in endpointConfigs.Values) { foreach (EndpointConfig endpoint in endpoints) { endpoint.Appid = this.appInfo.ID; endpoint.Container = this; list.Add(endpoint); } } return list; } // we override the default implementation since this container represents a single app anyway public override List<EndpointConfig> GetEndpointConfigs(Guid appid) { ThrowIfClosed(); if (appid == this.appInfo.ID) { return this.GetEndpointConfigs(); // all our endpoints are for that appid } else { return new List<EndpointConfig>(); } } public override void Remove(IList<EndpointConfig> endpointConfigs) { ThrowIfClosed(); Configuration config = GetConfiguration(false); // not read only Debug.Assert(config != null, "config != null"); bool anyRemoved = false; foreach (EndpointConfig endpointConfig in endpointConfigs) { Debug.Assert(endpointConfig.Appid == this.appInfo.ID, "can't remove endpoint for a different application"); bool removed = this.BaseRemoveEndpointConfig(config, endpointConfig); if (removed) { anyRemoved = true; if (!Tool.Options.ShowGuids) ToolConsole.WriteLine(SR.GetString(SR.InterfaceRemoved, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); else ToolConsole.WriteLine(SR.GetString(SR.InterfaceRemoved, endpointConfig.Clsid, endpointConfig.Iid)); } else if (!endpointConfig.IsMexEndpoint) { if (!Tool.Options.ShowGuids) ToolConsole.WriteWarning(SR.GetString(SR.InterfaceNotExposed, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); else ToolConsole.WriteWarning(SR.GetString(SR.InterfaceNotExposed, endpointConfig.Clsid, endpointConfig.Iid)); } } this.hasServices = ServiceModelSectionGroup.GetSectionGroup(config).Services.Services.Count > 0; if (anyRemoved) { WasModified = true; config.Save(); } } void ThrowIfClosed() { if (this.closed) { Debug.Assert(false, "attempting operation after container is closed"); throw new InvalidOperationException(); } } } }
// Copyright (c) 2021 Alachisoft // // 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 Alachisoft.NCache.Common.Logger; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Common.Collections; using Alachisoft.NCache.Common.Caching; namespace Alachisoft.NCache.Caching.Statistics { public interface StatisticCounter { /// <summary> /// Creates Instancename /// For outproc instanceName = CacheID /// For inProc instanceNAme = CacheID +"-" + ProcessID + ":" +port /// </summary> /// <param name="name"></param> /// <param name="port"></param> /// <param name="inProc"></param> /// <returns></returns> string GetInstanceName(string instanceName, int port, bool inProc); /// <summary> /// Returns true if the current user has the rights to read/write to performance counters /// under the category of object cache. /// </summary> string InstanceName { get; set; } /// <summary> /// Returns true if the current user has the rights to read/write to performance counters /// under the category of object cache. /// </summary> bool UserHasAccessRights { get; } #region / --- IDisposable --- / /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> void Dispose(); #endregion #region / --- Initialization --- / /// <summary> /// Initializes the counter instances and category. /// </summary> void InitializePerfCounters(bool inproc, bool ModuleConfigured = false); #endregion /// <summary> /// Increment the performance counter for Cache item count by one. /// </summary> void IncrementCountStats(long count); /// <summary> /// Increment the performance counter for Cache item count by one. /// </summary> void IncrementCacheLastAccessCountStats(long count); /// <summary> /// Increment the performance counter for Cache item count by one. /// </summary> void IncrementCountStatsBy(long count); /// <summary> /// Increment the performance counter for Cache hits per second. /// </summary> void IncrementHitsPerSecStats(); void IncrementByHitsPerSecStats(long value); /// <summary> /// Increment the performance counter for Cache misses per second. /// </summary> void IncrementMissPerSecStats(); void IncrementByMissPerSecStats(long value); void IncrementHitsRatioPerSecStats(); void IncrementHitsRatioPerSecBaseStats(); void IncrementByHitsRatioPerSecStats(long value); void IncrementByHitsRatioPerSecBaseStats(long value); /// <summary> /// Increment the performance counter for Cache get operations per second. /// </summary> void IncrementGetPerSecStats(); void IncrementByGetPerSecStats(long value); /// <summary> /// Increment the performance counter for Cache add operations per second. /// </summary> void IncrementAddPerSecStats(); /// <summary> /// Increment the performance counter for Cache add operations per second. /// </summary> void IncrementByAddPerSecStats(long value); /// <summary> /// Increment the performance counter for Cache update operations per second. /// </summary> void IncrementUpdPerSecStats(); /// <summary> /// Increment the performance counter for Cache update operations per second. /// </summary> void IncrementByUpdPerSecStats(long value); /// <summary> Increment the performance counter for Cache remove operations per second. </summary> void IncrementDelPerSecStats(); /// <summary> Increment the performance counter for Cache remove operations per second. </summary> void IncrementByDelPerSecStats(long value); /// <summary> Increment the performance counter by value for Cache remove operations per second. </summary> void IncrementDelPerSecStats(int value); /// <summary> Increment the performance counter for Cache evictions per second. </summary> void IncrementEvictPerSecStats(); /// <summary> Increment the performance counter for Cache expirations per second. </summary> void IncrementExpiryPerSecStats(); /// <summary> Increments the performance counter for Cache evictions per second by given value. </summary> void IncrementEvictPerSecStatsBy(long value); /// <summary> Increment the performance counter for Cache expirations per second by given value. </summary> void IncrementExpiryPerSecStatsBy(long value); /// <summary> /// Timestamps the start of sampling interval for Cache avg. and max. per micro-second time of /// fetch operations. /// </summary> void MsecPerGetBeginSample(); /// <summary> /// Timestample and updates the counter for Cache avg. and max. per micro-second time of /// fetch operations. /// </summary> void MsecPerGetEndSample(); /// <summary> /// Timestamps the start of sampling interval for Cache avg. and max. per micro-second time of /// add operations. /// </summary> void MsecPerAddBeginSample(); /// <summary> /// Timestample and updates the counter for Cache avg. and max. per micro-second time of /// add operations. /// </summary> void MsecPerAddEndSample(); /// <summary> /// Timestamps the start of sampling interval for Cache avg. and max. per micro-second time of /// update operations. /// </summary> void MsecPerUpdBeginSample(); /// <summary> /// Timestample and updates the counter for Cache avg. and max. per micro-second time of /// update operations. /// </summary> void MsecPerUpdEndSample(); /// <summary> /// Timestamps the start of sampling interval for Cache avg. and max. per micro-second time of /// remove operations. /// </summary> void MsecPerDelBeginSample(); /// <summary> /// Timestample and updates the counter for Cache avg. and max. per micro-second time of /// remove operations. /// </summary> void MsecPerDelEndSample(); void ResetStateTransferPerfmonCounter(); /// <summary> Increment the performance counter for State Txfr's per second. </summary> void IncrementStateTxfrPerSecStats(); /// <summary> Increment the performance counter for State Txfr's per second by given value. </summary> void IncrementStateTxfrPerSecStatsBy(long value); /// <summary> Increment the performance counter for Data Balance per second. </summary> void IncrementDataBalPerSecStats(); /// <summary> Increment the performance counter for Data Balance per second by given value. </summary> void IncrementDataBalPerSecStatsBy(long value); /// <summary> /// Increment the performance counter for write behind queue operation per sec /// </summary> /// <summary> /// Increment the performance counter for Mirror Queue size by one. /// </summary> void IncrementMirrorQueueSizeStats(long count); /// <summary> /// Increment the performance counter for SlidingIndex Queue size by one. /// </summary> void IncrementSlidingIndexQueueSizeStats(long count); ILogger NCacheLog { get; set;} void IncrementCacheSizeBy(long value); void IncrementCacheSize(); void SetCacheSize(long value); void SetEvictionIndexSize(long value); void IncrementEvictionIndexSizeBy(long value); void IncrementEvictionIndexSize(); void SetExpirationIndexSize(long value); void IncrementMsecPerMessagePublish(long count); void PubSubCounterSetter(string counterType, PerformanceOperator counterOperation); void SetPubSubCounter(long value, string counterType); void IncrementMessagePublishedPerSec(); void IncrementMessageDeliverPerSec(); void IncrementMessageDeliverPerSec(long value); double GetCounterValue(string counterName); void IncrementMessageExpiredPerSec(long 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; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.Versioning; namespace System.Collections.Generic { // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T> { private const int _defaultCapacity = 4; private T[] _items; [ContractPublicPropertyName("Count")] private int _size; private int _version; private object _syncRoot; static readonly T[] _emptyArray = new T[0]; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to _defaultCapacity, and then increased in multiples of two // as required. public List() { _items = _emptyArray; } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public List(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (capacity == 0) _items = _emptyArray; else _items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public List(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { int count = c.Count; if (count == 0) { _items = _emptyArray; } else { _items = new T[count]; c.CopyTo(_items, 0); _size = count; } } else { _size = 0; _items = _emptyArray; // This enumerable could be empty. Let Add allocate a new array, if needed. // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Add(en.Current); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return _items.Length; } set { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } Contract.EndContractBlock(); if (value != _items.Length) { if (value > 0) { var items = new T[value]; Array.Copy(_items, 0, items, 0, _size); _items = items; } else { _items = _emptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } bool System.Collections.IList.IsFixedSize { get { return false; } } // Is this List read-only? bool ICollection<T>.IsReadOnly { get { return false; } } bool System.Collections.IList.IsReadOnly { get { return false; } } // Is this List synchronized (thread-safe)? bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } // Sets or Gets the element at the given index. public T this[int index] { get { // Following trick can reduce the range check by one if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } object System.Collections.IList.this[int index] { get { return this[index]; } set { if (value == null && !(default(T) == null)) throw new ArgumentNullException(nameof(value)); try { this[index] = (T)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(T)), nameof(value)); } } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } int System.Collections.IList.Add(object item) { if (item == null && !(default(T) == null)) throw new ArgumentNullException(nameof(item)); try { Add((T)item); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item)); } return Count - 1; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. public void AddRange(IEnumerable<T> collection) { Contract.Ensures(Count >= Contract.OldValue(Count)); InsertRange(_size, collection); } public ReadOnlyCollection<T> AsReadOnly() { return new ReadOnlyCollection<T>(this); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() <= index + count); Contract.EndContractBlock(); return Array.BinarySearch<T>(_items, index, count, item, comparer); } public int BinarySearch(T item) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, null); } public int BinarySearch(T item, IComparer<T> comparer) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, comparer); } // Clears the contents of List. public void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // EqualityComparer<T>.Default.Equals(). public bool Contains(T item) { // PERF: IndexOf calls Array.IndexOf, which internally // calls EqualityComparer<T>.Default.IndexOf, which // is specialized for different types. This // boosts performance since instead of making a // virtual method call each iteration of the loop, // via EqualityComparer<T>.Default.Equals, we // only make one virtual call to EqualityComparer.IndexOf. return _size != 0 && IndexOf(item) != -1; } bool System.Collections.IList.Contains(object item) { if (IsCompatibleObject(item)) { return Contains((T)item); } return false; } // Copies this List into array, which must be of a // compatible array type. public void CopyTo(T[] array) { CopyTo(array, 0); } // Copies this List into array, which must be of a // compatible array type. void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } Contract.EndContractBlock(); try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Ensures that the capacity of this list is at least the given minimum // value. If the current capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast //if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } public bool Exists(Predicate<T> match) { return FindIndex(match) != -1; } public T Find(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { if (match(_items[i])) { return _items[i]; } } return default(T); } public List<T> FindAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); List<T> list = new List<T>(); for (int i = 0; i < _size; i++) { if (match(_items[i])) { list.Add(_items[i]); } } return list; } public int FindIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindIndex(0, _size, match); } public int FindIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + Count); return FindIndex(startIndex, _size - startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { if ((uint)startIndex > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _size - count) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + count); Contract.EndContractBlock(); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (match(_items[i])) return i; } return -1; } public T FindLast(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = _size - 1; i >= 0; i--) { if (match(_items[i])) { return _items[i]; } } return default(T); } public int FindLastIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindLastIndex(_size - 1, _size, match); } public int FindLastIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); return FindLastIndex(startIndex, startIndex + 1, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); Contract.EndContractBlock(); if (_size == 0) { // Special case for 0 length List if (startIndex != -1) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } } else if ((uint)startIndex >= (uint)_size) // Make sure we're not out of range { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { if (match(_items[i])) { return i; } } return -1; } public void ForEach(Action<T> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } int version = _version; for (int i = 0; i < _size; i++) { if (version != _version) { break; } action(_items[i]); } if (version != _version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public List<T> GetRange(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.Ensures(Contract.Result<List<T>>() != null); Contract.EndContractBlock(); List<T> list = new List<T>(count); Array.Copy(_items, index, list._items, 0, count); list._size = count; return list; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); } int System.Collections.IList.IndexOf(object item) { if (IsCompatibleObject(item)) { return IndexOf((T)item); } return -1; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. public int IndexOf(T item, int index) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. public int IndexOf(T item, int index, int count) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); if (count < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, count); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection); } Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = item; _size++; _version++; } void System.Collections.IList.Insert(int index, object item) { if (item == null && !(default(T) == null)) throw new ArgumentNullException(nameof(item)); try { Insert(index, (T)item); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item)); } } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. public void InsertRange(int index, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { // if collection is ICollection<T> int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } // If we're inserting a List into itself, we want to be able to deal with that. if (this == c) { // Copy first part of _items to insert location Array.Copy(_items, 0, _items, index, index); // Copy last part of _items back to inserted location Array.Copy(_items, index + count, _items, index * 2, _size - index); } else { T[] itemsToInsert = new T[count]; c.CopyTo(itemsToInsert, 0); Array.Copy(itemsToInsert, 0, _items, index, count); } _size += count; } } else { using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Insert(index++, en.Current); } } } _version++; } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. public int LastIndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); if (_size == 0) { // Special case for empty list return -1; } else { return LastIndexOf(item, _size - 1, _size); } } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. public int LastIndexOf(T item, int index) { if (index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); return LastIndexOf(item, index, index + 1); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. public int LastIndexOf(T item, int index, int count) { if ((Count != 0) && (index < 0)) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if ((Count != 0) && (count < 0)) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); if (_size == 0) { // Special case for empty list return -1; } if (index >= _size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (count > index + 1) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } return Array.LastIndexOf(_items, item, index, count); } // Removes the element at the given index. The size of the list is // decreased by one. public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } void System.Collections.IList.Remove(object item) { if (IsCompatibleObject(item)) { Remove((T)item); } } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count)); Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++; if (freeIndex >= _size) return 0; int current = freeIndex + 1; while (current < _size) { // Find the first item which needs to be kept. while (current < _size && match(_items[current])) current++; if (current < _size) { // copy item to the free slot. _items[freeIndex++] = _items[current++]; } } Array.Clear(_items, freeIndex, _size - freeIndex); int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. public void RemoveAt(int index) { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = default(T); _version++; } // Removes a range of elements from this list. public void RemoveRange(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count > 0) { int i = _size; _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } Array.Clear(_items, _size, count); _version++; } } // Reverses the elements in this list. public void Reverse() { Reverse(0, Count); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). public void Reverse(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = index; int j = index + count - 1; T[] array = _items; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } _version++; } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() { Sort(0, Count, null); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort(IComparer<T> comparer) { Sort(0, Count, comparer); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. public void Sort(int index, int count, IComparer<T> comparer) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); Array.Sort<T>(_items, index, count, comparer); _version++; } public void Sort(Comparison<T> comparison) { if (comparison == null) { throw new ArgumentNullException(nameof(comparison)); } Contract.EndContractBlock(); if (_size > 0) { IComparer<T> comparer = Comparer<T>.Create(comparison); Array.Sort(_items, 0, _size, comparer); } } // ToArray returns a new Object array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { Contract.Ensures(Contract.Result<T[]>() != null); Contract.Ensures(Contract.Result<T[]>().Length == Count); if (_size == 0) { return _emptyArray; } T[] array = new T[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimExcess(); public void TrimExcess() { int threshold = (int)(((double)_items.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } public bool TrueForAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { if (!match(_items[i])) { return false; } } return true; } public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private List<T> list; private int index; private int version; private T current; internal Enumerator(List<T> list) { this.list = list; index = 0; version = list._version; current = default(T); } public void Dispose() { } public bool MoveNext() { List<T> localList = list; if (version == localList._version && ((uint)index < (uint)localList._size)) { current = localList._items[index]; index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (version != list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = list._size + 1; current = default(T); return false; } public T Current { get { return current; } } object System.Collections.IEnumerator.Current { get { if (index == 0 || index == list._size + 1) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current; } } void System.Collections.IEnumerator.Reset() { if (version != list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = 0; current = default(T); } } } }
// 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 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> /// ElasticPoolActivitiesOperations operations. /// </summary> internal partial class ElasticPoolActivitiesOperations : IServiceOperations<SqlManagementClient>, IElasticPoolActivitiesOperations { /// <summary> /// Initializes a new instance of the ElasticPoolActivitiesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ElasticPoolActivitiesOperations(SqlManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SqlManagementClient /// </summary> public SqlManagementClient Client { get; private set; } /// <summary> /// Returns elastic pool activities. /// </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='elasticPoolName'> /// The name of the elastic pool for which to get the current activity. /// </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<IEnumerable<ElasticPoolActivity>>> ListByElasticPoolWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (elasticPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName"); } string apiVersion = "2014-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("elasticPoolName", elasticPoolName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByElasticPool", 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.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/elasticPoolActivity").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<ElasticPoolActivity>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ElasticPoolActivity>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace Mapbox.IO.Compression { using System.Diagnostics; using System; // This class decodes GZip header and footer information. // See RFC 1952 for details about the format. internal class GZipDecoder : IFileFormatReader { private GzipHeaderState gzipHeaderSubstate; private GzipHeaderState gzipFooterSubstate; private int gzip_header_flag; private int gzip_header_xlen; private uint expectedCrc32; private uint expectedOutputStreamSizeModulo; private int loopCounter; private uint actualCrc32; private long actualStreamSizeModulo; public GZipDecoder() { Reset(); } public void Reset() { gzipHeaderSubstate = GzipHeaderState.ReadingID1; gzipFooterSubstate = GzipHeaderState.ReadingCRC; expectedCrc32 = 0; expectedOutputStreamSizeModulo = 0; } public bool ReadHeader(InputBuffer input) { while (true) { int bits; switch (gzipHeaderSubstate) { case GzipHeaderState.ReadingID1: bits = input.GetBits(8); if (bits < 0) { return false; } if (bits != GZipConstants.ID1) { throw new InvalidDataException(SR.GetString(SR.CorruptedGZipHeader)); } gzipHeaderSubstate = GzipHeaderState.ReadingID2; goto case GzipHeaderState.ReadingID2; case GzipHeaderState.ReadingID2: bits = input.GetBits(8); if (bits < 0) { return false; } if (bits != GZipConstants.ID2) { throw new InvalidDataException(SR.GetString(SR.CorruptedGZipHeader)); } gzipHeaderSubstate = GzipHeaderState.ReadingCM; goto case GzipHeaderState.ReadingCM; case GzipHeaderState.ReadingCM: bits = input.GetBits(8); if (bits < 0) { return false; } if (bits != GZipConstants.Deflate) { // compression mode must be 8 (deflate) throw new InvalidDataException(SR.GetString(SR.UnknownCompressionMode)); } gzipHeaderSubstate = GzipHeaderState.ReadingFLG; ; goto case GzipHeaderState.ReadingFLG; case GzipHeaderState.ReadingFLG: bits = input.GetBits(8); if (bits < 0) { return false; } gzip_header_flag = bits; gzipHeaderSubstate = GzipHeaderState.ReadingMMTime; loopCounter = 0; // 4 MMTIME bytes goto case GzipHeaderState.ReadingMMTime; case GzipHeaderState.ReadingMMTime: bits = 0; while (loopCounter < 4) { bits = input.GetBits(8); if (bits < 0) { return false; } loopCounter++; } gzipHeaderSubstate = GzipHeaderState.ReadingXFL; loopCounter = 0; goto case GzipHeaderState.ReadingXFL; case GzipHeaderState.ReadingXFL: // ignore XFL bits = input.GetBits(8); if (bits < 0) { return false; } gzipHeaderSubstate = GzipHeaderState.ReadingOS; goto case GzipHeaderState.ReadingOS; case GzipHeaderState.ReadingOS: // ignore OS bits = input.GetBits(8); if (bits < 0) { return false; } gzipHeaderSubstate = GzipHeaderState.ReadingXLen1; goto case GzipHeaderState.ReadingXLen1; case GzipHeaderState.ReadingXLen1: if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.ExtraFieldsFlag) == 0) { goto case GzipHeaderState.ReadingFileName; } bits = input.GetBits(8); if (bits < 0) { return false; } gzip_header_xlen = bits; gzipHeaderSubstate = GzipHeaderState.ReadingXLen2; goto case GzipHeaderState.ReadingXLen2; case GzipHeaderState.ReadingXLen2: bits = input.GetBits(8); if (bits < 0) { return false; } gzip_header_xlen |= (bits << 8); gzipHeaderSubstate = GzipHeaderState.ReadingXLenData; loopCounter = 0; // 0 bytes of XLEN data read so far goto case GzipHeaderState.ReadingXLenData; case GzipHeaderState.ReadingXLenData: bits = 0; while (loopCounter < gzip_header_xlen) { bits = input.GetBits(8); if (bits < 0) { return false; } loopCounter++; } gzipHeaderSubstate = GzipHeaderState.ReadingFileName; loopCounter = 0; goto case GzipHeaderState.ReadingFileName; case GzipHeaderState.ReadingFileName: if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.FileNameFlag) == 0) { gzipHeaderSubstate = GzipHeaderState.ReadingComment; goto case GzipHeaderState.ReadingComment; } do { bits = input.GetBits(8); if (bits < 0) { return false; } if (bits == 0) { // see '\0' in the file name string break; } } while (true); gzipHeaderSubstate = GzipHeaderState.ReadingComment; goto case GzipHeaderState.ReadingComment; case GzipHeaderState.ReadingComment: if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.CommentFlag) == 0) { gzipHeaderSubstate = GzipHeaderState.ReadingCRC16Part1; goto case GzipHeaderState.ReadingCRC16Part1; } do { bits = input.GetBits(8); if (bits < 0) { return false; } if (bits == 0) { // see '\0' in the file name string break; } } while (true); gzipHeaderSubstate = GzipHeaderState.ReadingCRC16Part1; goto case GzipHeaderState.ReadingCRC16Part1; case GzipHeaderState.ReadingCRC16Part1: if ((gzip_header_flag & (int)GZipOptionalHeaderFlags.CRCFlag) == 0) { gzipHeaderSubstate = GzipHeaderState.Done; goto case GzipHeaderState.Done; } bits = input.GetBits(8); // ignore crc if (bits < 0) { return false; } gzipHeaderSubstate = GzipHeaderState.ReadingCRC16Part2; goto case GzipHeaderState.ReadingCRC16Part2; case GzipHeaderState.ReadingCRC16Part2: bits = input.GetBits(8); // ignore crc if (bits < 0) { return false; } gzipHeaderSubstate = GzipHeaderState.Done; goto case GzipHeaderState.Done; case GzipHeaderState.Done: return true; default: Debug.Assert(false, "We should not reach unknown state!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } } } public bool ReadFooter(InputBuffer input) { input.SkipToByteBoundary(); if (gzipFooterSubstate == GzipHeaderState.ReadingCRC) { while (loopCounter < 4) { int bits = input.GetBits(8); if (bits < 0) { return false; } expectedCrc32 |= ((uint)bits << (8 * loopCounter)); loopCounter++; } gzipFooterSubstate = GzipHeaderState.ReadingFileSize; loopCounter = 0; } if (gzipFooterSubstate == GzipHeaderState.ReadingFileSize) { if (loopCounter == 0) expectedOutputStreamSizeModulo = 0; while (loopCounter < 4) { int bits = input.GetBits(8); if (bits < 0) { return false; } expectedOutputStreamSizeModulo |= ((uint) bits << (8 * loopCounter)); loopCounter++; } } return true; } public void UpdateWithBytesRead(byte[] buffer, int offset, int copied) { actualCrc32 = Crc32Helper.UpdateCrc32(actualCrc32, buffer, offset, copied); long n = actualStreamSizeModulo + (uint) copied; if (n >= GZipConstants.FileLengthModulo) { n %= GZipConstants.FileLengthModulo; } actualStreamSizeModulo = n; } public void Validate() { if (expectedCrc32 != actualCrc32) { throw new InvalidDataException(SR.GetString(SR.InvalidCRC)); } if (actualStreamSizeModulo != expectedOutputStreamSizeModulo) { throw new InvalidDataException(SR.GetString(SR.InvalidStreamSize)); } } internal enum GzipHeaderState { // GZIP header ReadingID1, ReadingID2, ReadingCM, ReadingFLG, ReadingMMTime, // iterates 4 times ReadingXFL, ReadingOS, ReadingXLen1, ReadingXLen2, ReadingXLenData, ReadingFileName, ReadingComment, ReadingCRC16Part1, ReadingCRC16Part2, Done, // done reading GZIP header // GZIP footer ReadingCRC, // iterates 4 times ReadingFileSize // iterates 4 times } [Flags] internal enum GZipOptionalHeaderFlags { CRCFlag = 2, ExtraFieldsFlag = 4, FileNameFlag = 8, CommentFlag = 16 } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace WebApiStateful.AutoRest.Client { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; public partial class StatefullClient : ServiceClient<StatefullClient>, IStatefullClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Subscription credentials which uniquely identify client subscription. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets the IValues. /// </summary> public virtual IValues Values { get; private set; } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StatefullClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StatefullClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StatefullClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StatefullClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='credentials'> /// Required. Subscription credentials which uniquely identify client subscription. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public StatefullClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='credentials'> /// Required. Subscription credentials which uniquely identify client subscription. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public StatefullClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Subscription credentials which uniquely identify client subscription. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public StatefullClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StatefullClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Subscription credentials which uniquely identify client subscription. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public StatefullClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Values = new Values(this); this.BaseUri = new Uri("http://localhost:30002"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_XMLDOC using System.Xml; using System.Xml.XPath; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Types { internal static class DocBuilder { internal static string GetDefaultDocumentation(string methodName) { switch (methodName) { case "__abs__": return "x.__abs__() <==> abs(x)"; case "__add__": return "x.__add__(y) <==> x+y"; case "__call__": return "x.__call__(...) <==> x(...)"; case "__delitem__": return "x.__delitem__(y) <==> del x[y]"; case "__eq__": return "x.__eq__(y) <==> x==y"; case "__floordiv__": return "x.__floordiv__(y) <==> x//y"; case "__getitem__": return "x.__getitem__(y) <==> x[y]"; case "__gt__": return "x.__gt__(y) <==> x>y"; case "__hash__": return "x.__hash__() <==> hash(x)"; case "__init__": return "x.__init__(...) initializes x; see x.__class__.__doc__ for signature"; case "__len__": return "x.__len__() <==> len(x)"; case "__lshift__": return "x.__rshift__(y) <==> x<<y"; case "__lt__": return "x.__lt__(y) <==> x<y"; case "__mod__": return "x.__mod__(y) <==> x%y"; case "__mul__": return "x.__mul__(y) <==> x*y"; case "__neg__": return "x.__neg__() <==> -x"; case "__pow__": return "x.__pow__(y[, z]) <==> pow(x, y[, z])"; case "__reduce__": case "__reduce_ex__": return "helper for pickle"; case "__rshift__": return "x.__rshift__(y) <==> x>>y"; case "__setitem__": return "x.__setitem__(i, y) <==> x[i]="; case "__str__": return "x.__str__() <==> str(x)"; case "__sub__": return "x.__sub__(y) <==> x-y"; case "__truediv__": return "x.__truediv__(y) <==> x/y"; } return null; } private static string DocOneInfoForProperty(Type declaringType, string propertyName, MethodInfo getter, MethodInfo setter, IEnumerable<DocumentationAttribute> attrs) { if (!attrs.Any()) { StringBuilder autoDoc = new StringBuilder(); string summary = null; #if FEATURE_XMLDOC string returns = null; GetXmlDocForProperty(declaringType, propertyName, out summary, out returns); #endif if (summary != null) { autoDoc.AppendLine(summary); autoDoc.AppendLine(); } if (getter != null) { autoDoc.Append("Get: "); autoDoc.AppendLine(CreateAutoDoc(getter, propertyName, 0)); } if (setter != null) { autoDoc.Append("Set: "); autoDoc.Append(CreateAutoDoc(setter, propertyName, 1)); autoDoc.AppendLine(" = value"); } return autoDoc.ToString(); } StringBuilder docStr = new StringBuilder(); foreach (var attr in attrs) { docStr.Append(attr.Documentation); docStr.Append(Environment.NewLine); } return docStr.ToString(); } public static string DocOneInfo(ExtensionPropertyInfo info) { return DocOneInfoForProperty(info.DeclaringType, info.Name, info.Getter, info.Setter, Enumerable.Empty<DocumentationAttribute>()); } public static string DocOneInfo(PropertyInfo info) { var attrs = info.GetCustomAttributes<DocumentationAttribute>(); return DocOneInfoForProperty(info.DeclaringType, info.Name, info.GetGetMethod(), info.GetSetMethod(), attrs); } public static string DocOneInfo(FieldInfo info) { var attrs = info.GetCustomAttributes<DocumentationAttribute>(); return DocOneInfoForProperty(info.DeclaringType, info.Name, null, null, attrs); } public static string DocOneInfo(MethodBase info, string name) { return DocOneInfo(info, name, true); } public static string DocOneInfo(MethodBase info, string name, bool includeSelf) { // Look for methods tagged with [Documentation("doc string for foo")] var attr = info.GetCustomAttributes<DocumentationAttribute>().SingleOrDefault(); if (attr != null) { return attr.Documentation; } string defaultDoc = GetDefaultDocumentation(name); if (defaultDoc != null) { return defaultDoc; } return CreateAutoDoc(info, name, 0, includeSelf); } public static string CreateAutoDoc(MethodBase info) { return CreateAutoDoc(info, null, 0); } public static string CreateAutoDoc(EventInfo info) { string summary = null; #if FEATURE_XMLDOC string returns; GetXmlDoc(info, out summary, out returns); #endif return summary; } public static string CreateAutoDoc(Type t) { string summary = null; #if FEATURE_XMLDOC GetXmlDoc(t, out summary); #endif if (t.IsEnum) { string[] names = Enum.GetNames(t); Array values = Enum.GetValues(t); for (int i = 0; i < names.Length; i++) { names[i] = String.Concat(names[i], " (", Convert.ChangeType(values.GetValue(i), Enum.GetUnderlyingType(t), null).ToString(), ")"); } Array.Sort<string>(names); summary = String.Concat( summary, Environment.NewLine, Environment.NewLine, "enum ", t.IsDefined(typeof(FlagsAttribute), false) ? "(flags) ": "", GetPythonTypeName(t), ", values: ", String.Join(", ", names)); } return summary; } public static OverloadDoc GetOverloadDoc(MethodBase info, string name, int endParamSkip) { return GetOverloadDoc(info, name, endParamSkip, true); } /// <summary> /// Creates a DLR OverloadDoc object which describes information about this overload. /// </summary> /// <param name="info">The method to document</param> /// <param name="name">The name of the method if it should override the name in the MethodBase</param> /// <param name="endParamSkip">Parameters to skip at the end - used for removing the value on a setter method</param> /// <param name="includeSelf">true to include self on instance methods</param> public static OverloadDoc GetOverloadDoc(MethodBase info, string name, int endParamSkip, bool includeSelf) { string summary = null, returns = null; List<KeyValuePair<string, string>> parameters = null; #if FEATURE_XMLDOC GetXmlDoc(info, out summary, out returns, out parameters); #endif StringBuilder retType = new StringBuilder(); int returnCount = 0; MethodInfo mi = info as MethodInfo; if (mi != null) { if (mi.ReturnType != typeof(void)) { retType.Append(GetPythonTypeName(mi.ReturnType)); returnCount++; var typeAttrs = mi.ReturnParameter.GetCustomAttributes(typeof(SequenceTypeInfoAttribute), true); if (typeAttrs.Length > 0) { retType.Append(" (of "); SequenceTypeInfoAttribute typeAttr = (SequenceTypeInfoAttribute)typeAttrs[0]; for (int curTypeAttr = 0; curTypeAttr < typeAttr.Types.Count; curTypeAttr++) { if (curTypeAttr != 0) { retType.Append(", "); } retType.Append(GetPythonTypeName(typeAttr.Types[curTypeAttr])); } retType.Append(")"); } var dictTypeAttrs = mi.ReturnParameter.GetCustomAttributes(typeof(DictionaryTypeInfoAttribute), true); if (dictTypeAttrs.Length > 0) { var dictTypeAttr = (DictionaryTypeInfoAttribute)dictTypeAttrs[0]; retType.Append(String.Format(" (of {0} to {1})", GetPythonTypeName(dictTypeAttr.KeyType), GetPythonTypeName(dictTypeAttr.ValueType))); } } if (name == null) { var hashIndex = mi.Name.IndexOf('#'); if (hashIndex == -1) { name = mi.Name; } else { name = mi.Name.Substring(0, hashIndex); } } } else if(name == null) { name = "__new__"; } // For generic methods display either type parameters (for unbound methods) or // type arguments (for bound ones). if (mi != null && mi.IsGenericMethod) { Type[] typePars = mi.GetGenericArguments(); bool unbound = mi.ContainsGenericParameters; StringBuilder tmp = new StringBuilder(); tmp.Append(name); tmp.Append("["); if (typePars.Length > 1) tmp.Append("("); bool insertComma = false; foreach (Type t in typePars) { if (insertComma) tmp.Append(", "); if (unbound) tmp.Append(t.Name); else tmp.Append(GetPythonTypeName(t)); insertComma = true; } if (typePars.Length > 1) tmp.Append(")"); tmp.Append("]"); name = tmp.ToString(); } List<ParameterDoc> paramDoc = new List<ParameterDoc>(); if (mi == null) { if (name == "__new__") { // constructor, auto-insert cls paramDoc.Add(new ParameterDoc("cls", "type")); } } else if (!mi.IsStatic && includeSelf) { paramDoc.Add(new ParameterDoc("self", GetPythonTypeName(mi.DeclaringType))); } ParameterInfo[] pis = info.GetParameters(); for (int i = 0; i < pis.Length - endParamSkip; i++) { ParameterInfo pi = pis[i]; if (i == 0 && pi.ParameterType == typeof(CodeContext)) { // hide CodeContext parameters continue; } if ((pi.Attributes & ParameterAttributes.Out) == ParameterAttributes.Out || pi.ParameterType.IsByRef) { if (returnCount == 1) { retType.Insert(0, "("); } if (returnCount != 0) retType.Append(", "); returnCount++; retType.Append(GetPythonTypeName(pi.ParameterType)); if ((pi.Attributes & ParameterAttributes.Out) == ParameterAttributes.Out) continue; } ParameterFlags flags = ParameterFlags.None; if (pi.IsDefined(typeof(ParamArrayAttribute), false)) { flags |= ParameterFlags.ParamsArray; } else if (pi.IsDefined(typeof(ParamDictionaryAttribute), false)) { flags |= ParameterFlags.ParamsDict; } string paramDocString = null; if (parameters != null) { foreach (var paramXmlDoc in parameters) { if (paramXmlDoc.Key == pi.Name) { paramDocString = paramXmlDoc.Value; break; } } } paramDoc.Add( new ParameterDoc( pi.Name ?? "", // manufactured methods, such as string[].ctor(int) can have no parameter names. GetPythonTypeName(pi.ParameterType), paramDocString, flags ) ); } if (returnCount > 1) { retType.Append(')'); } ParameterDoc retDoc = new ParameterDoc(String.Empty, retType.ToString(), returns); return new OverloadDoc( name, summary, paramDoc, retDoc ); } internal static string CreateAutoDoc(MethodBase info, string name, int endParamSkip) { return CreateAutoDoc(info, name, endParamSkip, true); } internal static string CreateAutoDoc(MethodBase info, string name, int endParamSkip, bool includeSelf) { #if FEATURE_FULL_CONSOLE int lineWidth; try { lineWidth = Console.WindowWidth - 30; } catch { // console output has been redirected. lineWidth = 80; } #else int lineWidth = 80; #endif var docInfo = GetOverloadDoc(info, name, endParamSkip, includeSelf); StringBuilder ret = new StringBuilder(); ret.Append(docInfo.Name); ret.Append("("); string comma = ""; foreach (var param in docInfo.Parameters) { ret.Append(comma); if ((param.Flags & ParameterFlags.ParamsArray) != 0) { ret.Append('*'); } else if ((param.Flags & ParameterFlags.ParamsDict) != 0) { ret.Append("**"); } ret.Append(param.Name); if (!String.IsNullOrEmpty(param.TypeName)) { ret.Append(": "); ret.Append(param.TypeName); } comma = ", "; } ret.Append(")"); if (!String.IsNullOrEmpty(docInfo.ReturnParameter.TypeName)) { ret.Append(" -> "); ret.AppendLine(docInfo.ReturnParameter.TypeName); } // Append XML Doc Info if available if (!String.IsNullOrEmpty(docInfo.Documentation)) { ret.AppendLine(); ret.AppendLine(StringUtils.SplitWords(docInfo.Documentation, true, lineWidth)); } bool emittedParamDoc = false; foreach (var param in docInfo.Parameters) { if (!String.IsNullOrEmpty(param.Documentation)) { if (!emittedParamDoc) { ret.AppendLine(); emittedParamDoc = true; } ret.Append(" "); ret.Append(param.Name); ret.Append(": "); ret.AppendLine(StringUtils.SplitWords(param.Documentation, false, lineWidth)); } } if (!String.IsNullOrEmpty(docInfo.ReturnParameter.Documentation)) { ret.Append(" Returns: "); ret.AppendLine(StringUtils.SplitWords(docInfo.ReturnParameter.Documentation, false, lineWidth)); } return ret.ToString(); } private static string GetPythonTypeName(Type type) { if (type.IsByRef) { type = type.GetElementType(); } if (type.IsGenericParameter) { return type.Name; } return DynamicHelpers.GetPythonTypeFromType(type).Name; } #if FEATURE_XMLDOC private static readonly object _CachedDocLockObject = new object(); private static readonly List<Assembly> _AssembliesWithoutXmlDoc = new List<Assembly>(); [MultiRuntimeAware] private static XPathDocument _CachedDoc; [MultiRuntimeAware] private static string _CachedDocName; private static string GetXmlName(Type type) { StringBuilder res = new StringBuilder(); res.Append("T:"); AppendTypeFormat(type, res); return res.ToString(); } private static string GetXmlName(EventInfo field) { StringBuilder res = new StringBuilder(); res.Append("E:"); AppendTypeFormat(field.DeclaringType, res); res.Append('.'); res.Append(field.Name); return res.ToString(); } private static string GetXmlNameForProperty(Type declaringType, string propertyName) { StringBuilder res = new StringBuilder(); res.Append("P:"); if (!string.IsNullOrEmpty(declaringType.Namespace)) { res.Append(declaringType.Namespace); res.Append('.'); } res.Append(declaringType.Name); res.Append('.'); res.Append(propertyName); return res.ToString(); } private static string GetXmlName(MethodBase info) { StringBuilder res = new StringBuilder(); res.Append("M:"); if (!string.IsNullOrEmpty(info.DeclaringType.Namespace)) { res.Append(info.DeclaringType.Namespace); res.Append('.'); } res.Append(info.DeclaringType.Name); res.Append('.'); res.Append(info.Name); ParameterInfo[] pi = info.GetParameters(); if (pi.Length > 0) { res.Append('('); for (int i = 0; i < pi.Length; i++) { Type curType = pi[i].ParameterType; if (i != 0) res.Append(','); AppendTypeFormat(curType, res, pi[i]); } res.Append(')'); } return res.ToString(); } /// <summary> /// Converts a Type object into a string suitable for lookup in the help file. All generic types are /// converted down to their generic type definition. /// </summary> private static void AppendTypeFormat(Type curType, StringBuilder res, ParameterInfo pi=null) { if (curType.IsGenericType) { curType = curType.GetGenericTypeDefinition(); } if (curType.IsGenericParameter) { res.Append(ReflectionUtils.GenericArityDelimiter); res.Append(curType.GenericParameterPosition); } else if (curType.ContainsGenericParameters) { if (!string.IsNullOrEmpty(curType.Namespace)) { res.Append(curType.Namespace); res.Append('.'); } res.Append(curType.Name.Substring(0, curType.Name.Length - 2)); res.Append('{'); Type[] types = curType.GetGenericArguments(); for (int j = 0; j < types.Length; j++) { if (j != 0) res.Append(','); if (types[j].IsGenericParameter) { res.Append(ReflectionUtils.GenericArityDelimiter); res.Append(types[j].GenericParameterPosition); } else { AppendTypeFormat(types[j], res); } } res.Append('}'); } else { if (pi != null) { if((pi.IsOut || pi.ParameterType.IsByRef) && curType.FullName.EndsWith("&", StringComparison.Ordinal)) { res.Append(curType.FullName.Replace("&", "@")); } else { res.Append(curType.FullName); } } else { res.Append(curType.FullName); } } } private static string GetXmlDocLocation(Assembly assem) { if (_AssembliesWithoutXmlDoc.Contains(assem)) { return null; } string location = null; try { location = assem.Location; } catch (System.Security.SecurityException) { // FileIOPermission is required to access the file } catch (NotSupportedException) { // Dynamic assemblies do not support Assembly.Location } if (string.IsNullOrEmpty(location)) { _AssembliesWithoutXmlDoc.Add(assem); return null; } return location; } #if !NETCOREAPP && !NETSTANDARD private const string _frameworkReferencePath = @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"; #endif /// <summary> /// Gets the XPathDocument for the specified assembly, or null if one is not available. /// </summary> private static XPathDocument GetXPathDocument(Assembly asm) { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CurrentCulture; string location = GetXmlDocLocation(asm); if (location == null) { return null; } string baseDir = Path.GetDirectoryName(location); string baseFile = Path.GetFileNameWithoutExtension(location) + ".xml"; string xml = Path.Combine(Path.Combine(baseDir, ci.Name), baseFile); bool isRef = false; if (!File.Exists(xml)) { int hyphen = ci.Name.IndexOf('-'); if (hyphen != -1) { xml = Path.Combine(Path.Combine(baseDir, ci.Name.Substring(0, hyphen)), baseFile); } if (!File.Exists(xml)) { xml = Path.Combine(baseDir, baseFile); if (!File.Exists(xml)) { #if !NETCOREAPP && !NETSTANDARD // On .NET 4.0 documentation is in the reference assembly location // for 64-bit processes, we need to look in Program Files (x86) xml = Path.Combine( Path.Combine( Environment.GetFolderPath(Environment.Is64BitProcess ? Environment.SpecialFolder.ProgramFilesX86 : Environment.SpecialFolder.ProgramFiles), _frameworkReferencePath ), baseFile ); isRef = true; if (!File.Exists(xml)) #endif { _AssembliesWithoutXmlDoc.Add(asm); return null; } } } } XPathDocument xpd; lock (_CachedDocLockObject) { if (_CachedDocName == xml) { xpd = _CachedDoc; } else { xpd = new XPathDocument(xml); if (isRef) { // attempt to redirect if required var node = xpd.CreateNavigator().SelectSingleNode("/doc/@redirect"); if (node != null) { var redirect = node.Value; redirect = redirect.Replace("%PROGRAMFILESDIR%", Environment.GetFolderPath(Environment.Is64BitProcess ? Environment.SpecialFolder.ProgramFilesX86 : Environment.SpecialFolder.ProgramFiles) + Path.DirectorySeparatorChar); if (File.Exists(redirect)) { xpd = new XPathDocument(redirect); } } } } _CachedDoc = xpd; _CachedDocName = xml; } return xpd; } /// <summary> /// Gets the Xml documentation for the specified MethodBase. /// </summary> private static void GetXmlDoc(MethodBase info, out string summary, out string returns, out List<KeyValuePair<string, string>> parameters) { summary = null; returns = null; parameters = null; XPathDocument xpd = GetXPathDocument(info.DeclaringType.Assembly); if (xpd == null) return; XPathNavigator xpn = xpd.CreateNavigator(); string path = "/doc/members/member[@name='" + GetXmlName(info) + "']/*"; XPathNodeIterator iter = xpn.Select(path); while (iter.MoveNext()) { switch (iter.Current.Name) { case "summary": summary = XmlToString(iter); break; case "returns": returns = XmlToString(iter); break; case "param": string name = null; string paramText = XmlToString(iter); if (iter.Current.MoveToFirstAttribute()) { name = iter.Current.Value; } if (name != null) { if (parameters == null) { parameters = new List<KeyValuePair<string, string>>(); } parameters.Add(new KeyValuePair<string, string>(name, paramText.Trim())); } break; case "exception": break; } } } /// <summary> /// Gets the Xml documentation for the specified Type. /// </summary> private static void GetXmlDoc(Type type, out string summary) { summary = null; XPathDocument xpd = GetXPathDocument(type.Assembly); if (xpd == null) return; XPathNavigator xpn = xpd.CreateNavigator(); string path = "/doc/members/member[@name='" + GetXmlName(type) + "']/*"; XPathNodeIterator iter = xpn.Select(path); while (iter.MoveNext()) { switch (iter.Current.Name) { case "summary": summary = XmlToString(iter); break; } } } /// <summary> /// Gets the Xml documentation for the specified Field. /// </summary> private static void GetXmlDocForProperty(Type declaringType, string propertyName, out string summary, out string returns) { summary = null; returns = null; XPathDocument xpd = GetXPathDocument(declaringType.Assembly); if (xpd == null) return; XPathNavigator xpn = xpd.CreateNavigator(); string path = "/doc/members/member[@name='" + GetXmlNameForProperty(declaringType, propertyName) + "']/*"; XPathNodeIterator iter = xpn.Select(path); while (iter.MoveNext()) { switch (iter.Current.Name) { case "summary": summary = XmlToString(iter); break; case "returns": returns = XmlToString(iter); break; } } } /// <summary> /// Gets the Xml documentation for the specified Field. /// </summary> private static void GetXmlDoc(EventInfo info, out string summary, out string returns) { summary = null; returns = null; XPathDocument xpd = GetXPathDocument(info.DeclaringType.Assembly); if (xpd == null) return; XPathNavigator xpn = xpd.CreateNavigator(); string path = "/doc/members/member[@name='" + GetXmlName(info) + "']/*"; XPathNodeIterator iter = xpn.Select(path); while (iter.MoveNext()) { switch (iter.Current.Name) { case "summary": summary = XmlToString(iter) + Environment.NewLine; break; } } } /// <summary> /// Converts the XML as stored in the config file into a human readable string. /// </summary> private static string XmlToString(XPathNodeIterator iter) { XmlReader xr = iter.Current.ReadSubtree(); StringBuilder text = new StringBuilder(); if (xr.Read()) { for (; ; ) { switch (xr.NodeType) { case XmlNodeType.Text: text.Append(xr.ReadContentAsString()); continue; case XmlNodeType.Element: switch (xr.Name) { case "see": if (xr.MoveToFirstAttribute() && xr.ReadAttributeValue()) { int prefixlen = xr.Value.IndexOf(':') + 1; int arity = xr.Value.IndexOf(ReflectionUtils.GenericArityDelimiter); if (arity != -1) text.Append(xr.Value, prefixlen, arity - prefixlen); else text.Append(xr.Value, prefixlen, xr.Value.Length - prefixlen); } break; case "paramref": if (xr.MoveToAttribute("name")) { text.Append(xr.Value); } break; } break; } if (!xr.Read()) break; } } return text.ToString().Trim(); } #endif } }
// Copyright 2006-2008 Splicer Project - http://www.codeplex.com/splicer/ // // 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 NUnit.Framework; namespace Splicer.Timeline.Tests { [TestFixture] public class CompositionFixture : AbstractFixture { [Test] public void AddComposition() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); IComposition composition = group.AddComposition(); Assert.AreSame(group, composition.Container); Assert.AreSame(group, composition.Group); bool firedBefore = false; bool firedAfter = false; composition.AddingComposition += delegate { firedBefore = true; }; composition.AddedComposition += delegate { firedAfter = true; }; IComposition childComposition = composition.AddComposition(); Assert.AreSame(composition, childComposition.Container); Assert.AreSame(group, childComposition.Group); Assert.AreEqual(1, composition.Compositions.Count); Assert.IsTrue(firedBefore); Assert.IsTrue(firedAfter); } } [Test] public void AddCompositionWithName() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); IComposition composition = group.AddComposition("named", -1); Assert.AreEqual("named", composition.Name); } } [Test] public void AddEffect() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 100, 100); IComposition composition = group.AddComposition(); bool firedBefore = false; bool firedAfter = false; composition.AddingEffect += delegate { firedBefore = true; }; composition.AddedEffect += delegate { firedAfter = true; }; IEffect effect = composition.AddEffect("test", -1, 1, 2, StandardEffects.CreateBlurEffect(2, 2, 10)); Assert.AreEqual("test", effect.Name); Assert.AreEqual(1, effect.Offset); Assert.AreEqual(2, effect.Duration); Assert.AreEqual(1, composition.Effects.Count); Assert.IsTrue(firedBefore); Assert.IsTrue(firedAfter); } } [Test] public void AddTrack() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); IComposition composition = group.AddComposition(); bool firedBefore = false; bool firedAfter = false; composition.AddingTrack += delegate { firedBefore = true; }; composition.AddedTrack += delegate { firedAfter = true; }; ITrack track = composition.AddTrack(); Assert.AreEqual(1, composition.Tracks.Count); Assert.IsTrue(firedBefore); Assert.IsTrue(firedAfter); } } [Test] public void AddTransition() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 100, 100); IComposition composition = group.AddComposition(); bool firedBefore = false; bool firedAfter = false; composition.AddingTransition += delegate { firedBefore = true; }; composition.AddedTransition += delegate { firedAfter = true; }; ITransition transition = composition.AddTransition("test", 0, 2, StandardTransitions.CreateFade(), false); Assert.AreEqual(1, composition.Transitions.Count); Assert.AreEqual("test", transition.Name); Assert.AreEqual(0, transition.Offset); Assert.AreEqual(2, transition.Duration); Assert.IsTrue(firedBefore); Assert.IsTrue(firedAfter); } } [Test] public void CompositionPriorities() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); IComposition first = group.AddComposition("first", -1); IComposition second = group.AddComposition("second", 0); IComposition third = group.AddComposition("third", 1); IComposition fourth = group.AddComposition("fourth", -1); IComposition fifth = group.AddComposition("fifth", 2); Assert.AreEqual(3, first.Priority); Assert.AreEqual(0, second.Priority); Assert.AreEqual(1, third.Priority); Assert.AreEqual(4, fourth.Priority); Assert.AreEqual(2, fifth.Priority); } } [Test] public void EffectPrioirities() { using (ITimeline timeline = new DefaultTimeline()) { EffectDefinition definition = StandardEffects.CreateBlurEffect(2, 10, 2); IGroup group = timeline.AddAudioGroup(); IEffect first = group.AddEffect("first", -1, 0, 10, definition); IEffect second = group.AddEffect("second", 0, 0, 10, definition); IEffect third = group.AddEffect("third", 1, 0, 10, definition); IEffect fourth = group.AddEffect("fourth", -1, 0, 10, definition); IEffect fifth = group.AddEffect("fifth", 2, 0, 10, definition); Assert.AreEqual(3, first.Priority); Assert.AreEqual(0, second.Priority); Assert.AreEqual(1, third.Priority); Assert.AreEqual(4, fourth.Priority); Assert.AreEqual(2, fifth.Priority); } } [Test] public void RemoveEvents() { int count = 0; EventHandler increment = delegate { count++; }; EventHandler<AddedCompositionEventArgs> incrementForAfterCompositionAdded = delegate { count++; }; EventHandler<AddedEffectEventArgs> incrementForAfterEffectAdded = delegate { count++; }; EventHandler<AddedTrackEventArgs> incrementForAfterTrackAdded = delegate { count++; }; EventHandler<AddedTransitionEventArgs> incrementForAfterTransitionAdded = delegate { count++; }; EventHandler<AddedClipEventArgs> incrementForAfterClipAdded = delegate { count++; }; using (ITimeline timeline = new DefaultTimeline()) { IComposition composition = timeline.AddAudioGroup().AddComposition(); composition.AddedComposition += incrementForAfterCompositionAdded; composition.AddedEffect += incrementForAfterEffectAdded; composition.AddedTrack += incrementForAfterTrackAdded; composition.AddedTransition += incrementForAfterTransitionAdded; composition.AddedClip += incrementForAfterClipAdded; composition.AddingComposition += increment; composition.AddingEffect += increment; composition.AddingTrack += increment; composition.AddingTransition += increment; composition.AddingClip += increment; composition.AddComposition(); composition.AddEffect(0, 2, StandardEffects.CreateDefaultBlur()); composition.AddTrack().AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 0, 0, 1); composition.AddTransition(0, 2, StandardTransitions.CreateFade()); Assert.AreEqual(10, count); count = 0; composition.AddedComposition -= incrementForAfterCompositionAdded; composition.AddedEffect -= incrementForAfterEffectAdded; composition.AddedTrack -= incrementForAfterTrackAdded; composition.AddedTransition -= incrementForAfterTransitionAdded; composition.AddedClip -= incrementForAfterClipAdded; composition.AddingComposition -= increment; composition.AddingEffect -= increment; composition.AddingTrack -= increment; composition.AddingTransition -= increment; composition.AddingClip -= increment; composition.AddComposition(); composition.AddEffect(0, 2, StandardEffects.CreateDefaultBlur()); composition.AddTrack(); composition.AddTransition(2, 2, StandardTransitions.CreateFade()); Assert.AreEqual(0, count); } } [Test] public void TrackAddEffectBubblesToComposition() { int beforeCount = 0; int afterCount = 0; using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 100, 100); IComposition composition = group.AddComposition(); composition.AddingEffect += delegate { beforeCount++; }; composition.AddedEffect += delegate { afterCount++; }; ITrack track = composition.AddTrack(); track.AddEffect("test", -1, 1, 2, StandardEffects.CreateBlurEffect(2, 2, 10)); Assert.AreEqual(1, beforeCount); Assert.AreEqual(1, afterCount); } } [Test] public void TrackPrioirities() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); ITrack first = group.AddTrack("first", -1); ITrack second = group.AddTrack("second", 0); ITrack third = group.AddTrack("third", 1); ITrack fourth = group.AddTrack("fourth", -1); ITrack fifth = group.AddTrack("fifth", 2); Assert.AreEqual(3, first.Priority); Assert.AreEqual(0, second.Priority); Assert.AreEqual(1, third.Priority); Assert.AreEqual(4, fourth.Priority); Assert.AreEqual(2, fifth.Priority); } } } }
//----------------------------------------------------------------------- // <copyright file="ReadWriteAuthorization.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Windows Forms extender control that automatically</summary> //----------------------------------------------------------------------- using System; using System.Drawing; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; using Csla; using Wisej.Web; namespace CslaContrib.WisejWeb { /// <summary> /// Windows Forms extender control that automatically /// enables and disables detail form controls based /// on the authorization settings from a CSLA .NET /// business object. /// </summary> [DesignerCategory("")] [ProvideProperty("ApplyAuthorization", typeof(Control))] [ToolboxItem(true), ToolboxBitmap(typeof(ReadWriteAuthorization), "ReadWriteAuthorization")] public class ReadWriteAuthorization : Wisej.Web.Component, IExtenderProvider { // this class keeps track of the control status private class ControlStatus { public bool ApplyAuthorization { get; set; } public bool CanRead { get; set; } } private readonly Dictionary<Control, ControlStatus> _sources = new Dictionary<Control, ControlStatus>(); /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="container">The container of the control.</param> public ReadWriteAuthorization(IContainer container) { container.Add(this); } /// <summary> /// Gets a value indicating whether the extender control /// can extend the specified control. /// </summary> /// <param name="extendee">The control to be extended.</param> /// <remarks> /// Any control implementing either a ReadOnly property or /// Enabled property can be extended. /// </remarks> public bool CanExtend(object extendee) { if (IsPropertyImplemented(extendee, "ReadOnly") || IsPropertyImplemented(extendee, "Enabled")) return true; else return false; } /// <summary> /// Gets the custom ApplyAuthorization extender /// property added to extended controls. /// </summary> /// <param name="source">Control being extended.</param> [Category("Csla")] public bool GetApplyAuthorization(Control source) { ControlStatus result; if (_sources.TryGetValue(source, out result)) return result.ApplyAuthorization; else return false; } /// <summary> /// Sets the custom ApplyAuthorization extender /// property added to extended controls. /// </summary> /// <param name="source">Control being extended.</param> /// <param name="value">New value of property.</param> [Category("Csla")] public void SetApplyAuthorization(Control source, bool value) { ControlStatus status; if (_sources.TryGetValue(source, out status)) status.ApplyAuthorization = value; else _sources.Add( source, new ControlStatus { ApplyAuthorization = value, CanRead = true }); } /// <summary> /// Causes the ReadWriteAuthorization control /// to apply authorization rules from the business /// object to all extended controls on the form. /// </summary> /// <remarks> /// Call this method to refresh the display of detail /// controls on the form any time the authorization /// rules may have changed. Examples include: after /// a user logs in or out, and after an object has /// been updated, inserted, deleted or retrieved /// from the database. /// </remarks> public void ResetControlAuthorization() { foreach (var item in _sources) if (item.Value.ApplyAuthorization) ApplyAuthorizationRules(item.Key); } private void ApplyAuthorizationRules(Control control) { foreach (Binding binding in control.DataBindings) { // get the BindingSource if appropriate if (binding.DataSource is BindingSource) { BindingSource bs = (BindingSource)binding.DataSource; // get the BusinessObject if appropriate Csla.Security.IAuthorizeReadWrite ds = bs.Current as Csla.Security.IAuthorizeReadWrite; if (ds != null) { // get the object property name string propertyName = binding.BindingMemberInfo.BindingField; ApplyReadRules( control, binding, ds.CanReadProperty(propertyName)); ApplyWriteRules( control, binding, ds.CanWriteProperty(propertyName)); } } } } private void ApplyReadRules( Control ctl, Binding binding, bool canRead) { var status = GetControlStatus(ctl); // enable/disable reading of the value if (canRead) { ctl.Enabled = true; // if !CanRead remove format event and refresh value if (!status.CanRead) { binding.Format -= ReturnEmpty; binding.ReadValue(); } } else { ctl.Enabled = false; if (status.CanRead) { binding.Format += ReturnEmpty; } // clear the value displayed by the control var propertyInfo = ctl.GetType().GetProperty(binding.PropertyName, BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public); if (propertyInfo != null) { propertyInfo.SetValue(ctl, GetEmptyValue( Utilities.GetPropertyType( propertyInfo.PropertyType)), new object[] { }); } } // store new status status.CanRead = canRead; } private void ApplyWriteRules( Control ctl, Binding binding, bool canWrite) { if (ctl is Label) return; // enable/disable writing of the value PropertyInfo propertyInfo = ctl.GetType().GetProperty("ReadOnly", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public); if (propertyInfo != null) { bool couldWrite = (!(bool)propertyInfo.GetValue( ctl, new object[] { })); propertyInfo.SetValue( ctl, !canWrite, new object[] { }); if ((!couldWrite) && (canWrite)) binding.ReadValue(); } else { bool couldWrite = ctl.Enabled; ctl.Enabled = canWrite; if ((!couldWrite) && (canWrite)) binding.ReadValue(); } } private void ReturnEmpty( object sender, ConvertEventArgs e) { e.Value = GetEmptyValue(e.DesiredType); } private object GetEmptyValue(Type desiredType) { object result = null; if (desiredType.IsValueType) result = Activator.CreateInstance(desiredType); return result; } private static bool IsPropertyImplemented( object obj, string propertyName) { if (obj.GetType().GetProperty(propertyName, BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public) != null) return true; else return false; } private ControlStatus GetControlStatus(Control control) { return _sources[control]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private bool _disposed; private Stream _contentReadStream; private bool _canCalculateLength; internal const long MaxBufferSize = Int32.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !NETNative // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !NETNative // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(GetComputedOrBufferLength); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } #if NETNative internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, false, true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { if (_bufferedContent == null) { return false; } return _bufferedContent.TryGetBuffer(out buffer); } #endif protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", null); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null); } public Task<string> ReadAsStringAsync() { CheckDisposed(); var tcs = new TaskCompletionSource<string>(this); LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<string>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { return; } if (innerThis._bufferedContent.Length == 0) { innerTcs.TrySetResult(string.Empty); return; } // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; byte[] data = innerThis.GetDataBuffer(innerThis._bufferedContent); int dataLength = (int)innerThis._bufferedContent.Length; // Data is the raw buffer, it may not be full. // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if ((innerThis.Headers.ContentType != null) && (innerThis.Headers.ContentType.CharSet != null)) { try { encoding = Encoding.GetEncoding(innerThis.Headers.ContentType.CharSet); // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(data, dataLength, encoding); } catch (ArgumentException e) { innerTcs.TrySetException(new InvalidOperationException(SR.net_http_content_invalid_charset, e)); return; } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(data, dataLength, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } try { // Drop the BOM when decoding the data. string result = encoding.GetString(data, bomLength, dataLength - bomLength); innerTcs.TrySetResult(result); } catch (Exception ex) { innerTcs.TrySetException(ex); } }); return tcs.Task; } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); var tcs = new TaskCompletionSource<byte[]>(this); LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<byte[]>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerTcs.TrySetResult(innerThis._bufferedContent.ToArray()); } }); return tcs.Task; } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>(this); if (_contentReadStream == null && IsBuffered) { byte[] data = this.GetDataBuffer(_bufferedContent); // We can cast bufferedContent.Length to 'int' since the length will always be in the 'int' range // The .NET Framework doesn't support array lengths > int.MaxValue. Debug.Assert(_bufferedContent.Length <= (long)int.MaxValue); _contentReadStream = new MemoryStream(data, 0, (int)_bufferedContent.Length, false); } if (_contentReadStream != null) { tcs.TrySetResult(_contentReadStream); return tcs.Task; } CreateContentReadStreamAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<Stream>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerThis._contentReadStream = task.Result; innerTcs.TrySetResult(innerThis._contentReadStream); } }); return tcs.Task; } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); public Task CopyToAsync(Stream stream, TransportContext context) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException(nameof(stream)); } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); try { Task task = null; if (IsBuffered) { byte[] data = this.GetDataBuffer(_bufferedContent); task = stream.WriteAsync(data, 0, (int)_bufferedContent.Length); } else { task = SerializeToStreamAsync(stream, context); CheckTaskNotNull(task); } // If the copy operation fails, wrap the exception in an HttpRequestException() if appropriate. task.ContinueWithStandard(tcs, (copyTask, state) => { var innerTcs = (TaskCompletionSource<object>)state; if (copyTask.IsFaulted) { innerTcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException())); } else if (copyTask.IsCanceled) { innerTcs.TrySetCanceled(); } else { innerTcs.TrySetResult(null); } }); } catch (IOException e) { tcs.TrySetException(GetStreamCopyException(e)); } catch (ObjectDisposedException e) { tcs.TrySetException(GetStreamCopyException(e)); } return tcs.Task; } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return CreateCompletedTask(); } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): set the task as faulted and return the task. Debug.Assert(error != null); tcs.TrySetException(error); } else { try { Task task = SerializeToStreamAsync(tempBuffer, null); CheckTaskNotNull(task); task.ContinueWithStandard(copyTask => { try { if (copyTask.IsFaulted) { tempBuffer.Dispose(); // Cleanup partially filled stream. tcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException())); return; } if (copyTask.IsCanceled) { tempBuffer.Dispose(); // Cleanup partially filled stream. tcs.TrySetCanceled(); return; } tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; tcs.TrySetResult(null); } catch (Exception e) { // Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer. tcs.TrySetException(e); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "LoadIntoBufferAsync", e); } }); } catch (IOException e) { tcs.TrySetException(GetStreamCopyException(e)); } catch (ObjectDisposedException e) { tcs.TrySetException(GetStreamCopyException(e)); } } return tcs.Task; } protected virtual Task<Stream> CreateContentReadStreamAsync() { var tcs = new TaskCompletionSource<Stream>(this); // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) => { var innerTcs = (TaskCompletionSource<Stream>)state; var innerThis = (HttpContent)innerTcs.Task.AsyncState; if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs)) { innerTcs.TrySetResult(innerThis._bufferedContent); } }); return tcs.Task; } // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); private long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { Contract.Ensures((Contract.Result<MemoryStream>() != null) || (Contract.ValueAtReturn<Exception>(out error) != null)); error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } private byte[] GetDataBuffer(MemoryStream stream) { // TODO: Use TryGetBuffer() instead of ToArray(). return stream.ToArray(); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null) { _contentReadStream.Dispose(); } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_content_no_task_returned_copytoasync, this.GetType().ToString())); throw new InvalidOperationException(SR.net_http_content_no_task_returned); } } private static Task CreateCompletedTask() { TaskCompletionSource<object> completed = new TaskCompletionSource<object>(); bool resultSet = completed.TrySetResult(null); Debug.Assert(resultSet, "Can't set Task as completed."); return completed.Task; } private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. Exception result = originalException; if ((result is IOException) || (result is ObjectDisposedException)) { result = new HttpRequestException(SR.net_http_content_stream_copy_error, result); } return result; } private static int GetPreambleLength(byte[] data, int dataLength, Encoding encoding) { Debug.Assert(data != null); Debug.Assert(dataLength <= data.Length); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[0] == UTF8PreambleByte0 && data[1] == UTF8PreambleByte1 && data[2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !NETNative // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[0] == UTF32PreambleByte0 && data[1] == UTF32PreambleByte1 && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[0] == UnicodePreambleByte0 && data[1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[0] == BigEndianUnicodePreambleByte0 && data[1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return ByteArrayHasPrefix(data, dataLength, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(byte[] data, int dataLength, out Encoding encoding, out int preambleLength) { Debug.Assert(data != null); Debug.Assert(dataLength <= data.Length); if (dataLength >= 2) { int first2Bytes = data[0] << 8 | data[1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !NETNative // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool ByteArrayHasPrefix(byte[] byteArray, int dataLength, byte[] prefix) { if (prefix == null || byteArray == null || prefix.Length > dataLength || prefix.Length == 0) return false; for (int i = 0; i < prefix.Length; i++) { if (prefix[i] != byteArray[i]) return false; } return true; } #endregion Helpers private class LimitMemoryStream : MemoryStream { private int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { _maxSize = maxSize; } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, _maxSize)); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using Azure.Data.Tables; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Orleans; using Orleans.Configuration; using Orleans.Internal; using Orleans.Providers; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Serialization.TypeSystem; using Orleans.Storage; using Samples.StorageProviders; using TestExtensions; using UnitTests.Persistence; using UnitTests.StorageTests; using Xunit; using Xunit.Abstractions; namespace Tester.AzureUtils.Persistence { [Collection(TestEnvironmentFixture.DefaultCollection)] [TestCategory("Persistence")] public class PersistenceProviderTests_Local { private readonly IProviderRuntime providerRuntime; private readonly Dictionary<string, string> providerCfgProps = new Dictionary<string, string>(); private readonly ITestOutputHelper output; private readonly TestEnvironmentFixture fixture; public PersistenceProviderTests_Local(ITestOutputHelper output, TestEnvironmentFixture fixture) { this.output = output; this.fixture = fixture; this.providerRuntime = new ClientProviderRuntime( fixture.InternalGrainFactory, fixture.Services, fixture.Services.GetRequiredService<ClientGrainContext>()); this.providerCfgProps.Clear(); } [Fact, TestCategory("Functional")] public async Task PersistenceProvider_Mock_WriteRead() { const string testName = nameof(PersistenceProvider_Mock_WriteRead); var store = ActivatorUtilities.CreateInstance<MockStorageProvider>(fixture.Services, testName); await Test_PersistenceProvider_WriteRead(testName, store); } [Fact, TestCategory("Functional")] public async Task PersistenceProvider_FileStore_WriteRead() { const string testName = nameof(PersistenceProvider_FileStore_WriteRead); var store = new OrleansFileStorage("Data"); await Test_PersistenceProvider_WriteRead(testName, store); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure")] public async Task PersistenceProvider_Azure_Read() { TestUtils.CheckForAzureStorage(); const string testName = nameof(PersistenceProvider_Azure_Read); AzureTableGrainStorage store = await InitAzureTableGrainStorage(); await Test_PersistenceProvider_Read(testName, store); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, false)] [InlineData(null, true)] [InlineData(15 * 64 * 1024 - 256, false)] [InlineData(15 * 32 * 1024 - 256, true)] public async Task PersistenceProvider_Azure_WriteRead(int? stringLength, bool useJson) { var testName = string.Format("{0}({1} = {2}, {3} = {4})", nameof(PersistenceProvider_Azure_WriteRead), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJson), useJson); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var store = await InitAzureTableGrainStorage(useJson); await Test_PersistenceProvider_WriteRead(testName, store, grainState); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, false)] [InlineData(null, true)] [InlineData(15 * 64 * 1024 - 256, false)] [InlineData(15 * 32 * 1024 - 256, true)] public async Task PersistenceProvider_Azure_WriteClearRead(int? stringLength, bool useJson) { var testName = string.Format("{0}({1} = {2}, {3} = {4})", nameof(PersistenceProvider_Azure_WriteClearRead), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJson), useJson); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var store = await InitAzureTableGrainStorage(useJson); await Test_PersistenceProvider_WriteClearRead(testName, store, grainState); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, true, false)] [InlineData(null, false, true)] [InlineData(15 * 32 * 1024 - 256, true, false)] [InlineData(15 * 32 * 1024 - 256, false, true)] public async Task PersistenceProvider_Azure_ChangeReadFormat(int? stringLength, bool useJsonForWrite, bool useJsonForRead) { var testName = string.Format("{0}({1} = {2}, {3} = {4}, {5} = {6})", nameof(PersistenceProvider_Azure_ChangeReadFormat), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJsonForWrite), useJsonForWrite, nameof(useJsonForRead), useJsonForRead); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var grainId = LegacyGrainId.NewId(); var store = await InitAzureTableGrainStorage(useJsonForWrite); grainState = await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId); store = await InitAzureTableGrainStorage(useJsonForRead); await Test_PersistenceProvider_Read(testName, store, grainState, grainId); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, true, false)] [InlineData(null, false, true)] [InlineData(15 * 32 * 1024 - 256, true, false)] [InlineData(15 * 32 * 1024 - 256, false, true)] public async Task PersistenceProvider_Azure_ChangeWriteFormat(int? stringLength, bool useJsonForFirstWrite, bool useJsonForSecondWrite) { var testName = string.Format("{0}({1}={2},{3}={4},{5}={6})", nameof(PersistenceProvider_Azure_ChangeWriteFormat), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), "json1stW", useJsonForFirstWrite, "json2ndW", useJsonForSecondWrite); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var grainId = LegacyGrainId.NewId(); var store = await InitAzureTableGrainStorage(useJsonForFirstWrite); await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId); grainState = TestStoreGrainState.NewRandomState(stringLength); grainState.ETag = "*"; store = await InitAzureTableGrainStorage(useJsonForSecondWrite); await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, false)] [InlineData(null, true)] [InlineData(15 * 64 * 1024 - 256, false)] [InlineData(15 * 32 * 1024 - 256, true)] public async Task AzureTableStorage_ConvertToFromStorageFormat(int? stringLength, bool useJson) { var testName = string.Format("{0}({1} = {2}, {3} = {4})", nameof(AzureTableStorage_ConvertToFromStorageFormat), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJson), useJson); var state = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(state); var storage = await InitAzureTableGrainStorage(useJson); var initialState = state.State; var entity = new TableEntity(); storage.ConvertToStorageFormat(initialState, entity); var convertedState = storage.ConvertFromStorageFormat<TestStoreGrainState>(entity); Assert.NotNull(convertedState); Assert.Equal(initialState.A, convertedState.A); Assert.Equal(initialState.B, convertedState.B); Assert.Equal(initialState.C, convertedState.C); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure")] public async Task AzureTableStorage_ConvertJsonToFromStorageFormatWithCustomJsonProperties() { TestUtils.CheckForAzureStorage(); var state = TestStoreGrainStateWithCustomJsonProperties.NewRandomState(null); var storage = await InitAzureTableGrainStorage(useJson: true, typeNameHandling: TypeNameHandling.None); var initialState = state.State; var entity = new TableEntity(); storage.ConvertToStorageFormat(initialState, entity); var convertedState = storage.ConvertFromStorageFormat<TestStoreGrainStateWithCustomJsonProperties>(entity); Assert.NotNull(convertedState); Assert.Equal(initialState.String, convertedState.String); } [Fact, TestCategory("Functional"), TestCategory("MemoryStore")] public async Task PersistenceProvider_Memory_FixedLatency_WriteRead() { const string testName = nameof(PersistenceProvider_Memory_FixedLatency_WriteRead); TimeSpan expectedLatency = TimeSpan.FromMilliseconds(200); MemoryGrainStorageWithLatency store = new MemoryGrainStorageWithLatency(testName, new MemoryStorageWithLatencyOptions() { Latency = expectedLatency, MockCallsOnly = true }, NullLoggerFactory.Instance, this.providerRuntime.ServiceProvider.GetService<IGrainFactory>()); GrainReference reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); var state = TestStoreGrainState.NewRandomState(); Stopwatch sw = new Stopwatch(); sw.Start(); await store.WriteStateAsync(testName, reference, state); TimeSpan writeTime = sw.Elapsed; this.output.WriteLine("{0} - Write time = {1}", store.GetType().FullName, writeTime); Assert.True(writeTime >= expectedLatency, $"Write: Expected minimum latency = {expectedLatency} Actual = {writeTime}"); sw.Restart(); var storedState = new GrainState<TestStoreGrainState>(); await store.ReadStateAsync(testName, reference, storedState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime); Assert.True(readTime >= expectedLatency, $"Read: Expected minimum latency = {expectedLatency} Actual = {readTime}"); } [Fact, TestCategory("Functional")] public void LoadClassByName() { string className = typeof(MockStorageProvider).FullName; Type classType = new CachedTypeResolver().ResolveType(className); Assert.NotNull(classType); // Type Assert.True(typeof(IGrainStorage).IsAssignableFrom(classType), $"Is an IStorageProvider : {classType.FullName}"); } private async Task<AzureTableGrainStorage> InitAzureTableGrainStorage(AzureTableStorageOptions options) { // TODO change test to include more serializer? var serializer = new OrleansGrainStorageSerializer(this.providerRuntime.ServiceProvider.GetRequiredService<Serializer>()); AzureTableGrainStorage store = ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(this.providerRuntime.ServiceProvider, options, serializer, "TestStorage"); ISiloLifecycleSubject lifecycle = ActivatorUtilities.CreateInstance<SiloLifecycleSubject>(this.providerRuntime.ServiceProvider); store.Participate(lifecycle); await lifecycle.OnStart(); return store; } private async Task<AzureTableGrainStorage> InitAzureTableGrainStorage(bool useJson = false, TypeNameHandling? typeNameHandling = null) { var options = new AzureTableStorageOptions(); var jsonOptions = new JsonGrainStorageSerializerOptions { TypeNameHandling = typeNameHandling }; options.ConfigureTestDefaults(); // TODO change test to include more serializer? var binarySerializer = new OrleansGrainStorageSerializer(this.providerRuntime.ServiceProvider.GetRequiredService<Serializer>()); var jsonSerializer = new JsonGrainStorageSerializer(Options.Create(jsonOptions), this.providerRuntime.ServiceProvider); options.GrainStorageSerializer = useJson ? new GrainStorageSerializer(jsonSerializer, binarySerializer) : new GrainStorageSerializer(binarySerializer, jsonSerializer); AzureTableGrainStorage store = ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(this.providerRuntime.ServiceProvider, options, "TestStorage"); ISiloLifecycleSubject lifecycle = ActivatorUtilities.CreateInstance<SiloLifecycleSubject>(this.providerRuntime.ServiceProvider); store.Participate(lifecycle); await lifecycle.OnStart(); return store; } private async Task Test_PersistenceProvider_Read(string grainTypeName, IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default) { var reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(grainId.IsDefault ? (GrainId)LegacyGrainId.NewId() : grainId); if (grainState == null) { grainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState()); } var storedGrainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState()); Stopwatch sw = new Stopwatch(); sw.Start(); await store.ReadStateAsync(grainTypeName, reference, storedGrainState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime); var storedState = storedGrainState.State; Assert.Equal(grainState.State.A, storedState.A); Assert.Equal(grainState.State.B, storedState.B); Assert.Equal(grainState.State.C, storedState.C); } private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteRead(string grainTypeName, IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default) { GrainReference reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(grainId.IsDefault ? (GrainId)LegacyGrainId.NewId() : grainId); if (grainState == null) { grainState = TestStoreGrainState.NewRandomState(); } Stopwatch sw = new Stopwatch(); sw.Start(); await store.WriteStateAsync(grainTypeName, reference, grainState); TimeSpan writeTime = sw.Elapsed; sw.Restart(); var storedGrainState = new GrainState<TestStoreGrainState> { State = new TestStoreGrainState() }; await store.ReadStateAsync(grainTypeName, reference, storedGrainState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime); Assert.Equal(grainState.State.A, storedGrainState.State.A); Assert.Equal(grainState.State.B, storedGrainState.State.B); Assert.Equal(grainState.State.C, storedGrainState.State.C); return storedGrainState; } private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteClearRead(string grainTypeName, IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default) { GrainReference reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(grainId.IsDefault ? (GrainId)LegacyGrainId.NewId() : grainId); if (grainState == null) { grainState = TestStoreGrainState.NewRandomState(); } Stopwatch sw = new Stopwatch(); sw.Start(); await store.WriteStateAsync(grainTypeName, reference, grainState); TimeSpan writeTime = sw.Elapsed; sw.Restart(); await store.ClearStateAsync(grainTypeName, reference, grainState); var storedGrainState = new GrainState<TestStoreGrainState> { State = new TestStoreGrainState() }; await store.ReadStateAsync(grainTypeName, reference, storedGrainState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime); Assert.NotNull(storedGrainState.State); Assert.Equal(default(string), storedGrainState.State.A); Assert.Equal(default(int), storedGrainState.State.B); Assert.Equal(default(long), storedGrainState.State.C); return storedGrainState; } private static void EnsureEnvironmentSupportsState(GrainState<TestStoreGrainState> grainState) { if (grainState.State.A.Length > 400 * 1024) { StorageEmulatorUtilities.EnsureEmulatorIsNotUsed(); } TestUtils.CheckForAzureStorage(); } public class TestStoreGrainStateWithCustomJsonProperties { [JsonProperty("s")] public string String { get; set; } internal static GrainState<TestStoreGrainStateWithCustomJsonProperties> NewRandomState(int? aPropertyLength = null) { return new GrainState<TestStoreGrainStateWithCustomJsonProperties> { State = new TestStoreGrainStateWithCustomJsonProperties { String = aPropertyLength == null ? ThreadSafeRandom.Next().ToString(CultureInfo.InvariantCulture) : GenerateRandomDigitString(aPropertyLength.Value) } }; } private static string GenerateRandomDigitString(int stringLength) { var characters = new char[stringLength]; for (var i = 0; i < stringLength; ++i) { characters[i] = (char)ThreadSafeRandom.Next('0', '9' + 1); } return new string(characters); } } } }
namespace PokerTell.LiveTracker.Tests { using System.Collections.Generic; using System.Linq; using Infrastructure.Interfaces.LiveTracker; using Machine.Specifications; using Moq; using PokerTell.Infrastructure.Interfaces; using PokerTell.Infrastructure.Interfaces.PokerHand; using PokerTell.Infrastructure.Interfaces.Statistics; using PokerTell.Infrastructure.Services; using PokerTell.LiveTracker.Interfaces; using Tools.FunctionalCSharp; using It = Machine.Specifications.It; // Resharper disable InconsistentNaming public abstract class GameControllerSpecs { protected static Mock<IPlayerStatistics> _playerStatistics_Mock; protected static Mock<IPlayerStatisticsUpdater> _playerStatisticsUpdater_Mock; protected static IConstructor<IPlayerStatistics> _playerStatisticsMake; protected static Mock<IPokerTableStatisticsViewModel> _overlayPokerTableStatistics_Mock; protected static Mock<IPokerTableStatisticsViewModel> _liveStatsPokerTableStatistics_Mock; protected static Mock<IGameHistoryViewModel> _gameHistory_Mock; protected static Mock<IConvertedPokerHand> _newHand_Stub; protected static Mock<ILiveTrackerSettingsViewModel> _liveTrackerSettings_Stub; protected static Mock<IPokerTableStatisticsWindowManager> _liveStatsWindow_Mock; protected static Mock<IGameHistoryWindowManager> _gameHistoryWindow_Mock; protected static Mock<ITableOverlayManager> _tableOverlayManager_Mock; protected static GameControllerSut _sut; Establish specContext = () => { _playerStatistics_Mock = new Mock<IPlayerStatistics>(); _playerStatisticsUpdater_Mock = new Mock<IPlayerStatisticsUpdater>(); _playerStatisticsMake = new Constructor<IPlayerStatistics>(() => _playerStatistics_Mock.Object); _overlayPokerTableStatistics_Mock = new Mock<IPokerTableStatisticsViewModel>(); _liveStatsPokerTableStatistics_Mock = new Mock<IPokerTableStatisticsViewModel>(); _gameHistory_Mock = new Mock<IGameHistoryViewModel>(); _newHand_Stub = new Mock<IConvertedPokerHand>(); _liveTrackerSettings_Stub = new Mock<ILiveTrackerSettingsViewModel>(); _gameHistory_Mock = new Mock<IGameHistoryViewModel>(); _liveStatsWindow_Mock = new Mock<IPokerTableStatisticsWindowManager>(); _gameHistoryWindow_Mock = new Mock<IGameHistoryWindowManager>(); _tableOverlayManager_Mock = new Mock<ITableOverlayManager>(); _sut = new GameControllerSut( _gameHistory_Mock.Object, _overlayPokerTableStatistics_Mock.Object, _liveStatsPokerTableStatistics_Mock.Object, _playerStatisticsMake, _playerStatisticsUpdater_Mock.Object, _tableOverlayManager_Mock.Object, _liveStatsWindow_Mock.Object, _gameHistoryWindow_Mock.Object) { LiveTrackerSettings = _liveTrackerSettings_Stub.Object }; }; public abstract class Ctx_NewHand : GameControllerSpecs { protected const string heroName = "hero"; protected const int totalSeats = 2; protected const string pokerSite = "PokerStars"; protected const int showHoleCardsDuration = 1; protected const string tableName = "some table"; Establish context = () => { _newHand_Stub.SetupGet(h => h.HeroName).Returns(heroName); _newHand_Stub.SetupGet(h => h.TotalSeats).Returns(totalSeats); _newHand_Stub.SetupGet(h => h.Site).Returns(pokerSite); _newHand_Stub.SetupGet(h => h.TableName).Returns(tableName); var hero_Stub = new Mock<IConvertedPokerPlayer>(); hero_Stub.SetupGet(p => p.Name).Returns(heroName); _newHand_Stub.SetupGet(h => h.Players).Returns(new[] { hero_Stub.Object }); _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowHoleCardsDuration).Returns(showHoleCardsDuration); }; } public abstract class Ctx_NewHandWith_Bob_Ted_and_Jim_Sut_IsLaunched : Ctx_NewHand { protected const string bob = "bob"; protected const string ted = "ted"; protected const string jim = "jim"; protected static Mock<IPlayerStatistics> bobsStats_Mock; protected static Mock<IPlayerStatistics> tedsStats_Mock; protected static Mock<IPlayerStatistics> jimsStats_Mock; protected static Mock<IConvertedPokerPlayer> bob_Stub; protected static Mock<IConvertedPokerPlayer> ted_Stub; protected static Mock<IConvertedPokerPlayer> jim_Stub; protected static int statsMade; Establish newHandWithBobTedAndJim_Context = () => { bob_Stub = new Mock<IConvertedPokerPlayer>(); ted_Stub = new Mock<IConvertedPokerPlayer>(); jim_Stub = new Mock<IConvertedPokerPlayer>(); bob_Stub.SetupGet(p => p.Name).Returns(bob); ted_Stub.SetupGet(p => p.Name).Returns(ted); jim_Stub.SetupGet(p => p.Name).Returns(jim); bobsStats_Mock = new Mock<IPlayerStatistics>(); tedsStats_Mock = new Mock<IPlayerStatistics>(); jimsStats_Mock = new Mock<IPlayerStatistics>(); var bobsPlayerIdentity_Stub = new Mock<IPlayerIdentity>(); var tedsPlayerIdentity_Stub = new Mock<IPlayerIdentity>(); var jimsPlayerIdentity_Stub = new Mock<IPlayerIdentity>(); bobsStats_Mock.Setup(s => s.InitializePlayer(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(bobsStats_Mock.Object); tedsStats_Mock.Setup(s => s.InitializePlayer(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(tedsStats_Mock.Object); jimsStats_Mock.Setup(s => s.InitializePlayer(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(jimsStats_Mock.Object); bobsPlayerIdentity_Stub.SetupGet(pi => pi.Name).Returns(bob); tedsPlayerIdentity_Stub.SetupGet(pi => pi.Name).Returns(ted); jimsPlayerIdentity_Stub.SetupGet(pi => pi.Name).Returns(jim); bobsStats_Mock.SetupGet(s => s.PlayerIdentity).Returns(bobsPlayerIdentity_Stub.Object); tedsStats_Mock.SetupGet(s => s.PlayerIdentity).Returns(tedsPlayerIdentity_Stub.Object); jimsStats_Mock.SetupGet(s => s.PlayerIdentity).Returns(jimsPlayerIdentity_Stub.Object); statsMade = 0; _playerStatisticsMake = new Constructor<IPlayerStatistics>( () => statsMade.Match() .With(s => s == 0, s => { statsMade++; return bobsStats_Mock.Object; }) .With(s => s == 1, s => { statsMade++; return tedsStats_Mock.Object; }) .With(s => s == 2, s => { statsMade++; return jimsStats_Mock.Object; }) .Do()); _newHand_Stub.SetupGet(h => h.Players).Returns(new[] { bob_Stub.Object, ted_Stub.Object, jim_Stub.Object }); _sut = new GameControllerSut( _gameHistory_Mock.Object, _overlayPokerTableStatistics_Mock.Object, _liveStatsPokerTableStatistics_Mock.Object, _playerStatisticsMake, _playerStatisticsUpdater_Mock.Object, _tableOverlayManager_Mock.Object, _liveStatsWindow_Mock.Object, _gameHistoryWindow_Mock.Object) { LiveTrackerSettings = _liveTrackerSettings_Stub.Object }; _sut.SetIsLaunched(true); }; } [Subject(typeof(GameController), "New Hand, first time")] public class when_told_for_the_first_time_that_a_new_hand_was_found_and_the_user_does_not_want_to_see_the_overlay : Ctx_NewHand { const bool showTableOverlay = false; Establish context = () => _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowTableOverlay).Returns(showTableOverlay); Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_not_initialize_the_TableOverlayManager = () => _tableOverlayManager_Mock.Verify(tom => tom.InitializeWith(Moq.It.IsAny<IGameHistoryViewModel>(), Moq.It.IsAny<IPokerTableStatisticsViewModel>(), Moq.It.IsAny<int>(), Moq.It.IsAny<IConvertedPokerHand>()), Times.Never()); It should_set_IsLaunched_to_true = () => _sut.IsLaunched.ShouldBeTrue(); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "New Hand, first time")] public class when_told_for_the_first_time_that_a_new_hand_was_found_and_user_wants_to_see_the_overlay : Ctx_NewHand { const bool showTableOverlay = true; Establish context = () => _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowTableOverlay).Returns(showTableOverlay); Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_initialize_the_TableOverlayManager = () => _tableOverlayManager_Mock.Verify(tom => tom.InitializeWith(_gameHistory_Mock.Object, _overlayPokerTableStatistics_Mock.Object, showHoleCardsDuration, _newHand_Stub.Object)); It should_set_IsLaunched_to_true = () => _sut.IsLaunched.ShouldBeTrue(); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "New Hand, first time")] public class when_told_for_the_first_time_that_a_new_hand_was_found_and_user_wants_to_see_the_livestats_window_on_startup : Ctx_NewHand { const bool showLiveStatsWindowOnStartup = true; Establish context = () => _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowLiveStatsWindowOnStartup).Returns(showLiveStatsWindowOnStartup); Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_set_the_DataContext_of_the_LiveStats_window_to_the_livestats_pokertable_viewmodel = () => _liveStatsWindow_Mock.VerifySet(lsw => lsw.DataContext = _liveStatsPokerTableStatistics_Mock.Object); It should_show_the_LiveStats_window = () => _liveStatsWindow_Mock.Verify(lsw => lsw.Show()); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "New Hand, first time")] public class when_told_for_the_first_time_that_a_new_hand_was_found_and_user_does_not_want_to_see_the_livestats_window_on_startup : Ctx_NewHand { const bool showLiveStatsWindowOnStartup = false; Establish context = () => _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowLiveStatsWindowOnStartup).Returns(showLiveStatsWindowOnStartup); Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_set_the_DataContext_of_the_LiveStats_window_to_the_livestats_pokertable_viewmodel = () => _liveStatsWindow_Mock.VerifySet(lsw => lsw.DataContext = _liveStatsPokerTableStatistics_Mock.Object); It should_not_show_the_LiveStats_window = () => _liveStatsWindow_Mock.Verify(lsw => lsw.Show(), Times.Never()); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "New Hand, not first time")] public class when_told_that_a_new_hand_was_found_but_not_the_first_time_and_the_user_wants_to_see_LiveStats_and_Overlay_windows : Ctx_NewHand { const bool showLiveStatsWindowOnStartup = true; const bool showTableOverlay = true; Establish context = () => { _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowTableOverlay).Returns(showTableOverlay); _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowLiveStatsWindowOnStartup).Returns(showLiveStatsWindowOnStartup); _sut.SetIsLaunched(true); }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_not_initialize_the_TableOverlayManager_again = () => _tableOverlayManager_Mock.Verify(tom => tom.InitializeWith(Moq.It.IsAny<IGameHistoryViewModel>(), Moq.It.IsAny<IPokerTableStatisticsViewModel>(), Moq.It.IsAny<int>(), Moq.It.IsAny<IConvertedPokerHand>()), Times.Never()); It should_not_set_the_DataContext_of_the_LiveStats_window_to_the_livestats_pokertable_viewmodel_again = () => _liveStatsWindow_Mock.VerifySet(lsw => lsw.DataContext = _liveStatsPokerTableStatistics_Mock.Object, Times.Never()); It should_not_show_the_LiveStats_window_again = () => _liveStatsWindow_Mock.Verify(lsw => lsw.Show(), Times.Never()); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "New Hand")] public class when_told_that_a_new_hand_was_found_and_the_user_does_not_want_to_see_the_overlay : Ctx_NewHand { const bool showTableOverlay = false; Establish context = () => { _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowTableOverlay).Returns(showTableOverlay); _sut.SetIsLaunched(true); }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_add_the_new_hand_to_the_GameHistory_viewmodel = () => _gameHistory_Mock.Verify(gh => gh.AddNewHand(_newHand_Stub.Object)); It should_not_update_the_table_overlay_manager_with_the_players_and_the_board_contained_in_the_hand = () => _tableOverlayManager_Mock.Verify(tom => tom.UpdateWith(_newHand_Stub.Object), Times.Never()); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "New Hand")] public class when_told_about_a_new_hand_and_the_user_wants_to_see_the_table_overlay : Ctx_NewHand { const string board = "As Kh Qs"; const bool showTableOverlay = true; Establish context = () => { _newHand_Stub.SetupGet(h => h.Board).Returns(board); _liveTrackerSettings_Stub.SetupGet(lts => lts.ShowTableOverlay).Returns(showTableOverlay); _sut.SetIsLaunched(true); }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_add_the_new_hand_to_the_GameHistory_viewmodel = () => _gameHistory_Mock.Verify(gh => gh.AddNewHand(_newHand_Stub.Object)); It should_update_the_table_overlay_manager_with_the_players_and_the_board_contained_in_the_hand = () => _tableOverlayManager_Mock.Verify(tom => tom.UpdateWith(_newHand_Stub.Object)); It should_set_the_LiveStats_PokerTableStatistics_table_name_to_the_one_returned_by_the_hand = () => _liveStatsPokerTableStatistics_Mock.VerifySet(lsvm => lsvm.TableName = tableName); } [Subject(typeof(GameController), "NewHand")] public class when_told_about_new_hand_with_bob_ted_and_jim_and_PlayerStatistics_are_empty_and_jim_the_hero_wants_to_see_his_statistics : Ctx_NewHandWith_Bob_Ted_and_Jim_Sut_IsLaunched { Establish context = () => { _newHand_Stub .SetupGet(h => h.HeroName) .Returns(jim); _liveTrackerSettings_Stub .SetupGet(ls => ls.ShowMyStatistics) .Returns(true); }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_add_bob_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(bob); It should_add_ted_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(ted); It should_add_jim_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(jim); It should_initialize_bobs_statistics_with_the_site_and_his_name = () => bobsStats_Mock.Verify(s => s.InitializePlayer(bob, pokerSite)); It should_initialize_teds_statistics_with_the_site_and_his_name = () => tedsStats_Mock.Verify(s => s.InitializePlayer(ted, pokerSite)); It should_initialize_jims_statistics_with_the_site_and_his_name = () => jimsStats_Mock.Verify(s => s.InitializePlayer(jim, pokerSite)); It should_update_bobs_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == bob)))); It should_update_teds_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == ted)))); It should_update_jims_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == jim)))); } [Subject(typeof(GameController), "NewHand")] public class when_told_about_new_hand_with_bob_ted_and_jim_and_PlayerStatistics_are_empty_and_jim_the_hero_does_not_want_to_see_his_statistics : Ctx_NewHandWith_Bob_Ted_and_Jim_Sut_IsLaunched { Establish context = () => { _newHand_Stub .SetupGet(h => h.HeroName) .Returns(jim); _liveTrackerSettings_Stub .SetupGet(ls => ls.ShowMyStatistics) .Returns(false); }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_add_bob_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(bob); It should_add_ted_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(ted); It should_not_add_jim_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldNotContain(jim); It should_initialize_bobs_statistics_with_the_site_and_his_name = () => bobsStats_Mock.Verify(s => s.InitializePlayer(bob, pokerSite)); It should_initialize_teds_statistics_with_the_site_and_his_name = () => tedsStats_Mock.Verify(s => s.InitializePlayer(ted, pokerSite)); It should_not_initialize_jims_statistics_with_the_site_and_his_name = () => jimsStats_Mock.Verify(s => s.InitializePlayer(jim, pokerSite), Times.Never()); It should_update_bobs_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == bob)))); It should_update_teds_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == ted)))); It should_not_update_jims_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == jim))), Times.Never()); } [Subject(typeof(GameController), "NewHand")] public class when_told_about_new_hand_with_bob_ted_and_jim_and_PlayerStatistics_contain_bob_and_ted : Ctx_NewHandWith_Bob_Ted_and_Jim_Sut_IsLaunched { Establish context = () => { _sut.PlayerStatistics.Add(bob, bobsStats_Mock.Object); _sut.PlayerStatistics.Add(ted, tedsStats_Mock.Object); statsMade = 2; }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_add_jim_to_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(jim); It should_not_initialize_bobs_statistics_with_the_site_and_his_name_again = () => bobsStats_Mock.Verify(s => s.InitializePlayer(bob, pokerSite), Times.Never()); It should_not_initialize_teds_statistics_with_the_site_and_his_name_again = () => tedsStats_Mock.Verify(s => s.InitializePlayer(ted, pokerSite), Times.Never()); It should_initialize_jims_statistics_with_the_site_and_his_name = () => jimsStats_Mock.Verify(s => s.InitializePlayer(jim, pokerSite)); It should_update_bobs_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == bob)))); It should_update_teds_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == ted)))); It should_update_jims_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == jim)))); } [Subject(typeof(GameController), "NewHand")] public class when_told_about_new_hand_with_only_bob_and_ted_and_PlayerStatistics_contain_bob_ted_and_jim : Ctx_NewHandWith_Bob_Ted_and_Jim_Sut_IsLaunched { Establish context = () => { _sut.PlayerStatistics.Add(bob, bobsStats_Mock.Object); _sut.PlayerStatistics.Add(ted, tedsStats_Mock.Object); _sut.PlayerStatistics.Add(jim, jimsStats_Mock.Object); // jim left the table _newHand_Stub.SetupGet(h => h.Players).Returns(new[] { bob_Stub.Object, ted_Stub.Object }); }; Because of = () => _sut.NewHand(_newHand_Stub.Object); It should_not_remove_jim_from_the_PlayerStatistics = () => _sut.PlayerStatistics.Keys.ShouldContain(jim); It should_update_bobs_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == bob)))); It should_update_teds_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == ted)))); It should_not_update_jims_statistics = () => _playerStatisticsUpdater_Mock .Verify(su => su.Update(Moq.It.Is<IEnumerable<IPlayerStatistics>>(ps => ps.Any(s => s.PlayerIdentity.Name == jim))), Times.Never()); } [Subject(typeof(GameController), "PlayerStatisticsUpdater finished")] public class when_the_player_statistics_updater_says_that_he_finished_updating_the_statistics : GameControllerSpecs { static IEnumerable<IPlayerStatistics> playerStatistics_Stub; Establish context = () => playerStatistics_Stub = new[] { new Mock<IPlayerStatistics>().Object }; Because of = () => _playerStatisticsUpdater_Mock.Raise(u => u.FinishedUpdatingMultiplePlayerStatistics += null, playerStatistics_Stub); It should_update_the_overlay_pokertable_statistics_with_the_passed_player_statistics = () => _overlayPokerTableStatistics_Mock.Verify(ts => ts.UpdateWith(playerStatistics_Stub)); It should_update_the_liveStats_pokertable_statistics_with_the_passed_player_statistics = () => _liveStatsPokerTableStatistics_Mock.Verify(ts => ts.UpdateWith(playerStatistics_Stub)); } [Subject(typeof(GameController), "Table closed")] public class when_the_overlay_table_manager_says_that_the_table_is_closed : GameControllerSpecs { static bool shuttingDownRaised; Establish context = () => _sut.ShuttingDown += () => shuttingDownRaised = true; Because of = () => _tableOverlayManager_Mock.Raise(tom => tom.TableClosed += null); It should_dispose_the_table_overlay_manager = () => _tableOverlayManager_Mock.Verify(tom => tom.Dispose()); It should_dispose_the_live_stats_window_manager = () => _liveStatsWindow_Mock.Verify(ls => ls.Dispose()); It should_dispose_the_game_history_window_manager = () => _gameHistoryWindow_Mock.Verify(gh => gh.Dispose()); It should_raise_ShuttingDown = () => shuttingDownRaised.ShouldBeTrue(); } [Subject(typeof(GameController), "Show LiveStatsWindow requested")] public class when_the_user_requests_to_see_the_live_stats_window : GameControllerSpecs { Because of = () => _tableOverlayManager_Mock.Raise(tom => tom.ShowLiveStatsWindowRequested += null); It should_show_it = () => _liveStatsWindow_Mock.Verify(lsw => lsw.Show()); It should_activate_it = () => _liveStatsWindow_Mock.Verify(lsw => lsw.Activate()); } [Subject(typeof(GameController), "Show GameHistoryWindow requested")] public class when_the_user_requests_to_see_the_game_history_window : GameControllerSpecs { Because of = () => _tableOverlayManager_Mock.Raise(tom => tom.ShowGameHistoryWindowRequested += null); It should_set_its_DataContext_to_the_GameHistory_ViewModel = () => _gameHistoryWindow_Mock.VerifySet(ghw => ghw.DataContext = _gameHistory_Mock.Object); It should_show_it = () => _gameHistoryWindow_Mock.Verify(ghw => ghw.Show()); It should_activate_it = () => _gameHistoryWindow_Mock.Verify(ghw => ghw.Activate()); } protected class GameControllerSut : GameController { public GameControllerSut( IGameHistoryViewModel gameHistory, IPokerTableStatisticsViewModel overlayPokerTableStatistics, IPokerTableStatisticsViewModel liveStatsPokerTableStatistics, IConstructor<IPlayerStatistics> playerStatisticsMake, IPlayerStatisticsUpdater playerStatisticsUpdater, ITableOverlayManager tableOverlayManager, IPokerTableStatisticsWindowManager pokerTableStatisticsWindowManager, IGameHistoryWindowManager gameHistoryWindowManager) : base( gameHistory, overlayPokerTableStatistics, liveStatsPokerTableStatistics, playerStatisticsMake, playerStatisticsUpdater, tableOverlayManager, pokerTableStatisticsWindowManager, gameHistoryWindowManager) { } public GameControllerSut SetIsLaunched(bool isLaunched) { IsLaunched = isLaunched; return this; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using Baseline; using LamarCodeGeneration; using Marten.Internal.Linq.Includes; using Marten.Internal.Linq.QueryHandlers; using Marten.Internal.Storage; using Marten.Linq; using Marten.Linq.Fields; using Marten.Schema.Arguments; using Marten.Transforms; using Marten.Util; using Npgsql; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; namespace Marten.Internal.Linq { public partial class LinqHandlerBuilder { private readonly IMartenSession _session; private static IList<IMethodCallMatcher> _methodMatchers = new List<IMethodCallMatcher> { new AsJsonMatcher(), new TransformToJsonMatcher(), new TransformToOtherMatcher() }; public LinqHandlerBuilder(IMartenSession session, Expression expression, ResultOperatorBase additionalOperator = null, bool forCompiled = false) { _session = session; Model = forCompiled ? MartenQueryParser.TransformQueryFlyweight.GetParsedQuery(expression) : MartenQueryParser.Flyweight.GetParsedQuery(expression); if (additionalOperator != null) Model.ResultOperators.Add(additionalOperator); var storage = session.StorageFor(Model.SourceType()); TopStatement = CurrentStatement = new DocumentStatement(storage); // TODO -- this probably needs to get fancier later when this goes n-deep if (Model.MainFromClause.FromExpression is SubQueryExpression sub) { readQueryModel(Model, storage, false, storage.Fields); readQueryModel(sub.QueryModel, storage, true, _session.Options.ChildTypeMappingFor(sub.QueryModel.SourceType())); } else { readQueryModel(Model, storage, true, storage.Fields); } } public IList<IIncludePlan> AllIncludes { get; } = new List<IIncludePlan>(); private void readQueryModel(QueryModel queryModel, IDocumentStorage storage, bool considerSelectors, IFieldMapping fields) { var includes = readBodyClauses(queryModel, storage); if (considerSelectors && !(Model.SelectClause.Selector is QuerySourceReferenceExpression)) { var visitor = new SelectorVisitor(this); visitor.Visit(Model.SelectClause.Selector); } foreach (var resultOperator in queryModel.ResultOperators) { if (resultOperator is IncludeResultOperator include) { includes.Add(include.BuildInclude(_session, fields)); } else { AddResultOperator(resultOperator); } } if (includes.Any()) { AllIncludes.AddRange(includes); wrapIncludes(includes); } } private IList<IIncludePlan> readBodyClauses(QueryModel queryModel, IDocumentStorage storage) { var includes = new List<IIncludePlan>(); if (!(Model.SelectClause.Selector is QuerySourceReferenceExpression)) { var visitor = new IncludeVisitor(includes); visitor.Visit(Model.SelectClause.Selector); } for (var i = 0; i < queryModel.BodyClauses.Count; i++) { var clause = queryModel.BodyClauses[i]; switch (clause) { case WhereClause where: CurrentStatement.WhereClauses.Add(@where); break; case OrderByClause orderBy: CurrentStatement.Orderings.AddRange(orderBy.Orderings); break; case AdditionalFromClause additional: var isComplex = queryModel.BodyClauses.Count > i + 1 || queryModel.ResultOperators.Any() || includes.Any(); var elementType = additional.ItemType; var collectionField = storage.Fields.FieldFor(additional.FromExpression); CurrentStatement = CurrentStatement.ToSelectMany(collectionField, _session, isComplex, elementType); break; default: throw new NotSupportedException(); } } return includes; } public Statement CurrentStatement { get; set; } public Statement TopStatement { get; private set; } public QueryModel Model { get; } private void AddResultOperator(ResultOperatorBase resultOperator) { switch (resultOperator) { case ISelectableOperator selectable: CurrentStatement = selectable.ModifyStatement(CurrentStatement, _session); break; case TakeResultOperator take: CurrentStatement.Limit = (int)take.Count.Value(); break; case SkipResultOperator skip: CurrentStatement.Offset = (int)skip.Count.Value(); break; case AnyResultOperator _: CurrentStatement.ToAny(); break; case CountResultOperator _: if (CurrentStatement.IsDistinct) { CurrentStatement.ConvertToCommonTableExpression(_session); CurrentStatement = new CountStatement<int>(CurrentStatement); } else { CurrentStatement.ToCount<int>(); } break; case LongCountResultOperator _: if (CurrentStatement.IsDistinct) { CurrentStatement.ConvertToCommonTableExpression(_session); CurrentStatement = new CountStatement<long>(CurrentStatement); } else { CurrentStatement.ToCount<long>(); } break; case FirstResultOperator first: CurrentStatement.Limit = 1; CurrentStatement.SingleValue = true; CurrentStatement.ReturnDefaultWhenEmpty = first.ReturnDefaultWhenEmpty; CurrentStatement.CanBeMultiples = true; break; case SingleResultOperator single: CurrentStatement.Limit = 2; CurrentStatement.SingleValue = true; CurrentStatement.ReturnDefaultWhenEmpty = single.ReturnDefaultWhenEmpty; CurrentStatement.CanBeMultiples = false; break; case DistinctResultOperator _: CurrentStatement.IsDistinct = true; CurrentStatement.ApplySqlOperator("distinct"); break; case AverageResultOperator _: CurrentStatement.ApplyAggregateOperator("AVG"); break; case SumResultOperator _: CurrentStatement.ApplyAggregateOperator("SUM"); break; case MinResultOperator _: CurrentStatement.ApplyAggregateOperator("MIN"); break; case MaxResultOperator _: CurrentStatement.ApplyAggregateOperator("MAX"); break; case IncludeResultOperator _: // TODO -- ignoring this for now, but should do something with it later maybe? break; case ToJsonArrayResultOperator _: CurrentStatement.ToJsonSelector(); break; case LastResultOperator _: throw new InvalidOperationException("Marten does not support Last() or LastOrDefault() queries. Please reverse the ordering and use First()/FirstOrDefault() instead"); default: throw new NotSupportedException("Don't yet know how to deal with " + resultOperator); } } public IQueryHandler<TResult> BuildHandler<TResult>(QueryStatistics statistics) { BuildDatabaseStatement(statistics); var handler = buildHandlerForCurrentStatement<TResult>(); return AllIncludes.Any() ? new IncludeQueryHandler<TResult>(handler, AllIncludes.Select(x => x.BuildReader(_session)).ToArray()) : handler; } public void BuildDatabaseStatement(QueryStatistics statistics) { if (statistics != null) { CurrentStatement.UseStatistics(statistics); } TopStatement.CompileStructure(new MartenExpressionParser(_session.Serializer, _session.Options)); } private void wrapIncludes(IList<IIncludePlan> includes) { // Just need to guarantee that each include has an index for (var i = 0; i < includes.Count; i++) { includes[i].Index = i; } var statement = new IncludeIdentitySelectorStatement(TopStatement, includes, _session); TopStatement = statement.Top(); CurrentStatement = statement.Current(); } private IQueryHandler<TResult> buildHandlerForCurrentStatement<TResult>() { if (CurrentStatement.SingleValue) { return CurrentStatement.BuildSingleResultHandler<TResult>(_session, TopStatement); } return CurrentStatement.SelectClause.BuildHandler<TResult>(_session, TopStatement, CurrentStatement); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IQueryHandler<TResult> BuildHandler<TDocument, TResult>(ISelector<TDocument> selector, Statement statement) { if (typeof(TResult).CanBeCastTo<IEnumerable<TDocument>>()) { return (IQueryHandler<TResult>)new ListQueryHandler<TDocument>(statement, selector); } throw new NotSupportedException("Marten does not know how to use result type " + typeof(TResult).FullNameInCode()); } public void BuildDiagnosticCommand(FetchType fetchType, CommandBuilder sql) { switch (fetchType) { case FetchType.Any: CurrentStatement.ToAny(); break; case FetchType.Count: CurrentStatement.ToCount<long>(); break; case FetchType.FetchOne: CurrentStatement.Limit = 1; break; } TopStatement.CompileStructure(new MartenExpressionParser(_session.Serializer, _session.Options)); TopStatement.Configure(sql); } public NpgsqlCommand BuildDatabaseCommand(QueryStatistics statistics) { BuildDatabaseStatement(statistics); return _session.BuildCommand(TopStatement); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Dynamics; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Profiling; using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Constants = Umbraco.Core.Constants; using Member = umbraco.cms.businesslogic.member.Member; namespace Umbraco.Web { /// <summary> /// HtmlHelper extensions for use in templates /// </summary> public static class HtmlHelperRenderExtensions { /// <summary> /// Renders the markup for the profiler /// </summary> /// <param name="helper"></param> /// <returns></returns> public static IHtmlString RenderProfiler(this HtmlHelper helper) { return new HtmlString(ProfilerResolver.Current.Profiler.Render()); } /// <summary> /// Renders a partial view that is found in the specified area /// </summary> /// <param name="helper"></param> /// <param name="partial"></param> /// <param name="area"></param> /// <param name="model"></param> /// <param name="viewData"></param> /// <returns></returns> public static MvcHtmlString AreaPartial(this HtmlHelper helper, string partial, string area, object model = null, ViewDataDictionary viewData = null) { var originalArea = helper.ViewContext.RouteData.DataTokens["area"]; helper.ViewContext.RouteData.DataTokens["area"] = area; var result = helper.Partial(partial, model, viewData); helper.ViewContext.RouteData.DataTokens["area"] = originalArea; return result; } /// <summary> /// Will render the preview badge when in preview mode which is not required ever unless the MVC page you are /// using does not inherit from UmbracoTemplatePage /// </summary> /// <param name="helper"></param> /// <returns></returns> /// <remarks> /// See: http://issues.umbraco.org/issue/U4-1614 /// </remarks> public static MvcHtmlString PreviewBadge(this HtmlHelper helper) { if (UmbracoContext.Current.InPreviewMode) { var htmlBadge = String.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), IOHelper.ResolveUrl(SystemDirectories.UmbracoClient), UmbracoContext.Current.HttpContext.Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); return new MvcHtmlString(htmlBadge); } return new MvcHtmlString(""); } public static IHtmlString CachedPartial( this HtmlHelper htmlHelper, string partialViewName, object model, int cachedSeconds, bool cacheByPage = false, bool cacheByMember = false, ViewDataDictionary viewData = null, Func<object, ViewDataDictionary, string> contextualKeyBuilder = null) { var cacheKey = new StringBuilder(partialViewName); if (cacheByPage) { if (UmbracoContext.Current == null) { throw new InvalidOperationException("Cannot cache by page if the UmbracoContext has not been initialized, this parameter can only be used in the context of an Umbraco request"); } cacheKey.AppendFormat("{0}-", UmbracoContext.Current.PageId); } if (cacheByMember) { var currentMember = Member.GetCurrentMember(); cacheKey.AppendFormat("m{0}-", currentMember == null ? 0 : currentMember.Id); } if (contextualKeyBuilder != null) { var contextualKey = contextualKeyBuilder(model, viewData); cacheKey.AppendFormat("c{0}-", contextualKey); } return ApplicationContext.Current.ApplicationCache.CachedPartialView(htmlHelper, partialViewName, model, cachedSeconds, cacheKey.ToString(), viewData); } public static MvcHtmlString EditorFor<T>(this HtmlHelper htmlHelper, string templateName = "", string htmlFieldName = "", object additionalViewData = null) where T : new() { var model = new T(); var typedHelper = new HtmlHelper<T>( htmlHelper.ViewContext.CopyWithModel(model), htmlHelper.ViewDataContainer.CopyWithModel(model)); return typedHelper.EditorFor(x => model, templateName, htmlFieldName, additionalViewData); } /// <summary> /// A validation summary that lets you pass in a prefix so that the summary only displays for elements /// containing the prefix. This allows you to have more than on validation summary on a page. /// </summary> /// <param name="htmlHelper"></param> /// <param name="prefix"></param> /// <param name="excludePropertyErrors"></param> /// <param name="message"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string prefix = "", bool excludePropertyErrors = false, string message = "", IDictionary<string, object> htmlAttributes = null) { if (prefix.IsNullOrWhiteSpace()) { return htmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes); } //if there's a prefix applied, we need to create a new html helper with a filtered ModelState collection so that it only looks for //specific model state with the prefix. var filteredHtmlHelper = new HtmlHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer.FilterContainer(prefix)); return filteredHtmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes); } /// <summary> /// Returns the result of a child action of a strongly typed SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="actionName"></param> /// <returns></returns> public static IHtmlString Action<T>(this HtmlHelper htmlHelper, string actionName) where T : SurfaceController { return htmlHelper.Action(actionName, typeof(T)); } /// <summary> /// Returns the result of a child action of a SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="actionName"></param> /// <param name="surfaceType"></param> /// <returns></returns> public static IHtmlString Action(this HtmlHelper htmlHelper, string actionName, Type surfaceType) { Mandate.ParameterNotNull(surfaceType, "surfaceType"); Mandate.ParameterNotNullOrEmpty(actionName, "actionName"); var routeVals = new RouteValueDictionary(new {area = ""}); var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (!metaData.AreaName.IsNullOrWhiteSpace()) { //set the area to the plugin area if (routeVals.ContainsKey("area")) { routeVals["area"] = metaData.AreaName; } else { routeVals.Add("area", metaData.AreaName); } } return htmlHelper.Action(actionName, metaData.ControllerName, routeVals); } #region GetCropUrl [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, IPublishedContent mediaItem, string cropAlias) { return new HtmlString(mediaItem.GetCropUrl(cropAlias: cropAlias, useCropDimensions: true)); } [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, IPublishedContent mediaItem, string propertyAlias, string cropAlias) { return new HtmlString(mediaItem.GetCropUrl(propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true)); } [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, IPublishedContent mediaItem, int? width = null, int? height = null, string propertyAlias = Constants.Conventions.Media.File, string cropAlias = null, int? quality = null, ImageCropMode? imageCropMode = null, ImageCropAnchor? imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, bool cacheBuster = true, string furtherOptions = null, ImageCropRatioMode? ratioMode = null, bool upScale = true) { return new HtmlString(mediaItem.GetCropUrl(width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode, upScale)); } [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, string imageUrl, int? width = null, int? height = null, string imageCropperValue = null, string cropAlias = null, int? quality = null, ImageCropMode? imageCropMode = null, ImageCropAnchor? imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode? ratioMode = null, bool upScale = true) { return new HtmlString(imageUrl.GetCropUrl(width, height, imageCropperValue, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale)); } #endregion #region BeginUmbracoForm /// <summary> /// Used for rendering out the Form for BeginUmbracoForm /// </summary> internal class UmbracoForm : MvcForm { /// <summary> /// Creates an UmbracoForm /// </summary> /// <param name="viewContext"></param> /// <param name="controllerName"></param> /// <param name="controllerAction"></param> /// <param name="area"></param> /// <param name="method"></param> /// <param name="additionalRouteVals"></param> public UmbracoForm( ViewContext viewContext, string controllerName, string controllerAction, string area, FormMethod method, object additionalRouteVals = null) : base(viewContext) { _viewContext = viewContext; _method = method; _controllerName = controllerName; _encryptedString = UmbracoHelper.CreateEncryptedRouteString(controllerName, controllerAction, area, additionalRouteVals); } private readonly ViewContext _viewContext; private readonly FormMethod _method; private bool _disposed; private readonly string _encryptedString; private readonly string _controllerName; protected override void Dispose(bool disposing) { if (this._disposed) return; this._disposed = true; //Detect if the call is targeting UmbRegisterController/UmbProfileController/UmbLoginStatusController/UmbLoginController and if it is we automatically output a AntiForgeryToken() // We have a controllerName and area so we can match if (_controllerName == "UmbRegister" || _controllerName == "UmbProfile" || _controllerName == "UmbLoginStatus" || _controllerName == "UmbLogin") { _viewContext.Writer.Write(AntiForgery.GetHtml().ToString()); } //write out the hidden surface form routes _viewContext.Writer.Write("<input name='ufprt' type='hidden' value='" + _encryptedString + "' />"); base.Dispose(disposing); } } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName) { return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, object htmlAttributes, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, object htmlAttributes) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType) { return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, object htmlAttributes, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, object htmlAttributes) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, object htmlAttributes, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, object htmlAttributes) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNull(surfaceType, "surfaceType"); var area = ""; var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (metaData.AreaName.IsNullOrWhiteSpace() == false) { //set the area to the plugin area area = metaData.AreaName; } return html.BeginUmbracoForm(action, metaData.ControllerName, area, additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, htmlAttributes, FormMethod.Post); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, IDictionary<string, object> htmlAttributes) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area) { return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); var formAction = UmbracoContext.Current.OriginalRequestUrl.PathAndQuery; return html.RenderForm(formAction, method, htmlAttributes, controllerName, action, area, additionalRouteVals); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { return html.BeginUmbracoForm(action, controllerName, area, additionalRouteVals, htmlAttributes, FormMethod.Post); } /// <summary> /// This renders out the form for us /// </summary> /// <param name="htmlHelper"></param> /// <param name="formAction"></param> /// <param name="method"></param> /// <param name="htmlAttributes"></param> /// <param name="surfaceController"></param> /// <param name="surfaceAction"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> /// <remarks> /// This code is pretty much the same as the underlying MVC code that writes out the form /// </remarks> private static MvcForm RenderForm(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes, string surfaceController, string surfaceAction, string area, object additionalRouteVals = null) { //ensure that the multipart/form-data is added to the html attributes if (htmlAttributes.ContainsKey("enctype") == false) { htmlAttributes.Add("enctype", "multipart/form-data"); } var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(htmlAttributes); // action is implicitly generated, so htmlAttributes take precedence. tagBuilder.MergeAttribute("action", formAction); // method is an explicit parameter, so it takes precedence over the htmlAttributes. tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); var traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled && htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled == false; if (traditionalJavascriptEnabled) { // forms must have an ID for client validation tagBuilder.GenerateId("form" + Guid.NewGuid().ToString("N")); } htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); //new UmbracoForm: var theForm = new UmbracoForm(htmlHelper.ViewContext, surfaceController, surfaceAction, area, method, additionalRouteVals); if (traditionalJavascriptEnabled) { htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"]; } return theForm; } #endregion #region Wrap public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, params IHtmlTagWrapper[] children) { var item = html.Wrap(tag, innerText, (object)null); foreach (var child in children) { item.AddChild(child); } return item; } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner, object anonymousAttributes, params IHtmlTagWrapper[] children) { string innerText = null; if (inner != null && inner.GetType() != typeof(DynamicNull)) { innerText = string.Format("{0}", inner); } var item = html.Wrap(tag, innerText, anonymousAttributes); foreach (var child in children) { item.AddChild(child); } return item; } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner) { string innerText = null; if (inner != null && inner.GetType() != typeof(DynamicNull)) { innerText = string.Format("{0}", inner); } return html.Wrap(tag, innerText, (object)null); } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children) { var wrap = new HtmlTagWrapper(tag); if (anonymousAttributes != null) { wrap.ReflectAttributesFromAnonymousType(anonymousAttributes); } if (!string.IsNullOrWhiteSpace(innerText)) { wrap.AddChild(new HtmlTagWrapperTextNode(innerText)); } foreach (var child in children) { wrap.AddChild(child); } return wrap; } public static HtmlTagWrapper Wrap(this HtmlHelper html, bool visible, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children) { var item = html.Wrap(tag, innerText, anonymousAttributes, children); item.Visible = visible; return item; } #endregion #region canvasdesigner public static IHtmlString EnableCanvasDesigner(this HtmlHelper html, UrlHelper url, UmbracoContext umbCtx) { return html.EnableCanvasDesigner(url, umbCtx, string.Empty, string.Empty); } public static IHtmlString EnableCanvasDesigner(this HtmlHelper html, UrlHelper url, UmbracoContext umbCtx, string canvasdesignerConfigPath) { return html.EnableCanvasDesigner(url, umbCtx, canvasdesignerConfigPath, string.Empty); } public static IHtmlString EnableCanvasDesigner(this HtmlHelper html, UrlHelper url, UmbracoContext umbCtx, string canvasdesignerConfigPath, string canvasdesignerPalettesPath) { var umbracoPath = url.Content(SystemDirectories.Umbraco); string previewLink = @"<script src=""{0}/lib/jquery/jquery.min.js"" type=""text/javascript""></script>" + @"<script src=""{1}"" type=""text/javascript""></script>" + @"<script src=""{2}"" type=""text/javascript""></script>" + @"<script type=""text/javascript"">var pageId = '{3}'</script>" + @"<script src=""{0}/js/canvasdesigner.front.js"" type=""text/javascript""></script>"; string noPreviewLinks = @"<link href=""{1}"" type=""text/css"" rel=""stylesheet"" data-title=""canvasdesignerCss"" />"; // Get page value int pageId = umbCtx.PublishedContentRequest.UmbracoPage.PageID; string[] path = umbCtx.PublishedContentRequest.UmbracoPage.SplitPath; string result = string.Empty; string cssPath = CanvasDesignerUtility.GetStylesheetPath(path, false); if (umbCtx.InPreviewMode) { canvasdesignerConfigPath = string.IsNullOrEmpty(canvasdesignerConfigPath) == false ? canvasdesignerConfigPath : string.Format("{0}/js/canvasdesigner.config.js", umbracoPath); canvasdesignerPalettesPath = string.IsNullOrEmpty(canvasdesignerPalettesPath) == false ? canvasdesignerPalettesPath : string.Format("{0}/js/canvasdesigner.palettes.js", umbracoPath); if (string.IsNullOrEmpty(cssPath) == false) result = string.Format(noPreviewLinks, cssPath) + Environment.NewLine; result = result + string.Format(previewLink, umbracoPath, canvasdesignerConfigPath, canvasdesignerPalettesPath, pageId); } else { // Get css path for current page if (string.IsNullOrEmpty(cssPath) == false) result = string.Format(noPreviewLinks, cssPath); } return new HtmlString(result); } #endregion #region RelatedLink /// <summary> /// Renders an anchor element for a RelatedLink instance. /// Format: &lt;a href=&quot;relatedLink.Link&quot; target=&quot;_blank/_self&quot;&gt;relatedLink.Caption&lt;/a&gt; /// </summary> /// <param name="htmlHelper">The HTML helper instance that this method extends.</param> /// <param name="relatedLink">The RelatedLink instance</param> /// <returns>An anchor element </returns> public static MvcHtmlString GetRelatedLinkHtml(this HtmlHelper htmlHelper, RelatedLink relatedLink) { return htmlHelper.GetRelatedLinkHtml(relatedLink, null); } /// <summary> /// Renders an anchor element for a RelatedLink instance, accepting htmlAttributes. /// Format: &lt;a href=&quot;relatedLink.Link&quot; target=&quot;_blank/_self&quot; htmlAttributes&gt;relatedLink.Caption&lt;/a&gt; /// </summary> /// <param name="htmlHelper">The HTML helper instance that this method extends.</param> /// <param name="relatedLink">The RelatedLink instance</param> /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param> /// <returns></returns> public static MvcHtmlString GetRelatedLinkHtml(this HtmlHelper htmlHelper, RelatedLink relatedLink, object htmlAttributes) { var tagBuilder = new TagBuilder("a"); tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); tagBuilder.MergeAttribute("href", relatedLink.Link); tagBuilder.MergeAttribute("target", relatedLink.NewWindow ? "_blank" : "_self"); tagBuilder.InnerHtml = HttpUtility.HtmlEncode(relatedLink.Caption); return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); } #endregion } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2014-2015 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; #if UNITY using System.Collections; #endif // UNITY using System.Collections.Generic; #if UNITY using System.Reflection; #endif // UNITY using MsgPack.Serialization.CollectionSerializers; namespace MsgPack.Serialization.DefaultSerializers { #if !UNITY /// <summary> /// Provides default implementation for <see cref="Dictionary{TKey,TValue}"/>. /// </summary> /// <typeparam name="TKey">The type of keys of the <see cref="Dictionary{TKey,TValue}"/>.</typeparam> /// <typeparam name="TValue">The type of values of the <see cref="Dictionary{TKey,TValue}"/>.</typeparam> // ReSharper disable once InconsistentNaming internal class System_Collections_Generic_Dictionary_2MessagePackSerializer<TKey, TValue> : MessagePackSerializer<Dictionary<TKey, TValue>>, ICollectionInstanceFactory { private readonly MessagePackSerializer<TKey> _keySerializer; private readonly MessagePackSerializer<TValue> _valueSerializer; public System_Collections_Generic_Dictionary_2MessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) : base( ownerContext ) { this._keySerializer = ownerContext.GetSerializer<TKey>( keysSchema ); this._valueSerializer = ownerContext.GetSerializer<TValue>( valuesSchema ); } protected internal override void PackToCore( Packer packer, Dictionary<TKey, TValue> objectTree ) { PackerUnpackerExtensions.PackDictionaryCore( packer, objectTree, this._keySerializer, this._valueSerializer ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] protected internal override Dictionary<TKey, TValue> UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotMapHeader(); } var count = UnpackHelpers.GetItemsCount( unpacker ); var collection = new Dictionary<TKey, TValue>( count ); this.UnpackToCore( unpacker, collection, count ); return collection; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] protected internal override void UnpackToCore( Unpacker unpacker, Dictionary<TKey, TValue> collection ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotMapHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } private void UnpackToCore( Unpacker unpacker, Dictionary<TKey, TValue> collection, int count ) { for ( int i = 0; i < count; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } TKey key; if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { key = this._keySerializer.UnpackFromCore( subTreeUnpacker ); } } else { key = this._keySerializer.UnpackFromCore( unpacker ); } if ( !unpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { collection.Add( key, this._valueSerializer.UnpackFromCore( subTreeUnpacker ) ); } } else { collection.Add( key, this._valueSerializer.UnpackFromCore( unpacker ) ); } } } public object CreateInstance( int initialCapacity ) { return new Dictionary<TKey, TValue>( initialCapacity ); } } #else // ReSharper disable once InconsistentNaming internal class System_Collections_Generic_Dictionary_2MessagePackSerializer : NonGenericMessagePackSerializer, ICollectionInstanceFactory { private readonly IMessagePackSingleObjectSerializer _keySerializer; private readonly IMessagePackSingleObjectSerializer _valueSerializer; private readonly Type _keyType; private readonly ConstructorInfo _constructor; private readonly MethodInfo _add; public System_Collections_Generic_Dictionary_2MessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits traits, Type keyType, Type valueType, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) : base( ownerContext, targetType ) { this._keySerializer = ownerContext.GetSerializer( keyType, keysSchema ); this._valueSerializer = ownerContext.GetSerializer( valueType, valuesSchema ); this._keyType = keyType; this._constructor = targetType.GetConstructor( new[] { typeof( int ), typeof( IEqualityComparer<> ).MakeGenericType( keyType ) } ); this._add = traits.AddMethod; } protected internal override void PackToCore( Packer packer, object objectTree ) { var asDictionary = objectTree as IDictionary; if ( asDictionary == null ) { packer.PackNull(); return; } packer.PackMapHeader( asDictionary.Count ); foreach ( DictionaryEntry entry in asDictionary ) { this._keySerializer.PackTo( packer, entry.Key ); this._valueSerializer.PackTo( packer, entry.Value ); } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] protected internal override object UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotMapHeader(); } var count = UnpackHelpers.GetItemsCount( unpacker ); var collection = this.CreateInstance( count ); this.UnpackToCore( unpacker, collection, count ); return collection; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] protected internal override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotMapHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } private void UnpackToCore( Unpacker unpacker, object collection, int count ) { for ( int i = 0; i < count; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } object key; if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { key = this._keySerializer.UnpackFrom( subTreeUnpacker ); } } else { key = this._keySerializer.UnpackFrom( unpacker ); } if ( !unpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { this._add.InvokePreservingExceptionType( collection, key, this._valueSerializer.UnpackFrom( subTreeUnpacker ) ); } } else { this._add.InvokePreservingExceptionType( collection, key, this._valueSerializer.UnpackFrom( unpacker ) ); } } } public object CreateInstance( int initialCapacity ) { return AotHelper.CreateSystemCollectionsGenericDictionary( this._constructor, this._keyType, initialCapacity ); } } #endif // !UNITY }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ITGlobal.MarkDocs.Extensions; namespace ITGlobal.MarkDocs.Tags.Impl { /// <summary> /// Tags extension /// </summary> internal sealed class TagsExtension : ITagService, IExtension { #region fields private static readonly string[] EmptyTags = new string[0]; private static readonly IPage[] EmptyPageList = new IPage[0]; private readonly object _stateLock = new object(); private TagsExtensionState _state = TagsExtensionState.Empty; private TagsExtensionState _tempState; #endregion #region ITagService /// <summary> /// Gets a list of all known tags /// </summary> /// <param name="documentation"> /// Documentation /// </param> /// <returns> /// List of tags /// </returns> public IReadOnlyList<string> GetTags(IDocumentation documentation) { lock (_stateLock) { var branch = _state.GetBranch(documentation); return (IReadOnlyList<string>) branch?.Tags ?? Array.Empty<string>(); } } /// <summary> /// Gets a list of normalized page tags /// </summary> /// <param name="page"> /// Page /// </param> /// <returns> /// List of tags /// </returns> public IReadOnlyList<string> GetPageTags(IPage page) { lock (_stateLock) { var branch = _state.GetBranch(page.Documentation); if (branch != null && branch.Pages.TryGetValue(page.Id, out var node)) { return node.Tags; } return Array.Empty<string>(); } } /// <summary> /// Gets a list of pages with specified tag /// </summary> /// <param name="documentation"> /// Documentation /// </param> /// <param name="tag"> /// Tag /// </param> /// <returns> /// List of pages /// </returns> public IReadOnlyList<IPage> GetPagesByTag(IDocumentation documentation, string tag) { return GetPagesByTags(documentation, includeTags: new[] {tag}); } /// <summary> /// Gets a list of pages with tags /// </summary> /// <param name="documentation"> /// Documentation /// </param> /// <param name="includeTags"> /// Include only pages with specified tags /// </param> /// <param name="excludeTags"> /// Exclude pages with specified tags /// </param> /// <returns> /// List of pages /// </returns> public IReadOnlyList<IPage> GetPagesByTags( IDocumentation documentation, string[] includeTags = null, string[] excludeTags = null) { includeTags = NormalizeTags(includeTags); excludeTags = NormalizeTags(excludeTags); TagsExtensionStateBranch branch; lock (_stateLock) { branch = _state.GetBranch(documentation); } if (branch == null) { return Array.Empty<IPage>(); } var query = branch.Pages.AsEnumerable(); if (includeTags != null && includeTags.Length > 0) { foreach (var tag in includeTags) { query = query.Where(_ => _.Value.HasTag(tag)); } } if (excludeTags != null && excludeTags.Length > 0) { foreach (var tag in excludeTags) { query = query.Where(_ => !_.Value.HasTag(tag)); } } var pages = query.Select(_ => _.Value.Page).ToList(); return pages; } #endregion #region IExtension public void Initialize(IMarkDocState state) { var newState = TagsExtensionState.Empty; foreach (var documentation in state.List) { newState = newState.AddOrUpdate(documentation); } lock (_stateLock) { _state = newState; } } public void OnCreated(IDocumentation documentation) { TagsExtensionState state; lock (_stateLock) { state = _state; } state = state.AddOrUpdate(documentation); lock (_stateLock) { _state = state; } } public void OnUpdated(IDocumentation documentation) { TagsExtensionState state; lock (_stateLock) { state = _tempState ?? _state; } state = state.AddOrUpdate(documentation); lock (_stateLock) { _tempState = state; } } public void OnUpdateCompleted(IDocumentation documentation) { lock (_stateLock) { _state = _tempState ?? _state; _tempState = null; } } public void OnRemoved(IDocumentation documentation) { TagsExtensionState state; lock (_stateLock) { state = _state; } state = state.AddOrUpdate(documentation); lock (_stateLock) { _state = state; } } #endregion #region internal methods internal static string NormalizeTag(string tag) { var builder = new StringBuilder(); foreach (var c in tag) { if (char.IsLetterOrDigit(c)) { builder.Append(char.ToLowerInvariant(c)); } else if (char.IsPunctuation(c) || char.IsWhiteSpace(c)) { if (builder.Length > 0 && !char.IsPunctuation(builder[builder.Length - 1])) { builder.Append('-'); } } } while (builder.Length > 0 && char.IsPunctuation(builder[builder.Length - 1])) { builder.Remove(builder.Length - 1, 1); } return builder.ToString(); } internal static string[] NormalizeTags(string[] tags) { if (tags == null || tags.Length == 0) { return Array.Empty<string>(); } return tags.Select(NormalizeTag).ToArray(); } #endregion } }
/* * Timer.cs - Timer handling for Xsharp. * * 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 Xsharp { using System; /// <summary> /// <para>Instances of <see cref="T:Xsharp.Timer"/> are used to /// implement timeout functionality on X displays.</para> /// </summary> /// /// <remarks> /// <para>The delivery of timeout notifications may be delayed by /// event processing, operating system housekeeping, or system load. /// That is, they are not delivered in "real time". The only /// guarantee is that they will be delivered on or sometime after /// the specified time.</para> /// </remarks> public sealed class Timer : IDisposable { // Internal state. private Display dpy; private Delegate callback; private Object state; private DateTime nextDue; private int period; private bool onDisplayQueue; private bool stopped; private Timer next; private Timer prev; /// <summary> /// <para>Create a new timer.</para> /// </summary> /// /// <param name="callback"> /// <para>The delegate to invoke when the timer expires.</para> /// </param> /// /// <param name="state"> /// <para>The state information to pass to the callback.</para> /// </param> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="callback"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public Timer(TimerCallback callback, Object state, int dueTime) : this(null, callback, state, dueTime, -1) {} /// <summary> /// <para>Create a new timer.</para> /// </summary> /// /// <param name="callback"> /// <para>The delegate to invoke when the timer expires.</para> /// </param> /// /// <param name="state"> /// <para>The state information to pass to the callback.</para> /// </param> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <param name="period"> /// <para>The number of milliseconds between timer expiries, or /// -1 to only expire once at <paramref name="dueTime"/>.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="callback"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public Timer(TimerCallback callback, Object state, int dueTime, int period) : this(null, callback, state, dueTime, period) {} /// <summary> /// <para>Create a new timer.</para> /// </summary> /// /// <param name="dpy"> /// <para>The display to create the timer for, or <see langword="null"/> /// to use the application's primary display.</para> /// </param> /// /// <param name="callback"> /// <para>The delegate to invoke when the timer expires.</para> /// </param> /// /// <param name="state"> /// <para>The state information to pass to the callback.</para> /// </param> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="callback"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public Timer(Display dpy, TimerCallback callback, Object state, int dueTime) : this(dpy, callback, state, dueTime, -1) {} /// <summary> /// <para>Create a new timer.</para> /// </summary> /// /// <param name="dpy"> /// <para>The display to create the timer for, or <see langword="null"/> /// to use the application's primary display.</para> /// </param> /// /// <param name="callback"> /// <para>The delegate to invoke when the timer expires.</para> /// </param> /// /// <param name="state"> /// <para>The state information to pass to the callback.</para> /// </param> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <param name="period"> /// <para>The number of milliseconds between timer expiries, or /// -1 to only expire once at <paramref name="dueTime"/>.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="callback"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public Timer(Display dpy, TimerCallback callback, Object state, int dueTime, int period) { if(callback == null) { throw new ArgumentNullException("callback"); } if(dpy == null) { this.dpy = Application.Primary.Display; } else { this.dpy = dpy; } if(dueTime < 0) { throw new ArgumentOutOfRangeException ("dueTime", S._("X_NonNegative")); } this.callback = callback; this.state = state; this.nextDue = DateTime.UtcNow + new TimeSpan (dueTime * TimeSpan.TicksPerMillisecond); this.period = period; this.stopped = false; AddTimer(); } /// <summary> /// <para>Create a new timer.</para> /// </summary> /// /// <param name="dpy"> /// <para>The display to create the timer for, or <see langword="null"/> /// to use the application's primary display.</para> /// </param> /// /// <param name="callback"> /// <para>The delegate to invoke when the timer expires.</para> /// </param> /// /// <param name="state"> /// <para>The state information to pass to the callback.</para> /// </param> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <param name="period"> /// <para>The number of milliseconds between timer expiries, or /// -1 to only expire once at <paramref name="dueTime"/>.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="callback"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public Timer(Display dpy, EventHandler callback, Object state, int dueTime, int period) { if(callback == null) { throw new ArgumentNullException("callback"); } if(dpy == null) { this.dpy = Application.Primary.Display; } else { this.dpy = dpy; } if(dueTime < 0) { throw new ArgumentOutOfRangeException ("dueTime", S._("X_NonNegative")); } this.callback = callback; this.state = state; this.nextDue = DateTime.UtcNow + new TimeSpan (dueTime * TimeSpan.TicksPerMillisecond); this.period = period; this.stopped = false; AddTimer(); } /// <summary> /// <para>Change the parameters for this timer.</para> /// </summary> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public void Change(int dueTime) { Change(dueTime, -1); } /// <summary> /// <para>Change the parameters for this timer.</para> /// </summary> /// /// <param name="dueTime"> /// <para>The number of milliseconds until the timer expires /// for the first time.</para> /// </param> /// /// <param name="period"> /// <para>The number of milliseconds between timer expiries, or /// -1 to only expire once at <paramref name="dueTime"/>.</para> /// </param> /// /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <para>The <paramref name="dueTime"/> parameter is /// less than zero.</para> /// </exception> public void Change(int dueTime, int period) { if(dueTime < 0) { throw new ArgumentOutOfRangeException ("dueTime", S._("X_NonNegative")); } RemoveTimer(); this.nextDue = DateTime.UtcNow + new TimeSpan (dueTime * TimeSpan.TicksPerMillisecond); this.period = period; this.stopped = false; AddTimer(); } /// <summary> /// <para>Dispose of this timer, stopping any pending timeouts.</para> /// </summary> public void Dispose() { Stop(); state = null; } /// <summary> /// <para>Stop this timer. Another timeout can be started at /// some future point using <c>Change</c>.</para> /// </summary> public void Stop() { stopped = true; RemoveTimer(); } // Add the timer to the display's timer queue. private void AddTimer() { lock(dpy) { if(!onDisplayQueue) { Timer current = dpy.timerQueue; Timer prev = null; int iCount = 0; while(current != null && current.nextDue <= nextDue) { prev = current; current = current.next; } this.next = current; this.prev = prev; if(current != null) { current.prev = this; } if(prev != null) { prev.next = this; } else { dpy.timerQueue = this; } onDisplayQueue = true; } } } // Remove the timer from the display's timer queue. private void RemoveTimer() { lock(dpy) { if(onDisplayQueue) { if(next != null) { next.prev = prev; } if(prev != null) { prev.next = next; } else { dpy.timerQueue = next; } onDisplayQueue = false; next = null; prev = null; } } } // Activate timers that have fired on a particular display. // We assume that this is called with the display lock. internal static bool ActivateTimers(Display dpy) { // Bail out early if there are no timers, to avoid // calling "DateTime.UtcNow" if we don't need to. if(dpy.timerQueue == null) { return false; } DateTime now = DateTime.UtcNow; Timer timer; DateTime next; bool activated = false; for(;;) { // Remove the first timer from the queue if // it has expired. Bail out if it hasn't. timer = dpy.timerQueue; if(timer == null) { break; } else if(timer.nextDue <= now) { timer.RemoveTimer(); } else { break; } // Invoke the timer's callback delegate. activated = true; if(timer.callback is TimerCallback) { TimerCallback cb1 = timer.callback as TimerCallback; dpy.Unlock(); try { cb1(timer.state); } finally { dpy.Lock(); } } else { EventHandler cb2 = timer.callback as EventHandler; dpy.Unlock(); try { cb2(timer.state, EventArgs.Empty); } finally { dpy.Lock(); } } // Add the timer back onto the queue if necessary. if(!timer.stopped && !timer.onDisplayQueue) { if(timer.period < 0) { timer.stopped = true; } else { next = timer.nextDue + new TimeSpan(timer.period * TimeSpan.TicksPerMillisecond); // if the next due is less than now, the date/time may have changed. // since the timer expired right now the next due might be now + period if(next <= now) { next += new TimeSpan (((((Int64)(now - next).TotalMilliseconds) / timer.period) + 1) * timer.period * TimeSpan.TicksPerMillisecond); } /* do not increment here, since the time might have changed with years this would do a long loop here while(next <= now) { next += new TimeSpan (timer.period * TimeSpan.TicksPerMillisecond); } */ timer.nextDue = next; timer.AddTimer(); } } } return activated; } // fix all timers in the queue if the system time has been changed internal static void FixTimers( Timer timer ) { DateTime fixTime = DateTime.UtcNow; long tpms = TimeSpan.TicksPerMillisecond; while( null != timer ) { timer.nextDue = fixTime + new TimeSpan(timer.period * tpms); timer = timer.next; } } // Get the number of milliseconds until the next timeout. // Returns -1 if there are no active timers. internal static int GetNextTimeout(Display dpy) { lock(dpy) { if(dpy.timerQueue != null) { DateTime fireAt = dpy.timerQueue.nextDue; long diff = fireAt.Ticks - DateTime.UtcNow.Ticks; if(diff <= 0) { // The timeout has already fired or is about to. return 0; } else if (diff > (dpy.timerQueue.period * TimeSpan.TicksPerMillisecond)) { // The next due time is farther away than the time period we're // supposed to wait. This propably means the system clock has // been turned back (either manually or by NTP). In this case // we must calculate a new due time and just return 0. FixTimers( dpy.timerQueue ); /* dpy.timerQueue.nextDue = DateTime.UtcNow + new TimeSpan (dpy.timerQueue.period * TimeSpan.TicksPerMillisecond); */ return 0; } else if (diff > (100 * TimeSpan.TicksPerSecond)) { // Don't wait more than 100 seconds at a time. return 100000; } else { // Return the number of milliseconds + 1. // The "+ 1" takes care of rounding errors // due to converting ticks to milliseconds. return ((int)(diff / TimeSpan.TicksPerMillisecond)) + 1; } } } return -1; } } // class Timer } // namespace Xsharp
using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton; /// <summary> /// Exposes flex API, merged from flex API of /// sub-segments. /// <para/> /// @lucene.experimental /// </summary> public sealed class MultiTerms : Terms { private readonly Terms[] subs; private readonly ReaderSlice[] subSlices; private readonly IComparer<BytesRef> termComp; private readonly bool hasFreqs; private readonly bool hasOffsets; private readonly bool hasPositions; private readonly bool hasPayloads; /// <summary> /// Sole constructor. /// </summary> /// <param name="subs"> The <see cref="Terms"/> instances of all sub-readers. </param> /// <param name="subSlices"> A parallel array (matching /// <paramref name="subs"/>) describing the sub-reader slices. </param> public MultiTerms(Terms[] subs, ReaderSlice[] subSlices) { this.subs = subs; this.subSlices = subSlices; IComparer<BytesRef> _termComp = null; if (Debugging.AssertsEnabled) Debugging.Assert(subs.Length > 0, "inefficient: don't use MultiTerms over one sub"); bool _hasFreqs = true; bool _hasOffsets = true; bool _hasPositions = true; bool _hasPayloads = false; for (int i = 0; i < subs.Length; i++) { if (_termComp == null) { _termComp = subs[i].Comparer; } else { // We cannot merge sub-readers that have // different TermComps IComparer<BytesRef> subTermComp = subs[i].Comparer; if (subTermComp != null && !subTermComp.Equals(_termComp)) { throw IllegalStateException.Create("sub-readers have different BytesRef.Comparers; cannot merge"); } } _hasFreqs &= subs[i].HasFreqs; _hasOffsets &= subs[i].HasOffsets; _hasPositions &= subs[i].HasPositions; _hasPayloads |= subs[i].HasPayloads; } termComp = _termComp; hasFreqs = _hasFreqs; hasOffsets = _hasOffsets; hasPositions = _hasPositions; hasPayloads = hasPositions && _hasPayloads; // if all subs have pos, and at least one has payloads. } public override TermsEnum Intersect(CompiledAutomaton compiled, BytesRef startTerm) { IList<MultiTermsEnum.TermsEnumIndex> termsEnums = new List<MultiTermsEnum.TermsEnumIndex>(); for (int i = 0; i < subs.Length; i++) { TermsEnum termsEnum = subs[i].Intersect(compiled, startTerm); if (termsEnum != null) { termsEnums.Add(new MultiTermsEnum.TermsEnumIndex(termsEnum, i)); } } if (termsEnums.Count > 0) { return (new MultiTermsEnum(subSlices)).Reset(termsEnums.ToArray(/*MultiTermsEnum.TermsEnumIndex.EMPTY_ARRAY*/)); } else { return TermsEnum.EMPTY; } } public override TermsEnum GetEnumerator() { IList<MultiTermsEnum.TermsEnumIndex> termsEnums = new List<MultiTermsEnum.TermsEnumIndex>(); for (int i = 0; i < subs.Length; i++) { TermsEnum termsEnum = subs[i].GetEnumerator(); if (termsEnum != null) { termsEnums.Add(new MultiTermsEnum.TermsEnumIndex(termsEnum, i)); } } if (termsEnums.Count > 0) { return (new MultiTermsEnum(subSlices)).Reset(termsEnums.ToArray(/*MultiTermsEnum.TermsEnumIndex.EMPTY_ARRAY*/)); } else { return TermsEnum.EMPTY; } } public override long Count => -1; public override long SumTotalTermFreq { get { long sum = 0; foreach (Terms terms in subs) { long v = terms.SumTotalTermFreq; if (v == -1) { return -1; } sum += v; } return sum; } } public override long SumDocFreq { get { long sum = 0; foreach (Terms terms in subs) { long v = terms.SumDocFreq; if (v == -1) { return -1; } sum += v; } return sum; } } public override int DocCount { get { int sum = 0; foreach (Terms terms in subs) { int v = terms.DocCount; if (v == -1) { return -1; } sum += v; } return sum; } } public override IComparer<BytesRef> Comparer => termComp; public override bool HasFreqs => hasFreqs; public override bool HasOffsets => hasOffsets; public override bool HasPositions => hasPositions; public override bool HasPayloads => hasPayloads; } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Reflection; namespace NUnit.Gui { public class AboutBox : System.Windows.Forms.Form { private System.Windows.Forms.Button OkButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label versionLabel; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label copyright; private System.Windows.Forms.Label dotNetVersionLabel; private System.Windows.Forms.Label clrTypeLabel; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public AboutBox() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // Assembly executingAssembly = Assembly.GetExecutingAssembly(); string versionText = executingAssembly.GetName().Version.ToString(); object [] objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); if ( objectAttrs.Length > 0 ) versionText = ((AssemblyInformationalVersionAttribute)objectAttrs[0]).InformationalVersion; objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false); if ( objectAttrs.Length > 0 ) { string configText = ((AssemblyConfigurationAttribute)objectAttrs[0]).Configuration; if ( configText != "" ) versionText += string.Format(" ({0})",configText); } string copyrightText = "Copyright (C) 2002-2012 Charlie Poole.\r\nCopyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.\r\nCopyright (C) 2000-2002 Philip Craig.\r\nAll Rights Reserved."; objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if ( objectAttrs.Length > 0 ) copyrightText = ((AssemblyCopyrightAttribute)objectAttrs[0]).Copyright; versionLabel.Text = versionText; copyright.Text = copyrightText; dotNetVersionLabel.Text = NUnit.Core.RuntimeFramework.CurrentFramework.DisplayName; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutBox)); this.OkButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.versionLabel = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.copyright = new System.Windows.Forms.Label(); this.clrTypeLabel = new System.Windows.Forms.Label(); this.dotNetVersionLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); // // OkButton // this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.OkButton.Location = new System.Drawing.Point(368, 304); this.OkButton.Name = "OkButton"; this.OkButton.Size = new System.Drawing.Size(96, 29); this.OkButton.TabIndex = 0; this.OkButton.Text = "OK"; this.OkButton.Click += new System.EventHandler(this.button1_Click); // // label1 // this.label1.Location = new System.Drawing.Point(31, 240); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(102, 23); this.label1.TabIndex = 1; this.label1.Text = "NUnit Version:"; // // versionLabel // this.versionLabel.Location = new System.Drawing.Point(164, 240); this.versionLabel.Name = "versionLabel"; this.versionLabel.Size = new System.Drawing.Size(156, 23); this.versionLabel.TabIndex = 2; this.versionLabel.Text = "label2"; // // label2 // this.label2.Location = new System.Drawing.Point(31, 144); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(102, 29); this.label2.TabIndex = 3; this.label2.Text = "Developers:"; // // label3 // this.label3.Location = new System.Drawing.Point(164, 144); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(287, 48); this.label3.TabIndex = 4; this.label3.Text = "James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Philip Craig, Ethan Smith," + " Doug de la Torre, Charlie Poole"; // // linkLabel1 // this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 21); this.linkLabel1.Location = new System.Drawing.Point(164, 112); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(266, 16); this.linkLabel1.TabIndex = 5; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "http://www.nunit.org "; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // label4 // this.label4.Location = new System.Drawing.Point(31, 112); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(102, 16); this.label4.TabIndex = 6; this.label4.Text = "Information:"; // // label5 // this.label5.Location = new System.Drawing.Point(31, 200); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(102, 29); this.label5.TabIndex = 7; this.label5.Text = "Thanks to:"; // // label6 // this.label6.Location = new System.Drawing.Point(164, 200); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(215, 29); this.label6.TabIndex = 8; this.label6.Text = "Kent Beck and Erich Gamma"; // // label7 // this.label7.Location = new System.Drawing.Point(31, 20); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(102, 28); this.label7.TabIndex = 9; this.label7.Text = "Copyright:"; // // copyright // this.copyright.Location = new System.Drawing.Point(164, 20); this.copyright.Name = "copyright"; this.copyright.Size = new System.Drawing.Size(297, 84); this.copyright.TabIndex = 10; this.copyright.Text = "label8"; // // clrTypeLabel // this.clrTypeLabel.Location = new System.Drawing.Point(31, 272); this.clrTypeLabel.Name = "clrTypeLabel"; this.clrTypeLabel.Size = new System.Drawing.Size(127, 23); this.clrTypeLabel.TabIndex = 11; this.clrTypeLabel.Text = "Framework Version:"; // // dotNetVersionLabel // this.dotNetVersionLabel.Location = new System.Drawing.Point(164, 272); this.dotNetVersionLabel.Name = "dotNetVersionLabel"; this.dotNetVersionLabel.Size = new System.Drawing.Size(284, 23); this.dotNetVersionLabel.TabIndex = 12; this.dotNetVersionLabel.Text = "label9"; // // AboutBox // this.AcceptButton = this.OkButton; this.CancelButton = this.OkButton; this.ClientSize = new System.Drawing.Size(490, 346); this.Controls.Add(this.dotNetVersionLabel); this.Controls.Add(this.clrTypeLabel); this.Controls.Add(this.copyright); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.versionLabel); this.Controls.Add(this.label1); this.Controls.Add(this.OkButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AboutBox"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "About NUnit"; this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { this.Close(); } private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://nunit.org"); linkLabel1.LinkVisited = true; } } }
// // ReflectionReader.cs // // Author: // Jb Evain (jbevain@gmail.com) // // (C) 2005 - 2007 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Mono.Cecil { using System; using System.IO; using System.Text; using Mono.Cecil.Binary; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.Signatures; internal abstract class ReflectionReader : BaseReflectionReader { ModuleDefinition m_module; ImageReader m_reader; SecurityDeclarationReader m_secReader; protected MetadataTableReader m_tableReader; protected MetadataRoot m_root; protected TablesHeap m_tHeap; protected TypeDefinition [] m_typeDefs; protected TypeReference [] m_typeRefs; protected TypeReference [] m_typeSpecs; protected MethodDefinition [] m_meths; protected FieldDefinition [] m_fields; protected EventDefinition [] m_events; protected PropertyDefinition [] m_properties; protected MemberReference [] m_memberRefs; protected ParameterDefinition [] m_parameters; protected GenericParameter [] m_genericParameters; protected GenericInstanceMethod [] m_methodSpecs; bool m_isCorlib; AssemblyNameReference m_corlib; protected SignatureReader m_sigReader; protected CodeReader m_codeReader; protected ISymbolReader m_symbolReader; internal AssemblyNameReference Corlib { get { if (m_corlib != null) return m_corlib; foreach (AssemblyNameReference ar in m_module.AssemblyReferences) { if (ar.Name == Constants.Corlib) { m_corlib = ar; return m_corlib; } } return null; } } public ModuleDefinition Module { get { return m_module; } } public SignatureReader SigReader { get { return m_sigReader; } } public MetadataTableReader TableReader { get { return m_tableReader; } } public CodeReader Code { get { return m_codeReader; } } public ISymbolReader SymbolReader { get { return m_symbolReader; } set { m_symbolReader = value; } } public MetadataRoot MetadataRoot { get { return m_root; } } public ReflectionReader (ModuleDefinition module) { m_module = module; m_reader = m_module.ImageReader; m_root = m_module.Image.MetadataRoot; m_tHeap = m_root.Streams.TablesHeap; if (m_reader != null) m_tableReader = m_reader.MetadataReader.TableReader; m_codeReader = new CodeReader (this); m_sigReader = new SignatureReader (m_root, this); m_isCorlib = module.Assembly.Name.Name == Constants.Corlib; } public TypeDefinition GetTypeDefAt (uint rid) { return m_typeDefs [rid - 1]; } public TypeReference GetTypeRefAt (uint rid) { return m_typeRefs [rid - 1]; } public TypeReference GetTypeSpecAt (uint rid, GenericContext context) { int index = (int) rid - 1; TypeReference tspec = m_typeSpecs [index]; if (tspec != null) return tspec; TypeSpecTable tsTable = m_tableReader.GetTypeSpecTable (); TypeSpecRow tsRow = tsTable [index]; TypeSpec ts = m_sigReader.GetTypeSpec (tsRow.Signature); tspec = GetTypeRefFromSig (ts.Type, context); tspec.MetadataToken = MetadataToken.FromMetadataRow (TokenType.TypeSpec, index); m_typeSpecs [index] = tspec; return tspec; } public FieldDefinition GetFieldDefAt (uint rid) { return m_fields [rid - 1]; } public MethodDefinition GetMethodDefAt (uint rid) { return m_meths [rid - 1]; } public MemberReference GetMemberRefAt (uint rid, GenericContext context) { int index = (int) rid - 1; MemberReference member = m_memberRefs [rid - 1]; if (member != null) return member; MemberRefTable mrTable = m_tableReader.GetMemberRefTable (); MemberRefRow mrefRow = mrTable [index]; Signature sig = m_sigReader.GetMemberRefSig (mrefRow.Class.TokenType, mrefRow.Signature); switch (mrefRow.Class.TokenType) { case TokenType.TypeDef : case TokenType.TypeRef : case TokenType.TypeSpec : TypeReference declaringType = GetTypeDefOrRef (mrefRow.Class, context); GenericContext nc = context.Clone (); if (declaringType is GenericInstanceType) { TypeReference ct = declaringType; while (ct is GenericInstanceType) ct = (ct as GenericInstanceType).ElementType; nc.Type = ct; nc.AllowCreation = ct.GetType () == typeof (TypeReference); } if (sig is FieldSig) { FieldSig fs = sig as FieldSig; member = new FieldReference ( m_root.Streams.StringsHeap [mrefRow.Name], declaringType, GetTypeRefFromSig (fs.Type, nc)); } else { string name = m_root.Streams.StringsHeap [mrefRow.Name]; MethodSig ms = (MethodSig) sig; MethodReference methref = new MethodReference ( name, ms.HasThis, ms.ExplicitThis, ms.MethCallConv); methref.DeclaringType = declaringType; if (sig is MethodDefSig) { int arity = (sig as MethodDefSig).GenericParameterCount; for (int i = 0; i < arity; i++) methref.GenericParameters.Add (new GenericParameter (i, methref)); } if (methref.GenericParameters.Count > 0) nc.Method = methref; methref.ReturnType = GetMethodReturnType (ms, nc); methref.ReturnType.Method = methref; for (int j = 0; j < ms.ParamCount; j++) { Param p = ms.Parameters [j]; ParameterDefinition pdef = BuildParameterDefinition ( string.Concat ("A_", j), j, new ParameterAttributes (), p, nc); pdef.Method = methref; methref.Parameters.Add (pdef); } member = methref; } break; case TokenType.Method : // really not sure about this MethodDefinition methdef = GetMethodDefAt (mrefRow.Class.RID); MethodReference methRef = new MethodReference ( methdef.Name, methdef.HasThis, methdef.ExplicitThis, methdef.CallingConvention); methRef.DeclaringType = methdef.DeclaringType; methRef.ReturnType = methdef.ReturnType; foreach (ParameterDefinition param in methdef.Parameters) methRef.Parameters.Add (param); member = methRef; break; case TokenType.ModuleRef : break; // TODO, implement that, or not } member.MetadataToken = MetadataToken.FromMetadataRow (TokenType.MemberRef, index); m_module.MemberReferences.Add (member); m_memberRefs [index] = member; return member; } public PropertyDefinition GetPropertyDefAt (uint rid) { return m_properties [rid - 1]; } public EventDefinition GetEventDefAt (uint rid) { return m_events [rid - 1]; } public ParameterDefinition GetParamDefAt (uint rid) { return m_parameters [rid - 1]; } public GenericParameter GetGenericParameterAt (uint rid) { return m_genericParameters [rid - 1]; } public GenericInstanceMethod GetMethodSpecAt (uint rid, GenericContext context) { int index = (int) rid - 1; GenericInstanceMethod gim = m_methodSpecs [index]; if (gim != null) return gim; MethodSpecTable msTable = m_tableReader.GetMethodSpecTable (); MethodSpecRow msRow = msTable [index]; MethodSpec sig = m_sigReader.GetMethodSpec (msRow.Instantiation); MethodReference meth; if (msRow.Method.TokenType == TokenType.Method) meth = GetMethodDefAt (msRow.Method.RID); else if (msRow.Method.TokenType == TokenType.MemberRef) meth = (MethodReference) GetMemberRefAt (msRow.Method.RID, context); else throw new ReflectionException ("Unknown method type for method spec"); gim = new GenericInstanceMethod (meth); foreach (GenericArg arg in sig.Signature.Types) gim.GenericArguments.Add (GetGenericArg (arg, context)); m_methodSpecs [index] = gim; return gim; } public TypeReference GetTypeDefOrRef (MetadataToken token, GenericContext context) { if (token.RID == 0) return null; switch (token.TokenType) { case TokenType.TypeDef : return GetTypeDefAt (token.RID); case TokenType.TypeRef : return GetTypeRefAt (token.RID); case TokenType.TypeSpec : return GetTypeSpecAt (token.RID, context); default : return null; } } public TypeReference SearchCoreType (string fullName) { if (m_isCorlib) return m_module.Types [fullName]; TypeReference coreType = m_module.TypeReferences [fullName]; if (coreType == null) { string [] parts = fullName.Split ('.'); if (parts.Length != 2) throw new ReflectionException ("Unvalid core type name"); coreType = new TypeReference (parts [1], parts [0], Corlib); m_module.TypeReferences.Add (coreType); } if (!coreType.IsValueType) { switch (coreType.FullName) { case Constants.Boolean : case Constants.Char : case Constants.Single : case Constants.Double : case Constants.SByte : case Constants.Byte : case Constants.Int16 : case Constants.UInt16 : case Constants.Int32 : case Constants.UInt32 : case Constants.Int64 : case Constants.UInt64 : case Constants.IntPtr : case Constants.UIntPtr : coreType.IsValueType = true; break; } } return coreType; } public IMetadataTokenProvider LookupByToken (MetadataToken token) { switch (token.TokenType) { case TokenType.TypeDef : return GetTypeDefAt (token.RID); case TokenType.TypeRef : return GetTypeRefAt (token.RID); case TokenType.Method : return GetMethodDefAt (token.RID); case TokenType.Field : return GetFieldDefAt (token.RID); case TokenType.Event : return GetEventDefAt (token.RID); case TokenType.Property : return GetPropertyDefAt (token.RID); case TokenType.Param : return GetParamDefAt (token.RID); default : throw new NotSupportedException ("Lookup is not allowed on this kind of token"); } } public CustomAttribute GetCustomAttribute (MethodReference ctor, byte [] data, bool resolve) { CustomAttrib sig = m_sigReader.GetCustomAttrib (data, ctor, resolve); return BuildCustomAttribute (ctor, sig); } public CustomAttribute GetCustomAttribute (MethodReference ctor, byte [] data) { return GetCustomAttribute (ctor, data, false); } public override void VisitModuleDefinition (ModuleDefinition mod) { VisitTypeDefinitionCollection (mod.Types); } public override void VisitTypeDefinitionCollection (TypeDefinitionCollection types) { // type def reading TypeDefTable typesTable = m_tableReader.GetTypeDefTable (); m_typeDefs = new TypeDefinition [typesTable.Rows.Count]; for (int i = 0; i < typesTable.Rows.Count; i++) { TypeDefRow type = typesTable [i]; TypeDefinition t = new TypeDefinition ( m_root.Streams.StringsHeap [type.Name], m_root.Streams.StringsHeap [type.Namespace], type.Flags); t.MetadataToken = MetadataToken.FromMetadataRow (TokenType.TypeDef, i); m_typeDefs [i] = t; } // nested types if (m_tHeap.HasTable (NestedClassTable.RId)) { NestedClassTable nested = m_tableReader.GetNestedClassTable (); for (int i = 0; i < nested.Rows.Count; i++) { NestedClassRow row = nested [i]; TypeDefinition parent = GetTypeDefAt (row.EnclosingClass); TypeDefinition child = GetTypeDefAt (row.NestedClass); parent.NestedTypes.Add (child); } } foreach (TypeDefinition type in m_typeDefs) types.Add (type); // type ref reading if (m_tHeap.HasTable (TypeRefTable.RId)) { TypeRefTable typesRef = m_tableReader.GetTypeRefTable (); m_typeRefs = new TypeReference [typesRef.Rows.Count]; for (int i = 0; i < typesRef.Rows.Count; i++) AddTypeRef (typesRef, i); } else m_typeRefs = new TypeReference [0]; ReadTypeSpecs (); ReadMethodSpecs (); ReadMethods (); ReadGenericParameters (); // set base types for (int i = 0; i < typesTable.Rows.Count; i++) { TypeDefRow type = typesTable [i]; TypeDefinition child = m_typeDefs [i]; child.BaseType = GetTypeDefOrRef (type.Extends, new GenericContext (child)); } CompleteMethods (); ReadAllFields (); ReadMemberReferences (); } void AddTypeRef (TypeRefTable typesRef, int i) { // Check if index has been already added. if (m_typeRefs [i] != null) return; TypeRefRow type = typesRef [i]; IMetadataScope scope = null; TypeReference parent = null; if (type.ResolutionScope != MetadataToken.Zero) { switch (type.ResolutionScope.TokenType) { case TokenType.AssemblyRef: scope = m_module.AssemblyReferences [(int) type.ResolutionScope.RID - 1]; break; case TokenType.ModuleRef: scope = m_module.ModuleReferences [(int) type.ResolutionScope.RID - 1]; break; case TokenType.Module: scope = m_module.Assembly.Modules [(int) type.ResolutionScope.RID - 1]; break; case TokenType.TypeRef: AddTypeRef (typesRef, (int) type.ResolutionScope.RID - 1); parent = GetTypeRefAt (type.ResolutionScope.RID); scope = parent.Scope; break; } } TypeReference t = new TypeReference ( m_root.Streams.StringsHeap [type.Name], m_root.Streams.StringsHeap [type.Namespace], scope); t.MetadataToken = MetadataToken.FromMetadataRow (TokenType.TypeRef, i); if (parent != null) t.DeclaringType = parent; m_typeRefs [i] = t; m_module.TypeReferences.Add (t); } void ReadTypeSpecs () { if (!m_tHeap.HasTable (TypeSpecTable.RId)) return; TypeSpecTable tsTable = m_tableReader.GetTypeSpecTable (); m_typeSpecs = new TypeReference [tsTable.Rows.Count]; } void ReadMethodSpecs () { if (!m_tHeap.HasTable (MethodSpecTable.RId)) return; MethodSpecTable msTable = m_tableReader.GetMethodSpecTable (); m_methodSpecs = new GenericInstanceMethod [msTable.Rows.Count]; } void ReadGenericParameters () { if (!m_tHeap.HasTable (GenericParamTable.RId)) return; GenericParamTable gpTable = m_tableReader.GetGenericParamTable (); m_genericParameters = new GenericParameter [gpTable.Rows.Count]; for (int i = 0; i < gpTable.Rows.Count; i++) { GenericParamRow gpRow = gpTable [i]; IGenericParameterProvider owner; if (gpRow.Owner.TokenType == TokenType.Method) owner = GetMethodDefAt (gpRow.Owner.RID); else if (gpRow.Owner.TokenType == TokenType.TypeDef) owner = GetTypeDefAt (gpRow.Owner.RID); else throw new ReflectionException ("Unknown owner type for generic parameter"); GenericParameter gp = new GenericParameter (gpRow.Number, owner); gp.Attributes = gpRow.Flags; gp.Name = MetadataRoot.Streams.StringsHeap [gpRow.Name]; gp.MetadataToken = MetadataToken.FromMetadataRow (TokenType.GenericParam, i); owner.GenericParameters.Add (gp); m_genericParameters [i] = gp; } } void ReadAllFields () { TypeDefTable tdefTable = m_tableReader.GetTypeDefTable (); if (!m_tHeap.HasTable(FieldTable.RId)) { m_fields = new FieldDefinition [0]; return; } FieldTable fldTable = m_tableReader.GetFieldTable (); m_fields = new FieldDefinition [fldTable.Rows.Count]; for (int i = 0; i < m_typeDefs.Length; i++) { TypeDefinition dec = m_typeDefs [i]; GenericContext context = new GenericContext (dec); int index = i, next; if (index == tdefTable.Rows.Count - 1) next = fldTable.Rows.Count + 1; else next = (int) (tdefTable [index + 1]).FieldList; for (int j = (int) tdefTable [index].FieldList; j < next; j++) { FieldRow frow = fldTable [j - 1]; FieldSig fsig = m_sigReader.GetFieldSig (frow.Signature); FieldDefinition fdef = new FieldDefinition ( m_root.Streams.StringsHeap [frow.Name], GetTypeRefFromSig (fsig.Type, context), frow.Flags); fdef.MetadataToken = MetadataToken.FromMetadataRow (TokenType.Field, j - 1); if (fsig.CustomMods.Length > 0) fdef.FieldType = GetModifierType (fsig.CustomMods, fdef.FieldType); dec.Fields.Add (fdef); m_fields [j - 1] = fdef; } } } void ReadMethods () { if (!m_tHeap.HasTable (MethodTable.RId)) { m_meths = new MethodDefinition [0]; return; } MethodTable mTable = m_tableReader.GetMethodTable (); m_meths = new MethodDefinition [mTable.Rows.Count]; for (int i = 0; i < mTable.Rows.Count; i++) { MethodRow mRow = mTable [i]; MethodDefinition meth = new MethodDefinition ( m_root.Streams.StringsHeap [mRow.Name], mRow.Flags); meth.RVA = mRow.RVA; meth.ImplAttributes = mRow.ImplFlags; meth.MetadataToken = MetadataToken.FromMetadataRow (TokenType.Method, i); m_meths [i] = meth; } } void CompleteMethods () { TypeDefTable tdefTable = m_tableReader.GetTypeDefTable (); if (!m_tHeap.HasTable (MethodTable.RId)) { m_meths = new MethodDefinition [0]; return; } MethodTable methTable = m_tableReader.GetMethodTable (); ParamTable paramTable = m_tableReader.GetParamTable (); if (!m_tHeap.HasTable (ParamTable.RId)) m_parameters = new ParameterDefinition [0]; else m_parameters = new ParameterDefinition [paramTable.Rows.Count]; for (int i = 0; i < m_typeDefs.Length; i++) { TypeDefinition dec = m_typeDefs [i]; int index = i, next; if (index == tdefTable.Rows.Count - 1) next = methTable.Rows.Count + 1; else next = (int) (tdefTable [index + 1]).MethodList; for (int j = (int) tdefTable [index].MethodList; j < next; j++) { MethodRow methRow = methTable [j - 1]; MethodDefinition mdef = m_meths [j - 1]; if (mdef.IsConstructor) dec.Constructors.Add (mdef); else dec.Methods.Add (mdef); GenericContext context = new GenericContext (mdef); MethodDefSig msig = m_sigReader.GetMethodDefSig (methRow.Signature); mdef.HasThis = msig.HasThis; mdef.ExplicitThis = msig.ExplicitThis; mdef.CallingConvention = msig.MethCallConv; int prms; if (j == methTable.Rows.Count) prms = m_parameters.Length + 1; else prms = (int) (methTable [j]).ParamList; ParameterDefinition retparam = null; //TODO: optimize this int start = (int) methRow.ParamList - 1; if (paramTable != null && start < prms - 1) { ParamRow pRetRow = paramTable [start]; if (pRetRow != null && pRetRow.Sequence == 0) { // ret type retparam = new ParameterDefinition ( m_root.Streams.StringsHeap [pRetRow.Name], 0, pRetRow.Flags, null); retparam.Method = mdef; m_parameters [start] = retparam; start++; } } for (int k = 0; k < msig.ParamCount; k++) { int pointer = start + k; ParamRow pRow = null; if (paramTable != null && pointer < prms - 1) pRow = paramTable [pointer]; Param psig = msig.Parameters [k]; ParameterDefinition pdef; if (pRow != null) { pdef = BuildParameterDefinition ( m_root.Streams.StringsHeap [pRow.Name], pRow.Sequence, pRow.Flags, psig, context); pdef.MetadataToken = MetadataToken.FromMetadataRow (TokenType.Param, pointer); m_parameters [pointer] = pdef; } else pdef = BuildParameterDefinition ( string.Concat ("A_", mdef.IsStatic ? k : k + 1), k + 1, (ParameterAttributes) 0, psig, context); pdef.Method = mdef; mdef.Parameters.Add (pdef); } mdef.ReturnType = GetMethodReturnType (msig, context); MethodReturnType mrt = mdef.ReturnType; mrt.Method = mdef; if (retparam != null) { mrt.Parameter = retparam; mrt.Parameter.ParameterType = mrt.ReturnType; } } } uint eprid = CodeReader.GetRid ((int) m_reader.Image.CLIHeader.EntryPointToken); if (eprid > 0 && eprid <= m_meths.Length) m_module.Assembly.EntryPoint = GetMethodDefAt (eprid); } void ReadMemberReferences () { if (!m_tHeap.HasTable (MemberRefTable.RId)) return; MemberRefTable mrefTable = m_tableReader.GetMemberRefTable (); m_memberRefs = new MemberReference [mrefTable.Rows.Count]; } public override void VisitExternTypeCollection (ExternTypeCollection externs) { ExternTypeCollection ext = externs; if (!m_tHeap.HasTable (ExportedTypeTable.RId)) return; ExportedTypeTable etTable = m_tableReader.GetExportedTypeTable (); TypeReference [] buffer = new TypeReference [etTable.Rows.Count]; for (int i = 0; i < etTable.Rows.Count; i++) { ExportedTypeRow etRow = etTable [i]; if (etRow.Implementation.TokenType != TokenType.File) continue; string name = m_root.Streams.StringsHeap [etRow.TypeName]; string ns = m_root.Streams.StringsHeap [etRow.TypeNamespace]; if (ns.Length == 0) buffer [i] = m_module.TypeReferences [name]; else buffer [i] = m_module.TypeReferences [string.Concat (ns, '.', name)]; } for (int i = 0; i < etTable.Rows.Count; i++) { ExportedTypeRow etRow = etTable [i]; if (etRow.Implementation.TokenType != TokenType.ExportedType) continue; TypeReference owner = buffer [etRow.Implementation.RID - 1]; string name = m_root.Streams.StringsHeap [etRow.TypeName]; buffer [i] = m_module.TypeReferences [string.Concat (owner.FullName, '/', name)]; } for (int i = 0; i < buffer.Length; i++) { TypeReference curs = buffer [i]; if (curs != null) ext.Add (curs); } } static object GetFixedArgValue (CustomAttrib.FixedArg fa) { if (fa.SzArray) { object [] vals = new object [fa.NumElem]; for (int j = 0; j < vals.Length; j++) vals [j] = fa.Elems [j].Value; return vals; } else return fa.Elems [0].Value; } TypeReference GetFixedArgType (CustomAttrib.FixedArg fa) { if (fa.SzArray) { if (fa.NumElem == 0) return new ArrayType (SearchCoreType (Constants.Object)); else return new ArrayType (fa.Elems [0].ElemType); } else return fa.Elems [0].ElemType; } protected CustomAttribute BuildCustomAttribute (MethodReference ctor, CustomAttrib sig) { CustomAttribute cattr = new CustomAttribute (ctor); foreach (CustomAttrib.FixedArg fa in sig.FixedArgs) cattr.ConstructorParameters.Add (GetFixedArgValue (fa)); foreach (CustomAttrib.NamedArg na in sig.NamedArgs) { object value = GetFixedArgValue (na.FixedArg); if (na.Field) { cattr.Fields [na.FieldOrPropName] = value; cattr.SetFieldType (na.FieldOrPropName, GetFixedArgType (na.FixedArg)); } else if (na.Property) { cattr.Properties [na.FieldOrPropName] = value; cattr.SetPropertyType (na.FieldOrPropName, GetFixedArgType (na.FixedArg)); } else throw new ReflectionException ("Non valid named arg"); } return cattr; } public ParameterDefinition BuildParameterDefinition (string name, int sequence, ParameterAttributes attrs, Param psig, GenericContext context) { ParameterDefinition ret = new ParameterDefinition (name, sequence, attrs, null); TypeReference paramType; if (psig.ByRef) paramType = new ReferenceType (GetTypeRefFromSig (psig.Type, context)); else if (psig.TypedByRef) paramType = SearchCoreType (Constants.TypedReference); else paramType = GetTypeRefFromSig (psig.Type, context); if (psig.CustomMods.Length > 0) paramType = GetModifierType (psig.CustomMods, paramType); ret.ParameterType = paramType; return ret; } protected SecurityDeclaration BuildSecurityDeclaration (DeclSecurityRow dsRow) { return BuildSecurityDeclaration (dsRow.Action, m_root.Streams.BlobHeap.Read (dsRow.PermissionSet)); } public SecurityDeclaration BuildSecurityDeclaration (SecurityAction action, byte [] permset) { if (m_secReader == null) m_secReader = new SecurityDeclarationReader (m_root, this); return m_secReader.FromByteArray (action, permset); } protected MarshalSpec BuildMarshalDesc (MarshalSig ms, IHasMarshalSpec container) { if (ms.Spec is MarshalSig.Array) { ArrayMarshalSpec amd = new ArrayMarshalSpec (container); MarshalSig.Array ar = (MarshalSig.Array) ms.Spec; amd.ElemType = ar.ArrayElemType; amd.NumElem = ar.NumElem; amd.ParamNum = ar.ParamNum; amd.ElemMult = ar.ElemMult; return amd; } else if (ms.Spec is MarshalSig.CustomMarshaler) { CustomMarshalerSpec cmd = new CustomMarshalerSpec (container); MarshalSig.CustomMarshaler cmsig = (MarshalSig.CustomMarshaler) ms.Spec; cmd.Guid = cmsig.Guid.Length > 0 ? new Guid (cmsig.Guid) : new Guid (); cmd.UnmanagedType = cmsig.UnmanagedType; cmd.ManagedType = cmsig.ManagedType; cmd.Cookie = cmsig.Cookie; return cmd; } else if (ms.Spec is MarshalSig.FixedArray) { FixedArraySpec fad = new FixedArraySpec (container); MarshalSig.FixedArray fasig = (MarshalSig.FixedArray) ms.Spec; fad.ElemType = fasig.ArrayElemType; fad.NumElem = fasig.NumElem; return fad; } else if (ms.Spec is MarshalSig.FixedSysString) { FixedSysStringSpec fssc = new FixedSysStringSpec (container); fssc.Size = ((MarshalSig.FixedSysString) ms.Spec).Size; return fssc; } else if (ms.Spec is MarshalSig.SafeArray) { SafeArraySpec sad = new SafeArraySpec (container); sad.ElemType = ((MarshalSig.SafeArray) ms.Spec).ArrayElemType; return sad; } else { return new MarshalSpec (ms.NativeInstrinsic, container); } } public TypeReference GetModifierType (CustomMod [] cmods, TypeReference type) { TypeReference ret = type; for (int i = cmods.Length - 1; i >= 0; i--) { CustomMod cmod = cmods [i]; TypeReference modType; if (cmod.TypeDefOrRef.TokenType == TokenType.TypeDef) modType = GetTypeDefAt (cmod.TypeDefOrRef.RID); else modType = GetTypeRefAt (cmod.TypeDefOrRef.RID); if (cmod.CMOD == CustomMod.CMODType.OPT) ret = new ModifierOptional (ret, modType); else if (cmod.CMOD == CustomMod.CMODType.REQD) ret = new ModifierRequired (ret, modType); } return ret; } public MethodReturnType GetMethodReturnType (MethodSig msig, GenericContext context) { TypeReference retType; if (msig.RetType.Void) retType = SearchCoreType (Constants.Void); else if (msig.RetType.ByRef) retType = new ReferenceType (GetTypeRefFromSig (msig.RetType.Type, context)); else if (msig.RetType.TypedByRef) retType = SearchCoreType (Constants.TypedReference); else retType = GetTypeRefFromSig (msig.RetType.Type, context); if (msig.RetType.CustomMods.Length > 0) retType = GetModifierType (msig.RetType.CustomMods, retType); return new MethodReturnType (retType); } public TypeReference GetTypeRefFromSig (SigType t, GenericContext context) { switch (t.ElementType) { case ElementType.Class : CLASS c = t as CLASS; return GetTypeDefOrRef (c.Type, context); case ElementType.ValueType : VALUETYPE vt = t as VALUETYPE; TypeReference vtr = GetTypeDefOrRef (vt.Type, context); vtr.IsValueType = true; return vtr; case ElementType.String : return SearchCoreType (Constants.String); case ElementType.Object : return SearchCoreType (Constants.Object); case ElementType.Void : return SearchCoreType (Constants.Void); case ElementType.Boolean : return SearchCoreType (Constants.Boolean); case ElementType.Char : return SearchCoreType (Constants.Char); case ElementType.I1 : return SearchCoreType (Constants.SByte); case ElementType.U1 : return SearchCoreType (Constants.Byte); case ElementType.I2 : return SearchCoreType (Constants.Int16); case ElementType.U2 : return SearchCoreType (Constants.UInt16); case ElementType.I4 : return SearchCoreType (Constants.Int32); case ElementType.U4 : return SearchCoreType (Constants.UInt32); case ElementType.I8 : return SearchCoreType (Constants.Int64); case ElementType.U8 : return SearchCoreType (Constants.UInt64); case ElementType.R4 : return SearchCoreType (Constants.Single); case ElementType.R8 : return SearchCoreType (Constants.Double); case ElementType.I : return SearchCoreType (Constants.IntPtr); case ElementType.U : return SearchCoreType (Constants.UIntPtr); case ElementType.TypedByRef : return SearchCoreType (Constants.TypedReference); case ElementType.Array : ARRAY ary = t as ARRAY; return new ArrayType (GetTypeRefFromSig (ary.Type, context), ary.Shape); case ElementType.SzArray : SZARRAY szary = t as SZARRAY; ArrayType at = new ArrayType (GetTypeRefFromSig (szary.Type, context)); return at; case ElementType.Ptr : PTR pointer = t as PTR; if (pointer.Void) return new PointerType (SearchCoreType (Constants.Void)); return new PointerType (GetTypeRefFromSig (pointer.PtrType, context)); case ElementType.FnPtr : FNPTR funcptr = t as FNPTR; FunctionPointerType fnptr = new FunctionPointerType (funcptr.Method.HasThis, funcptr.Method.ExplicitThis, funcptr.Method.MethCallConv, GetMethodReturnType (funcptr.Method, context)); for (int i = 0; i < funcptr.Method.ParamCount; i++) { Param p = funcptr.Method.Parameters [i]; fnptr.Parameters.Add (BuildParameterDefinition ( string.Concat ("A_", i), i, (ParameterAttributes) 0, p, context)); } MethodRefSig refSig = funcptr.Method as MethodRefSig; if (refSig != null && refSig.Sentinel >= 0) CreateSentinel (fnptr, refSig.Sentinel); return fnptr; case ElementType.Var: VAR var = t as VAR; if (context.AllowCreation) CheckGenericParameters (context, var); if (context.Type is GenericInstanceType) return (context.Type as GenericInstanceType).GenericArguments [var.Index]; else return context.Type.GenericParameters [var.Index]; case ElementType.MVar: MVAR mvar = t as MVAR; if (context.Method is GenericInstanceMethod) return (context.Method as GenericInstanceMethod).GenericArguments [mvar.Index]; else return context.Method.GenericParameters [mvar.Index]; case ElementType.GenericInst: GENERICINST ginst = t as GENERICINST; GenericInstanceType instance = new GenericInstanceType (GetTypeDefOrRef (ginst.Type, context)); instance.IsValueType = ginst.ValueType; for (int i = 0; i < ginst.Signature.Arity; i++) instance.GenericArguments.Add (GetGenericArg ( ginst.Signature.Types [i], context)); return instance; default: break; } return null; } public static void CreateSentinel (IMethodSignature meth, int sentinel) { if (sentinel < 0 || sentinel >= meth.Parameters.Count) throw new ArgumentException ("Invalid sentinel"); ParameterDefinition param = meth.Parameters [sentinel]; param.ParameterType = new SentinelType (param.ParameterType); } TypeReference GetGenericArg (GenericArg arg, GenericContext context) { TypeReference type = GetTypeRefFromSig (arg.Type, context); if (arg.CustomMods != null && arg.CustomMods.Length > 0) type = GetModifierType (arg.CustomMods, type); return type; } static void CheckGenericParameters (GenericContext context, VAR v) { for (int i = context.Type.GenericParameters.Count; i <= v.Index; i++) context.Type.GenericParameters.Add (new GenericParameter (i, context.Type)); } protected object GetConstant (uint pos, ElementType elemType) { byte [] constant = m_root.Streams.BlobHeap.Read (pos); BinaryReader br = new BinaryReader (new MemoryStream (constant)); switch (elemType) { case ElementType.Boolean : return br.ReadByte () == 1; case ElementType.Char : return (char) br.ReadUInt16 (); case ElementType.I1 : return br.ReadSByte (); case ElementType.I2 : return br.ReadInt16 (); case ElementType.I4 : return br.ReadInt32 (); case ElementType.I8 : return br.ReadInt64 (); case ElementType.U1 : return br.ReadByte (); case ElementType.U2 : return br.ReadUInt16 (); case ElementType.U4 : return br.ReadUInt32 (); case ElementType.U8 : return br.ReadUInt64 (); case ElementType.R4 : return br.ReadSingle (); case ElementType.R8 : return br.ReadDouble (); case ElementType.String : byte [] bytes = br.ReadBytes (constant.Length); string str = Encoding.Unicode.GetString (bytes, 0, bytes.Length); return str; case ElementType.Class : return null; default : throw new ReflectionException ("Non valid element in constant table"); } } protected void SetInitialValue (FieldDefinition field) { int size = 0; TypeReference fieldType = field.FieldType; switch (fieldType.FullName) { case Constants.Byte: case Constants.SByte: size = 1; break; case Constants.Int16: case Constants.UInt16: case Constants.Char: size = 2; break; case Constants.Int32: case Constants.UInt32: case Constants.Single: size = 4; break; case Constants.Int64: case Constants.UInt64: case Constants.Double: size = 8; break; default: while (fieldType is TypeSpecification) fieldType = ((TypeSpecification) fieldType).ElementType; TypeDefinition fieldTypeDef = fieldType as TypeDefinition; if (fieldTypeDef != null) size = (int) fieldTypeDef.ClassSize; break; } if (size > 0 && field.RVA != RVA.Zero) { BinaryReader br = m_reader.MetadataReader.GetDataReader (field.RVA); field.InitialValue = br == null ? new byte [size] : br.ReadBytes (size); } else field.InitialValue = new byte [0]; } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using InTheHand.Net.Sockets; using System.IO; using InTheHand.Net.Bluetooth.Widcomm; using InTheHand.Net.Bluetooth; using System.Threading; using System.Diagnostics; namespace InTheHand.Net.Tests.Widcomm { [TestFixture] public class WidcommBluetoothClientInquiryTest { class TestInquiryBtIf : IBtIf { WidcommBtInterface m_parent; // public ManualResetEvent startInquiryCalled = new ManualResetEvent(false); public int stopInquiryCalled; public bool startInquiryFails; public bool testDoCallbacksFromWithinStartInquiry; /// <summary> /// If not set then BondQuery throws, otherwise returns the set value. /// </summary> public bool? bondQueryResult; public void SetParent(WidcommBtInterface parent) { m_parent = parent; } public void Create() { } public void Destroy(bool disposing) { } // public bool StartInquiry() { bool success = startInquiryCalled.Set(); Assert.IsTrue(success, "startInquiryCalled.Set"); if (startInquiryFails) return false; if (testDoCallbacksFromWithinStartInquiry) { // ???? dodgy, on the same thread???? InquiryEventsOne(); } return true; } public void StopInquiry() { ++stopInquiryCalled; } public void InquiryEventsOne() { m_parent.HandleDeviceResponded(WidcommAddressA, DevclassXXXX, WidcommDeviceNameA, false); m_parent.HandleDeviceResponded(WidcommAddressB, DevclassXXXX, WidcommDeviceNameB, false); m_parent.HandleInquiryComplete(true, 2); } public void InquiryEventsTwoWithSecondNameEvent() { m_parent.HandleDeviceResponded(WidcommAddressA, DevclassXXXX, null, false); m_parent.HandleDeviceResponded(WidcommAddressB, DevclassXXXX, WidcommDeviceNameB, false); m_parent.HandleDeviceResponded(WidcommAddressA, DevclassXXXX, WidcommDeviceNameA, false); m_parent.HandleInquiryComplete(true, 2); } public void InquiryEventsOne_WithNoCompletedEvent() { m_parent.HandleDeviceResponded(WidcommAddressA, DevclassXXXX, WidcommDeviceNameA, false); m_parent.HandleDeviceResponded(WidcommAddressB, DevclassXXXX, WidcommDeviceNameB, false); //////m_parentxxxx.HandleInquiryComplete(true, 2); } //-------- public bool StartDiscovery(BluetoothAddress address, Guid serviceGuid) { throw new NotImplementedException(); } public DISCOVERY_RESULT GetLastDiscoveryResult(out BluetoothAddress address, out UInt16 p_num_recs) { throw new NotImplementedException(); } public ISdpDiscoveryRecordsBuffer ReadDiscoveryRecords(BluetoothAddress address, int maxCount, ServiceDiscoveryParams args) { throw new NotImplementedException(); } public bool GetLocalDeviceVersionInfo(ref DEV_VER_INFO devVerInfo) { throw new NotImplementedException(); } //---- #region Get(Next)RemoteDeviceInfo REM_DEV_INFO[] _RememberedDevices; int? _RememberedDevicesResultIndex; public void SetRememberedDevices(REM_DEV_INFO[] list) { if (_RememberedDevicesResultIndex != null) throw new InvalidOperationException("Operation in progress."); _RememberedDevices = list; } public REM_DEV_INFO_RETURN_CODE GetRemoteDeviceInfo(ref REM_DEV_INFO remDevInfo, IntPtr p_rem_dev_info, int cb) { //return REM_DEV_INFO_RETURN_CODE.EOF; return ReturnRememberedDevice(ref remDevInfo, true); } public REM_DEV_INFO_RETURN_CODE GetNextRemoteDeviceInfo(ref REM_DEV_INFO remDevInfo, IntPtr p_rem_dev_info, int cb) { //throw new NotImplementedException(); return ReturnRememberedDevice(ref remDevInfo, false); } private REM_DEV_INFO_RETURN_CODE ReturnRememberedDevice(ref REM_DEV_INFO remDevInfo, bool firstGet) { if (_RememberedDevices == null) { Debug.Assert(_RememberedDevicesResultIndex == null); if (firstGet) { return REM_DEV_INFO_RETURN_CODE.EOF; } else { throw new InvalidOperationException("Not in progress."); } } // In progress? Must NOT for Get, MUST for Next. if (firstGet) { if (_RememberedDevicesResultIndex != null) throw new InvalidOperationException("In progress."); _RememberedDevicesResultIndex = 0; } else { if (_RememberedDevicesResultIndex == null) return REM_DEV_INFO_RETURN_CODE.ERROR; } // At end? if (_RememberedDevicesResultIndex.Value > _RememberedDevices.Length) throw new InvalidOperationException("Test infrastructure error -- out of range somehow."); if (_RememberedDevicesResultIndex.Value == _RememberedDevices.Length) { _RememberedDevicesResultIndex = null; return REM_DEV_INFO_RETURN_CODE.EOF; } Debug.Assert(_RememberedDevicesResultIndex.Value < _RememberedDevices.Length); // Success remDevInfo = _RememberedDevices[(int)_RememberedDevicesResultIndex++]; return REM_DEV_INFO_RETURN_CODE.SUCCESS; } #endregion public bool GetLocalDeviceName(byte[] bdName) { throw new Exception("The method or operation is not implemented."); } public void IsDeviceConnectableDiscoverable(out bool conno, out bool disco) { throw new Exception("The method or operation is not implemented."); } public bool GetLocalDeviceInfoBdAddr(byte[] bdAddr) { throw new Exception("The method or operation is not implemented."); } public int GetRssi(byte[] bd_addr) { throw new Exception("The method or operation is not implemented."); } public bool BondQuery(byte[] bd_addr) { if (!bondQueryResult.HasValue) { throw new InvalidOperationException("BondQuery not allowed here??!??"); } return bondQueryResult.Value; } public BOND_RETURN_CODE Bond(BluetoothAddress address, string passphrase) { throw new Exception("The method or operation is not implemented."); } public bool UnBond(BluetoothAddress address) { throw new Exception("The method or operation is not implemented."); } public WBtRc GetExtendedError() { throw new Exception("The method or operation is not implemented."); } public SDK_RETURN_CODE IsRemoteDevicePresent(byte[] bd_addr) { throw new NotImplementedException("The method or operation is not implemented."); } public bool IsRemoteDeviceConnected(byte[] bd_addr) { throw new NotImplementedException("The method or operation is not implemented."); } public void IsStackUpAndRadioReady(out bool stackServerUp, out bool deviceReady) { throw new NotImplementedException(); } public void SetDeviceConnectableDiscoverable(bool connectable, bool pairedOnly, bool discoverable) { throw new NotImplementedException(); } }//class private static void Create_BluetoothClient(out TestInquiryBtIf btIf, out BluetoothClient cli) { // Ensure this is setup, as we call it from a thread which will not work. TestUtilities.IsUnderTestHarness(); // btIf = new TestInquiryBtIf(); TestRfcommPort port; Stream strm2; WidcommBluetoothClientCommsTest.Create_BluetoothClient(btIf, out port, out cli, out strm2); } //-------------------------------------------------------------- static readonly byte[] _widcommAddressA = { 0, 1, 2, 3, 4, 5 }; static readonly byte[] _widcommAddressB = { 0x00, 0x1F, 0x2E, 0x3D, 0x4C, 0x5B }; static readonly byte[] _devclassXXXX = { 0x02, 0x01, 0x04 }; static readonly byte[] _widcommDeviceNameA ={ (byte)'d', (byte)'e', (byte)'v', (byte)'A' }; static readonly byte[] _widcommDeviceNameB ={ (byte)'d', (byte)'e', (byte)'v', 0xC3, 0x89 }; // TODO maximum length name?248/7 public static byte[] WidcommAddressA { get { return Clone(WidcommBluetoothClientInquiryTest._widcommAddressA); } } public static byte[] WidcommAddressB { get { return Clone(WidcommBluetoothClientInquiryTest._widcommAddressB); } } public static byte[] DevclassXXXX { get { return Clone(WidcommBluetoothClientInquiryTest._devclassXXXX); } } public static byte[] WidcommDeviceNameA { get { return Clone(WidcommBluetoothClientInquiryTest._widcommDeviceNameA); } } public static byte[] WidcommDeviceNameB { get { return Clone(WidcommBluetoothClientInquiryTest._widcommDeviceNameB); } } private static byte[] Clone(byte[] p) { return (byte[])p.Clone(); } // readonly BluetoothAddress AddressA = BluetoothAddress.Parse("00:01:02:03:04:05"); readonly BluetoothAddress AddressB = BluetoothAddress.Parse("00:1F:2E:3D:4C:5B"); const string NameA = "devA"; const string NameB = "dev\u00C9"; // unicode E-acute const uint CodXXXX = 0x20104/*00*/; const ServiceClass CodXXXXSvcClass = ServiceClass.Network; const DeviceClass CodXXXXDeviceClass = DeviceClass.DesktopComputer; private void VerifyDevicesOne(BluetoothDeviceInfo[] devices) { Assert.AreEqual(2, devices.Length, "count"); Assert.AreEqual(AddressA, devices[0].DeviceAddress, "addrA"); Assert.AreEqual(NameA, devices[0].DeviceName, "nameA"); Assert.AreEqual(AddressB, devices[1].DeviceAddress, "addrB"); Assert.AreEqual(NameB, devices[1].DeviceName, "nameB"); // TODO Assert DeviceClass etc etc. Assert.AreEqual(CodXXXXSvcClass, devices[0].ClassOfDevice.Service, "codSvcA"); Assert.AreEqual(CodXXXXDeviceClass, devices[0].ClassOfDevice.Device, "codDevA"); Assert.AreEqual(CodXXXX, devices[0].ClassOfDevice.Value, "codA"); } [Test] public void One() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsOne(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; BluetoothDeviceInfo[] devices = cli.DiscoverDevices(); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devices); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void StartInquiryFails_ThenTestOne() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); // btIf.startInquiryFails = true; try { BluetoothDeviceInfo[] devicesX = cli.DiscoverDevices(); Assert.Fail("should have thrown!"); } catch (System.Net.Sockets.SocketException) { } bool signalled1 = btIf.startInquiryCalled.WaitOne(0, false); Assert.IsTrue(signalled1, "!signalled_a!!!!!"); // btIf.startInquiryCalled.Reset(); btIf.startInquiryFails = false; // ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsOne(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; IAsyncResult arDD = cli.BeginDiscoverDevices(255, true, true, true, true, null, null); TestsApmUtils.SafeNoHangWait(arDD, "DiscoverDevices"); BluetoothDeviceInfo[] devices = cli.EndDiscoverDevices(arDD); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devices); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void One_Remembered() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; BluetoothDeviceInfo[] devices = cli.DiscoverDevices(1000, false, true, false, false); Assert.AreEqual(0, devices.Length); Assert.AreEqual(0, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void One_SameThread() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); btIf.testDoCallbacksFromWithinStartInquiry = true; WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; BluetoothDeviceInfo[] devices = cli.DiscoverDevices(); VerifyDevicesOne(devices); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void TwoWithSecondNameEvent() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsTwoWithSecondNameEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; BluetoothDeviceInfo[] devices = cli.DiscoverDevices(); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devices); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void FromRegistry_Attempt() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); btIf.testDoCallbacksFromWithinStartInquiry = true; btIf.bondQueryResult = false; WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = true; try { BluetoothDeviceInfo[] devices = cli.DiscoverDevices(); // May succeed, if the current machine has Widcomm installed... } catch (IOException ex) { // May fail, if the current machine doesn't have Widcomm installed... Assert.IsInstanceOfType(typeof(IOException), ex, "ex.Type"); Assert.AreEqual("Widcomm 'Devices' key not found in the Registry.", ex.Message, "ex.Message"); } } //-------- [Test] public void EventsOccurWithNoPrecedingDiscoverDevicesCall() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); } void _EventsOccurWithNoPrecedingDiscoverDevicesCall( TestInquiryBtIf btIf, BluetoothClient cli) { Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(0, false); Assert.IsFalse(signalled, "!signalled_A!!!!!"); btIf.InquiryEventsOne(); signalled = btIf.startInquiryCalled.WaitOne(0, false); Assert.IsFalse(signalled, "!signalled_B!!!!!"); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void EventsOccurWithNoPrecedingDiscoverDevicesCall_WithNoCompletedEvent() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); } void _EventsOccurWithNoPrecedingDiscoverDevicesCall_WithNoCompletedEvent( TestInquiryBtIf btIf, BluetoothClient cli) { Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(0, false); Assert.IsFalse(signalled, "!signalled_A!!!!!"); btIf.InquiryEventsOne_WithNoCompletedEvent(); signalled = btIf.startInquiryCalled.WaitOne(0, false); Assert.IsFalse(signalled, "!signalled_B!!!!!"); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? Assert.AreEqual(0, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void EventsOccurWithNoPrecedingDiscoverDevicesCall_BothRepeated() { TestInquiryBtIf btIf; BluetoothClient cli; Create_BluetoothClient(out btIf, out cli); // _EventsOccurWithNoPrecedingDiscoverDevicesCall_WithNoCompletedEvent(btIf, cli); _EventsOccurWithNoPrecedingDiscoverDevicesCall_WithNoCompletedEvent(btIf, cli); _EventsOccurWithNoPrecedingDiscoverDevicesCall(btIf, cli); btIf.stopInquiryCalled = 0; _EventsOccurWithNoPrecedingDiscoverDevicesCall(btIf, cli); } // With default non-infinite InquiryLength, test now no correct.[Test] public void One_CompletedEventLateOrNeverComes() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsOne_WithNoCompletedEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; Assert.IsTrue(cli.InquiryLength.CompareTo(TimeSpan.Zero) < 0, "Excepted infinite InquiryLength, but was: " + cli.InquiryLength); IAsyncResult arDD = cli.BeginDiscoverDevices(255, true, true, true, false, null, null); bool completed = arDD.AsyncWaitHandle.WaitOne(1 * 1000, false); Assert.IsFalse(completed, "Expected DD to time-out."); // NON USEFUL/WOULD BLOCK //BluetoothDeviceInfo[] devices = cli.EndDiscoverDevices(arDD); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? //VerifyDevicesOne(devices); //Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void One_CompletedEventLateOrNeverComes_ButHasTimeout() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); cli.InquiryLength = TimeSpan.FromMilliseconds(750); // Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsOne_WithNoCompletedEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; Assert.IsTrue(cli.InquiryLength.CompareTo(TimeSpan.Zero) > 0, "blehhhhhhhhhhhhhhhhhhhhhh"); IAsyncResult arDD = cli.BeginDiscoverDevices(255, true, true, true, false, null, null); // Timeout Killer occurs 1.5 times the InquiryLength, 1125ms bool completed = arDD.AsyncWaitHandle.WaitOne(1500, false); Assert.IsTrue(completed, "Unexpected DD time-out."); BluetoothDeviceInfo[] devices = cli.EndDiscoverDevices(arDD); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devices); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void One_TimeoutSet_ButCompletesBeforeTimeout() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); cli.InquiryLength = TimeSpan.FromSeconds(1); // Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsOne(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; BluetoothDeviceInfo[] devices = cli.DiscoverDevices(); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devices); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); // Wait around, trying to see any exception on the timeout thread. Thread.Sleep(1650); } [Test] public void TwoDiscosConcurrently_lattersGetFirstsInquiredList_basedOnTestOne() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsOne(); }; WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; // We really should test with two BtCli instances but that's a bit hard to set-up. IAsyncResult ar1 = cli.BeginDiscoverDevices(255, true, true, true, false, null, null); IAsyncResult ar2 = cli.BeginDiscoverDevices(255, true, true, true, false, null, null); IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); bool signalledAr = _WaitAll(new WaitHandle[] { ar1.AsyncWaitHandle, ar2.AsyncWaitHandle }, 15000); Assert.IsTrue(signalledAr, "signalledAr"); BluetoothDeviceInfo[] devices1 = cli.EndDiscoverDevices(ar1); BluetoothDeviceInfo[] devices2 = cli.EndDiscoverDevices(ar2); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devices1); VerifyDevicesOne(devices2); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } #if !NETCF // TODO ! Need test with 'remembered' devices... [Test] public void Ebap_TwoWithSecondNameEvent() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsTwoWithSecondNameEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; var bc = new BluetoothComponent(cli); var devicesSteps = new List<BluetoothDeviceInfo[]>(); BluetoothDeviceInfo[] devicesResult = null; var complete = new ManualResetEvent(false); bc.DiscoverDevicesProgress += delegate(object sender, DiscoverDevicesEventArgs e) { devicesSteps.Add(e.Devices); }; bc.DiscoverDevicesComplete += delegate(object sender, DiscoverDevicesEventArgs e) { try { devicesResult = e.Devices; } finally { complete.Set(); } }; bc.DiscoverDevicesAsync(255, true, true, true, false, 999); bool signalled2 = complete.WaitOne(15000); Assert.IsTrue(signalled2, "signalled2"); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devicesResult); Assert.AreEqual(3, devicesSteps.Count); Assert.AreEqual(1, devicesSteps[0].Length, "[0].Len"); Assert.AreEqual(AddressA, devicesSteps[0][0].DeviceAddress, "[0][0].Addr"); Assert.AreEqual(AddressA.ToString("C"), devicesSteps[0][0].DeviceName, "[0][0].Name"); // no name Assert.AreEqual(1, devicesSteps[1].Length, "[1].Len"); Assert.AreEqual(AddressB, devicesSteps[1][0].DeviceAddress, "[1][0].Addr"); Assert.AreEqual(NameB, devicesSteps[1][0].DeviceName, "[1][0].Name"); Assert.AreEqual(1, devicesSteps[2].Length, "[2].Len"); Assert.AreEqual(AddressA, devicesSteps[2][0].DeviceAddress, "[2][0].Addr"); Assert.AreEqual(NameA, devicesSteps[2][0].DeviceName, "[2][0].Name"); Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void Ebap_WithRememberedDuplicateDevices_From_TwoWithSecondNameEvent() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsTwoWithSecondNameEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; var bc = new BluetoothComponent(cli); var devicesSteps = new List<BluetoothDeviceInfo[]>(); BluetoothDeviceInfo[] devicesResult = null; var complete = new ManualResetEvent(false); bc.DiscoverDevicesProgress += delegate(object sender, DiscoverDevicesEventArgs e) { devicesSteps.Add(e.Devices); }; bc.DiscoverDevicesComplete += delegate(object sender, DiscoverDevicesEventArgs e) { try { devicesResult = e.Devices; } finally { complete.Set(); } }; // REM_DEV_INFO[] remembered = { CreateREM_DEV_INFO(NameB, AddressB), CreateREM_DEV_INFO(NameA, AddressA), }; btIf.SetRememberedDevices(remembered); // bc.DiscoverDevicesAsync(255, true, true, true, false, 999); bool signalled2 = complete.WaitOne(15000); Assert.IsTrue(signalled2, "signalled2"); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devicesResult); Assert.AreEqual(4, devicesSteps.Count); int step = 0; Assert.AreEqual(2, devicesSteps[step].Length, "[0].Len"); Assert.AreEqual(AddressB, devicesSteps[step][0].DeviceAddress, "[0][1].Addr"); Assert.AreEqual(NameB, devicesSteps[step][0].DeviceName, "[0][1].Name"); // no name Assert.AreEqual(AddressA, devicesSteps[step][1].DeviceAddress, "[0][0].Addr"); Assert.AreEqual(NameA, devicesSteps[step][1].DeviceName, "[0][0].Name"); // no name ++step; Assert.AreEqual(1, devicesSteps[step].Length, "[0].Len"); Assert.AreEqual(AddressA, devicesSteps[step][0].DeviceAddress, "[0][0].Addr"); Assert.AreEqual(AddressA.ToString("C"), devicesSteps[step][0].DeviceName, "[0][0].Name"); // no name ++step; Assert.AreEqual(1, devicesSteps[step].Length, "[1].Len"); Assert.AreEqual(AddressB, devicesSteps[step][0].DeviceAddress, "[1][0].Addr"); Assert.AreEqual(NameB, devicesSteps[step][0].DeviceName, "[1][0].Name"); ++step; Assert.AreEqual(1, devicesSteps[step].Length, "[2].Len"); Assert.AreEqual(AddressA, devicesSteps[step][0].DeviceAddress, "[2][0].Addr"); Assert.AreEqual(NameA, devicesSteps[step][0].DeviceName, "[2][0].Name"); ++step; Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } [Test] public void Ebap_WithRememberedOnePartDuplicateDevice_From_TwoWithSecondNameEvent() { TestInquiryBtIf btIf; BluetoothClient cli; // Create_BluetoothClient(out btIf, out cli); Assert.IsFalse(btIf.testDoCallbacksFromWithinStartInquiry, "tdcfwsi"); ThreadStart dlgt = delegate { bool signalled = btIf.startInquiryCalled.WaitOne(10000, false); Assert.IsTrue(signalled, "!signalled!!!!!"); btIf.InquiryEventsTwoWithSecondNameEvent(); }; IAsyncResult arDlgt = Delegate2.BeginInvoke(dlgt, null, null); // WidcommBluetoothClient.ReadKnownDeviceFromTheRegistry = false; var bc = new BluetoothComponent(cli); var devicesSteps = new List<BluetoothDeviceInfo[]>(); BluetoothDeviceInfo[] devicesResult = null; var complete = new ManualResetEvent(false); bc.DiscoverDevicesProgress += delegate(object sender, DiscoverDevicesEventArgs e) { devicesSteps.Add(e.Devices); }; bc.DiscoverDevicesComplete += delegate(object sender, DiscoverDevicesEventArgs e) { try { devicesResult = e.Devices; } finally { complete.Set(); } }; // REM_DEV_INFO[] remembered = { CreateREM_DEV_INFO(null, AddressB), }; btIf.SetRememberedDevices(remembered); // bc.DiscoverDevicesAsync(255, true, true, true, false, 999); bool signalled2 = complete.WaitOne(15000); Assert.IsTrue(signalled2, "signalled2"); Delegate2.EndInvoke(dlgt, arDlgt); // any exceptions? VerifyDevicesOne(devicesResult); Assert.AreEqual(4, devicesSteps.Count); int step = 0; Assert.AreEqual(1, devicesSteps[step].Length, "[0].Len"); Assert.AreEqual(AddressB, devicesSteps[step][0].DeviceAddress, "[0][1].Addr"); Assert.AreEqual(AddressB.ToString("C"), devicesSteps[step][0].DeviceName, "[0][1].Name"); // no name ++step; Assert.AreEqual(1, devicesSteps[step].Length, "[0].Len"); Assert.AreEqual(AddressA, devicesSteps[step][0].DeviceAddress, "[0][0].Addr"); Assert.AreEqual(AddressA.ToString("C"), devicesSteps[step][0].DeviceName, "[0][0].Name"); // no name ++step; Assert.AreEqual(1, devicesSteps[step].Length, "[1].Len"); Assert.AreEqual(AddressB, devicesSteps[step][0].DeviceAddress, "[1][0].Addr"); Assert.AreEqual(NameB, devicesSteps[step][0].DeviceName, "[1][0].Name"); ++step; Assert.AreEqual(1, devicesSteps[step].Length, "[2].Len"); Assert.AreEqual(AddressA, devicesSteps[step][0].DeviceAddress, "[2][0].Addr"); Assert.AreEqual(NameA, devicesSteps[step][0].DeviceName, "[2][0].Name"); ++step; Assert.AreEqual(1, btIf.stopInquiryCalled, "stopInquiryCalled"); } private REM_DEV_INFO CreateREM_DEV_INFO(string name, BluetoothAddress addr) { var dev = new REM_DEV_INFO(); if (name != null) dev.bd_name = Encoding.UTF8.GetBytes(name + "\0"); if (addr != null) dev.bda = WidcommUtils.FromBluetoothAddress(addr); return dev; } #endif //------------------------------------------------------------ static bool _WaitAll(WaitHandle[] events, int timeout) { #if false && !NETCF return WaitHandle.WaitAll(events, timeout); #else var final = DateTime.UtcNow.AddMilliseconds(timeout); foreach (var curE in events) { TimeSpan curTo = final.Subtract(DateTime.UtcNow); if (curTo.CompareTo(TimeSpan.Zero) <= 0) { Debug.Fail("Should we expect to get here? Normally exit at !signalled below..."); return false; } bool signalled = curE.WaitOne((int)curTo.TotalMilliseconds, false); if (!signalled) { return false; } }//for return true; #endif } } }
using System; using System.Collections.Specialized; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using SteamKit2; using System.Net; using Newtonsoft.Json; using SteamTrade.TradeOffers.Enums; using SteamTrade.TradeOffers.Objects; namespace SteamTrade.TradeOffers { public class TradeOffers { public List<ulong> OurPendingTradeOffers; private readonly object _ourPendingTradeOffersLock; private readonly SteamID _botId; private readonly SteamWeb _steamWeb; private readonly List<ulong> _handledTradeOffers; private readonly List<ulong> _awaitingConfirmationTradeOffers; private readonly List<ulong> _inEscrowTradeOffers; private readonly string _accountApiKey; private bool _shouldCheckPendingTradeOffers; private readonly int _tradeOfferRefreshRate; public TradeOffers(SteamID botId, SteamWeb steamWeb, string accountApiKey, int tradeOfferRefreshRate, List<ulong> pendingTradeOffers = null) { _botId = botId; _steamWeb = steamWeb; _accountApiKey = accountApiKey; _shouldCheckPendingTradeOffers = true; _tradeOfferRefreshRate = tradeOfferRefreshRate; OurPendingTradeOffers = pendingTradeOffers ?? new List<ulong>(); _ourPendingTradeOffersLock = new object(); _handledTradeOffers = new List<ulong>(); _awaitingConfirmationTradeOffers = new List<ulong>(); _inEscrowTradeOffers = new List<ulong>(); new Thread(CheckPendingTradeOffers).Start(); } /// <summary> /// Create a new trade offer session. /// </summary> /// <param name="partnerId">The SteamID of the user you want to send a trade offer to.</param> /// <returns>A 'Trade' object in which you can apply further actions</returns> public Trade CreateTrade(SteamID partnerId) { return new Trade(this, partnerId, _steamWeb); } /// <summary> /// Accepts a pending trade offer. /// </summary> /// <param name="tradeOfferId">The ID of the trade offer</param> /// <param name="tradeId">The trade ID of the completed trade</param> /// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception> /// <returns>True if successful, false if not</returns> public bool AcceptTrade(ulong tradeOfferId) { var tradeOfferResponse = GetTradeOffer(tradeOfferId); return tradeOfferResponse.Offer != null && AcceptTrade(tradeOfferResponse.Offer); } /// <summary> /// Accepts a pending trade offer /// </summary> /// <param name="tradeOffer">The trade offer object</param> /// <param name="tradeId">The trade ID of the completed trade</param> /// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception> /// <returns>True if successful, false if not</returns> public bool AcceptTrade(TradeOffer tradeOffer) { var tradeOfferId = tradeOffer.Id; var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/accept"; var referer = "http://steamcommunity.com/tradeoffer/" + tradeOfferId + "/"; var data = new NameValueCollection { {"sessionid", _steamWeb.SessionId}, {"serverid", "1"}, {"tradeofferid", tradeOfferId.ToString()}, {"partner", tradeOffer.OtherSteamId.ToString()} }; var response = RetryWebRequest(_steamWeb, url, "POST", data, true, referer); if (string.IsNullOrEmpty(response)) return false; dynamic json = JsonConvert.DeserializeObject(response); if (json.strError != null) throw new TradeOfferSteamException(json.strError); if (json.tradeid == null) return false; return true; } /// <summary> /// Declines a pending trade offer /// </summary> /// <param name="tradeOffer">The trade offer object</param> /// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception> /// <returns>True if successful, false if not</returns> public bool DeclineTrade(TradeOffer tradeOffer) { return DeclineTrade(tradeOffer.Id); } /// <summary> /// Declines a pending trade offer /// </summary> /// <param name="tradeOfferId">The trade offer ID</param> /// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception> /// <returns>True if successful, false if not</returns> public bool DeclineTrade(ulong tradeOfferId) { var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/decline"; const string referer = "http://steamcommunity.com/"; var data = new NameValueCollection {{"sessionid", _steamWeb.SessionId}, {"serverid", "1"}}; var response = RetryWebRequest(_steamWeb, url, "POST", data, true, referer); dynamic json = JsonConvert.DeserializeObject(response); if (json.strError != null) throw new TradeOfferSteamException(json.strError); return json.tradeofferid != null; } /// <summary> /// Cancels a pending sent trade offer /// </summary> /// <param name="tradeOffer">The trade offer object</param> /// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception> /// <returns>True if successful, false if not</returns> public bool CancelTrade(TradeOffer tradeOffer) { return CancelTrade(tradeOffer.Id); } /// <summary> /// Cancels a pending sent trade offer /// </summary> /// <param name="tradeOfferId">The trade offer ID</param> /// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception> /// <returns>True if successful, false if not</returns> public bool CancelTrade(ulong tradeOfferId) { var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/cancel"; const string referer = "http://steamcommunity.com/"; var data = new NameValueCollection {{"sessionid", _steamWeb.SessionId}}; var response = RetryWebRequest(_steamWeb, url, "POST", data, true, referer); dynamic json = JsonConvert.DeserializeObject(response); if (json.strError != null) throw new TradeOfferSteamException(json.strError); return json.tradeofferid != null; } /// <summary> /// Get a list of incoming trade offers. /// </summary> /// <returns>An 'int' list of trade offer IDs</returns> public List<ulong> GetIncomingTradeOffers() { var incomingTradeOffers = new List<ulong>(); var url = "http://steamcommunity.com/profiles/" + _botId.ConvertToUInt64() + "/tradeoffers/"; var html = RetryWebRequest(_steamWeb, url, "GET", null); var reg = new Regex("ShowTradeOffer\\((.*?)\\);"); var matches = reg.Matches(html); foreach (Match match in matches) { if (match.Success) { var tradeId = Convert.ToUInt64(match.Groups[1].Value.Replace("'", "")); if (!incomingTradeOffers.Contains(tradeId)) incomingTradeOffers.Add(tradeId); } } return incomingTradeOffers; } public GetTradeOffer.GetTradeOfferResponse GetTradeOffer(ulong tradeOfferId) { var url = string.Format("https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key={0}&tradeofferid={1}&language={2}", _accountApiKey, tradeOfferId, "en_us"); var response = RetryWebRequest(_steamWeb, url, "GET", null, false, "http://steamcommunity.com"); var result = JsonConvert.DeserializeObject<GetTradeOffer>(response); if (result.Response != null) { return result.Response; } return null; } /// <summary> /// Get list of trade offers from API /// </summary> /// <param name="getActive">Set this to true to get active-only trade offers</param> /// <returns>list of trade offers</returns> public List<TradeOffer> GetTradeOffers(bool getActive = false) { var temp = new List<TradeOffer>(); var url = "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=" + _accountApiKey + "&get_sent_offers=1&get_received_offers=1"; if (getActive) { url += "&active_only=1&time_historical_cutoff=" + (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } else { url += "&active_only=0"; } var response = RetryWebRequest(_steamWeb, url, "GET", null, false, "http://steamcommunity.com"); var json = JsonConvert.DeserializeObject<dynamic>(response); var sentTradeOffers = json.response.trade_offers_sent; if (sentTradeOffers != null) { foreach (var tradeOffer in sentTradeOffers) { TradeOffer tempTrade = JsonConvert.DeserializeObject<TradeOffer>(Convert.ToString(tradeOffer)); temp.Add(tempTrade); } } var receivedTradeOffers = json.response.trade_offers_received; if (receivedTradeOffers != null) { foreach (var tradeOffer in receivedTradeOffers) { TradeOffer tempTrade = JsonConvert.DeserializeObject<TradeOffer>(Convert.ToString(tradeOffer)); temp.Add(tempTrade); } } return temp; } /// <summary> /// Manually validate if a trade offer went through by checking /inventoryhistory/ /// You shouldn't use this since it may be exploitable. I'm keeping it here in case I want to rework this in the future. /// </summary> /// <param name="tradeOffer">A 'TradeOffer' object</param> /// <returns>True if the trade offer was successfully accepted, false if otherwise</returns> // public bool ValidateTradeAccept(TradeOffer tradeOffer) // { // try // { // var history = GetTradeHistory(); // foreach (var completedTrade in history) // { // if (tradeOffer.ItemsToGive.Length == completedTrade.GivenItems.Count && tradeOffer.ItemsToReceive.Length == completedTrade.ReceivedItems.Count) // { // var numFoundGivenItems = 0; // var numFoundReceivedItems = 0; // var foundItemIds = new List<ulong>(); // foreach (var historyItem in completedTrade.GivenItems) // { // foreach (var tradeOfferItem in tradeOffer.ItemsToGive) // { // if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId) // { // if (!foundItemIds.Contains(tradeOfferItem.AssetId)) // { // foundItemIds.Add(tradeOfferItem.AssetId); // numFoundGivenItems++; // } // } // } // } // foreach (var historyItem in completedTrade.ReceivedItems) // { // foreach (var tradeOfferItem in tradeOffer.ItemsToReceive) // { // if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId) // { // if (!foundItemIds.Contains(tradeOfferItem.AssetId)) // { // foundItemIds.Add(tradeOfferItem.AssetId); // numFoundReceivedItems++; // } // } // } // } // if (numFoundGivenItems == tradeOffer.ItemsToGive.Length && numFoundReceivedItems == tradeOffer.ItemsToReceive.Length) // { // return true; // } // } // } // } // catch (Exception ex) // { // Console.WriteLine("Error validating trade:"); // Console.WriteLine(ex); // } // return false; // } /// <summary> /// Retrieves completed trades from /inventoryhistory/ /// </summary> /// <param name="limit">Max number of trades to retrieve</param> /// <param name="numPages">How many pages to retrieve</param> /// <returns>A List of 'TradeHistory' objects</returns> public List<TradeHistory> GetTradeHistory(int limit = 0, int numPages = 1) { var tradeHistoryPages = new Dictionary<int, TradeHistory[]>(); for (var i = 0; i < numPages; i++) { var tradeHistoryPageList = new TradeHistory[30]; try { var url = "http://steamcommunity.com/profiles/" + _botId.ConvertToUInt64() + "/inventoryhistory/?p=" + i; var html = RetryWebRequest(_steamWeb, url, "GET", null); // TODO: handle rgHistoryCurrency as well var reg = new Regex("rgHistoryInventory = (.*?)};"); var m = reg.Match(html); if (m.Success) { var json = m.Groups[1].Value + "}"; var schemaResult = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<ulong, Dictionary<ulong, TradeHistory.HistoryItem>>>>(json); var trades = new Regex("HistoryPageCreateItemHover\\((.*?)\\);"); var tradeMatches = trades.Matches(html); foreach (Match match in tradeMatches) { if (!match.Success) continue; var historyString = match.Groups[1].Value.Replace("'", "").Replace(" ", ""); var split = historyString.Split(','); var tradeString = split[0]; var tradeStringSplit = tradeString.Split('_'); var tradeNum = Convert.ToInt32(tradeStringSplit[0].Replace("trade", "")); if (limit > 0 && tradeNum >= limit) break; if (tradeHistoryPageList[tradeNum] == null) { tradeHistoryPageList[tradeNum] = new TradeHistory(); } var tradeHistoryItem = tradeHistoryPageList[tradeNum]; var appId = Convert.ToInt32(split[1]); var contextId = Convert.ToUInt64(split[2]); var itemId = Convert.ToUInt64(split[3]); var amount = Convert.ToInt32(split[4]); var historyItem = schemaResult[appId][contextId][itemId]; if (historyItem.OwnerId == 0) tradeHistoryItem.ReceivedItems.Add(historyItem); else tradeHistoryItem.GivenItems.Add(historyItem); } } } catch (Exception ex) { Console.WriteLine("Error retrieving trade history:"); Console.WriteLine(ex); } tradeHistoryPages.Add(i, tradeHistoryPageList); } return tradeHistoryPages.Values.SelectMany(tradeHistoryPage => tradeHistoryPage).ToList(); } public void AddPendingTradeOfferToList(ulong tradeOfferId) { lock (_ourPendingTradeOffersLock) { OurPendingTradeOffers.Add(tradeOfferId); } } private void RemovePendingTradeOfferFromList(ulong tradeOfferId) { lock (_ourPendingTradeOffersLock) { OurPendingTradeOffers.Remove(tradeOfferId); } } public void StopCheckingPendingTradeOffers() { _shouldCheckPendingTradeOffers = false; } private void CheckPendingTradeOffers() { new Thread(() => { while (_shouldCheckPendingTradeOffers) { var tradeOffers = GetTradeOffers(true); foreach (var tradeOffer in tradeOffers) { if (tradeOffer.IsOurOffer) { lock (_ourPendingTradeOffersLock) { if (OurPendingTradeOffers.Contains(tradeOffer.Id)) continue; } AddPendingTradeOfferToList(tradeOffer.Id); } else { var args = new TradeOfferEventArgs(tradeOffer); if (tradeOffer.State == TradeOfferState.Active) { if (tradeOffer.ConfirmationMethod != TradeOfferConfirmationMethod.Invalid) { OnTradeOfferNeedsConfirmation(args); } else { OnTradeOfferReceived(args); } } } } Thread.Sleep(_tradeOfferRefreshRate); } }).Start(); while (_shouldCheckPendingTradeOffers) { var checkingThreads = new List<Thread>(); List<ulong> ourPendingTradeOffers; lock (_ourPendingTradeOffersLock) { ourPendingTradeOffers = OurPendingTradeOffers.ToList(); } foreach (var thread in ourPendingTradeOffers.Select(tradeOfferId => new Thread(() => { var pendingTradeOffer = GetTradeOffer(tradeOfferId); if (pendingTradeOffer.Offer == null) { // Steam's GetTradeOffer/v1 API only gives data for the last 1000 received and 500 sent trade offers, so sometimes this happens pendingTradeOffer.Offer = new TradeOffer { Id = tradeOfferId }; OnTradeOfferNoData(new TradeOfferEventArgs(pendingTradeOffer.Offer)); } else { var args = new TradeOfferEventArgs(pendingTradeOffer.Offer); if (pendingTradeOffer.Offer.State == TradeOfferState.Active) { // fire this so that trade can be cancelled in UserHandler if the bot owner wishes (e.g. if pending too long) OnTradeOfferChecked(args); } else { // check if trade offer has been accepted/declined, or items unavailable (manually validate) if (pendingTradeOffer.Offer.State == TradeOfferState.Accepted) { // fire event OnTradeOfferAccepted(args); // remove from list RemovePendingTradeOfferFromList(pendingTradeOffer.Offer.Id); } else { if (pendingTradeOffer.Offer.State == TradeOfferState.NeedsConfirmation) { // fire event OnTradeOfferNeedsConfirmation(args); } else if (pendingTradeOffer.Offer.State == TradeOfferState.Invalid || pendingTradeOffer.Offer.State == TradeOfferState.InvalidItems) { OnTradeOfferInvalid(args); RemovePendingTradeOfferFromList(pendingTradeOffer.Offer.Id); } else if (pendingTradeOffer.Offer.State == TradeOfferState.InEscrow) { OnTradeOfferInEscrow(args); } else { if (pendingTradeOffer.Offer.State == TradeOfferState.Canceled) { OnTradeOfferCanceled(args); } else { OnTradeOfferDeclined(args); } RemovePendingTradeOfferFromList(pendingTradeOffer.Offer.Id); } } } } }))) { checkingThreads.Add(thread); thread.Start(); } foreach (var thread in checkingThreads) { thread.Join(); } Thread.Sleep(_tradeOfferRefreshRate); } } protected virtual void OnTradeOfferChecked(TradeOfferEventArgs e) { var handler = TradeOfferChecked; if (handler != null) { handler(this, e); } } protected virtual void OnTradeOfferReceived(TradeOfferEventArgs e) { if (!_handledTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferReceived; if (handler != null) { handler(this, e); } _handledTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferAccepted(TradeOfferEventArgs e) { if (!_handledTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferAccepted; if (handler != null) { handler(this, e); } _handledTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferDeclined(TradeOfferEventArgs e) { if (!_handledTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferDeclined; if (handler != null) { handler(this, e); } _handledTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferCanceled(TradeOfferEventArgs e) { if (!_handledTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferCanceled; if (handler != null) { handler(this, e); } _handledTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferInvalid(TradeOfferEventArgs e) { if (!_handledTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferInvalid; if (handler != null) { handler(this, e); } _handledTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferNeedsConfirmation(TradeOfferEventArgs e) { if (!_awaitingConfirmationTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferNeedsConfirmation; if (handler != null) { handler(this, e); } _awaitingConfirmationTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferInEscrow(TradeOfferEventArgs e) { if (!_inEscrowTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferInEscrow; if (handler != null) { handler(this, e); } _inEscrowTradeOffers.Add(e.TradeOffer.Id); } } protected virtual void OnTradeOfferNoData(TradeOfferEventArgs e) { if (!_handledTradeOffers.Contains(e.TradeOffer.Id)) { var handler = TradeOfferNoData; if (handler != null) { handler(this, e); } _handledTradeOffers.Add(e.TradeOffer.Id); } } public event TradeOfferStatusEventHandler TradeOfferChecked; public event TradeOfferStatusEventHandler TradeOfferReceived; public event TradeOfferStatusEventHandler TradeOfferAccepted; public event TradeOfferStatusEventHandler TradeOfferDeclined; public event TradeOfferStatusEventHandler TradeOfferCanceled; public event TradeOfferStatusEventHandler TradeOfferInvalid; public event TradeOfferStatusEventHandler TradeOfferNeedsConfirmation; public event TradeOfferStatusEventHandler TradeOfferInEscrow; public event TradeOfferStatusEventHandler TradeOfferNoData; public class TradeOfferEventArgs : EventArgs { public TradeOffer TradeOffer { get; private set; } public TradeOfferEventArgs(TradeOffer tradeOffer) { TradeOffer = tradeOffer; } } public delegate void TradeOfferStatusEventHandler(Object sender, TradeOfferEventArgs e); public static string RetryWebRequest(SteamWeb steamWeb, string url, string method, NameValueCollection data, bool ajax = false, string referer = "") { //(_steamWeb, url, "GET", null, false, "http://steamcommunity.com"); for (var i = 0; i < 10; i++) { try { var response = steamWeb.Request(url, method, data, ajax, referer); using (var responseStream = response.GetResponseStream()) { if (responseStream == null) continue; using (var reader = new System.IO.StreamReader(responseStream)) { var result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) { Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode); Thread.Sleep(1000); } else { return result; } } } } catch (WebException ex) { try { using (var responseStream = ex.Response.GetResponseStream()) { if (responseStream == null) continue; using (var reader = new System.IO.StreamReader(responseStream)) { var result = reader.ReadToEnd(); if (!string.IsNullOrEmpty(result)) { return result; } if (ex.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code: {0}, {1} for {2}", (int)((HttpWebResponse)ex.Response).StatusCode, ((HttpWebResponse)ex.Response).StatusDescription, url); } } } } catch { // ignored } } catch (Exception ex) { Console.WriteLine(ex); } } return ""; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; namespace _4PosBackOffice.NET { internal partial class frmStockTakeCSV : System.Windows.Forms.Form { ADODB.Recordset rs; string Te_Name; string MyFTypes; string sql1; // picture loading Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); // to select W/H for stock take int lMWNo; private void loadLanguage() { //NOTE: Caption has a spelling mistake, DB Entry 1213 is correct! modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1213; //Stock Take if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2506; //Show Differendce|Checked if (modRecordSet.rsLang.RecordCount){cmdDiff.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdDiff.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //NOTE: DB Entry 2507 requires "&" for accelerator key modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2507; //Save and Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1838; //Barcode|Checked if (modRecordSet.rsLang.RecordCount){Label1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1674; //Description|Checked if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1676; //Qty|Checked if (modRecordSet.rsLang.RecordCount){Label3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080; //Search|Checked if (modRecordSet.rsLang.RecordCount){cmdsearch.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdsearch.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2512; //Show Pictures|Checked if (modRecordSet.rsLang.RecordCount){chkPic.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkPic.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmStockTakeCSV.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } //UPGRADE_WARNING: Event chkPic.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' private void chkPic_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs) { if (chkPic.CheckState) { this.Width = sizeConvertors.twipsToPixels(12675, true); picBC.Visible = true; imgBC.Visible = true; this.Left = sizeConvertors.twipsToPixels(400, true); } else { this.Width = sizeConvertors.twipsToPixels(8640, true); picBC.Visible = false; imgBC.Visible = false; } } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { int MStockNew = 0; // ERROR: Not supported in C#: OnErrorStatement ADODB.Recordset rsB = default(ADODB.Recordset); ADODB.Recordset rsk = default(ADODB.Recordset); rsB = new ADODB.Recordset(); rsk = new ADODB.Recordset(); rsk = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + ""); if (rsk.RecordCount > 0) { //UPGRADE_WARNING: Couldn't resolve default property of object MStockNew. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' MStockNew = 2; rsB = modRecordSet.getRS(ref "INSERT INTO StockGroup(StockGroup_Name,StockGroup_Disabled)VALUES('" + Te_Name + "',0)"); UpdateCatalogID(ref (Te_Name)); } MyErH: this.Close(); } private void report_WHTransfer(ref string tblName) { ADODB.Recordset rs = default(ADODB.Recordset); string sql = null; CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument); Report.Load("cryWHRecVerify.rpt"); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; rs = modRecordSet.getRS(ref "SELECT Company.Company_Name FROM Company;"); Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name")); rs.Close(); sql = "SELECT Handheld777_0.HandHeldID, StockItem.StockItem_Name, Handheld777_0.Quantity"; sql = sql + " FROM Handheld777_0 INNER JOIN StockItem ON Handheld777_0.HandHeldID = StockItem.StockItemID;"; rs = modRecordSet.getRS(ref sql); CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument); ReportNone.Load("cryNoRecords.rpt"); if (rs.BOF | rs.EOF) { ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString); ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString); My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone; My.MyProject.Forms.frmReportShow.mReport = ReportNone; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); return; } Report.Database.Tables(1).SetDataSource(rs); //Report.VerifyOnEveryPrint = True My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report; My.MyProject.Forms.frmReportShow.mReport = Report; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); } private void cmdDiff_Click(System.Object eventSender, System.EventArgs eventArgs) { string strIn = null; string strFldName = null; //Te_Name ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rj = default(ADODB.Recordset); // ERROR: Not supported in C#: OnErrorStatement //Set rs = getRS("SELECT * FROM Te_Name") modRecordSet.cnnDB.Execute("DELETE * FROM Handheld777_0;"); modRecordSet.cnnDB.Execute("DROP TABLE Handheld777_0;"); strFldName = "HandHeldID Number,Handheld_Barcode Text(50), Quantity Currency"; modRecordSet.cnnDB.Execute("CREATE TABLE " + "Handheld777_0" + " (" + strFldName + ")"); System.Windows.Forms.Application.DoEvents(); rj = modRecordSet.getRS(ref "SELECT WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID, WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID, WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity From WarehouseStockItemLnk WHERE (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID)=" + lMWNo + ") AND ((WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity)>0))"); while (rj.EOF == false) { rs = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + " WHERE HandHeldID=" + rj.Fields("WarehouseStockItemLnk_StockItemID").Value + ";"); if (rs.RecordCount > 0) { } else { strIn = "INSERT INTO Handheld777_0 (HandHeldID,Handheld_Barcode,Quantity) VALUES (" + rj.Fields("WarehouseStockItemLnk_StockItemID").Value + ", '" + rj.Fields("WarehouseStockItemLnk_Quantity").Value + "', " + rj.Fields("WarehouseStockItemLnk_Quantity").Value + ")"; modRecordSet.cnnDB.Execute(strIn); } rj.moveNext(); } report_WHTransfer(ref "Handheld777_0"); modRecordSet.cnnDB.Execute("DELETE * FROM Handheld777_0;"); modRecordSet.cnnDB.Execute("DROP TABLE Handheld777_0;"); return; diff_Error: Interaction.MsgBox(Err().Number + " " + Err().Description); } private void cmdsearch_Click(System.Object eventSender, System.EventArgs eventArgs) { string eroor = null; // ERROR: Not supported in C#: OnErrorStatement //openConnection ADODB.Recordset rsP = default(ADODB.Recordset); ADODB.Recordset rsk = default(ADODB.Recordset); ADODB.Recordset rsTest = default(ADODB.Recordset); ADODB.Recordset rsNew = default(ADODB.Recordset); rs = new ADODB.Recordset(); rsP = new ADODB.Recordset(); rsk = new ADODB.Recordset(); rsk = new ADODB.Recordset(); rsTest = new ADODB.Recordset(); rsNew = new ADODB.Recordset(); if (string.IsNullOrEmpty(this.txtcode.Text)) return; //If Me.txtCode.Text <> "" Then //creating table name //Te_Name = "HandHeld" & Trim(Year(Date)) & Trim(Month(Date)) & Trim(Day(Date)) & Trim(Hour(Now)) & Trim(Minute(Now)) & Trim(Second(Now)) & "_" & frmMenu.lblUser.Tag rsTest = modRecordSet.getRS(ref "SELECT Barcodes,Description,Quantity FROM " + Te_Name + ""); //If rsTest.RecordCount And MStockNew = 0 Then rs = modRecordSet.getRS(ref "SELECT * FROM Catalogue WHERE Catalogue_Barcode='" + this.txtcode.Text + "'"); //check if the barcode exists if (rs.RecordCount > 0) { rsP = modRecordSet.getRS(ref "SELECT StockItem_Name FROM StockItem WHERE StockItemID=" + rs.Fields("Catalogue_StockItemID").Value + ""); this.txtdesc.Text = rsP.Fields("StockItem_Name").Value; this.txtqty.Focus(); //show pic if (this.cmdsearch.Text != "&Add") { if (chkPic.CheckState & picBC.Visible == true) { if (fso.FileExists(modRecordSet.serverPath + "\\images\\" + this.txtcode.Text + ".jpg")) { picBC.Image = System.Drawing.Image.FromFile(modRecordSet.serverPath + "\\images\\" + this.txtcode.Text + ".jpg"); imgBC.Image = picBC.Image; } else { Interaction.MsgBox("No picture found for " + this.txtcode.Text); } } } //show pic this.cmdsearch.Text = "&Add"; //if the barcode does not exist display a message } else if (rs.RecordCount < 1) { Interaction.MsgBox("The Item does not exist,Please add it in Stock Create/Edit, New Stock Item", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly, "4POS"); this.txtcode.Text = ""; this.txtcode.Focus(); return; } //Checking if the barcode was found and if the quantity textbox has a value double NewQty = 0; if (this.cmdsearch.Text == "&Add" & !string.IsNullOrEmpty(this.txtqty.Text)) { //creating fields with their data types MyFTypes = "HandHeldID Number,Barcodes Text(50),Description Text(50),Quantity Currency"; rsk = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + ""); //if the table has not been created yet create it switch (eroor) { case // ERROR: Case labels with binary operators are unsupported : LessThan 0: // ERROR: Not supported in C#: ErrorStatement break; case 1: goto erh; break; } erh: modRecordSet.cnnDB.Execute("CREATE TABLE " + Te_Name + " (" + MyFTypes + ")"); //selecting from the new table created rsNew = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + " WHERE Barcodes='" + this.txtcode.Text + "'"); //if the item is already in the newly created table then add the previous quantity to the new one then update it if (rsNew.RecordCount > 0) { NewQty = Convert.ToDouble(this.txtqty.Text); NewQty = NewQty + rsNew.Fields("Quantity").Value; //update the quantity rsk = modRecordSet.getRS(ref "UPDATE " + Te_Name + " SET Quantity=" + NewQty + " WHERE Barcodes='" + this.txtcode.Text + "'"); } else if (rsNew.RecordCount < 1) { //inserting into the newly created table rsk = modRecordSet.getRS(ref "INSERT INTO " + Te_Name + "(HandHeldID,Barcodes,Description,Quantity)VALUES(" + rs.Fields("Catalogue_StockItemID").Value + ",'" + this.txtcode.Text + "','" + this.txtdesc.Text + "'," + this.txtqty.Text + " )"); } //selecting from the newly created table rsk = modRecordSet.getRS(ref "SELECT Barcodes,Description,Quantity FROM " + Te_Name + ""); //filling the datagrid with the record consisting of barcode,description,quantity if the barcode exist this.DataGrid1.DataSource = rsk; this.txtcode.Text = ""; this.txtdesc.Text = ""; this.txtqty.Text = ""; this.cmdsearch.Text = "&Search"; this.txtcode.Focus(); } //ElseIf rsTest.RecordCount > 0 And MStockNew = 2 Then //MsgBox "A Table with the Same Name Already Exist", vbApplicationModal + vbOKOnly, "4POS" //Me.txtCode.Text = "" //Me.cmdClose.SetFocus //End If } private void frmStockTakeCSV_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 13 & this.cmdsearch.Text == "&Search" & !string.IsNullOrEmpty(this.txtcode.Text)) { cmdsearch_Click(cmdsearch, new System.EventArgs()); } else if (KeyAscii == 13 & this.cmdsearch.Text == "&Add" & !string.IsNullOrEmpty(this.txtdesc.Text)) { cmdsearch_Click(cmdsearch, new System.EventArgs()); } else if (KeyAscii == 27) { cmdClose_Click(cmdClose, new System.EventArgs()); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } public void UpdateCatalogID(ref string st_Name) { string strFldName = null; string strIn = null; ADODB.Recordset rj = default(ADODB.Recordset); ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rID = default(ADODB.Recordset); //Set rID = getRS("SELECT * FROM " & st_Name) //Do While rID.EOF = False // If prgUpdate.value = prgUpdate.Max Then // prgUpdate.value = 0 // Else // prgUpdate.value = prgUpdate.value + 1 // End If // 'rID("Handheld_Barcode") = 0 // rID("HandHeldID") = 0 // rID.update '"HandHeldID", 0 // rID.moveNext //Loop strIn = "UPDATE " + st_Name + " SET HandHeldID = 0 WHERE Quantity > 0;"; modRecordSet.cnnDB.Execute(strIn); rj = modRecordSet.getRS(ref "SELECT * FROM " + st_Name); while (rj.EOF == false) { //If prgUpdate.value = prgUpdate.Max Then // prgUpdate.value = 0 //Else // prgUpdate.value = prgUpdate.value + 1 //End If //Set rs = getRS("SELECT * FROM Catalogue WHERE Catalogue_Barcode = '" & rj("Handheld_Barcode") & "'") rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Disabled, StockItem.StockItem_Discontinued, * FROM Catalogue INNER JOIN StockItem ON Catalogue.Catalogue_StockItemID = StockItem.StockItemID WHERE (((Catalogue.Catalogue_Barcode)='" + rj.Fields("Barcodes").Value + "') AND ((StockItem.StockItem_Disabled)=False) AND ((StockItem.StockItem_Discontinued)=False));"); if (rs.RecordCount > 0) modRecordSet.cnnDB.Execute("UPDATE " + st_Name + " SET HandHeldID = " + rs.Fields("Catalogue_StockItemID").Value + ", Quantity = " + (rj.Fields("Quantity").Value * rs.Fields("Catalogue_Quantity").Value) + " WHERE Barcodes = '" + rj.Fields("Barcodes").Value + "'"); rj.moveNext(); } //chkDuplicate: strFldName = "HandHeldID Number,Barcodes Text(50),Description Text(50),Quantity Currency"; modRecordSet.cnnDB.Execute("CREATE TABLE " + "Handheld777" + " (" + strFldName + ")"); System.Windows.Forms.Application.DoEvents(); rj = modRecordSet.getRS(ref "SELECT * FROM " + st_Name); while (rj.EOF == false) { rs = modRecordSet.getRS(ref "SELECT * FROM Handheld777 WHERE HandHeldID=" + rj.Fields("HandHeldID").Value + ";"); if (rs.RecordCount > 0) { strIn = "UPDATE Handheld777 SET Quantity = " + (rs.Fields("Quantity").Value + rj.Fields("Quantity").Value) + " WHERE HandHeldID=" + rj.Fields("HandHeldID").Value + ";"; } else { strIn = "INSERT INTO Handheld777 (HandHeldID,Barcodes,Quantity) VALUES (" + rj.Fields("HandHeldID").Value + ", '" + rj.Fields("Barcodes").Value + "', " + rj.Fields("Quantity").Value + ")"; } modRecordSet.cnnDB.Execute(strIn); rj.moveNext(); } modRecordSet.cnnDB.Execute("DELETE * FROM " + st_Name + ";"); //strIn = "SELECT Handheld777.* INTO " & st_Name & " FROM Handheld777" '& ResolveTable(cmbTables.Text) modRecordSet.cnnDB.Execute("INSERT INTO " + st_Name + " SELECT * FROM Handheld777;"); modRecordSet.cnnDB.Execute("DROP TABLE Handheld777;"); //chkDuplicate: //DeleteBlankID //MsgBox "File was extracted and exported succesfully", vbApplicationModal + vbInformation + vbOKOnly, App.title //prgUpdate.value = 300 } private void frmStockTakeCSV_Load(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement if (modRecordSet.cnnDB == null) { if (openConnection() == true) { } } //creating table name Te_Name = "HandHeld" + Strings.Trim(Convert.ToString(DateAndTime.Year(DateAndTime.Today))) + Strings.Trim(Convert.ToString(DateAndTime.Month(DateAndTime.Today))) + Strings.Trim(Convert.ToString(DateAndTime.Day(DateAndTime.Today))) + Strings.Trim(Convert.ToString(DateAndTime.Hour(DateAndTime.Now))) + Strings.Trim(Convert.ToString(DateAndTime.Minute(DateAndTime.Now))) + Strings.Trim(Convert.ToString(DateAndTime.Second(DateAndTime.Now))) + "_" + My.MyProject.Forms.frmMenu.lblUser.Tag; loadLanguage(); lMWNo = My.MyProject.Forms.frmMWSelect.getMWNo(); if (lMWNo > 1) { //Set rsWH = getRS("SELECT * FROM Warehouse WHERE WarehouseID=" & lMWNo & ";") //Report.txtWH.SetText rsWH("Warehouse_Name") } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C11_City_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="C11_City_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C10_City"/> collection. /// </remarks> [Serializable] public partial class C11_City_ReChild : BusinessBase<C11_City_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name"); /// <summary> /// Gets or sets the CityRoads Child Name. /// </summary> /// <value>The CityRoads Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C11_City_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="C11_City_ReChild"/> object.</returns> internal static C11_City_ReChild NewC11_City_ReChild() { return DataPortal.CreateChild<C11_City_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="C11_City_ReChild"/> object, based on given parameters. /// </summary> /// <param name="city_ID2">The City_ID2 parameter of the C11_City_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="C11_City_ReChild"/> object.</returns> internal static C11_City_ReChild GetC11_City_ReChild(int city_ID2) { return DataPortal.FetchChild<C11_City_ReChild>(city_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C11_City_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C11_City_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C11_City_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C11_City_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="city_ID2">The City ID2.</param> protected void Child_Fetch(int city_ID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetC11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", city_ID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, city_ID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C11_City_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C11_City_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddC11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="C11_City_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C10_City parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateC11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="C11_City_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteC11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using UnityEngine; using System; using System.Collections.Generic; using System.Linq; using NLog; /** * Central manager of all input in a scene. * Sends input messages to all recievers, allows ordering and swallowing of messages. * Raycasts to provide hit info. * Uses both touch and mouse input. */ public class InputManager : MonoBehaviour { public float doubleTapTimeDelta = 0.2f; public float deadZone = 0.01f; private List<InputReceiver> inputReceivers = new List<InputReceiver>(); private enum TouchState { TapUp, Dragging, Pinching, TapDown }; private InputInfo currTouch = new InputInfo(); private InputInfo lastTouch = new InputInfo(); private TouchState touchState = TouchState.TapUp; private Logger log; public void AddInputReceiver( InputReceiver inputReceiver ) { log.Trace( "Adding input receiver: " + inputReceiver.name + " with cam " + inputReceiver.inputCamera ); inputReceivers.Add( inputReceiver ); inputReceivers.Sort( CompareInputReceivers ); } public void RemoveInputReceiver( InputReceiver inputReceiver ) { inputReceivers.Remove( inputReceiver ); } #region Unity events void Awake() { log = LogManager.GetLogger( "Input" ); Check.Equal( 1, Find.SceneObjects<InputManager>().Length );//, "There should only be one InputManager per scene" ); //inputReceivers.AddRange( Find.SceneObjects<InputReceiver>() ); } void Start() { // Camera may be assigned during Awake. inputReceivers.Sort( CompareInputReceivers ); } void Update() { if( touchState == TouchState.TapUp ) { UpdateUpState(); } else if( touchState == TouchState.TapDown ) { UpdateDownState(); } else if( touchState == TouchState.Dragging ) { UpdateDragState(); } else if( touchState == TouchState.Pinching ) { UpdatePinchState(); } } private void UpdateUpState() { // Clear touch of tap is up for too long if( currTouch.time != 0 && currTouch.time - lastTouch.time < doubleTapTimeDelta ) { EndTouchInput(); } Vector2 tapStart; if( TapStart( out tapStart ) ) { touchState = TouchState.TapDown; currTouch.pos = tapStart; currTouch.time = Time.time; StartTouchInput( tapStart ); SendTapDownMessage( MakeHitInputEvent() ); } } private void UpdateDownState() { Vector2 tapDown; bool isDown = TapDown( out tapDown ); currTouch.time = Time.time; if( isDown ) { if ( ( tapDown - currTouch.pos ).magnitude > deadZone ) { touchState = TouchState.Dragging; lastTouch = currTouch; } } else { // tap up if( lastTouch.time != 0 && currTouch.time - lastTouch.time < doubleTapTimeDelta ) { SendDoubleTapMessage( MakeHitInputEvent() ); } else { SendSingleTapMessage( MakeHitInputEvent() ); } SendTapUpMessage( MakeHitInputEvent() ); lastTouch = currTouch; touchState = TouchState.TapUp; currTouch.pos = Vector3.zero; SendTapMessage( MakeInputEvent() ); } } private void UpdateDragState() { Vector2 tapDown; if( TapDown( out tapDown ) == false ) { touchState = TouchState.TapUp; SendTapUpMessage( MakeHitInputEvent() ); lastTouch = currTouch; } else if( (tapDown - currTouch.pos).magnitude > deadZone ) { currTouch.pos = tapDown; SendDragMessage( MakeInputEvent() ); // No raycast for drag lastTouch = currTouch; } } private void UpdatePinchState() { } #endregion #region Public static helpers #endregion #region Input helpers private bool TapStart( out Vector2 position ) { if( Input.GetMouseButtonDown( 0 ) ) { position = Input.mousePosition; return true; } if( Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began ) { position = Input.touches[0].position; return true; } position = Vector2.zero; return false; } private bool TapDown( out Vector2 position ) { if( Input.GetMouseButton( 0 ) ) { position = Input.mousePosition; return true; } if( Input.touchCount > 0 && ( Input.touches[0].phase == TouchPhase.Moved || Input.touches[0].phase == TouchPhase.Stationary ) ) { position = Input.touches[0].position; return true; } position = Vector2.zero; return false; } #endregion #region Private helpers private void SendSingleTapMessage( InputEvent inputEvent ) { DoSendMessage( "OnSingleTap", inputEvent ); } private void SendDoubleTapMessage( InputEvent inputEvent ) { DoSendMessage( "OnDoubleTap", inputEvent ); } private void SendTapDownMessage( InputEvent inputEvent ) { DoSendMessage( "OnTapDown", inputEvent ); } private void SendTapUpMessage( InputEvent inputEvent ) { DoSendMessage( "OnTapUp", inputEvent ); } private void SendTapMessage( InputEvent inputEvent ) { DoSendMessage( "OnTap", inputEvent ); } private void SendDragMessage( InputEvent inputEvent ) { DoSendMessage( "OnDrag", inputEvent ); } private void DoSendMessage( string msgName, InputEvent inputEvent ) { log.Trace( "Attempting to send message: " + msgName + " cam: " + currTouch.cam ); inputEvent.hit = currTouch.hit; if( currTouch.receiver != null ) { log.Trace( "Sending message " + msgName + " to " + currTouch.receiver.name ); currTouch.receiver.SendMessage( msgName, inputEvent, SendMessageOptions.DontRequireReceiver ); } IEnumerable<InputReceiver> globalReceivers = inputReceivers.FindAll( ir => ir != null && ir.receiveAllInput == true ); globalReceivers.ForEach( ir => { log.Trace( "Sending message " + msgName + " to " + ir.name ); ir.SendMessage( msgName, inputEvent, SendMessageOptions.DontRequireReceiver ); } ); } private bool ScreenPointInRects( Vector3 point3, Rect[] rects ) { Vector2 point2 = point3.xy(); point2.y = Screen.height - point2.y; // Screen pos start start lower left. foreach( Rect r in rects ) { if( r.Contains( point2 ) ) return true; } return false; } private InputEvent MakeInputEvent() { return new InputEvent() { lastPos = lastTouch.pos, pos = currTouch.pos, time = currTouch.time, }; } private InputEvent MakeHitInputEvent() { return new InputEvent() { lastPos = lastTouch.pos, pos = currTouch.pos, time = currTouch.time, }; } private void StartTouchInput( Vector3 pos ) { IEnumerable<InputReceiver> validInputReceviers = inputReceivers.FindAll( ir => !ScreenPointInRects( pos, ir.ignoreAreas ) ); log.Trace( "Hit test start touch against " + validInputReceviers.Count().ToString() + " receivers." ); foreach( InputReceiver inputReceiver in validInputReceviers ) { RaycastHit hit = Picker.Pick( inputReceiver.inputCamera, pos ); currTouch.hit = hit.transform; if( hit.transform != null && FindChild( inputReceiver.transform, hit.transform ) ) { currTouch.cam = inputReceiver.inputCamera; currTouch.receiver = inputReceiver.transform; log.Trace( "Start input chain. Pos: " + pos + " Hit: " + currTouch.hit + " receiver: " + currTouch.receiver ); return; } } log.Trace( "Didn't find any hit targets." ); } private void EndTouchInput() { log.Trace( "End input chain" ); currTouch.Reset(); } private bool FindChild( Transform parentTransform, Transform targetTransform ) { if( parentTransform == targetTransform ) { return true; } foreach( Transform childTransform in parentTransform ) { if( childTransform == targetTransform ) return true; if( FindChild( childTransform, targetTransform ) ) { return true; } } return false; } private static int CompareInputReceivers( InputReceiver recv1, InputReceiver recv2 ) { return (int)(recv2.inputCamera.depth - recv1.inputCamera.depth); // highest goes first } #endregion private struct InputInfo { public Vector2 pos; public float time; public Transform hit; public Transform receiver; public Camera cam; public void Reset() { pos = Vector2.zero; time = 0; hit = null; receiver = null; cam = null; } public override string ToString() { return string.Format( "Pos:{0} Time:{1}", pos, time ); } } }
using System; using System.IO; using System.Runtime.CompilerServices; using System.Text; namespace Zipkin.Codecs.Json { // // See: https://github.com/openzipkin/zipkin/blob/master/zipkin/src/main/java/zipkin/internal/Buffer.java // public static class StreamWriterExtensions { private static readonly string[] ReplacementChars; private const string U2028 = "\\u2028"; private const string U2029 = "\\u2029"; static StreamWriterExtensions() { ReplacementChars = new string[128]; for (int i = 0; i <= 0x1f; i++) { ReplacementChars[i] = string.Format("\\u%04x", (int)i); } ReplacementChars['"'] = "\\\""; ReplacementChars['\\'] = "\\\\"; ReplacementChars['\t'] = "\\t"; ReplacementChars['\b'] = "\\b"; ReplacementChars['\n'] = "\\n"; ReplacementChars['\r'] = "\\r"; ReplacementChars['\f'] = "\\f"; } private static readonly char[] HexDigits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static bool NeedsJsonEscaping(byte[] v) { for (int i = 0; i < v.Length; i++) { int current = v[i] & 0xFF; if (i >= 2 && // Is this the end of a u2028 or u2028 UTF-8 codepoint? // 0xE2 0x80 0xA8 == u2028; 0xE2 0x80 0xA9 == u2028 (current == 0xA8 || current == 0xA9) && (v[i - 1] & 0xFF) == 0x80 && (v[i - 2] & 0xFF) == 0xE2) { return true; } else if (current < 0x80 && ReplacementChars[current] != null) { return true; } } return false; // must be a string we don't need to escape. } public static void WriteLowerHex(this TextWriter source, long val) { WriteHexByte((byte)((val >> 56) & 0xff), source); WriteHexByte((byte)((val >> 48) & 0xff), source); WriteHexByte((byte)((val >> 40) & 0xff), source); WriteHexByte((byte)((val >> 32) & 0xff), source); WriteHexByte((byte)((val >> 24) & 0xff), source); WriteHexByte((byte)((val >> 16) & 0xff), source); WriteHexByte((byte)((val >> 8) & 0xff), source); WriteHexByte((byte)(val & 0xff), source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteHexByte(byte v, TextWriter writer) { writer.Write(HexDigits[(v >> 4) & 0xf]); writer.Write(HexDigits[v & 0xf]); } public static void WriteJsonEscaped(this StreamWriter source, byte[] val) { if (NeedsJsonEscaping(val)) { WriteJsonEscaped(source, Encoding.UTF8.GetString(val)); } else { // source.Write(val, 0, val.Length); WriteAsciiOrUtf8(source, Encoding.UTF8.GetString(val)); } } public static void WriteJsonEscaped(this StreamWriter source, string val) { var afterReplacement = 0; var length = val.Length; StringBuilder builder = null; for (var i = 0; i < length; i++) { var c = val[i]; string replacement; if (c < 0x80) { replacement = ReplacementChars[c]; if (replacement == null) { continue; } } else switch (c) { case '\u2028': replacement = U2028; break; case '\u2029': replacement = U2029; break; default: continue; } if (afterReplacement < i) { // write characters between the last replacement and now if (builder == null) { builder = new StringBuilder(); } builder.Append(val, afterReplacement, i); } if (builder == null) { builder = new StringBuilder(); } builder.Append(replacement); afterReplacement = i + 1; } if (builder == null) { // then we didn't escape anything WriteAsciiOrUtf8(source, val); return; } if (afterReplacement < length) { builder.Append(val, afterReplacement, length); } WriteAsciiOrUtf8(source, builder.ToString()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteAsciiOrUtf8(this StreamWriter source, string val) { if (IsAscii(val)) { InternalWriteAscii(source, val); } else { InternalWriteUtf8(source, val); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InternalWriteAscii(StreamWriter source, string s) { source.Write(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InternalWriteUtf8(StreamWriter source, string s) { var temp = Encoding.UTF8.GetBytes(s); source.Write(temp); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteBase64Url(this StreamWriter source, byte[] val) { source.Write( Convert.ToBase64String(val) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsAscii(string val) { foreach (var c in val) { if (c >= 0x80) { return false; } } return true; } } }
namespace Epi.Windows.Analysis.Dialogs { partial class MergeDialog { /// <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 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(MergeDialog)); this.btnBuildKey = new System.Windows.Forms.Button(); this.txtKey = new System.Windows.Forms.TextBox(); this.cbxUpdate = new System.Windows.Forms.CheckBox(); this.lblKey = new System.Windows.Forms.Label(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnEllipse = new System.Windows.Forms.Button(); this.tabctrlShow = new System.Windows.Forms.TabControl(); this.tabPageViews = new System.Windows.Forms.TabPage(); this.lbxShowViews = new System.Windows.Forms.ListBox(); this.tabPageAll = new System.Windows.Forms.TabPage(); this.lbxShowAll = new System.Windows.Forms.ListBox(); this.btnClear = new System.Windows.Forms.Button(); this.cmbDataFormats = new System.Windows.Forms.ComboBox(); this.txtDataSource = new System.Windows.Forms.TextBox(); this.lblDataSource = new System.Windows.Forms.Label(); this.lblDataFormats = new System.Windows.Forms.Label(); this.cbxAppend = new System.Windows.Forms.CheckBox(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.tabctrlShow.SuspendLayout(); this.tabPageViews.SuspendLayout(); this.tabPageAll.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); // // btnBuildKey // resources.ApplyResources(this.btnBuildKey, "btnBuildKey"); this.btnBuildKey.Name = "btnBuildKey"; this.btnBuildKey.Click += new System.EventHandler(this.btnBuildKey_Click); // // txtKey // resources.ApplyResources(this.txtKey, "txtKey"); this.txtKey.Name = "txtKey"; // // cbxUpdate // this.cbxUpdate.Checked = true; this.cbxUpdate.CheckState = System.Windows.Forms.CheckState.Checked; resources.ApplyResources(this.cbxUpdate, "cbxUpdate"); this.cbxUpdate.Name = "cbxUpdate"; // // lblKey // this.lblKey.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblKey, "lblKey"); this.lblKey.Name = "lblKey"; // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click_1); // // btnEllipse // resources.ApplyResources(this.btnEllipse, "btnEllipse"); this.btnEllipse.Name = "btnEllipse"; this.btnEllipse.Click += new System.EventHandler(this.btnEllipse_Click); // // tabctrlShow // this.tabctrlShow.Controls.Add(this.tabPageViews); this.tabctrlShow.Controls.Add(this.tabPageAll); resources.ApplyResources(this.tabctrlShow, "tabctrlShow"); this.tabctrlShow.Name = "tabctrlShow"; this.tabctrlShow.SelectedIndex = 0; // // tabPageViews // this.tabPageViews.Controls.Add(this.lbxShowViews); resources.ApplyResources(this.tabPageViews, "tabPageViews"); this.tabPageViews.Name = "tabPageViews"; this.tabPageViews.UseVisualStyleBackColor = true; // // lbxShowViews // resources.ApplyResources(this.lbxShowViews, "lbxShowViews"); this.lbxShowViews.Name = "lbxShowViews"; // // tabPageAll // this.tabPageAll.Controls.Add(this.lbxShowAll); resources.ApplyResources(this.tabPageAll, "tabPageAll"); this.tabPageAll.Name = "tabPageAll"; this.tabPageAll.UseVisualStyleBackColor = true; // // lbxShowAll // resources.ApplyResources(this.lbxShowAll, "lbxShowAll"); this.lbxShowAll.Name = "lbxShowAll"; // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // cmbDataFormats // resources.ApplyResources(this.cmbDataFormats, "cmbDataFormats"); this.cmbDataFormats.Name = "cmbDataFormats"; this.cmbDataFormats.SelectedValueChanged += new System.EventHandler(this.cmbDataFormats_SelectedValueChanged); // // txtDataSource // resources.ApplyResources(this.txtDataSource, "txtDataSource"); this.txtDataSource.Name = "txtDataSource"; // // lblDataSource // this.lblDataSource.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblDataSource, "lblDataSource"); this.lblDataSource.Name = "lblDataSource"; // // lblDataFormats // this.lblDataFormats.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblDataFormats, "lblDataFormats"); this.lblDataFormats.Name = "lblDataFormats"; // // cbxAppend // this.cbxAppend.Checked = true; this.cbxAppend.CheckState = System.Windows.Forms.CheckState.Checked; resources.ApplyResources(this.cbxAppend, "cbxAppend"); this.cbxAppend.Name = "cbxAppend"; // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click_1); // // MergeDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.cbxAppend); this.Controls.Add(this.txtKey); this.Controls.Add(this.txtDataSource); this.Controls.Add(this.cbxUpdate); this.Controls.Add(this.btnBuildKey); this.Controls.Add(this.lblKey); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnEllipse); this.Controls.Add(this.tabctrlShow); this.Controls.Add(this.btnClear); this.Controls.Add(this.cmbDataFormats); this.Controls.Add(this.lblDataSource); this.Controls.Add(this.lblDataFormats); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MergeDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.Merge_Load); this.tabctrlShow.ResumeLayout(false); this.tabPageViews.ResumeLayout(false); this.tabPageAll.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnEllipse; private System.Windows.Forms.TabControl tabctrlShow; private System.Windows.Forms.TabPage tabPageViews; private System.Windows.Forms.ListBox lbxShowViews; private System.Windows.Forms.TabPage tabPageAll; private System.Windows.Forms.ListBox lbxShowAll; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.ComboBox cmbDataFormats; private System.Windows.Forms.TextBox txtDataSource; private System.Windows.Forms.Label lblDataSource; private System.Windows.Forms.Button btnBuildKey; private System.Windows.Forms.TextBox txtKey; private System.Windows.Forms.CheckBox cbxUpdate; private System.Windows.Forms.Label lblKey; private System.Windows.Forms.Label lblDataFormats; private System.Windows.Forms.CheckBox cbxAppend; private System.Windows.Forms.Button btnSaveOnly; } }
// 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 Microsoft.CodeAnalysis.DocumentationComments; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions2 { public static Glyph GetGlyph(this ISymbol symbol) { Glyph publicIcon; switch (symbol.Kind) { case SymbolKind.Alias: return ((IAliasSymbol)symbol).Target.GetGlyph(); case SymbolKind.Assembly: return Glyph.Assembly; case SymbolKind.ArrayType: return ((IArrayTypeSymbol)symbol).ElementType.GetGlyph(); case SymbolKind.DynamicType: return Glyph.ClassPublic; case SymbolKind.Event: publicIcon = Glyph.EventPublic; break; case SymbolKind.Field: var containingType = symbol.ContainingType; if (containingType != null && containingType.TypeKind == TypeKind.Enum) { return Glyph.EnumMember; } publicIcon = ((IFieldSymbol)symbol).IsConst ? Glyph.ConstantPublic : Glyph.FieldPublic; break; case SymbolKind.Label: return Glyph.Label; case SymbolKind.Local: return Glyph.Local; case SymbolKind.NamedType: case SymbolKind.ErrorType: { switch (((INamedTypeSymbol)symbol).TypeKind) { case TypeKind.Class: publicIcon = Glyph.ClassPublic; break; case TypeKind.Delegate: publicIcon = Glyph.DelegatePublic; break; case TypeKind.Enum: publicIcon = Glyph.EnumPublic; break; case TypeKind.Interface: publicIcon = Glyph.InterfacePublic; break; case TypeKind.Module: publicIcon = Glyph.ModulePublic; break; case TypeKind.Struct: publicIcon = Glyph.StructurePublic; break; case TypeKind.Error: return Glyph.Error; default: throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol)); } break; } case SymbolKind.Method: { var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion) { return Glyph.Operator; } else if (methodSymbol.IsExtensionMethod || methodSymbol.MethodKind == MethodKind.ReducedExtension) { publicIcon = Glyph.ExtensionMethodPublic; } else { publicIcon = Glyph.MethodPublic; } } break; case SymbolKind.Namespace: return Glyph.Namespace; case SymbolKind.NetModule: return Glyph.Assembly; case SymbolKind.Parameter: return symbol.IsImplicitValueParameter() ? Glyph.Keyword : Glyph.Parameter; case SymbolKind.PointerType: return ((IPointerTypeSymbol)symbol).PointedAtType.GetGlyph(); case SymbolKind.Property: { var propertySymbol = (IPropertySymbol)symbol; if (propertySymbol.IsWithEvents) { publicIcon = Glyph.FieldPublic; } else { publicIcon = Glyph.PropertyPublic; } } break; case SymbolKind.RangeVariable: return Glyph.RangeVariable; case SymbolKind.TypeParameter: return Glyph.TypeParameter; default: throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol)); } switch (symbol.DeclaredAccessibility) { case Accessibility.Private: publicIcon += Glyph.ClassPrivate - Glyph.ClassPublic; break; case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: publicIcon += Glyph.ClassProtected - Glyph.ClassPublic; break; case Accessibility.Internal: publicIcon += Glyph.ClassInternal - Glyph.ClassPublic; break; } return publicIcon; } public static IEnumerable<TaggedText> GetDocumentationParts(this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { string documentation = GetDocumentation(symbol, cancellationToken); return documentation != null ? formatter.Format(documentation, semanticModel, position, CrefFormat) : SpecializedCollections.EmptyEnumerable<TaggedText>(); } private static string GetDocumentation(ISymbol symbol, CancellationToken cancellationToken) { switch (symbol) { case IParameterSymbol parameter: return parameter.ContainingSymbol.OriginalDefinition.GetDocumentationComment(cancellationToken: cancellationToken).GetParameterText(symbol.Name); case ITypeParameterSymbol typeParam: return typeParam.ContainingSymbol.GetDocumentationComment(cancellationToken: cancellationToken).GetTypeParameterText(symbol.Name); case IMethodSymbol method: return GetMethodDocumentation(method); case IAliasSymbol alias: return alias.Target.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText; default: return symbol.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText; } } public static Func<CancellationToken, IEnumerable<TaggedText>> GetDocumentationPartsFactory( this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter) { return c => symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken: c); } public static readonly SymbolDisplayFormat CrefFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static string GetMethodDocumentation(IMethodSymbol method) { switch (method.MethodKind) { case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: case MethodKind.PropertyGet: case MethodKind.PropertySet: return method.ContainingSymbol.GetDocumentationComment().SummaryText; default: return method.GetDocumentationComment().SummaryText; } } public static IList<SymbolDisplayPart> ToAwaitableParts(this ISymbol symbol, string awaitKeyword, string initializedVariableName, SemanticModel semanticModel, int position) { var spacePart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " "); var parts = new List<SymbolDisplayPart>(); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, $"\r\n{WorkspacesResources.Usage_colon}\r\n ")); var returnType = symbol.InferAwaitableReturnType(semanticModel, position); returnType = returnType != null && returnType.SpecialType != SpecialType.System_Void ? returnType : null; if (returnType != null) { if (semanticModel.Language == "C#") { parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName)); } else { parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "Dim")); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "as")); parts.Add(spacePart); parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position)); } parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "=")); parts.Add(spacePart); } parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, awaitKeyword)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name)); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "(")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, symbol.GetParameters().Any() ? "..." : "")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, semanticModel.Language == "C#" ? ";" : "")); return parts; } public static ITypeSymbol InferAwaitableReturnType(this ISymbol symbol, SemanticModel semanticModel, int position) { var methodSymbol = symbol as IMethodSymbol; if (methodSymbol == null) { return null; } var returnType = methodSymbol.ReturnType; if (returnType == null) { return null; } var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: returnType, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true); var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any()); if (!getAwaiters.Any()) { return null; } var getResults = getAwaiters.SelectMany(g => semanticModel.LookupSymbols(position, container: g.ReturnType, name: WellKnownMemberNames.GetResult)); var getResult = getResults.OfType<IMethodSymbol>().FirstOrDefault(g => !g.IsStatic); if (getResult == null) { return null; } return getResult.ReturnType; } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class NewArrayListTests { #region Tests [Fact] public static void CheckBoolArrayListTest() { bool[][] array = new bool[][] { new bool[] { }, new bool[] { true }, new bool[] { true, false } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { bool val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(bool)); } } for (int i = 0; i < array.Length; i++) { VerifyBoolArrayList(array[i], exprs[i]); } } [Fact] public static void CheckByteArrayListTest() { byte[][] array = new byte[][] { new byte[] { }, new byte[] { 0 }, new byte[] { 0, 1, byte.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { byte val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(byte)); } } for (int i = 0; i < array.Length; i++) { VerifyByteArrayList(array[i], exprs[i]); } } [Fact] public static void CheckCustomArrayListTest() { C[][] array = new C[][] { new C[] { }, new C[] { null }, new C[] { new C(), new D(), new D(0), new D(5) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { C val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(C)); } } for (int i = 0; i < array.Length; i++) { VerifyCustomArrayList(array[i], exprs[i]); } } [Fact] public static void CheckCharArrayListTest() { char[][] array = new char[][] { new char[] { }, new char[] { '\0' }, new char[] { '\0', '\b', 'A', '\uffff' } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { char val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(char)); } } for (int i = 0; i < array.Length; i++) { VerifyCharArrayList(array[i], exprs[i]); } } [Fact] public static void CheckCustom2ArrayListTest() { D[][] array = new D[][] { new D[] { }, new D[] { null }, new D[] { null, new D(), new D(0), new D(5) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { D val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(D)); } } for (int i = 0; i < array.Length; i++) { VerifyCustom2ArrayList(array[i], exprs[i]); } } [Fact] public static void CheckDecimalArrayListTest() { decimal[][] array = new decimal[][] { new decimal[] { }, new decimal[] { decimal.Zero }, new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { decimal val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(decimal)); } } for (int i = 0; i < array.Length; i++) { VerifyDecimalArrayList(array[i], exprs[i]); } } [Fact] public static void CheckDelegateArrayListTest() { Delegate[][] array = new Delegate[][] { new Delegate[] { }, new Delegate[] { null }, new Delegate[] { null, (Func<object>) delegate() { return null; }, (Func<int, int>) delegate(int i) { return i+1; }, (Action<object>) delegate { } } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Delegate val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Delegate)); } } for (int i = 0; i < array.Length; i++) { VerifyDelegateArrayList(array[i], exprs[i]); } } [Fact] public static void CheckDoubleArrayListTest() { double[][] array = new double[][] { new double[] { }, new double[] { 0 }, new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { double val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(double)); } } for (int i = 0; i < array.Length; i++) { VerifyDoubleArrayList(array[i], exprs[i]); } } [Fact] public static void CheckEnumArrayListTest() { E[][] array = new E[][] { new E[] { }, new E[] { (E) 0 }, new E[] { (E) 0, E.A, E.B, (E) int.MaxValue, (E) int.MinValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { E val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(E)); } } for (int i = 0; i < array.Length; i++) { VerifyEnumArrayList(array[i], exprs[i]); } } [Fact] public static void CheckEnumLongArrayListTest() { El[][] array = new El[][] { new El[] { }, new El[] { (El) 0 }, new El[] { (El) 0, El.A, El.B, (El) long.MaxValue, (El) long.MinValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { El val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(El)); } } for (int i = 0; i < array.Length; i++) { VerifyEnumLongArrayList(array[i], exprs[i]); } } [Fact] public static void CheckFloatArrayListTest() { float[][] array = new float[][] { new float[] { }, new float[] { 0 }, new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { float val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(float)); } } for (int i = 0; i < array.Length; i++) { VerifyFloatArrayList(array[i], exprs[i]); } } [Fact] public static void CheckFuncArrayListTest() { Func<object>[][] array = new Func<object>[][] { new Func<object>[] { }, new Func<object>[] { null }, new Func<object>[] { null, (Func<object>) delegate() { return null; } } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Func<object> val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Func<object>)); } } for (int i = 0; i < array.Length; i++) { VerifyFuncArrayList(array[i], exprs[i]); } } [Fact] public static void CheckInterfaceArrayListTest() { I[][] array = new I[][] { new I[] { }, new I[] { null }, new I[] { null, new C(), new D(), new D(0), new D(5) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { I val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(I)); } } for (int i = 0; i < array.Length; i++) { VerifyInterfaceArrayList(array[i], exprs[i]); } } [Fact] public static void CheckIEquatableCustomArrayListTest() { IEquatable<C>[][] array = new IEquatable<C>[][] { new IEquatable<C>[] { }, new IEquatable<C>[] { null }, new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { IEquatable<C> val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(IEquatable<C>)); } } for (int i = 0; i < array.Length; i++) { VerifyIEquatableCustomArrayList(array[i], exprs[i]); } } [Fact] public static void CheckIEquatableCustom2ArrayListTest() { IEquatable<D>[][] array = new IEquatable<D>[][] { new IEquatable<D>[] { }, new IEquatable<D>[] { null }, new IEquatable<D>[] { null, new D(), new D(0), new D(5) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { IEquatable<D> val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(IEquatable<D>)); } } for (int i = 0; i < array.Length; i++) { VerifyIEquatableCustom2ArrayList(array[i], exprs[i]); } } [Fact] public static void CheckIntArrayListTest() { int[][] array = new int[][] { new int[] { }, new int[] { 0 }, new int[] { 0, 1, -1, int.MinValue, int.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { int val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(int)); } } for (int i = 0; i < array.Length; i++) { VerifyIntArrayList(array[i], exprs[i]); } } [Fact] public static void CheckLongArrayListTest() { long[][] array = new long[][] { new long[] { }, new long[] { 0 }, new long[] { 0, 1, -1, long.MinValue, long.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { long val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(long)); } } for (int i = 0; i < array.Length; i++) { VerifyLongArrayList(array[i], exprs[i]); } } [Fact] public static void CheckObjectArrayListTest() { object[][] array = new object[][] { new object[] { }, new object[] { null }, new object[] { null, new object(), new C(), new D(3) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { object val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(object)); } } for (int i = 0; i < array.Length; i++) { VerifyObjectArrayList(array[i], exprs[i]); } } [Fact] public static void CheckStructArrayListTest() { S[][] array = new S[][] { new S[] { }, new S[] { default(S) }, new S[] { default(S), new S() } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { S val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(S)); } } for (int i = 0; i < array.Length; i++) { VerifyStructArrayList(array[i], exprs[i]); } } [Fact] public static void CheckSByteArrayListTest() { sbyte[][] array = new sbyte[][] { new sbyte[] { }, new sbyte[] { 0 }, new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { sbyte val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(sbyte)); } } for (int i = 0; i < array.Length; i++) { VerifySByteArrayList(array[i], exprs[i]); } } [Fact] public static void CheckStructWithStringArrayListTest() { Sc[][] array = new Sc[][] { new Sc[] { }, new Sc[] { default(Sc) }, new Sc[] { default(Sc), new Sc(), new Sc(null) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Sc val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Sc)); } } for (int i = 0; i < array.Length; i++) { VerifyStructWithStringArrayList(array[i], exprs[i]); } } [Fact] public static void CheckStructWithStringAndFieldArrayListTest() { Scs[][] array = new Scs[][] { new Scs[] { }, new Scs[] { default(Scs) }, new Scs[] { default(Scs), new Scs(), new Scs(null,new S()) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Scs val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Scs)); } } for (int i = 0; i < array.Length; i++) { VerifyStructWithStringAndFieldArrayList(array[i], exprs[i]); } } [Fact] public static void CheckShortArrayListTest() { short[][] array = new short[][] { new short[] { }, new short[] { 0 }, new short[] { 0, 1, -1, short.MinValue, short.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { short val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(short)); } } for (int i = 0; i < array.Length; i++) { VerifyShortArrayList(array[i], exprs[i]); } } [Fact] public static void CheckStructWithTwoValuesArrayListTest() { Sp[][] array = new Sp[][] { new Sp[] { }, new Sp[] { default(Sp) }, new Sp[] { default(Sp), new Sp(), new Sp(5,5.0) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Sp val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Sp)); } } for (int i = 0; i < array.Length; i++) { VerifyStructWithTwoValuesArrayList(array[i], exprs[i]); } } [Fact] public static void CheckStructWithValueArrayListTest() { Ss[][] array = new Ss[][] { new Ss[] { }, new Ss[] { default(Ss) }, new Ss[] { default(Ss), new Ss(), new Ss(new S()) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Ss val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Ss)); } } for (int i = 0; i < array.Length; i++) { VerifyStructWithValueArrayList(array[i], exprs[i]); } } [Fact] public static void CheckStringArrayListTest() { string[][] array = new string[][] { new string[] { }, new string[] { null }, new string[] { null, "", "a", "foo" } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { string val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(string)); } } for (int i = 0; i < array.Length; i++) { VerifyStringArrayList(array[i], exprs[i]); } } [Fact] public static void CheckUIntArrayListTest() { uint[][] array = new uint[][] { new uint[] { }, new uint[] { 0 }, new uint[] { 0, 1, uint.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { uint val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(uint)); } } for (int i = 0; i < array.Length; i++) { VerifyUIntArrayList(array[i], exprs[i]); } } [Fact] public static void CheckULongArrayListTest() { ulong[][] array = new ulong[][] { new ulong[] { }, new ulong[] { 0 }, new ulong[] { 0, 1, ulong.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { ulong val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(ulong)); } } for (int i = 0; i < array.Length; i++) { VerifyULongArrayList(array[i], exprs[i]); } } [Fact] public static void CheckUShortArrayListTest() { ushort[][] array = new ushort[][] { new ushort[] { }, new ushort[] { 0 }, new ushort[] { 0, 1, ushort.MaxValue } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { ushort val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(ushort)); } } for (int i = 0; i < array.Length; i++) { VerifyUShortArrayList(array[i], exprs[i]); } } [Fact] public static void CheckGenericCustomArrayListTest() { CheckGenericArrayListHelper<C>(); } [Fact] public static void CheckGenericEnumArrayListTest() { CheckGenericArrayListHelper<E>(); } [Fact] public static void CheckGenericObjectArrayListTest() { CheckGenericArrayListHelper<object>(); } [Fact] public static void CheckGenericStructArrayListTest() { CheckGenericArrayListHelper<S>(); } [Fact] public static void CheckGenericStructWithStringAndFieldArrayListTest() { CheckGenericArrayListHelper<Scs>(); } [Fact] public static void CheckGenericCustomWithClassRestrictionArrayListTest() { CheckGenericWithClassRestrictionArrayListHelper<C>(); } [Fact] public static void CheckGenericObjectWithClassRestrictionArrayListTest() { CheckGenericWithClassRestrictionArrayListHelper<object>(); } [Fact] public static void CheckGenericCustomWithSubClassRestrictionArrayListTest() { CheckGenericWithSubClassRestrictionArrayListHelper<C>(); } [Fact] public static void CheckGenericCustomWithClassAndNewRestrictionArrayListTest() { CheckGenericWithClassAndNewRestrictionArrayListHelper<C>(); } [Fact] public static void CheckGenericObjectWithClassAndNewRestrictionArrayListTest() { CheckGenericWithClassAndNewRestrictionArrayListHelper<object>(); } [Fact] public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayListTest() { CheckGenericWithSubClassAndNewRestrictionArrayListHelper<C>(); } [Fact] public static void CheckGenericEnumWithStructRestrictionArrayListTest() { CheckGenericWithStructRestrictionArrayListHelper<E>(); } [Fact] public static void CheckGenericStructWithStructRestrictionArrayListTest() { CheckGenericWithStructRestrictionArrayListHelper<S>(); } [Fact] public static void CheckGenericStructWithStringAndFieldWithStructRestrictionArrayListTest() { CheckGenericWithStructRestrictionArrayListHelper<Scs>(); } #endregion #region Helper methods private static void CheckGenericArrayListHelper<T>() { T[][] array = new T[][] { new T[] { }, new T[] { default(T) }, new T[] { default(T) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { T val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(T)); } } for (int i = 0; i < array.Length; i++) { VerifyGenericArrayList<T>(array[i], exprs[i]); } } private static void CheckGenericWithClassRestrictionArrayListHelper<Tc>() where Tc : class { Tc[][] array = new Tc[][] { new Tc[] { }, new Tc[] { default(Tc) }, new Tc[] { default(Tc) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Tc val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Tc)); } } for (int i = 0; i < array.Length; i++) { VerifyGenericWithClassRestrictionArrayList<Tc>(array[i], exprs[i]); } } private static void CheckGenericWithSubClassRestrictionArrayListHelper<TC>() where TC : C { TC[][] array = new TC[][] { new TC[] { }, new TC[] { default(TC) }, new TC[] { default(TC) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { TC val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(TC)); } } for (int i = 0; i < array.Length; i++) { VerifyGenericWithSubClassRestrictionArrayList<TC>(array[i], exprs[i]); } } private static void CheckGenericWithClassAndNewRestrictionArrayListHelper<Tcn>() where Tcn : class, new() { Tcn[][] array = new Tcn[][] { new Tcn[] { }, new Tcn[] { default(Tcn) }, new Tcn[] { default(Tcn) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Tcn val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Tcn)); } } for (int i = 0; i < array.Length; i++) { VerifyGenericWithClassAndNewRestrictionArrayList<Tcn>(array[i], exprs[i]); } } private static void CheckGenericWithSubClassAndNewRestrictionArrayListHelper<TCn>() where TCn : C, new() { TCn[][] array = new TCn[][] { new TCn[] { }, new TCn[] { default(TCn) }, new TCn[] { default(TCn) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { TCn val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(TCn)); } } for (int i = 0; i < array.Length; i++) { VerifyGenericWithSubClassAndNewRestrictionArrayList<TCn>(array[i], exprs[i]); } } private static void CheckGenericWithStructRestrictionArrayListHelper<Ts>() where Ts : struct { Ts[][] array = new Ts[][] { new Ts[] { }, new Ts[] { default(Ts) }, new Ts[] { default(Ts) } }; Expression[][] exprs = new Expression[array.Length][]; for (int i = 0; i < array.Length; i++) { exprs[i] = new Expression[array[i].Length]; for (int j = 0; j < array[i].Length; j++) { Ts val = array[i][j]; exprs[i][j] = Expression.Constant(val, typeof(Ts)); } } for (int i = 0; i < array.Length; i++) { VerifyGenericWithStructRestrictionArrayList<Ts>(array[i], exprs[i]); } } #endregion #region verifiers private static void VerifyBoolArrayList(bool[] val, Expression[] exprs) { Expression<Func<bool[]>> e = Expression.Lambda<Func<bool[]>>( Expression.NewArrayInit(typeof(bool), exprs), Enumerable.Empty<ParameterExpression>()); Func<bool[]> f = e.Compile(); bool[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyByteArrayList(byte[] val, Expression[] exprs) { Expression<Func<byte[]>> e = Expression.Lambda<Func<byte[]>>( Expression.NewArrayInit(typeof(byte), exprs), Enumerable.Empty<ParameterExpression>()); Func<byte[]> f = e.Compile(); byte[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyCustomArrayList(C[] val, Expression[] exprs) { Expression<Func<C[]>> e = Expression.Lambda<Func<C[]>>( Expression.NewArrayInit(typeof(C), exprs), Enumerable.Empty<ParameterExpression>()); Func<C[]> f = e.Compile(); C[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyCharArrayList(char[] val, Expression[] exprs) { Expression<Func<char[]>> e = Expression.Lambda<Func<char[]>>( Expression.NewArrayInit(typeof(char), exprs), Enumerable.Empty<ParameterExpression>()); Func<char[]> f = e.Compile(); char[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyCustom2ArrayList(D[] val, Expression[] exprs) { Expression<Func<D[]>> e = Expression.Lambda<Func<D[]>>( Expression.NewArrayInit(typeof(D), exprs), Enumerable.Empty<ParameterExpression>()); Func<D[]> f = e.Compile(); D[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyDecimalArrayList(decimal[] val, Expression[] exprs) { Expression<Func<decimal[]>> e = Expression.Lambda<Func<decimal[]>>( Expression.NewArrayInit(typeof(decimal), exprs), Enumerable.Empty<ParameterExpression>()); Func<decimal[]> f = e.Compile(); decimal[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyDelegateArrayList(Delegate[] val, Expression[] exprs) { Expression<Func<Delegate[]>> e = Expression.Lambda<Func<Delegate[]>>( Expression.NewArrayInit(typeof(Delegate), exprs), Enumerable.Empty<ParameterExpression>()); Func<Delegate[]> f = e.Compile(); Delegate[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyDoubleArrayList(double[] val, Expression[] exprs) { Expression<Func<double[]>> e = Expression.Lambda<Func<double[]>>( Expression.NewArrayInit(typeof(double), exprs), Enumerable.Empty<ParameterExpression>()); Func<double[]> f = e.Compile(); double[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyEnumArrayList(E[] val, Expression[] exprs) { Expression<Func<E[]>> e = Expression.Lambda<Func<E[]>>( Expression.NewArrayInit(typeof(E), exprs), Enumerable.Empty<ParameterExpression>()); Func<E[]> f = e.Compile(); E[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyEnumLongArrayList(El[] val, Expression[] exprs) { Expression<Func<El[]>> e = Expression.Lambda<Func<El[]>>( Expression.NewArrayInit(typeof(El), exprs), Enumerable.Empty<ParameterExpression>()); Func<El[]> f = e.Compile(); El[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyFloatArrayList(float[] val, Expression[] exprs) { Expression<Func<float[]>> e = Expression.Lambda<Func<float[]>>( Expression.NewArrayInit(typeof(float), exprs), Enumerable.Empty<ParameterExpression>()); Func<float[]> f = e.Compile(); float[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyFuncArrayList(Func<object>[] val, Expression[] exprs) { Expression<Func<Func<object>[]>> e = Expression.Lambda<Func<Func<object>[]>>( Expression.NewArrayInit(typeof(Func<object>), exprs), Enumerable.Empty<ParameterExpression>()); Func<Func<object>[]> f = e.Compile(); Func<object>[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyInterfaceArrayList(I[] val, Expression[] exprs) { Expression<Func<I[]>> e = Expression.Lambda<Func<I[]>>( Expression.NewArrayInit(typeof(I), exprs), Enumerable.Empty<ParameterExpression>()); Func<I[]> f = e.Compile(); I[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyIEquatableCustomArrayList(IEquatable<C>[] val, Expression[] exprs) { Expression<Func<IEquatable<C>[]>> e = Expression.Lambda<Func<IEquatable<C>[]>>( Expression.NewArrayInit(typeof(IEquatable<C>), exprs), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<C>[]> f = e.Compile(); IEquatable<C>[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyIEquatableCustom2ArrayList(IEquatable<D>[] val, Expression[] exprs) { Expression<Func<IEquatable<D>[]>> e = Expression.Lambda<Func<IEquatable<D>[]>>( Expression.NewArrayInit(typeof(IEquatable<D>), exprs), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<D>[]> f = e.Compile(); IEquatable<D>[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyIntArrayList(int[] val, Expression[] exprs) { Expression<Func<int[]>> e = Expression.Lambda<Func<int[]>>( Expression.NewArrayInit(typeof(int), exprs), Enumerable.Empty<ParameterExpression>()); Func<int[]> f = e.Compile(); int[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyLongArrayList(long[] val, Expression[] exprs) { Expression<Func<long[]>> e = Expression.Lambda<Func<long[]>>( Expression.NewArrayInit(typeof(long), exprs), Enumerable.Empty<ParameterExpression>()); Func<long[]> f = e.Compile(); long[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyObjectArrayList(object[] val, Expression[] exprs) { Expression<Func<object[]>> e = Expression.Lambda<Func<object[]>>( Expression.NewArrayInit(typeof(object), exprs), Enumerable.Empty<ParameterExpression>()); Func<object[]> f = e.Compile(); object[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyStructArrayList(S[] val, Expression[] exprs) { Expression<Func<S[]>> e = Expression.Lambda<Func<S[]>>( Expression.NewArrayInit(typeof(S), exprs), Enumerable.Empty<ParameterExpression>()); Func<S[]> f = e.Compile(); S[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifySByteArrayList(sbyte[] val, Expression[] exprs) { Expression<Func<sbyte[]>> e = Expression.Lambda<Func<sbyte[]>>( Expression.NewArrayInit(typeof(sbyte), exprs), Enumerable.Empty<ParameterExpression>()); Func<sbyte[]> f = e.Compile(); sbyte[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyStructWithStringArrayList(Sc[] val, Expression[] exprs) { Expression<Func<Sc[]>> e = Expression.Lambda<Func<Sc[]>>( Expression.NewArrayInit(typeof(Sc), exprs), Enumerable.Empty<ParameterExpression>()); Func<Sc[]> f = e.Compile(); Sc[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyStructWithStringAndFieldArrayList(Scs[] val, Expression[] exprs) { Expression<Func<Scs[]>> e = Expression.Lambda<Func<Scs[]>>( Expression.NewArrayInit(typeof(Scs), exprs), Enumerable.Empty<ParameterExpression>()); Func<Scs[]> f = e.Compile(); Scs[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyShortArrayList(short[] val, Expression[] exprs) { Expression<Func<short[]>> e = Expression.Lambda<Func<short[]>>( Expression.NewArrayInit(typeof(short), exprs), Enumerable.Empty<ParameterExpression>()); Func<short[]> f = e.Compile(); short[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyStructWithTwoValuesArrayList(Sp[] val, Expression[] exprs) { Expression<Func<Sp[]>> e = Expression.Lambda<Func<Sp[]>>( Expression.NewArrayInit(typeof(Sp), exprs), Enumerable.Empty<ParameterExpression>()); Func<Sp[]> f = e.Compile(); Sp[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyStructWithValueArrayList(Ss[] val, Expression[] exprs) { Expression<Func<Ss[]>> e = Expression.Lambda<Func<Ss[]>>( Expression.NewArrayInit(typeof(Ss), exprs), Enumerable.Empty<ParameterExpression>()); Func<Ss[]> f = e.Compile(); Ss[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyStringArrayList(string[] val, Expression[] exprs) { Expression<Func<string[]>> e = Expression.Lambda<Func<string[]>>( Expression.NewArrayInit(typeof(string), exprs), Enumerable.Empty<ParameterExpression>()); Func<string[]> f = e.Compile(); string[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyUIntArrayList(uint[] val, Expression[] exprs) { Expression<Func<uint[]>> e = Expression.Lambda<Func<uint[]>>( Expression.NewArrayInit(typeof(uint), exprs), Enumerable.Empty<ParameterExpression>()); Func<uint[]> f = e.Compile(); uint[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyULongArrayList(ulong[] val, Expression[] exprs) { Expression<Func<ulong[]>> e = Expression.Lambda<Func<ulong[]>>( Expression.NewArrayInit(typeof(ulong), exprs), Enumerable.Empty<ParameterExpression>()); Func<ulong[]> f = e.Compile(); ulong[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyUShortArrayList(ushort[] val, Expression[] exprs) { Expression<Func<ushort[]>> e = Expression.Lambda<Func<ushort[]>>( Expression.NewArrayInit(typeof(ushort), exprs), Enumerable.Empty<ParameterExpression>()); Func<ushort[]> f = e.Compile(); ushort[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyGenericArrayList<T>(T[] val, Expression[] exprs) { Expression<Func<T[]>> e = Expression.Lambda<Func<T[]>>( Expression.NewArrayInit(typeof(T), exprs), Enumerable.Empty<ParameterExpression>()); Func<T[]> f = e.Compile(); T[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyGenericWithClassRestrictionArrayList<Tc>(Tc[] val, Expression[] exprs) where Tc : class { Expression<Func<Tc[]>> e = Expression.Lambda<Func<Tc[]>>( Expression.NewArrayInit(typeof(Tc), exprs), Enumerable.Empty<ParameterExpression>()); Func<Tc[]> f = e.Compile(); Tc[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyGenericWithSubClassRestrictionArrayList<TC>(TC[] val, Expression[] exprs) where TC : C { Expression<Func<TC[]>> e = Expression.Lambda<Func<TC[]>>( Expression.NewArrayInit(typeof(TC), exprs), Enumerable.Empty<ParameterExpression>()); Func<TC[]> f = e.Compile(); TC[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyGenericWithClassAndNewRestrictionArrayList<Tcn>(Tcn[] val, Expression[] exprs) where Tcn : class, new() { Expression<Func<Tcn[]>> e = Expression.Lambda<Func<Tcn[]>>( Expression.NewArrayInit(typeof(Tcn), exprs), Enumerable.Empty<ParameterExpression>()); Func<Tcn[]> f = e.Compile(); Tcn[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyGenericWithSubClassAndNewRestrictionArrayList<TCn>(TCn[] val, Expression[] exprs) where TCn : C, new() { Expression<Func<TCn[]>> e = Expression.Lambda<Func<TCn[]>>( Expression.NewArrayInit(typeof(TCn), exprs), Enumerable.Empty<ParameterExpression>()); Func<TCn[]> f = e.Compile(); TCn[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } private static void VerifyGenericWithStructRestrictionArrayList<Ts>(Ts[] val, Expression[] exprs) where Ts : struct { Expression<Func<Ts[]>> e = Expression.Lambda<Func<Ts[]>>( Expression.NewArrayInit(typeof(Ts), exprs), Enumerable.Empty<ParameterExpression>()); Func<Ts[]> f = e.Compile(); Ts[] result = f(); Assert.Equal(val.Length, result.Length); for (int i = 0; i < result.Length; i++) { Assert.Equal(val[i], result[i]); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.JSInterop; namespace Microsoft.AspNetCore.Components.Web.Virtualization { /// <summary> /// Provides functionality for rendering a virtualized list of items. /// </summary> /// <typeparam name="TItem">The <c>context</c> type for the items being rendered.</typeparam> public sealed class Virtualize<TItem> : ComponentBase, IVirtualizeJsCallbacks, IAsyncDisposable { private VirtualizeJsInterop? _jsInterop; private ElementReference _spacerBefore; private ElementReference _spacerAfter; private int _itemsBefore; private int _visibleItemCapacity; private int _itemCount; private int _loadedItemsStartIndex; private int _lastRenderedItemCount; private int _lastRenderedPlaceholderCount; private float _itemSize; private IEnumerable<TItem>? _loadedItems; private CancellationTokenSource? _refreshCts; private Exception? _refreshException; private ItemsProviderDelegate<TItem> _itemsProvider = default!; private RenderFragment<TItem>? _itemTemplate; private RenderFragment<PlaceholderContext>? _placeholder; [Inject] private IJSRuntime JSRuntime { get; set; } = default!; /// <summary> /// Gets or sets the item template for the list. /// </summary> [Parameter] public RenderFragment<TItem>? ChildContent { get; set; } /// <summary> /// Gets or sets the item template for the list. /// </summary> [Parameter] public RenderFragment<TItem>? ItemContent { get; set; } /// <summary> /// Gets or sets the template for items that have not yet been loaded in memory. /// </summary> [Parameter] public RenderFragment<PlaceholderContext>? Placeholder { get; set; } /// <summary> /// Gets the size of each item in pixels. Defaults to 50px. /// </summary> [Parameter] public float ItemSize { get; set; } = 50f; /// <summary> /// Gets or sets the function providing items to the list. /// </summary> [Parameter] public ItemsProviderDelegate<TItem>? ItemsProvider { get; set; } /// <summary> /// Gets or sets the fixed item source. /// </summary> [Parameter] public ICollection<TItem>? Items { get; set; } /// <summary> /// Gets or sets a value that determines how many additional items will be rendered /// before and after the visible region. This help to reduce the frequency of rendering /// during scrolling. However, higher values mean that more elements will be present /// in the page. /// </summary> [Parameter] public int OverscanCount { get; set; } = 3; /// <summary> /// Instructs the component to re-request data from its <see cref="ItemsProvider"/>. /// This is useful if external data may have changed. There is no need to call this /// when using <see cref="Items"/>. /// </summary> /// <returns>A <see cref="Task"/> representing the completion of the operation.</returns> public async Task RefreshDataAsync() { // We don't auto-render after this operation because in the typical use case, the // host component calls this from one of its lifecycle methods, and will naturally // re-render afterwards anyway. It's not desirable to re-render twice. await RefreshDataCoreAsync(renderOnSuccess: false); } /// <inheritdoc /> protected override void OnParametersSet() { if (ItemSize <= 0) { throw new InvalidOperationException( $"{GetType()} requires a positive value for parameter '{nameof(ItemSize)}'."); } if (_itemSize <= 0) { _itemSize = ItemSize; } if (ItemsProvider != null) { if (Items != null) { throw new InvalidOperationException( $"{GetType()} can only accept one item source from its parameters. " + $"Do not supply both '{nameof(Items)}' and '{nameof(ItemsProvider)}'."); } _itemsProvider = ItemsProvider; } else if (Items != null) { _itemsProvider = DefaultItemsProvider; // When we have a fixed set of in-memory data, it doesn't cost anything to // re-query it on each cycle, so do that. This means the developer can add/remove // items in the collection and see the UI update without having to call RefreshDataAsync. var refreshTask = RefreshDataCoreAsync(renderOnSuccess: false); // We know it's synchronous and has its own error handling Debug.Assert(refreshTask.IsCompletedSuccessfully); } else { throw new InvalidOperationException( $"{GetType()} requires either the '{nameof(Items)}' or '{nameof(ItemsProvider)}' parameters to be specified " + $"and non-null."); } _itemTemplate = ItemContent ?? ChildContent; _placeholder = Placeholder ?? DefaultPlaceholder; } /// <inheritdoc /> protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { _jsInterop = new VirtualizeJsInterop(this, JSRuntime); await _jsInterop.InitializeAsync(_spacerBefore, _spacerAfter); } } /// <inheritdoc /> protected override void BuildRenderTree(RenderTreeBuilder builder) { if (_refreshException != null) { var oldRefreshException = _refreshException; _refreshException = null; throw oldRefreshException; } builder.OpenElement(0, "div"); builder.AddAttribute(1, "style", GetSpacerStyle(_itemsBefore)); builder.AddElementReferenceCapture(2, elementReference => _spacerBefore = elementReference); builder.CloseElement(); var lastItemIndex = Math.Min(_itemsBefore + _visibleItemCapacity, _itemCount); var renderIndex = _itemsBefore; var placeholdersBeforeCount = Math.Min(_loadedItemsStartIndex, lastItemIndex); builder.OpenRegion(3); // Render placeholders before the loaded items. for (; renderIndex < placeholdersBeforeCount; renderIndex++) { // This is a rare case where it's valid for the sequence number to be programmatically incremented. // This is only true because we know for certain that no other content will be alongside it. builder.AddContent(renderIndex, _placeholder, new PlaceholderContext(renderIndex, _itemSize)); } builder.CloseRegion(); _lastRenderedItemCount = 0; // Render the loaded items. if (_loadedItems != null && _itemTemplate != null) { var itemsToShow = _loadedItems .Skip(_itemsBefore - _loadedItemsStartIndex) .Take(lastItemIndex - _loadedItemsStartIndex); builder.OpenRegion(4); foreach (var item in itemsToShow) { _itemTemplate(item)(builder); _lastRenderedItemCount++; } renderIndex += _lastRenderedItemCount; builder.CloseRegion(); } _lastRenderedPlaceholderCount = Math.Max(0, lastItemIndex - _itemsBefore - _lastRenderedItemCount); builder.OpenRegion(5); // Render the placeholders after the loaded items. for (; renderIndex < lastItemIndex; renderIndex++) { builder.AddContent(renderIndex, _placeholder, new PlaceholderContext(renderIndex, _itemSize)); } builder.CloseRegion(); var itemsAfter = Math.Max(0, _itemCount - _visibleItemCapacity - _itemsBefore); builder.OpenElement(6, "div"); builder.AddAttribute(7, "style", GetSpacerStyle(itemsAfter)); builder.AddElementReferenceCapture(8, elementReference => _spacerAfter = elementReference); builder.CloseElement(); } private string GetSpacerStyle(int itemsInSpacer) => $"height: {(itemsInSpacer * _itemSize).ToString(CultureInfo.InvariantCulture)}px;"; void IVirtualizeJsCallbacks.OnBeforeSpacerVisible(float spacerSize, float spacerSeparation, float containerSize) { CalcualteItemDistribution(spacerSize, spacerSeparation, containerSize, out var itemsBefore, out var visibleItemCapacity); // Since we know the before spacer is now visible, we absolutely have to slide the window up // by at least one element. If we're not doing that, the previous item size info we had must // have been wrong, so just move along by one in that case to trigger an update and apply the // new size info. if (itemsBefore == _itemsBefore && itemsBefore > 0) { itemsBefore--; } UpdateItemDistribution(itemsBefore, visibleItemCapacity); } void IVirtualizeJsCallbacks.OnAfterSpacerVisible(float spacerSize, float spacerSeparation, float containerSize) { CalcualteItemDistribution(spacerSize, spacerSeparation, containerSize, out var itemsAfter, out var visibleItemCapacity); var itemsBefore = Math.Max(0, _itemCount - itemsAfter - visibleItemCapacity); // Since we know the after spacer is now visible, we absolutely have to slide the window down // by at least one element. If we're not doing that, the previous item size info we had must // have been wrong, so just move along by one in that case to trigger an update and apply the // new size info. if (itemsBefore == _itemsBefore && itemsBefore < _itemCount - visibleItemCapacity) { itemsBefore++; } UpdateItemDistribution(itemsBefore, visibleItemCapacity); } private void CalcualteItemDistribution( float spacerSize, float spacerSeparation, float containerSize, out int itemsInSpacer, out int visibleItemCapacity) { if (_lastRenderedItemCount > 0) { _itemSize = (spacerSeparation - (_lastRenderedPlaceholderCount * _itemSize)) / _lastRenderedItemCount; } if (_itemSize <= 0) { // At this point, something unusual has occurred, likely due to misuse of this component. // Reset the calculated item size to the user-provided item size. _itemSize = ItemSize; } itemsInSpacer = Math.Max(0, (int)Math.Floor(spacerSize / _itemSize) - OverscanCount); visibleItemCapacity = (int)Math.Ceiling(containerSize / _itemSize) + 2 * OverscanCount; } private void UpdateItemDistribution(int itemsBefore, int visibleItemCapacity) { // If the itemcount just changed to a lower number, and we're already scrolled past the end of the new // reduced set of items, clamp the scroll position to the new maximum if (itemsBefore + visibleItemCapacity > _itemCount) { itemsBefore = Math.Max(0, _itemCount - visibleItemCapacity); } // If anything about the offset changed, re-render if (itemsBefore != _itemsBefore || visibleItemCapacity != _visibleItemCapacity) { _itemsBefore = itemsBefore; _visibleItemCapacity = visibleItemCapacity; var refreshTask = RefreshDataCoreAsync(renderOnSuccess: true); if (!refreshTask.IsCompleted) { StateHasChanged(); } } } private async ValueTask RefreshDataCoreAsync(bool renderOnSuccess) { _refreshCts?.Cancel(); CancellationToken cancellationToken; if (_itemsProvider == DefaultItemsProvider) { // If we're using the DefaultItemsProvider (because the developer supplied a fixed // Items collection) we know it will complete synchronously, and there's no point // instantiating a new CancellationTokenSource _refreshCts = null; cancellationToken = CancellationToken.None; } else { _refreshCts = new CancellationTokenSource(); cancellationToken = _refreshCts.Token; } var request = new ItemsProviderRequest(_itemsBefore, _visibleItemCapacity, cancellationToken); try { var result = await _itemsProvider(request); // Only apply result if the task was not canceled. if (!cancellationToken.IsCancellationRequested) { _itemCount = result.TotalItemCount; _loadedItems = result.Items; _loadedItemsStartIndex = request.StartIndex; if (renderOnSuccess) { StateHasChanged(); } } } catch (Exception e) { if (e is OperationCanceledException oce && oce.CancellationToken == cancellationToken) { // No-op; we canceled the operation, so it's fine to suppress this exception. } else { // Cache this exception so the renderer can throw it. _refreshException = e; // Re-render the component to throw the exception. StateHasChanged(); } } } private ValueTask<ItemsProviderResult<TItem>> DefaultItemsProvider(ItemsProviderRequest request) { return ValueTask.FromResult(new ItemsProviderResult<TItem>( Items!.Skip(request.StartIndex).Take(request.Count), Items!.Count)); } private RenderFragment DefaultPlaceholder(PlaceholderContext context) => (builder) => { builder.OpenElement(0, "div"); builder.AddAttribute(1, "style", $"height: {_itemSize.ToString(CultureInfo.InvariantCulture)}px;"); builder.CloseElement(); }; /// <inheritdoc /> public async ValueTask DisposeAsync() { _refreshCts?.Cancel(); if (_jsInterop != null) { await _jsInterop.DisposeAsync(); } } } }
#region License // // Copyright (c) 2018, Fluent Migrator 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. // #endregion using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.SqlServer; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit.Generators.SqlServer2000 { [TestFixture] public class SqlServer2000ClusteredTests : BaseSqlServerClusteredTests { protected SqlServer2000Generator Generator; [SetUp] public void Setup() { Generator = new SqlServer2000Generator(); } [Test] public override void CanCreateClusteredIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateIndexExpression(); expression.Index.IsClustered = true; expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC)"); } [Test] public override void CanCreateClusteredIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateIndexExpression(); expression.Index.IsClustered = true; var result = Generator.Generate(expression); result.ShouldBe("CREATE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC)"); } [Test] public override void CanCreateMultiColumnClusteredIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnCreateIndexExpression(); expression.Index.IsClustered = true; expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC, [TestColumn2] DESC)"); } [Test] public override void CanCreateMultiColumnClusteredIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnCreateIndexExpression(); expression.Index.IsClustered = true; var result = Generator.Generate(expression); result.ShouldBe("CREATE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC, [TestColumn2] DESC)"); } [Test] public override void CanCreateNamedClusteredPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY CLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedClusteredPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY CLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedClusteredUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE CLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedClusteredUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE CLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedMultiColumnClusteredPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY CLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnClusteredPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY CLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnClusteredUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE CLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnClusteredUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.Clustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE CLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnNonClusteredPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY NONCLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnNonClusteredPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY NONCLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnNonClusteredUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE NONCLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedMultiColumnNonClusteredUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE NONCLUSTERED ([TestColumn1], [TestColumn2])"); } [Test] public override void CanCreateNamedNonClusteredPrimaryKeyConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY NONCLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedNonClusteredPrimaryKeyConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTPRIMARYKEY] PRIMARY KEY NONCLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedNonClusteredUniqueConstraintWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); expression.Constraint.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE NONCLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateNamedNonClusteredUniqueConstraintWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression(); expression.Constraint.AdditionalFeatures.Add(SqlServerExtensions.ConstraintType, SqlServerConstraintType.NonClustered); var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE [TestTable1] ADD CONSTRAINT [TESTUNIQUECONSTRAINT] UNIQUE NONCLUSTERED ([TestColumn1])"); } [Test] public override void CanCreateUniqueClusteredIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateUniqueIndexExpression(); expression.Index.IsClustered = true; expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC)"); } [Test] public override void CanCreateUniqueClusteredIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateUniqueIndexExpression(); expression.Index.IsClustered = true; var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC)"); } [Test] public override void CanCreateUniqueClusteredMultiColumnIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateUniqueMultiColumnIndexExpression(); expression.Index.IsClustered = true; expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC, [TestColumn2] DESC)"); } [Test] public override void CanCreateUniqueClusteredMultiColumnIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateUniqueMultiColumnIndexExpression(); expression.Index.IsClustered = true; var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE CLUSTERED INDEX [TestIndex] ON [TestTable1] ([TestColumn1] ASC, [TestColumn2] DESC)"); } } }
// http://paulmoore.mit-license.org using System; using System.Collections; using System.Text; using SimpleAI.Framework; namespace AmazonGame { internal enum AmazonCell : byte { FREE, WHITE_QUEEN, BLACK_QUEEN, ARROW } internal enum AmazonPlayer : byte { WHITE, BLACK } internal struct AmazonAction { public AmazonPlayer role; public int v; // queen initial row, column public sbyte qr, qc; // queen final row, column public sbyte qfr, qfc; // queen arrow row, column public sbyte ar, ac; public override string ToString () { return string.Format("[AmazonAction] qr:{0}, qc:{1}, qfr:{2}, qfc:{3}, ar:{4}, ac:{5}, v:{6}, role:{7}", qr, qc, qfr, qfc, ar, ac, v, role); } } internal sealed class AmazonBuilder : ActionBuilder<AmazonAction, int> { public int PosInf { get { return int.MaxValue; } } public int NegInf { get { return int.MinValue; } } public int ExtractValue (AmazonAction action) { return action.v; } public AmazonAction InsertValue (AmazonAction action, int val) { action.v = val; return action; } public AmazonAction Clone (AmazonAction action) { return action; } public int Compare (int v0, int v1) { return v0.CompareTo(v1); } } internal sealed class AmazonState : State<AmazonAction>, MutableClone<AmazonState> { public const sbyte NUM_ROWS = 10; public const sbyte NUM_COLS = 10; public static readonly sbyte[,] dirs = {{1, 1}, {-1, 1}, {1, -1}, {-1, -1}, {0, 1}, {0, -1}, {1, 0}, {-1, 0}}; private readonly sbyte[,] whiteQueens = new sbyte[4, 2]; private readonly sbyte[,] blackQueens = new sbyte[4, 2]; private readonly AmazonCell[,] board = new AmazonCell[NUM_ROWS, NUM_COLS]; public AmazonState () { whiteQueens[0, 0] = 3; whiteQueens[0, 1] = 0; whiteQueens[1, 0] = 0; whiteQueens[1, 1] = 3; whiteQueens[2, 0] = 0; whiteQueens[2, 1] = 6; whiteQueens[3, 0] = 3; whiteQueens[3, 1] = 9; blackQueens[0, 0] = 6; blackQueens[0, 1] = 0; blackQueens[1, 0] = 9; blackQueens[1, 1] = 3; blackQueens[2, 0] = 9; blackQueens[2, 1] = 6; blackQueens[3, 0] = 6; blackQueens[3, 1] = 9; board[whiteQueens[0, 0], whiteQueens[0, 1]] = AmazonCell.WHITE_QUEEN; board[whiteQueens[1, 0], whiteQueens[1, 1]] = AmazonCell.WHITE_QUEEN; board[whiteQueens[2, 0], whiteQueens[2, 1]] = AmazonCell.WHITE_QUEEN; board[whiteQueens[3, 0], whiteQueens[3, 1]] = AmazonCell.WHITE_QUEEN; board[blackQueens[0, 0], blackQueens[0, 1]] = AmazonCell.BLACK_QUEEN; board[blackQueens[1, 0], blackQueens[1, 1]] = AmazonCell.BLACK_QUEEN; board[blackQueens[2, 0], blackQueens[2, 1]] = AmazonCell.BLACK_QUEEN; board[blackQueens[3, 0], blackQueens[3, 1]] = AmazonCell.BLACK_QUEEN; } public sbyte[,] GetQueens (AmazonPlayer player) { if (player == AmazonPlayer.WHITE) { return whiteQueens; } return blackQueens; } public bool InBounds (int row, int col) { return row >= 0 && row < NUM_ROWS && col >= 0 && col < NUM_COLS; } public bool IsFree (int row, int col) { return board[row, col] == AmazonCell.FREE; } public bool QueenAt (AmazonPlayer player, int row, int col) { return board[row, col] == (player == AmazonPlayer.WHITE ? AmazonCell.WHITE_QUEEN : AmazonCell.BLACK_QUEEN); } public void ApplyAction (AmazonAction action) { sbyte[,] queens; AmazonCell marker; if (action.role == AmazonPlayer.WHITE) { queens = whiteQueens; marker = AmazonCell.WHITE_QUEEN; } else { queens = blackQueens; marker = AmazonCell.BLACK_QUEEN; } for (int i = 0; i < queens.GetLength(0); i++) { // find the correct queen, and move it if (queens[i, 0] == action.qr && queens[i, 1] == action.qc) { queens[i, 0] = action.qfr; queens[i, 1] = action.qfc; break; } } board[action.qr, action.qc] = AmazonCell.FREE; board[action.qfr, action.qfc] = marker; // this has to be done last, since the queen can fire back on herself board[action.ar, action.ac] = AmazonCell.ARROW; } public void UndoAction (AmazonAction action) { sbyte[,] queens; AmazonCell marker; if (action.role == AmazonPlayer.WHITE) { queens = whiteQueens; marker = AmazonCell.WHITE_QUEEN; } else { queens = blackQueens; marker = AmazonCell.BLACK_QUEEN; } for (int i = 0; i < queens.GetLength(0); i++) { if (queens[i, 0] == action.qfr && queens[i, 1] == action.qfc) { queens[i, 0] = action.qr; queens[i, 1] = action.qc; break; } } board[action.qfr, action.qfc] = AmazonCell.FREE; board[action.ar, action.ac] = AmazonCell.FREE; board[action.qr, action.qc] = marker; } public AmazonState Clone () { AmazonState clone = new AmazonState(); Array.Copy(board, clone.board, board.Length); Array.Copy(whiteQueens, clone.whiteQueens, whiteQueens.Length); Array.Copy(blackQueens, clone.blackQueens, blackQueens.Length); return clone; } public override string ToString () { // prints out a human readable representation of the board StringBuilder sb = new StringBuilder(); sb.Append(" +"); for (int j = 0; j < board.GetLength(1) * 2 - 1; j++) { sb.Append("-"); } sb.Append("+"); sb.AppendLine(); for (int i = board.GetLength(0) - 1; i >= 0; i--) { if (i + 1 < 10) { sb.Append(i + 1); sb.Append(" "); } else { sb.Append(i + 1); } sb.Append("|"); for (int j = 0; j < board.GetLength(1); j++) { switch (board[i, j]) { case AmazonCell.WHITE_QUEEN: sb.Append("W"); break; case AmazonCell.BLACK_QUEEN: sb.Append("B"); break; case AmazonCell.ARROW: sb.Append("A"); break; case AmazonCell.FREE: sb.Append(" "); break; } sb.Append("|"); } sb.AppendLine(); } sb.Append(" +"); for (int j = 0; j < board.GetLength(1) * 2 - 1; j++) { sb.Append("-"); } sb.Append("+"); sb.AppendLine(); sb.Append(" "); for (int j = 0; j < board.GetLength(1); j++) { sb.Append((char)('a' + j)); sb.Append(" "); } return sb.ToString(); } } internal sealed class AmazonCutoffTest : CutoffTest<AmazonState, AmazonAction> { private readonly int maxSearchTime; private int startTime; public AmazonCutoffTest (int maxSearchTime) { this.maxSearchTime = maxSearchTime; } public void Begin () { startTime = Environment.TickCount; Console.WriteLine(string.Format("CT Beginning at {0}s", startTime / 1000)); } public void End () { Console.WriteLine(string.Format("CT Search lasted {0}s", (Environment.TickCount - startTime) / 1000)); } public bool Test (AmazonState state) { // really all we are concerned about is time, we don't have to worry about memory since it is mostly allocated up front return Environment.TickCount - startTime > maxSearchTime; } } internal sealed class AmazonSuccessorFunction : SuccessorFunction<AmazonState, AmazonAction, byte, AmazonPlayer> { public void Partition (AmazonState state, AmazonPlayer player, Action<byte> partitioner) { // partitioning in this case is simple, each queen is one partition partitioner(0); partitioner(1); partitioner(2); partitioner(3); } public void Expand (AmazonState state, AmazonPlayer player, byte partition, Func<AmazonAction, bool> expander) { // take our queen, and find all possible moves she can make sbyte[,] queens = state.GetQueens(player); sbyte[,] dirs = AmazonState.dirs; for (int i = 0; i < dirs.GetLength(0); i++) { if (!CalculateQueenMoves(state, player, expander, queens[partition, 0], queens[partition, 1], dirs[i, 0], dirs[i, 1])) { return; } } } private bool CalculateQueenMoves (AmazonState state, AmazonPlayer player, Func<AmazonAction, bool> expander, sbyte qr, sbyte qc, sbyte dr, sbyte dc) { sbyte[,] dirs = AmazonState.dirs; sbyte row = (sbyte)(qr + dr), col = (sbyte)(qc + dc); while (state.InBounds(row, col) && state.IsFree(row, col)) { for (int i = 0; i < dirs.GetLength(0); i++) { if (!CalculateArrowShots(state, player, expander, qr, qc, row, col, dirs[i, 0], dirs[i, 1])) { return false; } } row += dr; col += dc; } return true; } private bool CalculateArrowShots (AmazonState state, AmazonPlayer player, Func<AmazonAction, bool> expander, sbyte qr, sbyte qc, sbyte qfr, sbyte qfc, sbyte dr, sbyte dc) { sbyte row = (sbyte)(qfr + dr), col = (sbyte)(qfc + dc); while (state.InBounds(row, col) && (state.IsFree(row, col) || (row == qr && col == qc))) { AmazonAction action = new AmazonAction(); action.role = player; action.qr = qr; action.qc = qc; action.qfr = qfr; action.qfc = qfc; action.ar = row; action.ac = col; if (!expander(action)) { return false; } row += dr; col += dc; } return true; } } /// <summary> /// An Amazon evaluation function which values territory. /// </summary> /// <remarks> /// In this evaluation function, territory is measured by how much more easily we can 'hop' to a square as opposed to our enemy. /// The break down is as follows: /// * If we can get to a square in at most one hop, and the enemy cannot reach the square in at most two hops, we get 3 points. /// * If we can get to a square in at most one hop, and the enemy cannot reach the square in at most one hop, we get 2 points. /// * If we can get to a square in at most two hops, and the enemy cannot reach the square in at most two hops, we get 1 point. /// The same score for the enemy is negated from our score. /// </remarks> internal sealed class AmazonEvaluationFunction : EvaluationFunction<AmazonState, AmazonAction, int, AmazonPlayer> { private readonly BitArray ourOneHop, ourTwoHop, oppOneHop, oppTwoHop; private AmazonPlayer player; public AmazonEvaluationFunction () { ourOneHop = new BitArray(AmazonState.NUM_ROWS * AmazonState.NUM_COLS); ourTwoHop = new BitArray(AmazonState.NUM_ROWS * AmazonState.NUM_COLS); oppOneHop = new BitArray(AmazonState.NUM_ROWS * AmazonState.NUM_COLS); oppTwoHop = new BitArray(AmazonState.NUM_ROWS * AmazonState.NUM_COLS); } public int Evaluate (AmazonState state, AmazonPlayer player) { this.player = player; CalculateHops(state, player); CalculateHops(state, player == AmazonPlayer.WHITE ? AmazonPlayer.BLACK : AmazonPlayer.WHITE); int evaluation = 0; for (int i = 0; i < AmazonState.NUM_ROWS * AmazonState.NUM_COLS; i++) { // calculate our score based on the owned territory if (ourOneHop[i] && !oppTwoHop[i]) { evaluation += 3; } else if (ourOneHop[i] && !oppOneHop[i]) { evaluation += 2; } else if (ourTwoHop[i] && !oppTwoHop[i]) { evaluation += 1; } // do the same evaluation for the enemy, but negate it from our score if (oppOneHop[i] && !ourTwoHop[i]) { evaluation -= 4; } else if (oppOneHop[i] && !ourOneHop[i]) { evaluation -= 2; } else if (oppTwoHop[i] && !ourTwoHop[i]) { evaluation -= 1; } } this.player = default(AmazonPlayer); ourOneHop.SetAll(false); ourTwoHop.SetAll(false); oppOneHop.SetAll(false); oppTwoHop.SetAll(false); return evaluation; } private void CalculateHops (AmazonState state, AmazonPlayer player) { BitArray oneHop, twoHop; if (player == this.player) { oneHop = ourOneHop; twoHop = ourTwoHop; } else { oneHop = oppOneHop; twoHop = oppTwoHop; } sbyte[,] dirs = AmazonState.dirs; sbyte[,] queens = state.GetQueens(player); for (sbyte q = 0; q < queens.GetLength(0); q++) { for (sbyte d = 0; d < dirs.GetLength(0); d++) { int r = queens[q, 0] + dirs[d, 0]; int c = queens[q, 1] + dirs[d, 1]; while (state.InBounds(r, c) && state.IsFree(r, c)) { oneHop.Set(r * AmazonState.NUM_ROWS + c, true); for (sbyte d2 = 0; d2 < dirs.GetLength(0); d2++) { int r2 = r + dirs[d2, 0]; int c2 = c + dirs[d2, 1]; while (state.InBounds(r2, c2) && state.IsFree(r2, c2)) { twoHop.Set(r2 * AmazonState.NUM_ROWS + c2, true); r2 += dirs[d2, 0]; c2 += dirs[d2, 1]; } } r += dirs[d, 0]; c += dirs[d, 1]; } } } } public EvaluationFunction<AmazonState, AmazonAction, int, AmazonPlayer> Clone () { var clone = new AmazonEvaluationFunction(); clone.ourOneHop.Or(ourOneHop); clone.ourTwoHop.Or(ourTwoHop); clone.oppOneHop.Or(oppOneHop); clone.oppTwoHop.Or(oppTwoHop); clone.player = player; return clone; } } internal sealed class AmazonMoveValidator { public static string Validate (AmazonState state, AmazonAction move) { // check the opponent has a queen at the starting position if (state.QueenAt(move.role, move.qr, move.qc)) { // validate the queen's dr sbyte dr, dc; if (move.qfr < move.qr) { dr = -1; } else if (move.qfr > move.qr) { dr = 1; } else { dr = 0; } // validate the queen's dc if (move.qfc < move.qc) { dc = -1; } else if (move.qfc > move.qc) { dc = 1; } else { dc = 0; } // walk to the queen's final position if (dr != 0 || dc != 0) { sbyte qr = (sbyte)(move.qr + dr), qc = (sbyte)(move.qc + dc); while (state.InBounds(qr, qc) && state.IsFree(qr, qc)) { if (qr == move.qfr && qc == move.qfc) { // validate the arrow's dr if (move.ar < move.qfr) { dr = -1; } else if (move.ar > move.qfr) { dr = 1; } else { dr = 0; } // validate the arrow's dc if (move.ac < move.qfc) { dc = -1; } else if (move.ac > move.qfc) { dc = 1; } else { dc = 0; } if (dr != 0 || dc != 0) { // walk to the arrow's final position sbyte ar = (sbyte)(move.qfr + dr), ac = (sbyte)(move.qfc + dc); while (state.InBounds(ar, ac) && (state.IsFree(ar, ac) || (ar == move.qr && ac == move.qc))) { if (ar == move.ar && ac == move.ac) { // all conditions are met return null; } ar += dr; ac += dc; } return "The arrow's path is not clear!"; } return "Invalid arrow direction!"; } qr += dr; qc += dc; } return "The queen's path is not clear!"; } return "Invalid queen direction!"; } return "No queen found at starting location!"; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.AIPlatform.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedIndexEndpointServiceClientTest { [xunit::FactAttribute] public void GetIndexEndpointRequestObject() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIndexEndpointRequest request = new GetIndexEndpointRequest { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.GetIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint response = client.GetIndexEndpoint(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIndexEndpointRequestObjectAsync() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIndexEndpointRequest request = new GetIndexEndpointRequest { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.GetIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint responseCallSettings = await client.GetIndexEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); IndexEndpoint responseCancellationToken = await client.GetIndexEndpointAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIndexEndpoint() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIndexEndpointRequest request = new GetIndexEndpointRequest { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.GetIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint response = client.GetIndexEndpoint(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIndexEndpointAsync() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIndexEndpointRequest request = new GetIndexEndpointRequest { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.GetIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint responseCallSettings = await client.GetIndexEndpointAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); IndexEndpoint responseCancellationToken = await client.GetIndexEndpointAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIndexEndpointResourceNames() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIndexEndpointRequest request = new GetIndexEndpointRequest { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.GetIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint response = client.GetIndexEndpoint(request.IndexEndpointName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIndexEndpointResourceNamesAsync() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIndexEndpointRequest request = new GetIndexEndpointRequest { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.GetIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint responseCallSettings = await client.GetIndexEndpointAsync(request.IndexEndpointName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); IndexEndpoint responseCancellationToken = await client.GetIndexEndpointAsync(request.IndexEndpointName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateIndexEndpointRequestObject() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest { IndexEndpoint = new IndexEndpoint(), UpdateMask = new wkt::FieldMask(), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.UpdateIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint response = client.UpdateIndexEndpoint(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateIndexEndpointRequestObjectAsync() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest { IndexEndpoint = new IndexEndpoint(), UpdateMask = new wkt::FieldMask(), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.UpdateIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint responseCallSettings = await client.UpdateIndexEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); IndexEndpoint responseCancellationToken = await client.UpdateIndexEndpointAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateIndexEndpoint() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest { IndexEndpoint = new IndexEndpoint(), UpdateMask = new wkt::FieldMask(), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.UpdateIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint response = client.UpdateIndexEndpoint(request.IndexEndpoint, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateIndexEndpointAsync() { moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest { IndexEndpoint = new IndexEndpoint(), UpdateMask = new wkt::FieldMask(), }; IndexEndpoint expectedResponse = new IndexEndpoint { IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", DeployedIndexes = { new DeployedIndex(), }, Etag = "etage8ad7218", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Network = "networkd22ce091", }; mockGrpcClient.Setup(x => x.UpdateIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null); IndexEndpoint responseCallSettings = await client.UpdateIndexEndpointAsync(request.IndexEndpoint, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); IndexEndpoint responseCancellationToken = await client.UpdateIndexEndpointAsync(request.IndexEndpoint, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
//----------------------------------------------------------------------- // <copyright file="MockeryTest.cs" company="NMock2"> // // http://www.sourceforge.net/projects/NMock2 // // 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> // This is the easiest way to ignore StyleCop rules on this file, even if we shouldn't use this tag: // <auto-generated /> //----------------------------------------------------------------------- using System; using System.Collections; using System.IO; using System.Reflection; using NMocha; using NMocha.Internal; using NMocha.Monitoring; using NMock2.Internal; using NMock2.Monitoring; using NUnit.Framework; namespace NMock2.Test { [TestFixture] public class MockeryTest { #region Setup/Teardown [SetUp] public void SetUp() { _mockery = new Mockery(); _mock = (IMockedType) _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock"); _expectation1 = new MockExpectation(); _expectation2 = new MockExpectation(); } [TearDown] public void TearDown() { } #endregion public interface IMockedType { void DoStuff(); } public interface InterfaceWithoutIPrefix { } public interface ARSEIInterfaceWithAdditionalPrefixBeforeI { } public interface INTERFACE_WITH_UPPER_CLASS_NAME { } private Mockery _mockery; private IMockedType _mock; private MockExpectation _expectation1; private MockExpectation _expectation2; private void AddExpectationsToMockery() { var mockObjectControl = (IMockObject) _mock; mockObjectControl.AddExpectation(_expectation1); mockObjectControl.AddExpectation(_expectation2); } // AKR Code provided by Adrian Krummenacher, Roche Rotkreuz public interface IMockObjectWithGenericMethod : IMockedType { T Find<T>(); T Search<T>(T instance, string Name); } // AKR Code provided by Adrian Krummenacher, Roche Rotkreuz public interface IParentInterface { void DoSomething(); } public interface IChildInterface : IParentInterface { } public class TestingMockObjectFactoryWithNoDefaultConstructor : IMockObjectFactory { public TestingMockObjectFactoryWithNoDefaultConstructor(string someArg) { } #region IMockObjectFactory Members public object CreateMock(Mockery mockery, CompositeType mockedTypes, string name, object[] constructorArgs) { return null; } #endregion } public sealed class SampleSealedClass { public int Add(int a, int b) { return a + b; } } public class SampleClass { public int Add(int a, int b) { return DoAdd(a, b); } protected virtual int DoAdd(int a, int b) { return a + b; } public virtual int Divide(int a, int b, out decimal remainder) { remainder = a%b; return a/b; } } public class SampleClassWithConstructorArgs { public SampleClassWithConstructorArgs(int i, string s) { } } public class SampleGenericClass<T> { public virtual T GetDefault() { return default(T); } } public class SampleClassWithGenericMethods { public virtual string GetStringValue<T>(T input) { return input.ToString(); } public virtual int GetCount<T>(T list) where T : IList { return list.Count; } } [Test] public void CanCreateClassMockWithConstructor() { var mock = _mockery.NewInstanceOfRole<SampleClassWithConstructorArgs>(1, "A"); } [Test] public void CanCreateMockWithoutCastingBySpecifingTypeAsGenericParameter() { var mock = _mockery.NewInstanceOfRole<IMockedType>(); Console.WriteLine("Generic mock create test ran"); } [Test] public void CanMockClassWithGenericMethods() { var mock = _mockery.NewInstanceOfRole<SampleClassWithGenericMethods>(); } [Test] public void CanMockGenericClass() { var mock = _mockery.NewInstanceOfRole<SampleGenericClass<string>>(); } [Test] public void ClassMockReturnsDefaultNameFromMockNameProperty() { var mock = (IMockObject) _mockery.NewInstanceOfRole<SampleClass>(); Assert.AreEqual("sampleClass", mock.MockName); } [Test] public void CreateMocksWithGenericMethod() { object mock = _mockery.NewInstanceOfRole(typeof (IMockObjectWithGenericMethod)); } [Test] public void CreatedClassMockComparesReferenceIdentityWithEqualsMethod() { object mock1 = _mockery.NewInstanceOfRole(typeof (SampleClass)); object mock2 = _mockery.NewInstanceOfRole(typeof (SampleClass)); Assert.IsTrue(mock1.Equals(mock1), "same object should be equal"); Assert.IsFalse(mock1.Equals(mock2), "different objects should not be equal"); } [Test] public void CreatedMockComparesReferenceIdentityWithEqualsMethod() { object mock1 = _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock1"); object mock2 = _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock2"); Assert.IsTrue(mock1.Equals(mock1), "same object should be equal"); Assert.IsFalse(mock1.Equals(mock2), "different objects should not be equal"); } [Test] public void CreatedMockReturnsNameFromToString() { object mock1 = _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock1"); object mock2 = _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock2"); Assert.AreEqual("mock1", mock1.ToString(), "mock1.ToString()"); Assert.AreEqual("mock2", mock2.ToString(), "mock2.ToString()"); } [Test] public void CreatesClassMocksThatCanBeCastToIMockObject() { object mock = _mockery.NewInstanceOfRole<SampleClass>(); Assert.IsTrue(mock is IMockObject, "should be instance of IMock"); } [Test] public void CreatesMocksThatCanBeCastToIMockObject() { object mock = _mockery.NewInstanceOfRole(typeof (IMockedType)); Assert.IsTrue(mock is IMockObject, "should be instance of IMock"); } [Test] public void CreatesMocksThatCanBeCastToMockedType() { object mock = _mockery.NewInstanceOfRole(typeof (IMockedType)); Assert.IsTrue(mock is IMockedType, "should be instance of mocked type"); } [Test, ExpectedException(typeof (ExpectationException))] public void DetectsWhenFirstExpectationHasNotBeenMet() { AddExpectationsToMockery(); _expectation1.HasBeenMet = false; _expectation2.HasBeenMet = true; _mockery.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof (ExpectationException))] public void DetectsWhenSecondExpectationHasNotBeenMet() { AddExpectationsToMockery(); _expectation1.HasBeenMet = true; _expectation2.HasBeenMet = false; _mockery.VerifyAllExpectationsHaveBeenMet(); } [Test] public void DispatchesInvocationBySearchingForMatchingExpectationInOrderOfAddition() { AddExpectationsToMockery(); _expectation2.Previous = _expectation1; _expectation1.ExpectedInvokedObject = _expectation2.ExpectedInvokedObject = _mock; _expectation1.ExpectedInvokedMethod = _expectation2.ExpectedInvokedMethod = typeof (IMockedType).GetMethod("DoStuff", new Type[0]); _expectation1.Matches_Result = false; _expectation2.Matches_Result = true; _mock.DoStuff(); Assert.IsTrue(_expectation1.Matches_HasBeenCalled, "should have tried to match expectation1"); Assert.IsFalse(_expectation1.Perform_HasBeenCalled, "should not have performed expectation1"); Assert.IsTrue(_expectation2.Matches_HasBeenCalled, "should have tried to match expectation2"); Assert.IsTrue(_expectation2.Perform_HasBeenCalled, "should have performed expectation2"); } [Test, ExpectedException(typeof (ExpectationException))] public void FailsTestIfNoExpectationsMatch() { AddExpectationsToMockery(); _expectation1.Matches_Result = false; _expectation2.Matches_Result = false; _mock.DoStuff(); } [Test] public void GivesMocksDefaultNameIfNoNameSpecified() { Assert.AreEqual("mockedType", _mockery.NewInstanceOfRole(typeof (IMockedType)).ToString()); Assert.AreEqual("interfaceWithoutIPrefix", _mockery.NewInstanceOfRole(typeof (InterfaceWithoutIPrefix)).ToString()); Assert.AreEqual("interfaceWithAdditionalPrefixBeforeI", _mockery.NewInstanceOfRole(typeof (ARSEIInterfaceWithAdditionalPrefixBeforeI)).ToString()); Assert.AreEqual("interface_with_upper_class_name", _mockery.NewInstanceOfRole(typeof (INTERFACE_WITH_UPPER_CLASS_NAME)).ToString()); } [Test] public void MockReturnsNameFromMockNameProperty() { var mock = (IMockObject) _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock"); Assert.AreEqual("mock", mock.MockName); } [Test] public void MockReturnsNameFromToString() { object mock = _mockery.NewNamedInstanceOfRole(typeof (IMockedType), "mock"); Assert.AreEqual("mock", mock.ToString()); } [Test] [ExpectedException(typeof (ArgumentException))] public void MockingSealedClassThrowsArgumentException() { var mock = _mockery.NewInstanceOfRole<SampleSealedClass>(); } [Test] public void ShouldBeAbleToInvokeMethodOnInheritedInterface() { var mockery = new Mockery(); var childMock = (IChildInterface) mockery.NewInstanceOfRole(typeof (IChildInterface)); Expect.AtLeastOnce.On(childMock).Message("DoSomething"); childMock.DoSomething(); mockery.VerifyAllExpectationsHaveBeenMet(); } [Test] public void StopsSearchingForMatchingExpectationAsSoonAsOneMatches() { AddExpectationsToMockery(); _expectation2.Previous = _expectation1; _expectation1.ExpectedInvokedObject = _expectation2.ExpectedInvokedObject = _mock; _expectation1.ExpectedInvokedMethod = _expectation2.ExpectedInvokedMethod = typeof (IMockedType).GetMethod("DoStuff", new Type[0]); _expectation1.Matches_Result = true; _mock.DoStuff(); Assert.IsTrue(_expectation1.Matches_HasBeenCalled, "should have tried to match expectation1"); Assert.IsTrue(_expectation1.Perform_HasBeenCalled, "should have performed expectation1"); Assert.IsFalse(_expectation2.Matches_HasBeenCalled, "should not have tried to match expectation2"); Assert.IsFalse(_expectation2.Perform_HasBeenCalled, "should not have performed expectation2"); } [Test] public void VerifiesWhenAllExpectationsHaveBeenMet() { AddExpectationsToMockery(); _expectation1.HasBeenMet = true; _expectation2.HasBeenMet = true; _mockery.VerifyAllExpectationsHaveBeenMet(); } } internal class MockExpectation : IExpectation { public string Description = ""; public MethodInfo ExpectedInvokedMethod; public object ExpectedInvokedObject; public bool Matches_HasBeenCalled; public bool Matches_Result; public bool Perform_HasBeenCalled; public MockExpectation Previous; #region IExpectation Members /// <summary> /// Checks whether stored expectations matches the specified invocation. /// </summary> /// <param name="invocation">The invocation to check.</param> /// <returns>Returns whether one of the stored expectations has met the specified invocation.</returns> public bool Matches(Invocation invocation) { CheckInvocation(invocation); Assert.IsTrue(Previous == null || Previous.Matches_HasBeenCalled, "called out of order"); Matches_HasBeenCalled = true; return Matches_Result; } public bool MatchesIgnoringIsActive(Invocation invocation) { throw new NotImplementedException(); } public void Perform(Invocation invocation) { CheckInvocation(invocation); Assert.IsTrue(Matches_HasBeenCalled, "Matches should have been called"); Perform_HasBeenCalled = true; } public void DescribeActiveExpectationsTo(IDescription writer) { writer.AppendText(Description); } public void DescribeUnmetExpectationsTo(IDescription writer) { writer.AppendText(Description); } public bool IsActive { get; set; } public bool HasBeenMet { get; set; } #endregion private void CheckInvocation(Invocation invocation) { Assert.IsTrue(ExpectedInvokedObject == null || ExpectedInvokedObject == invocation.Receiver, "should have received invocation on expected object"); Assert.IsTrue(ExpectedInvokedMethod == null || ExpectedInvokedMethod == invocation.Method, "should have received invocation of expected method"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #nullable enable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Reflection; namespace Azure.Data.Tables { internal static class DictionaryTableExtensions { /// <summary> /// A cache for reflected <see cref="PropertyInfo"/> array for the given <see cref="Type"/>. /// </summary> private static readonly ConcurrentDictionary<Type, PropertyInfo[]> s_propertyInfoCache = new ConcurrentDictionary<Type, PropertyInfo[]>(); /// <summary> /// Returns a new Dictionary with the appropriate Odata type annotation for a given propertyName value pair. /// The default case is intentionally unhandled as this means that no type annotation for the specified type is required. /// This is because the type is naturally serialized in a way that the table service can interpret without hints. /// </summary> internal static Dictionary<string, object> ToOdataAnnotatedDictionary(this IDictionary<string, object> tableEntityProperties) { // Remove the ETag property, as it does not need to be serialized tableEntityProperties.Remove(TableConstants.PropertyNames.ETag); var annotatedDictionary = new Dictionary<string, object>(tableEntityProperties.Keys.Count * 2); foreach (var item in tableEntityProperties) { annotatedDictionary[item.Key] = item.Value; switch (item.Value) { case byte[] _: annotatedDictionary[item.Key.ToOdataTypeString()] = TableConstants.Odata.EdmBinary; break; case long _: annotatedDictionary[item.Key.ToOdataTypeString()] = TableConstants.Odata.EdmInt64; // Int64 / long should be serialized as string. annotatedDictionary[item.Key] = item.Value.ToString(); break; case double _: annotatedDictionary[item.Key.ToOdataTypeString()] = TableConstants.Odata.EdmDouble; break; case Guid _: annotatedDictionary[item.Key.ToOdataTypeString()] = TableConstants.Odata.EdmGuid; break; case DateTimeOffset _: annotatedDictionary[item.Key.ToOdataTypeString()] = TableConstants.Odata.EdmDateTime; break; case DateTime _: annotatedDictionary[item.Key.ToOdataTypeString()] = TableConstants.Odata.EdmDateTime; break; case Enum enumValue: throw new NotSupportedException("Enum values are only supported for custom model types implementing ITableEntity."); } } return annotatedDictionary; } /// <summary> /// Cleans a List of Dictionaries of its Odata type annotations, while using them to cast its entities accordingly. /// </summary> internal static void CastAndRemoveAnnotations(this IReadOnlyList<IDictionary<string, object>> entityList) { var typeAnnotationsWithKeys = new Dictionary<string, (string typeAnnotation, string annotationKey)>(); foreach (var entity in entityList) { entity.CastAndRemoveAnnotations(typeAnnotationsWithKeys); } } /// <summary> /// Cleans a Dictionary of its Odata type annotations, while using them to cast its entities accordingly. /// </summary> internal static void CastAndRemoveAnnotations(this IDictionary<string, object> entity, Dictionary<string, (string typeAnnotation, string annotationKey)>? typeAnnotationsWithKeys = null) { typeAnnotationsWithKeys ??= new Dictionary<string, (string typeAnnotation, string annotationKey)>(); var spanOdataSuffix = TableConstants.Odata.OdataTypeString.AsSpan(); typeAnnotationsWithKeys.Clear(); foreach (var propertyName in entity.Keys) { var spanPropertyName = propertyName.AsSpan(); var iSuffix = spanPropertyName.IndexOf(spanOdataSuffix); if (iSuffix > 0) { // This property is an Odata annotation. Save it in the typeAnnoations dictionary. typeAnnotationsWithKeys[spanPropertyName.Slice(0, iSuffix).ToString()] = (typeAnnotation: (entity[propertyName] as string)!, annotationKey: propertyName); } } // Iterate through the types that are serialized as string by default and Parse them as the correct type, as indicated by the type annotations. foreach (var annotation in typeAnnotationsWithKeys.Keys) { entity[annotation] = typeAnnotationsWithKeys[annotation].typeAnnotation switch { TableConstants.Odata.EdmBinary => Convert.FromBase64String(entity[annotation] as string), TableConstants.Odata.EdmDateTime => DateTimeOffset.Parse(entity[annotation] as string, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), TableConstants.Odata.EdmGuid => Guid.Parse(entity[annotation] as string), TableConstants.Odata.EdmInt64 => long.Parse(entity[annotation] as string, CultureInfo.InvariantCulture), _ => throw new NotSupportedException("Not supported type " + typeAnnotationsWithKeys[annotation]) }; // Remove the type annotation property from the dictionary. entity.Remove(typeAnnotationsWithKeys[annotation].annotationKey); } // The Timestamp property is not annotated, since it is a known system property // so we must cast it without a type annotation if (entity.TryGetValue(TableConstants.PropertyNames.TimeStamp, out var value) && value is string) { entity[TableConstants.PropertyNames.TimeStamp] = DateTimeOffset.Parse(entity[TableConstants.PropertyNames.TimeStamp] as string, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); } } /// <summary> /// Converts a List of Dictionaries containing properties and Odata type annotations to a custom entity type. /// </summary> internal static List<T> ToTableEntityList<T>(this IReadOnlyList<IDictionary<string, object>> entityList) where T : class, ITableEntity, new() { PropertyInfo[] properties = s_propertyInfoCache.GetOrAdd(typeof(T), (type) => { return type.GetProperties(BindingFlags.Instance | BindingFlags.Public); }); var result = new List<T>(entityList.Count); foreach (var entity in entityList) { var tableEntity = entity.ToTableEntity<T>(properties); result.Add(tableEntity); } return result; } /// <summary> /// Cleans a Dictionary of its Odata type annotations, while using them to cast its entities accordingly. /// </summary> internal static T ToTableEntity<T>(this IDictionary<string, object> entity, PropertyInfo[]? properties = null) where T : class, ITableEntity, new() { var result = new T(); if (result is IDictionary<string, object> dictionary) { entity.CastAndRemoveAnnotations(); foreach (var entProperty in entity.Keys) { dictionary[entProperty] = entity[entProperty]; } return result; } properties ??= s_propertyInfoCache.GetOrAdd(typeof(T), (type) => { return type.GetProperties(BindingFlags.Instance | BindingFlags.Public); }); // Iterate through each property of the entity and set them as the correct type. foreach (var property in properties) { if (entity.TryGetValue(property.Name, out var propertyValue)) { if (typeActions.TryGetValue(property.PropertyType, out var propertyAction)) { propertyAction(property, propertyValue, result); } else { if (property.PropertyType.IsEnum) { typeActions[typeof(Enum)](property, propertyValue, result); } else { property.SetValue(result, propertyValue); } } } } // Populate the ETag if present. if (entity.TryGetValue(TableConstants.PropertyNames.EtagOdata, out var etag)) { result.ETag = new ETag((etag as string)!); } return result; } private static Dictionary<Type, Action<PropertyInfo, object, object>> typeActions = new Dictionary<Type, Action<PropertyInfo, object, object>> { {typeof(byte[]), (property, propertyValue, result) => property.SetValue(result, Convert.FromBase64String(propertyValue as string))}, {typeof(long), (property, propertyValue, result) => property.SetValue(result, long.Parse(propertyValue as string, CultureInfo.InvariantCulture))}, {typeof(long?), (property, propertyValue, result) => property.SetValue(result, long.Parse(propertyValue as string, CultureInfo.InvariantCulture))}, {typeof(double), (property, propertyValue, result) => property.SetValue(result, propertyValue)}, {typeof(double?), (property, propertyValue, result) => property.SetValue(result, propertyValue)}, {typeof(bool), (property, propertyValue, result) => property.SetValue(result, (bool)propertyValue)}, {typeof(bool?), (property, propertyValue, result) => property.SetValue(result, (bool?)propertyValue)}, {typeof(Guid), (property, propertyValue, result) => property.SetValue(result, Guid.Parse(propertyValue as string))}, {typeof(Guid?), (property, propertyValue, result) => property.SetValue(result, Guid.Parse(propertyValue as string))}, {typeof(DateTimeOffset), (property, propertyValue, result) => property.SetValue(result, DateTimeOffset.Parse(propertyValue as string, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind))}, {typeof(DateTimeOffset?), (property, propertyValue, result) => property.SetValue(result, DateTimeOffset.Parse(propertyValue as string, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind))}, {typeof(DateTime), (property, propertyValue, result) => property.SetValue(result, DateTime.Parse(propertyValue as string, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind))}, {typeof(DateTime?), (property, propertyValue, result) => property.SetValue(result, DateTime.Parse(propertyValue as string, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind))}, {typeof(string), (property, propertyValue, result) => property.SetValue(result, propertyValue as string)}, {typeof(int), (property, propertyValue, result) => property.SetValue(result, (int)propertyValue)}, {typeof(int?), (property, propertyValue, result) => property.SetValue(result, (int?)propertyValue)}, {typeof(Enum), (property, propertyValue, result) => property.SetValue(result, Enum.Parse(property.PropertyType, propertyValue as string ))}, }; } }
// // System.Web.Security.Roles // // Authors: // Ben Maurer (bmaurer@users.sourceforge.net) // // (C) 2003 Ben Maurer // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System.Collections; using System.Collections.Specialized; using System.Text; namespace System.Web.Security { public sealed class Roles { public static void AddUsersToRole (string [] usernames, string rolename) { Provider.AddUsersToRoles (usernames, new string[] {rolename}); } public static void AddUsersToRoles (string [] usernames, string [] rolenames) { Provider.AddUsersToRoles (usernames, rolenames); } public static void AddUserToRole (string username, string rolename) { Provider.AddUsersToRoles (new string[] {username}, new string[] {rolename}); } public static void AddUserToRoles (string username, string [] rolenames) { Provider.AddUsersToRoles (new string[] {username}, rolenames); } public static void CreateRole (string rolename) { Provider.CreateRole (rolename); } [MonoTODO] public static void DeleteCookie () { throw new NotImplementedException (); } public static bool DeleteRole (string rolename) { return Provider.DeleteRole (rolename, true); } public static bool DeleteRole (string rolename, bool throwOnPopulatedRole) { return Provider.DeleteRole (rolename, throwOnPopulatedRole); } public static string [] GetAllRoles () { return Provider.GetAllRoles (); } public static string [] GetRolesForUser () { return Provider.GetRolesForUser (CurrentUser); } static string CurrentUser { get { if (HttpContext.Current != null && HttpContext.Current.User != null) return HttpContext.Current.User.Identity.Name; else return System.Threading.Thread.CurrentPrincipal.Identity.Name; } } public static string [] GetRolesForUser (string username) { return Provider.GetRolesForUser (username); } public static string [] GetUsersInRole (string rolename) { return Provider.GetUsersInRole (rolename); } public static bool IsUserInRole (string rolename) { return Provider.IsUserInRole (CurrentUser, rolename); } public static bool IsUserInRole (string username, string rolename) { return Provider.IsUserInRole (username, rolename); } public static void RemoveUserFromRole (string username, string rolename) { Provider.RemoveUsersFromRoles (new string[] {username}, new string[] {rolename}); } public static void RemoveUserFromRoles (string username, string [] rolenames) { Provider.RemoveUsersFromRoles (new string[] {username}, rolenames); } public static void RemoveUsersFromRole (string [] usernames, string rolename) { Provider.RemoveUsersFromRoles (usernames, new string[] {rolename}); } public static void RemoveUsersFromRoles (string [] usernames, string [] rolenames) { Provider.RemoveUsersFromRoles (usernames, rolenames); } public static bool RoleExists (string rolename) { return Provider.RoleExists (rolename); } public static string[] FinsUsersInRole (string rolename, string usernameToMatch) { return Provider.FindUsersInRole (rolename, usernameToMatch); } public static string ApplicationName { get { return Provider.ApplicationName; } set { Provider.ApplicationName = value; } } [MonoTODO] public static bool CacheRolesInCookie { get { throw new NotImplementedException (); } } [MonoTODO] public static string CookieName { get { throw new NotImplementedException (); } } [MonoTODO] public static string CookiePath { get { throw new NotImplementedException (); } } [MonoTODO] public static CookieProtection CookieProtectionValue { get { throw new NotImplementedException (); } } [MonoTODO] public static bool CookieRequireSSL { get { throw new NotImplementedException (); } } [MonoTODO] public static bool CookieSlidingExpiration { get { throw new NotImplementedException (); } } [MonoTODO] public static int CookieTimeout { get { throw new NotImplementedException (); } } [MonoTODO] public static bool Enabled { get { throw new NotImplementedException (); } } [MonoTODO] public static RoleProvider Provider { get { throw new NotImplementedException (); } } [MonoTODO] public static RoleProviderCollection Providers { get { throw new NotImplementedException (); } } } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Text; using Cats.Data.Repository; using Cats.Data.UnitWork; using Cats.Models.ViewModels; using Moq; using NUnit.Framework; using Cats.Services.Procurement; using Cats.Models; namespace Cats.Data.Tests.ServicesTest.Procurement { [TestFixture] public class TransportOrderTests { #region SetUp / TearDown private IList<ReliefRequisition> _reliefRequisitions; private IList<TransportOrder> _transportOrders; private TransportOrderService _transportOrderService; [SetUp] public void Init() { _reliefRequisitions = new List<ReliefRequisition>() { new ReliefRequisition() { RegionID = 1, ProgramID = 1, CommodityID = 1, ZoneID = 2, RequisitionNo = "REQ-001", Round = 1, RegionalRequestID = 1, RequisitionID = 1, Status = 1, AdminUnit = new AdminUnit { AdminUnitID = 2, Name = "Zone1" }, AdminUnit1 = new AdminUnit { AdminUnitID = 1, Name = "Region1" }, Commodity = new Commodity { CommodityID = 1, CommodityCode = "C1", Name = "CSB" }, HubAllocations = new List<HubAllocation>(){new HubAllocation() { HubAllocationID = 1, HubID = 1, RequisitionID = 1, Hub = new Hub { HubId = 1, Name = "Test Hub", } }}, ReliefRequisitionDetails = new Collection<ReliefRequisitionDetail> { new ReliefRequisitionDetail() { RequisitionID = 1, RequisitionDetailID = 1, Amount = 100, CommodityID = 1, FDPID = 1, BenficiaryNo = 10, DonorID = 1 }, new ReliefRequisitionDetail() { RequisitionID = 1, RequisitionDetailID = 2, Amount = 50, CommodityID = 1, FDPID = 2, BenficiaryNo = 10, DonorID = 1 }, new ReliefRequisitionDetail() { RequisitionID = 1, RequisitionDetailID = 3, Amount = 60, CommodityID = 1, FDPID = 1, BenficiaryNo = 10, DonorID = 1 }, new ReliefRequisitionDetail() { RequisitionID = 1, RequisitionDetailID = 4, Amount = 70, CommodityID = 1, FDPID = 2, BenficiaryNo = 10, DonorID = 1 } } } }; _transportOrders = new List<TransportOrder>(); //Arrange var mockUnitOfWork = new Mock<IUnitOfWork>(); var mockReliefRequisitionRepository = new Mock<IGenericRepository<ReliefRequisition>>(); mockReliefRequisitionRepository.Setup( t => t.Get(It.IsAny<Expression<Func<ReliefRequisition, bool>>>(), It.IsAny<Func<IQueryable<ReliefRequisition>, IOrderedQueryable<ReliefRequisition>>>(), It.IsAny<string>())).Returns( (Expression<Func<ReliefRequisition, bool>> perdicate, Func<IQueryable<ReliefRequisition>, IOrderedQueryable<ReliefRequisition>> obrderBy, string prop) => { var result = _reliefRequisitions.AsQueryable(); return result; } ); mockUnitOfWork.Setup(t => t.ReliefRequisitionRepository).Returns(mockReliefRequisitionRepository.Object); var transportOrderRepository = new Mock<IGenericRepository<TransportOrder>>(); transportOrderRepository.Setup( t => t.Get(It.IsAny<Expression<Func<TransportOrder, bool>>>(), null, It.IsAny<string>())).Returns( (Expression<Func<TransportOrder, bool>> perdicate, string prop) => { var result = _transportOrders . AsQueryable (); return result; } ); _transportOrderService = new TransportOrderService(mockUnitOfWork.Object); //Act } [TearDown] public void Dispose() { _transportOrderService.Dispose(); } #endregion #region Tests [Test] public void Can_Get_All_Requisions_With_Project_Code() { //Act var assignedRequisitons = _transportOrderService.GetProjectCodeAssignedRequisitions().ToList(); //Assert Assert.IsInstanceOf<IList<ReliefRequisition>>(assignedRequisitons); Assert.IsNotEmpty(assignedRequisitons); } [Test] public void Can_Generate_Requisiton_Ready_To_Dispatch() { //Act var requisitionToDispatch = _transportOrderService.GetRequisitionToDispatch().ToList(); //Assert Assert.IsInstanceOf<IList<RequisitionToDispatch>>(requisitionToDispatch); Assert.AreEqual(1, requisitionToDispatch.Count()); } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShuffleHighUInt160() { var test = new ImmUnaryOpTest__ShuffleHighUInt160(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShuffleHighUInt160 { private struct TestStruct { public Vector128<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShuffleHighUInt160 testClass) { var result = Sse2.ShuffleHigh(_fld, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar; private Vector128<UInt16> _fld; private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable; static ImmUnaryOpTest__ShuffleHighUInt160() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public ImmUnaryOpTest__ShuffleHighUInt160() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShuffleHigh( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShuffleHigh( Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShuffleHigh( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShuffleHigh), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShuffleHigh), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShuffleHigh), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShuffleHigh( _clsVar, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr); var result = Sse2.ShuffleHigh(firstOp, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)); var result = Sse2.ShuffleHigh(firstOp, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)); var result = Sse2.ShuffleHigh(firstOp, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShuffleHighUInt160(); var result = Sse2.ShuffleHigh(test._fld, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShuffleHigh(_fld, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShuffleHigh(test._fld, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i <= 3 ? (firstOp[i] != result[i]) : (firstOp[4] != result[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShuffleHigh)}<UInt16>(Vector128<UInt16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //Testing simple math on local vars and fields - sub #pragma warning disable 0414 using System; internal class lclfldsub { //user-defined class that overloads operator - public class numHolder { private int _i_num; private uint _ui_num; private long _l_num; private ulong _ul_num; private float _f_num; private double _d_num; private decimal _m_num; public numHolder(int i_num) { _i_num = Convert.ToInt32(i_num); _ui_num = Convert.ToUInt32(i_num); _l_num = Convert.ToInt64(i_num); _ul_num = Convert.ToUInt64(i_num); _f_num = Convert.ToSingle(i_num); _d_num = Convert.ToDouble(i_num); _m_num = Convert.ToDecimal(i_num); } public static int operator -(numHolder a, int b) { return a._i_num - b; } public numHolder(uint ui_num) { _i_num = Convert.ToInt32(ui_num); _ui_num = Convert.ToUInt32(ui_num); _l_num = Convert.ToInt64(ui_num); _ul_num = Convert.ToUInt64(ui_num); _f_num = Convert.ToSingle(ui_num); _d_num = Convert.ToDouble(ui_num); _m_num = Convert.ToDecimal(ui_num); } public static uint operator -(numHolder a, uint b) { return a._ui_num - b; } public numHolder(long l_num) { _i_num = Convert.ToInt32(l_num); _ui_num = Convert.ToUInt32(l_num); _l_num = Convert.ToInt64(l_num); _ul_num = Convert.ToUInt64(l_num); _f_num = Convert.ToSingle(l_num); _d_num = Convert.ToDouble(l_num); _m_num = Convert.ToDecimal(l_num); } public static long operator -(numHolder a, long b) { return a._l_num - b; } public numHolder(ulong ul_num) { _i_num = Convert.ToInt32(ul_num); _ui_num = Convert.ToUInt32(ul_num); _l_num = Convert.ToInt64(ul_num); _ul_num = Convert.ToUInt64(ul_num); _f_num = Convert.ToSingle(ul_num); _d_num = Convert.ToDouble(ul_num); _m_num = Convert.ToDecimal(ul_num); } public static long operator -(numHolder a, ulong b) { return (long)(a._ul_num - b); } public numHolder(float f_num) { _i_num = Convert.ToInt32(f_num); _ui_num = Convert.ToUInt32(f_num); _l_num = Convert.ToInt64(f_num); _ul_num = Convert.ToUInt64(f_num); _f_num = Convert.ToSingle(f_num); _d_num = Convert.ToDouble(f_num); _m_num = Convert.ToDecimal(f_num); } public static float operator -(numHolder a, float b) { return a._f_num - b; } public numHolder(double d_num) { _i_num = Convert.ToInt32(d_num); _ui_num = Convert.ToUInt32(d_num); _l_num = Convert.ToInt64(d_num); _ul_num = Convert.ToUInt64(d_num); _f_num = Convert.ToSingle(d_num); _d_num = Convert.ToDouble(d_num); _m_num = Convert.ToDecimal(d_num); } public static double operator -(numHolder a, double b) { return a._d_num - b; } public numHolder(decimal m_num) { _i_num = Convert.ToInt32(m_num); _ui_num = Convert.ToUInt32(m_num); _l_num = Convert.ToInt64(m_num); _ul_num = Convert.ToUInt64(m_num); _f_num = Convert.ToSingle(m_num); _d_num = Convert.ToDouble(m_num); _m_num = Convert.ToDecimal(m_num); } public static int operator -(numHolder a, decimal b) { return (int)(a._m_num - b); } public static int operator -(numHolder a, numHolder b) { return a._i_num - b._i_num; } } private static int s_i_s_op1 = 16; private static uint s_ui_s_op1 = 16; private static long s_l_s_op1 = 16; private static ulong s_ul_s_op1 = 16; private static float s_f_s_op1 = 16; private static double s_d_s_op1 = 16; private static decimal s_m_s_op1 = 16; private static int s_i_s_op2 = 15; private static uint s_ui_s_op2 = 15; private static long s_l_s_op2 = 15; private static ulong s_ul_s_op2 = 15; private static float s_f_s_op2 = 15; private static double s_d_s_op2 = 15; private static decimal s_m_s_op2 = 15; private static numHolder s_nHldr_s_op2 = new numHolder(15); public static int i_f(String s) { if (s == "op1") return 16; else return 15; } public static uint ui_f(String s) { if (s == "op1") return 16; else return 15; } public static long l_f(String s) { if (s == "op1") return 16; else return 15; } public static ulong ul_f(String s) { if (s == "op1") return 16; else return 15; } public static float f_f(String s) { if (s == "op1") return 16; else return 15; } public static double d_f(String s) { if (s == "op1") return 16; else return 15; } public static decimal m_f(String s) { if (s == "op1") return 16; else return 15; } public static numHolder nHldr_f(String s) { if (s == "op1") return new numHolder(16); else return new numHolder(15); } private class CL { public int i_cl_op1 = 16; public uint ui_cl_op1 = 16; public long l_cl_op1 = 16; public ulong ul_cl_op1 = 16; public float f_cl_op1 = 16; public double d_cl_op1 = 16; public decimal m_cl_op1 = 16; public int i_cl_op2 = 15; public uint ui_cl_op2 = 15; public long l_cl_op2 = 15; public ulong ul_cl_op2 = 15; public float f_cl_op2 = 15; public double d_cl_op2 = 15; public decimal m_cl_op2 = 15; public numHolder nHldr_cl_op2 = new numHolder(15); } private struct VT { public int i_vt_op1; public uint ui_vt_op1; public long l_vt_op1; public ulong ul_vt_op1; public float f_vt_op1; public double d_vt_op1; public decimal m_vt_op1; public int i_vt_op2; public uint ui_vt_op2; public long l_vt_op2; public ulong ul_vt_op2; public float f_vt_op2; public double d_vt_op2; public decimal m_vt_op2; public numHolder nHldr_vt_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.i_vt_op1 = 16; vt1.ui_vt_op1 = 16; vt1.l_vt_op1 = 16; vt1.ul_vt_op1 = 16; vt1.f_vt_op1 = 16; vt1.d_vt_op1 = 16; vt1.m_vt_op1 = 16; vt1.i_vt_op2 = 15; vt1.ui_vt_op2 = 15; vt1.l_vt_op2 = 15; vt1.ul_vt_op2 = 15; vt1.f_vt_op2 = 15; vt1.d_vt_op2 = 15; vt1.m_vt_op2 = 15; vt1.nHldr_vt_op2 = new numHolder(15); int[] i_arr1d_op1 = { 0, 16 }; int[,] i_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; int[,,] i_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; uint[] ui_arr1d_op1 = { 0, 16 }; uint[,] ui_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; uint[,,] ui_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; long[] l_arr1d_op1 = { 0, 16 }; long[,] l_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; long[,,] l_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; ulong[] ul_arr1d_op1 = { 0, 16 }; ulong[,] ul_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; ulong[,,] ul_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; float[] f_arr1d_op1 = { 0, 16 }; float[,] f_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; float[,,] f_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; double[] d_arr1d_op1 = { 0, 16 }; double[,] d_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; double[,,] d_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; decimal[] m_arr1d_op1 = { 0, 16 }; decimal[,] m_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; decimal[,,] m_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; int[] i_arr1d_op2 = { 15, 0, 1 }; int[,] i_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; int[,,] i_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; uint[] ui_arr1d_op2 = { 15, 0, 1 }; uint[,] ui_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; uint[,,] ui_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; long[] l_arr1d_op2 = { 15, 0, 1 }; long[,] l_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; long[,,] l_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; ulong[] ul_arr1d_op2 = { 15, 0, 1 }; ulong[,] ul_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; ulong[,,] ul_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; float[] f_arr1d_op2 = { 15, 0, 1 }; float[,] f_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; float[,,] f_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; double[] d_arr1d_op2 = { 15, 0, 1 }; double[,] d_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; double[,,] d_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; decimal[] m_arr1d_op2 = { 15, 0, 1 }; decimal[,] m_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; decimal[,,] m_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; numHolder[] nHldr_arr1d_op2 = { new numHolder(15), new numHolder(0), new numHolder(1) }; numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } }; numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { int i_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((i_l_op1 - i_l_op2 != i_l_op1 - ui_l_op2) || (i_l_op1 - ui_l_op2 != i_l_op1 - l_l_op2) || (i_l_op1 - l_l_op2 != i_l_op1 - (int)ul_l_op2) || (i_l_op1 - (int)ul_l_op2 != i_l_op1 - f_l_op2) || (i_l_op1 - f_l_op2 != i_l_op1 - d_l_op2) || ((decimal)(i_l_op1 - d_l_op2) != i_l_op1 - m_l_op2) || (i_l_op1 - m_l_op2 != i_l_op1 - i_l_op2) || (i_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 1 failed"); passed = false; } if ((i_l_op1 - s_i_s_op2 != i_l_op1 - s_ui_s_op2) || (i_l_op1 - s_ui_s_op2 != i_l_op1 - s_l_s_op2) || (i_l_op1 - s_l_s_op2 != i_l_op1 - (int)s_ul_s_op2) || (i_l_op1 - (int)s_ul_s_op2 != i_l_op1 - s_f_s_op2) || (i_l_op1 - s_f_s_op2 != i_l_op1 - s_d_s_op2) || ((decimal)(i_l_op1 - s_d_s_op2) != i_l_op1 - s_m_s_op2) || (i_l_op1 - s_m_s_op2 != i_l_op1 - s_i_s_op2) || (i_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 2 failed"); passed = false; } if ((s_i_s_op1 - i_l_op2 != s_i_s_op1 - ui_l_op2) || (s_i_s_op1 - ui_l_op2 != s_i_s_op1 - l_l_op2) || (s_i_s_op1 - l_l_op2 != s_i_s_op1 - (int)ul_l_op2) || (s_i_s_op1 - (int)ul_l_op2 != s_i_s_op1 - f_l_op2) || (s_i_s_op1 - f_l_op2 != s_i_s_op1 - d_l_op2) || ((decimal)(s_i_s_op1 - d_l_op2) != s_i_s_op1 - m_l_op2) || (s_i_s_op1 - m_l_op2 != s_i_s_op1 - i_l_op2) || (s_i_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 3 failed"); passed = false; } if ((s_i_s_op1 - s_i_s_op2 != s_i_s_op1 - s_ui_s_op2) || (s_i_s_op1 - s_ui_s_op2 != s_i_s_op1 - s_l_s_op2) || (s_i_s_op1 - s_l_s_op2 != s_i_s_op1 - (int)s_ul_s_op2) || (s_i_s_op1 - (int)s_ul_s_op2 != s_i_s_op1 - s_f_s_op2) || (s_i_s_op1 - s_f_s_op2 != s_i_s_op1 - s_d_s_op2) || ((decimal)(s_i_s_op1 - s_d_s_op2) != s_i_s_op1 - s_m_s_op2) || (s_i_s_op1 - s_m_s_op2 != s_i_s_op1 - s_i_s_op2) || (s_i_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 4 failed"); passed = false; } } { uint ui_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ui_l_op1 - i_l_op2 != ui_l_op1 - ui_l_op2) || (ui_l_op1 - ui_l_op2 != ui_l_op1 - l_l_op2) || ((ulong)(ui_l_op1 - l_l_op2) != ui_l_op1 - ul_l_op2) || (ui_l_op1 - ul_l_op2 != ui_l_op1 - f_l_op2) || (ui_l_op1 - f_l_op2 != ui_l_op1 - d_l_op2) || ((decimal)(ui_l_op1 - d_l_op2) != ui_l_op1 - m_l_op2) || (ui_l_op1 - m_l_op2 != ui_l_op1 - i_l_op2) || (ui_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 5 failed"); passed = false; } if ((ui_l_op1 - s_i_s_op2 != ui_l_op1 - s_ui_s_op2) || (ui_l_op1 - s_ui_s_op2 != ui_l_op1 - s_l_s_op2) || ((ulong)(ui_l_op1 - s_l_s_op2) != ui_l_op1 - s_ul_s_op2) || (ui_l_op1 - s_ul_s_op2 != ui_l_op1 - s_f_s_op2) || (ui_l_op1 - s_f_s_op2 != ui_l_op1 - s_d_s_op2) || ((decimal)(ui_l_op1 - s_d_s_op2) != ui_l_op1 - s_m_s_op2) || (ui_l_op1 - s_m_s_op2 != ui_l_op1 - s_i_s_op2) || (ui_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 6 failed"); passed = false; } if ((s_ui_s_op1 - i_l_op2 != s_ui_s_op1 - ui_l_op2) || (s_ui_s_op1 - ui_l_op2 != s_ui_s_op1 - l_l_op2) || ((ulong)(s_ui_s_op1 - l_l_op2) != s_ui_s_op1 - ul_l_op2) || (s_ui_s_op1 - ul_l_op2 != s_ui_s_op1 - f_l_op2) || (s_ui_s_op1 - f_l_op2 != s_ui_s_op1 - d_l_op2) || ((decimal)(s_ui_s_op1 - d_l_op2) != s_ui_s_op1 - m_l_op2) || (s_ui_s_op1 - m_l_op2 != s_ui_s_op1 - i_l_op2) || (s_ui_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 7 failed"); passed = false; } if ((s_ui_s_op1 - s_i_s_op2 != s_ui_s_op1 - s_ui_s_op2) || (s_ui_s_op1 - s_ui_s_op2 != s_ui_s_op1 - s_l_s_op2) || ((ulong)(s_ui_s_op1 - s_l_s_op2) != s_ui_s_op1 - s_ul_s_op2) || (s_ui_s_op1 - s_ul_s_op2 != s_ui_s_op1 - s_f_s_op2) || (s_ui_s_op1 - s_f_s_op2 != s_ui_s_op1 - s_d_s_op2) || ((decimal)(s_ui_s_op1 - s_d_s_op2) != s_ui_s_op1 - s_m_s_op2) || (s_ui_s_op1 - s_m_s_op2 != s_ui_s_op1 - s_i_s_op2) || (s_ui_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 8 failed"); passed = false; } } { long l_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((l_l_op1 - i_l_op2 != l_l_op1 - ui_l_op2) || (l_l_op1 - ui_l_op2 != l_l_op1 - l_l_op2) || (l_l_op1 - l_l_op2 != l_l_op1 - (long)ul_l_op2) || (l_l_op1 - (long)ul_l_op2 != l_l_op1 - f_l_op2) || (l_l_op1 - f_l_op2 != l_l_op1 - d_l_op2) || ((decimal)(l_l_op1 - d_l_op2) != l_l_op1 - m_l_op2) || (l_l_op1 - m_l_op2 != l_l_op1 - i_l_op2) || (l_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 9 failed"); passed = false; } if ((l_l_op1 - s_i_s_op2 != l_l_op1 - s_ui_s_op2) || (l_l_op1 - s_ui_s_op2 != l_l_op1 - s_l_s_op2) || (l_l_op1 - s_l_s_op2 != l_l_op1 - (long)s_ul_s_op2) || (l_l_op1 - (long)s_ul_s_op2 != l_l_op1 - s_f_s_op2) || (l_l_op1 - s_f_s_op2 != l_l_op1 - s_d_s_op2) || ((decimal)(l_l_op1 - s_d_s_op2) != l_l_op1 - s_m_s_op2) || (l_l_op1 - s_m_s_op2 != l_l_op1 - s_i_s_op2) || (l_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 10 failed"); passed = false; } if ((s_l_s_op1 - i_l_op2 != s_l_s_op1 - ui_l_op2) || (s_l_s_op1 - ui_l_op2 != s_l_s_op1 - l_l_op2) || (s_l_s_op1 - l_l_op2 != s_l_s_op1 - (long)ul_l_op2) || (s_l_s_op1 - (long)ul_l_op2 != s_l_s_op1 - f_l_op2) || (s_l_s_op1 - f_l_op2 != s_l_s_op1 - d_l_op2) || ((decimal)(s_l_s_op1 - d_l_op2) != s_l_s_op1 - m_l_op2) || (s_l_s_op1 - m_l_op2 != s_l_s_op1 - i_l_op2) || (s_l_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 11 failed"); passed = false; } if ((s_l_s_op1 - s_i_s_op2 != s_l_s_op1 - s_ui_s_op2) || (s_l_s_op1 - s_ui_s_op2 != s_l_s_op1 - s_l_s_op2) || (s_l_s_op1 - s_l_s_op2 != s_l_s_op1 - (long)s_ul_s_op2) || (s_l_s_op1 - (long)s_ul_s_op2 != s_l_s_op1 - s_f_s_op2) || (s_l_s_op1 - s_f_s_op2 != s_l_s_op1 - s_d_s_op2) || ((decimal)(s_l_s_op1 - s_d_s_op2) != s_l_s_op1 - s_m_s_op2) || (s_l_s_op1 - s_m_s_op2 != s_l_s_op1 - s_i_s_op2) || (s_l_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 12 failed"); passed = false; } } { ulong ul_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ul_l_op1 - (ulong)i_l_op2 != ul_l_op1 - ui_l_op2) || (ul_l_op1 - ui_l_op2 != ul_l_op1 - (ulong)l_l_op2) || (ul_l_op1 - (ulong)l_l_op2 != ul_l_op1 - ul_l_op2) || (ul_l_op1 - ul_l_op2 != ul_l_op1 - f_l_op2) || (ul_l_op1 - f_l_op2 != ul_l_op1 - d_l_op2) || ((decimal)(ul_l_op1 - d_l_op2) != ul_l_op1 - m_l_op2) || (ul_l_op1 - m_l_op2 != ul_l_op1 - (ulong)i_l_op2) || (ul_l_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 13 failed"); passed = false; } if ((ul_l_op1 - (ulong)s_i_s_op2 != ul_l_op1 - s_ui_s_op2) || (ul_l_op1 - s_ui_s_op2 != ul_l_op1 - (ulong)s_l_s_op2) || (ul_l_op1 - (ulong)s_l_s_op2 != ul_l_op1 - s_ul_s_op2) || (ul_l_op1 - s_ul_s_op2 != ul_l_op1 - s_f_s_op2) || (ul_l_op1 - s_f_s_op2 != ul_l_op1 - s_d_s_op2) || ((decimal)(ul_l_op1 - s_d_s_op2) != ul_l_op1 - s_m_s_op2) || (ul_l_op1 - s_m_s_op2 != ul_l_op1 - (ulong)s_i_s_op2) || (ul_l_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 14 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)i_l_op2 != s_ul_s_op1 - ui_l_op2) || (s_ul_s_op1 - ui_l_op2 != s_ul_s_op1 - (ulong)l_l_op2) || (s_ul_s_op1 - (ulong)l_l_op2 != s_ul_s_op1 - ul_l_op2) || (s_ul_s_op1 - ul_l_op2 != s_ul_s_op1 - f_l_op2) || (s_ul_s_op1 - f_l_op2 != s_ul_s_op1 - d_l_op2) || ((decimal)(s_ul_s_op1 - d_l_op2) != s_ul_s_op1 - m_l_op2) || (s_ul_s_op1 - m_l_op2 != s_ul_s_op1 - (ulong)i_l_op2) || (s_ul_s_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 15 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)s_i_s_op2 != s_ul_s_op1 - s_ui_s_op2) || (s_ul_s_op1 - s_ui_s_op2 != s_ul_s_op1 - (ulong)s_l_s_op2) || (s_ul_s_op1 - (ulong)s_l_s_op2 != s_ul_s_op1 - s_ul_s_op2) || (s_ul_s_op1 - s_ul_s_op2 != s_ul_s_op1 - s_f_s_op2) || (s_ul_s_op1 - s_f_s_op2 != s_ul_s_op1 - s_d_s_op2) || ((decimal)(s_ul_s_op1 - s_d_s_op2) != s_ul_s_op1 - s_m_s_op2) || (s_ul_s_op1 - s_m_s_op2 != s_ul_s_op1 - (ulong)s_i_s_op2) || (s_ul_s_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 16 failed"); passed = false; } } { float f_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((f_l_op1 - i_l_op2 != f_l_op1 - ui_l_op2) || (f_l_op1 - ui_l_op2 != f_l_op1 - l_l_op2) || (f_l_op1 - l_l_op2 != f_l_op1 - ul_l_op2) || (f_l_op1 - ul_l_op2 != f_l_op1 - f_l_op2) || (f_l_op1 - f_l_op2 != f_l_op1 - d_l_op2) || (f_l_op1 - d_l_op2 != f_l_op1 - (float)m_l_op2) || (f_l_op1 - (float)m_l_op2 != f_l_op1 - i_l_op2) || (f_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 17 failed"); passed = false; } if ((f_l_op1 - s_i_s_op2 != f_l_op1 - s_ui_s_op2) || (f_l_op1 - s_ui_s_op2 != f_l_op1 - s_l_s_op2) || (f_l_op1 - s_l_s_op2 != f_l_op1 - s_ul_s_op2) || (f_l_op1 - s_ul_s_op2 != f_l_op1 - s_f_s_op2) || (f_l_op1 - s_f_s_op2 != f_l_op1 - s_d_s_op2) || (f_l_op1 - s_d_s_op2 != f_l_op1 - (float)s_m_s_op2) || (f_l_op1 - (float)s_m_s_op2 != f_l_op1 - s_i_s_op2) || (f_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 18 failed"); passed = false; } if ((s_f_s_op1 - i_l_op2 != s_f_s_op1 - ui_l_op2) || (s_f_s_op1 - ui_l_op2 != s_f_s_op1 - l_l_op2) || (s_f_s_op1 - l_l_op2 != s_f_s_op1 - ul_l_op2) || (s_f_s_op1 - ul_l_op2 != s_f_s_op1 - f_l_op2) || (s_f_s_op1 - f_l_op2 != s_f_s_op1 - d_l_op2) || (s_f_s_op1 - d_l_op2 != s_f_s_op1 - (float)m_l_op2) || (s_f_s_op1 - (float)m_l_op2 != s_f_s_op1 - i_l_op2) || (s_f_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 19 failed"); passed = false; } if ((s_f_s_op1 - s_i_s_op2 != s_f_s_op1 - s_ui_s_op2) || (s_f_s_op1 - s_ui_s_op2 != s_f_s_op1 - s_l_s_op2) || (s_f_s_op1 - s_l_s_op2 != s_f_s_op1 - s_ul_s_op2) || (s_f_s_op1 - s_ul_s_op2 != s_f_s_op1 - s_f_s_op2) || (s_f_s_op1 - s_f_s_op2 != s_f_s_op1 - s_d_s_op2) || (s_f_s_op1 - s_d_s_op2 != s_f_s_op1 - (float)s_m_s_op2) || (s_f_s_op1 - (float)s_m_s_op2 != s_f_s_op1 - s_i_s_op2) || (s_f_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 20 failed"); passed = false; } } { double d_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((d_l_op1 - i_l_op2 != d_l_op1 - ui_l_op2) || (d_l_op1 - ui_l_op2 != d_l_op1 - l_l_op2) || (d_l_op1 - l_l_op2 != d_l_op1 - ul_l_op2) || (d_l_op1 - ul_l_op2 != d_l_op1 - f_l_op2) || (d_l_op1 - f_l_op2 != d_l_op1 - d_l_op2) || (d_l_op1 - d_l_op2 != d_l_op1 - (double)m_l_op2) || (d_l_op1 - (double)m_l_op2 != d_l_op1 - i_l_op2) || (d_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 21 failed"); passed = false; } if ((d_l_op1 - s_i_s_op2 != d_l_op1 - s_ui_s_op2) || (d_l_op1 - s_ui_s_op2 != d_l_op1 - s_l_s_op2) || (d_l_op1 - s_l_s_op2 != d_l_op1 - s_ul_s_op2) || (d_l_op1 - s_ul_s_op2 != d_l_op1 - s_f_s_op2) || (d_l_op1 - s_f_s_op2 != d_l_op1 - s_d_s_op2) || (d_l_op1 - s_d_s_op2 != d_l_op1 - (double)s_m_s_op2) || (d_l_op1 - (double)s_m_s_op2 != d_l_op1 - s_i_s_op2) || (d_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 22 failed"); passed = false; } if ((s_d_s_op1 - i_l_op2 != s_d_s_op1 - ui_l_op2) || (s_d_s_op1 - ui_l_op2 != s_d_s_op1 - l_l_op2) || (s_d_s_op1 - l_l_op2 != s_d_s_op1 - ul_l_op2) || (s_d_s_op1 - ul_l_op2 != s_d_s_op1 - f_l_op2) || (s_d_s_op1 - f_l_op2 != s_d_s_op1 - d_l_op2) || (s_d_s_op1 - d_l_op2 != s_d_s_op1 - (double)m_l_op2) || (s_d_s_op1 - (double)m_l_op2 != s_d_s_op1 - i_l_op2) || (s_d_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 23 failed"); passed = false; } if ((s_d_s_op1 - s_i_s_op2 != s_d_s_op1 - s_ui_s_op2) || (s_d_s_op1 - s_ui_s_op2 != s_d_s_op1 - s_l_s_op2) || (s_d_s_op1 - s_l_s_op2 != s_d_s_op1 - s_ul_s_op2) || (s_d_s_op1 - s_ul_s_op2 != s_d_s_op1 - s_f_s_op2) || (s_d_s_op1 - s_f_s_op2 != s_d_s_op1 - s_d_s_op2) || (s_d_s_op1 - s_d_s_op2 != s_d_s_op1 - (double)s_m_s_op2) || (s_d_s_op1 - (double)s_m_s_op2 != s_d_s_op1 - s_i_s_op2) || (s_d_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 24 failed"); passed = false; } } { decimal m_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((m_l_op1 - i_l_op2 != m_l_op1 - ui_l_op2) || (m_l_op1 - ui_l_op2 != m_l_op1 - l_l_op2) || (m_l_op1 - l_l_op2 != m_l_op1 - ul_l_op2) || (m_l_op1 - ul_l_op2 != m_l_op1 - (decimal)f_l_op2) || (m_l_op1 - (decimal)f_l_op2 != m_l_op1 - (decimal)d_l_op2) || (m_l_op1 - (decimal)d_l_op2 != m_l_op1 - m_l_op2) || (m_l_op1 - m_l_op2 != m_l_op1 - i_l_op2) || (m_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 25 failed"); passed = false; } if ((m_l_op1 - s_i_s_op2 != m_l_op1 - s_ui_s_op2) || (m_l_op1 - s_ui_s_op2 != m_l_op1 - s_l_s_op2) || (m_l_op1 - s_l_s_op2 != m_l_op1 - s_ul_s_op2) || (m_l_op1 - s_ul_s_op2 != m_l_op1 - (decimal)s_f_s_op2) || (m_l_op1 - (decimal)s_f_s_op2 != m_l_op1 - (decimal)s_d_s_op2) || (m_l_op1 - (decimal)s_d_s_op2 != m_l_op1 - s_m_s_op2) || (m_l_op1 - s_m_s_op2 != m_l_op1 - s_i_s_op2) || (m_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 26 failed"); passed = false; } if ((s_m_s_op1 - i_l_op2 != s_m_s_op1 - ui_l_op2) || (s_m_s_op1 - ui_l_op2 != s_m_s_op1 - l_l_op2) || (s_m_s_op1 - l_l_op2 != s_m_s_op1 - ul_l_op2) || (s_m_s_op1 - ul_l_op2 != s_m_s_op1 - (decimal)f_l_op2) || (s_m_s_op1 - (decimal)f_l_op2 != s_m_s_op1 - (decimal)d_l_op2) || (s_m_s_op1 - (decimal)d_l_op2 != s_m_s_op1 - m_l_op2) || (s_m_s_op1 - m_l_op2 != s_m_s_op1 - i_l_op2) || (s_m_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 27 failed"); passed = false; } if ((s_m_s_op1 - s_i_s_op2 != s_m_s_op1 - s_ui_s_op2) || (s_m_s_op1 - s_ui_s_op2 != s_m_s_op1 - s_l_s_op2) || (s_m_s_op1 - s_l_s_op2 != s_m_s_op1 - s_ul_s_op2) || (s_m_s_op1 - s_ul_s_op2 != s_m_s_op1 - (decimal)s_f_s_op2) || (s_m_s_op1 - (decimal)s_f_s_op2 != s_m_s_op1 - (decimal)s_d_s_op2) || (s_m_s_op1 - (decimal)s_d_s_op2 != s_m_s_op1 - s_m_s_op2) || (s_m_s_op1 - s_m_s_op2 != s_m_s_op1 - s_i_s_op2) || (s_m_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 28 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
using System; using NullGuard; public class SimpleClass { public SimpleClass() { } // Why would anyone place an out parameter on a ctor?! I don't know, but I'll support your idiocy. public SimpleClass(out string nonNullOutArg) { nonNullOutArg = null; } public SimpleClass(string nonNullArg, [AllowNull] string nullArg) { Console.WriteLine(nonNullArg + " " + nullArg); } public void SomeMethod(string nonNullArg, [AllowNull] string nullArg) { Console.WriteLine(nonNullArg); } public string NonNullProperty { get; set; } [AllowNull] public string NullProperty { get; set; } public string PropertyAllowsNullGetButDoesNotAllowNullSet { [return: AllowNull] get; set; } public string PropertyAllowsNullSetButDoesNotAllowNullGet { get; [param: AllowNull] set; } public int? NonNullNullableProperty { get; set; } public string MethodWithReturnValue(bool returnNull) { return returnNull ? null : ""; } public void MethodWithRef(ref object returnNull) { } public void MethodWithGeneric<T>(T returnNull) { } public void MethodWithGenericRef<T>(ref T returnNull) { } [return: AllowNull] public string MethodAllowsNullReturnValue() { return null; } [CanBeNull] public string MethodWithCanBeNullResult() { return null; } public void MethodWithOutValue(out string nonNullOutArg) { nonNullOutArg = null; } public void MethodWithAllowedNullOutValue([AllowNull]out string nonNullOutArg) { nonNullOutArg = null; } public void PublicWrapperOfPrivateMethod() { SomePrivateMethod(null); } void SomePrivateMethod(string x) { Console.WriteLine(x); } public void MethodWithTwoRefs(ref string first, ref string second) { } public void MethodWithTwoOuts(out string first, out string second) { first = null; second = null; } public void MethodWithOptionalParameter(string optional = null) { } public void MethodWithOptionalParameterWithNonNullDefaultValue(string optional = "default") { } public void MethodWithOptionalParameterWithNonNullDefaultValueButAllowNullAttribute([AllowNull] string optional = "default") { } public void MethodWithGenericOut<T>(out T item) { item = default; } public T MethodWithGenericReturn<T>(bool returnNull) { return returnNull ? default : Activator.CreateInstance<T>(); } public object MethodWithOutAndReturn(out string prefix) { prefix = null; return null; } public void MethodWithExistingArgumentGuard(string x) { if (string.IsNullOrEmpty(x)) throw new ArgumentException("x is null or empty.", "x"); Console.WriteLine(x); } public void MethodWithExistingArgumentNullGuard(string x) { if (string.IsNullOrEmpty(x)) throw new ArgumentNullException("x"); Console.WriteLine(x); } public void MethodWithExistingArgumentNullGuardWithMessage(string x) { if (string.IsNullOrEmpty(x)) throw new ArgumentNullException("x", "x is null or empty."); Console.WriteLine(x); } public string ReturnValueChecksWithBranchToRetInstruction() { // This is a regression test scenario for the "Branch to RET" issue described in https://github.com/Fody/NullGuard/issues/57. // It is important that the return value is assigned *before* the branch, otherwise the C# compiler emits // instructions before the RET instructions, which wouldn't trigger the original issue. string returnValue = null; // The following, not-reachable, branch will jump directly to the RET statement (at least with Roslyn 1.0 with // enabled optimizations flag) which triggers the issue (the return value checks will be skipped). if ("".Length == 42) throw new Exception("Not reachable"); return returnValue; } public void OutValueChecksWithBranchToRetInstruction(out string outParam) { // This is the same scenario as above, but for out parameters. outParam = null; if ("".Length == 42) throw new Exception("Not reachable"); } public string GetterReturnValueChecksWithBranchToRetInstruction { get { // This is the same scenario as above, but for property getters. string returnValue = null; if ("".Length == 42) throw new Exception("Not reachable"); return returnValue; } } public void OutValueChecksWithRetInstructionAsSwitchCase(int i, out string outParam) { // This is the same scenario as above, but with a SWITCH instruction with branch targets to RET // instructions (they are handled specially). // Note that its important to have more than sections to prove that all sections with only a RET instruction are handled. outParam = null; switch (i) { case 0: return; case 1: Console.WriteLine("1"); break; case 2: return; case 3: Console.WriteLine("3"); break; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Text; using System.Threading.Tasks; using Avalonia.Controls; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.FreeDesktop; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Input.TextInput; using Avalonia.OpenGL; using Avalonia.OpenGL.Egl; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.X11.Glx; using static Avalonia.X11.XLib; // ReSharper disable IdentifierTypo // ReSharper disable StringLiteralTypo namespace Avalonia.X11 { unsafe partial class X11Window : IWindowImpl, IPopupImpl, IXI2Client, ITopLevelImplWithNativeMenuExporter, ITopLevelImplWithNativeControlHost, ITopLevelImplWithTextInputMethod { private readonly AvaloniaX11Platform _platform; private readonly bool _popup; private readonly X11Info _x11; private XConfigureEvent? _configure; private PixelPoint? _configurePoint; private bool _triggeredExpose; private IInputRoot _inputRoot; private readonly MouseDevice _mouse; private readonly TouchDevice _touch; private readonly IKeyboardDevice _keyboard; private PixelPoint? _position; private PixelSize _realSize; private IntPtr _handle; private IntPtr _xic; private IntPtr _renderHandle; private bool _mapped; private bool _wasMappedAtLeastOnce = false; private double? _scalingOverride; private bool _disabled; private TransparencyHelper _transparencyHelper; public object SyncRoot { get; } = new object(); class InputEventContainer { public RawInputEventArgs Event; } private readonly Queue<InputEventContainer> _inputQueue = new Queue<InputEventContainer>(); private InputEventContainer _lastEvent; private bool _useRenderWindow = false; public X11Window(AvaloniaX11Platform platform, IWindowImpl popupParent) { _platform = platform; _popup = popupParent != null; _x11 = platform.Info; _mouse = new MouseDevice(); _touch = new TouchDevice(); _keyboard = platform.KeyboardDevice; var glfeature = AvaloniaLocator.Current.GetService<IPlatformOpenGlInterface>(); XSetWindowAttributes attr = new XSetWindowAttributes(); var valueMask = default(SetWindowValuemask); attr.backing_store = 1; attr.bit_gravity = Gravity.NorthWestGravity; attr.win_gravity = Gravity.NorthWestGravity; valueMask |= SetWindowValuemask.BackPixel | SetWindowValuemask.BorderPixel | SetWindowValuemask.BackPixmap | SetWindowValuemask.BackingStore | SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity; if (_popup) { attr.override_redirect = 1; valueMask |= SetWindowValuemask.OverrideRedirect; } XVisualInfo? visualInfo = null; // OpenGL seems to be do weird things to it's current window which breaks resize sometimes _useRenderWindow = glfeature != null; var glx = glfeature as GlxPlatformOpenGlInterface; if (glx != null) visualInfo = *glx.Display.VisualInfo; else if (glfeature == null) visualInfo = _x11.TransparentVisualInfo; var egl = glfeature as EglPlatformOpenGlInterface; var visual = IntPtr.Zero; var depth = 24; if (visualInfo != null) { visual = visualInfo.Value.visual; depth = (int)visualInfo.Value.depth; attr.colormap = XCreateColormap(_x11.Display, _x11.RootWindow, visualInfo.Value.visual, 0); valueMask |= SetWindowValuemask.ColorMap; } int defaultWidth = 0, defaultHeight = 0; if (!_popup && Screen != null) { var monitor = Screen.AllScreens.OrderBy(x => x.PixelDensity) .FirstOrDefault(m => m.Bounds.Contains(Position)); if (monitor != null) { // Emulate Window 7+'s default window size behavior. defaultWidth = (int)(monitor.WorkingArea.Width * 0.75d); defaultHeight = (int)(monitor.WorkingArea.Height * 0.7d); } } // check if the calculated size is zero then compensate to hardcoded resolution defaultWidth = Math.Max(defaultWidth, 300); defaultHeight = Math.Max(defaultHeight, 200); _handle = XCreateWindow(_x11.Display, _x11.RootWindow, 10, 10, defaultWidth, defaultHeight, 0, depth, (int)CreateWindowArgs.InputOutput, visual, new UIntPtr((uint)valueMask), ref attr); if (_useRenderWindow) _renderHandle = XCreateWindow(_x11.Display, _handle, 0, 0, defaultWidth, defaultHeight, 0, depth, (int)CreateWindowArgs.InputOutput, visual, new UIntPtr((uint)(SetWindowValuemask.BorderPixel | SetWindowValuemask.BitGravity | SetWindowValuemask.WinGravity | SetWindowValuemask.BackingStore)), ref attr); else _renderHandle = _handle; Handle = new PlatformHandle(_handle, "XID"); _realSize = new PixelSize(defaultWidth, defaultHeight); platform.Windows[_handle] = OnEvent; XEventMask ignoredMask = XEventMask.SubstructureRedirectMask | XEventMask.ResizeRedirectMask | XEventMask.PointerMotionHintMask; if (platform.XI2 != null) ignoredMask |= platform.XI2.AddWindow(_handle, this); var mask = new IntPtr(0xffffff ^ (int)ignoredMask); XSelectInput(_x11.Display, _handle, mask); var protocols = new[] { _x11.Atoms.WM_DELETE_WINDOW }; XSetWMProtocols(_x11.Display, _handle, protocols, protocols.Length); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_WINDOW_TYPE, _x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, new[] {_x11.Atoms._NET_WM_WINDOW_TYPE_NORMAL}, 1); if (platform.Options.WmClass != null) SetWmClass(platform.Options.WmClass); var surfaces = new List<object> { new X11FramebufferSurface(_x11.DeferredDisplay, _renderHandle, depth, () => RenderScaling) }; if (egl != null) surfaces.Insert(0, new EglGlPlatformSurface(egl, new SurfaceInfo(this, _x11.DeferredDisplay, _handle, _renderHandle))); if (glx != null) surfaces.Insert(0, new GlxGlPlatformSurface(glx.Display, glx.DeferredContext, new SurfaceInfo(this, _x11.Display, _handle, _renderHandle))); Surfaces = surfaces.ToArray(); UpdateMotifHints(); UpdateSizeHints(null); _transparencyHelper = new TransparencyHelper(_x11, _handle, platform.Globals); _transparencyHelper.SetTransparencyRequest(WindowTransparencyLevel.None); CreateIC(); XFlush(_x11.Display); if(_popup) PopupPositioner = new ManagedPopupPositioner(new ManagedPopupPositionerPopupImplHelper(popupParent, MoveResize)); if (platform.Options.UseDBusMenu) NativeMenuExporter = DBusMenuExporter.TryCreate(_handle); NativeControlHost = new X11NativeControlHost(_platform, this); DispatcherTimer.Run(() => { Paint?.Invoke(default); return _handle != IntPtr.Zero; }, TimeSpan.FromMilliseconds(100)); InitializeIme(); } class SurfaceInfo : EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo { private readonly X11Window _window; private readonly IntPtr _display; private readonly IntPtr _parent; public SurfaceInfo(X11Window window, IntPtr display, IntPtr parent, IntPtr xid) { _window = window; _display = display; _parent = parent; Handle = xid; } public IntPtr Handle { get; } public PixelSize Size { get { XLockDisplay(_display); XGetGeometry(_display, _parent, out var geo); XResizeWindow(_display, Handle, geo.width, geo.height); XUnlockDisplay(_display); return new PixelSize(geo.width, geo.height); } } public double Scaling => _window.RenderScaling; } void UpdateMotifHints() { var functions = MotifFunctions.Move | MotifFunctions.Close | MotifFunctions.Resize | MotifFunctions.Minimize | MotifFunctions.Maximize; var decorations = MotifDecorations.Menu | MotifDecorations.Title | MotifDecorations.Border | MotifDecorations.Maximize | MotifDecorations.Minimize | MotifDecorations.ResizeH; if (_popup || _systemDecorations == SystemDecorations.None) decorations = 0; if (!_canResize) { functions &= ~(MotifFunctions.Resize | MotifFunctions.Maximize); decorations &= ~(MotifDecorations.Maximize | MotifDecorations.ResizeH); } var hints = new MotifWmHints { flags = new IntPtr((int)(MotifFlags.Decorations | MotifFlags.Functions)), decorations = new IntPtr((int)decorations), functions = new IntPtr((int)functions) }; XChangeProperty(_x11.Display, _handle, _x11.Atoms._MOTIF_WM_HINTS, _x11.Atoms._MOTIF_WM_HINTS, 32, PropertyMode.Replace, ref hints, 5); } void UpdateSizeHints(PixelSize? preResize) { var min = _minMaxSize.minSize; var max = _minMaxSize.maxSize; if (!_canResize) max = min = _realSize; if (preResize.HasValue) { var desired = preResize.Value; max = new PixelSize(Math.Max(desired.Width, max.Width), Math.Max(desired.Height, max.Height)); min = new PixelSize(Math.Min(desired.Width, min.Width), Math.Min(desired.Height, min.Height)); } var hints = new XSizeHints { min_width = min.Width, min_height = min.Height }; hints.height_inc = hints.width_inc = 1; var flags = XSizeHintsFlags.PMinSize | XSizeHintsFlags.PResizeInc; // People might be passing double.MaxValue if (max.Width < 100000 && max.Height < 100000) { hints.max_width = max.Width; hints.max_height = max.Height; flags |= XSizeHintsFlags.PMaxSize; } hints.flags = (IntPtr)flags; XSetWMNormalHints(_x11.Display, _handle, ref hints); } public Size ClientSize => new Size(_realSize.Width / RenderScaling, _realSize.Height / RenderScaling); public Size? FrameSize { get { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_FRAME_EXTENTS, IntPtr.Zero, new IntPtr(4), false, (IntPtr)Atom.AnyPropertyType, out var _, out var _, out var nitems, out var _, out var prop); if (nitems.ToInt64() != 4) { // Window hasn't been mapped by the WM yet, so can't get the extents. return null; } var data = (IntPtr*)prop.ToPointer(); var extents = new Thickness(data[0].ToInt32(), data[2].ToInt32(), data[1].ToInt32(), data[3].ToInt32()); XFree(prop); return new Size( (_realSize.Width + extents.Left + extents.Right) / RenderScaling, (_realSize.Height + extents.Top + extents.Bottom) / RenderScaling); } } public double RenderScaling { get { lock (SyncRoot) return _scaling; } private set => _scaling = value; } public double DesktopScaling => RenderScaling; public IEnumerable<object> Surfaces { get; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size, PlatformResizeReason> Resized { get; set; } //TODO public Action<double> ScalingChanged { get; set; } public Action Deactivated { get; set; } public Action Activated { get; set; } public Func<bool> Closing { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public Action<WindowTransparencyLevel> TransparencyLevelChanged { get => _transparencyHelper.TransparencyLevelChanged; set => _transparencyHelper.TransparencyLevelChanged = value; } public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; } public Thickness ExtendedMargins { get; } = new Thickness(); public Thickness OffScreenMargin { get; } = new Thickness(); public bool IsClientAreaExtendedToDecorations { get; } public Action Closed { get; set; } public Action<PixelPoint> PositionChanged { get; set; } public Action LostFocus { get; set; } public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); var customRendererFactory = AvaloniaLocator.Current.GetService<IRendererFactory>(); if (customRendererFactory != null) return customRendererFactory.Create(root, loop); return _platform.Options.UseDeferredRendering ? new DeferredRenderer(root, loop) { RenderOnlyOnRenderThread = true } : (IRenderer)new X11ImmediateRendererProxy(root, loop); } void OnEvent(ref XEvent ev) { lock (SyncRoot) OnEventSync(ref ev); } void OnEventSync(ref XEvent ev) { if (ev.type == XEventName.MapNotify) { _mapped = true; if (_useRenderWindow) XMapWindow(_x11.Display, _renderHandle); } else if (ev.type == XEventName.UnmapNotify) _mapped = false; else if (ev.type == XEventName.Expose || (ev.type == XEventName.VisibilityNotify && ev.VisibilityEvent.state < 2)) { if (!_triggeredExpose) { _triggeredExpose = true; Dispatcher.UIThread.Post(() => { _triggeredExpose = false; DoPaint(); }, DispatcherPriority.Render); } } else if (ev.type == XEventName.FocusIn) { if (ActivateTransientChildIfNeeded()) return; Activated?.Invoke(); _imeControl?.SetWindowActive(true); } else if (ev.type == XEventName.FocusOut) { _imeControl?.SetWindowActive(false); Deactivated?.Invoke(); } else if (ev.type == XEventName.MotionNotify) MouseEvent(RawPointerEventType.Move, ref ev, ev.MotionEvent.state); else if (ev.type == XEventName.LeaveNotify) MouseEvent(RawPointerEventType.LeaveWindow, ref ev, ev.CrossingEvent.state); else if (ev.type == XEventName.PropertyNotify) { OnPropertyChange(ev.PropertyEvent.atom, ev.PropertyEvent.state == 0); } else if (ev.type == XEventName.ButtonPress) { if (ActivateTransientChildIfNeeded()) return; if (ev.ButtonEvent.button < 4 || ev.ButtonEvent.button == 8 || ev.ButtonEvent.button == 9) MouseEvent( ev.ButtonEvent.button switch { 1 => RawPointerEventType.LeftButtonDown, 2 => RawPointerEventType.MiddleButtonDown, 3 => RawPointerEventType.RightButtonDown, 8 => RawPointerEventType.XButton1Down, 9 => RawPointerEventType.XButton2Down }, ref ev, ev.ButtonEvent.state); else { var delta = ev.ButtonEvent.button == 4 ? new Vector(0, 1) : ev.ButtonEvent.button == 5 ? new Vector(0, -1) : ev.ButtonEvent.button == 6 ? new Vector(1, 0) : new Vector(-1, 0); ScheduleInput(new RawMouseWheelEventArgs(_mouse, (ulong)ev.ButtonEvent.time.ToInt64(), _inputRoot, new Point(ev.ButtonEvent.x, ev.ButtonEvent.y), delta, TranslateModifiers(ev.ButtonEvent.state)), ref ev); } } else if (ev.type == XEventName.ButtonRelease) { if (ev.ButtonEvent.button < 4 || ev.ButtonEvent.button == 8 || ev.ButtonEvent.button == 9) MouseEvent( ev.ButtonEvent.button switch { 1 => RawPointerEventType.LeftButtonUp, 2 => RawPointerEventType.MiddleButtonUp, 3 => RawPointerEventType.RightButtonUp, 8 => RawPointerEventType.XButton1Up, 9 => RawPointerEventType.XButton2Up }, ref ev, ev.ButtonEvent.state); } else if (ev.type == XEventName.ConfigureNotify) { if (ev.ConfigureEvent.window != _handle) return; var needEnqueue = (_configure == null); _configure = ev.ConfigureEvent; if (ev.ConfigureEvent.override_redirect != 0 || ev.ConfigureEvent.send_event != 0) _configurePoint = new PixelPoint(ev.ConfigureEvent.x, ev.ConfigureEvent.y); else { XTranslateCoordinates(_x11.Display, _handle, _x11.RootWindow, 0, 0, out var tx, out var ty, out _); _configurePoint = new PixelPoint(tx, ty); } if (needEnqueue) Dispatcher.UIThread.Post(() => { if (_configure == null) return; var cev = _configure.Value; var npos = _configurePoint.Value; _configure = null; _configurePoint = null; var nsize = new PixelSize(cev.width, cev.height); var changedSize = _realSize != nsize; var changedPos = _position == null || npos != _position; _realSize = nsize; _position = npos; bool updatedSizeViaScaling = false; if (changedPos) { PositionChanged?.Invoke(npos); updatedSizeViaScaling = UpdateScaling(); } UpdateImePosition(); if (changedSize && !updatedSizeViaScaling && !_popup) Resized?.Invoke(ClientSize, PlatformResizeReason.Unspecified); Dispatcher.UIThread.RunJobs(DispatcherPriority.Layout); }, DispatcherPriority.Layout); if (_useRenderWindow) XConfigureResizeWindow(_x11.Display, _renderHandle, ev.ConfigureEvent.width, ev.ConfigureEvent.height); } else if (ev.type == XEventName.DestroyNotify && ev.DestroyWindowEvent.window == _handle) { Cleanup(); } else if (ev.type == XEventName.ClientMessage) { if (ev.ClientMessageEvent.message_type == _x11.Atoms.WM_PROTOCOLS) { if (ev.ClientMessageEvent.ptr1 == _x11.Atoms.WM_DELETE_WINDOW) { if (Closing?.Invoke() != true) Dispose(); } } } else if (ev.type == XEventName.KeyPress || ev.type == XEventName.KeyRelease) { if (ActivateTransientChildIfNeeded()) return; HandleKeyEvent(ref ev); } } private bool UpdateScaling(bool skipResize = false) { lock (SyncRoot) { double newScaling; if (_scalingOverride.HasValue) newScaling = _scalingOverride.Value; else { var monitor = _platform.X11Screens.Screens.OrderBy(x => x.PixelDensity) .FirstOrDefault(m => m.Bounds.Contains(Position)); newScaling = monitor?.PixelDensity ?? RenderScaling; } if (RenderScaling != newScaling) { var oldScaledSize = ClientSize; RenderScaling = newScaling; ScalingChanged?.Invoke(RenderScaling); UpdateImePosition(); SetMinMaxSize(_scaledMinMaxSize.minSize, _scaledMinMaxSize.maxSize); if(!skipResize) Resize(oldScaledSize, true, PlatformResizeReason.DpiChange); return true; } return false; } } private WindowState _lastWindowState; public WindowState WindowState { get => _lastWindowState; set { if(_lastWindowState == value) return; _lastWindowState = value; if (value == WindowState.Minimized) { XIconifyWindow(_x11.Display, _handle, _x11.DefaultScreen); } else if (value == WindowState.Maximized) { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(true, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } else if (value == WindowState.FullScreen) { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(true, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } else { ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_HIDDEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_FULLSCREEN); ChangeWMAtoms(false, _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT, _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ); } } } private void OnPropertyChange(IntPtr atom, bool hasValue) { if (atom == _x11.Atoms._NET_FRAME_EXTENTS) { // Occurs once the window has been mapped, which is the earliest the extents // can be retrieved, so invoke event to force update of TopLevel.FrameSize. Resized.Invoke(ClientSize, PlatformResizeReason.Unspecified); } if (atom == _x11.Atoms._NET_WM_STATE) { WindowState state = WindowState.Normal; if(hasValue) { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, IntPtr.Zero, new IntPtr(256), false, (IntPtr)Atom.XA_ATOM, out _, out _, out var nitems, out _, out var prop); int maximized = 0; var pitems = (IntPtr*)prop.ToPointer(); for (var c = 0; c < nitems.ToInt32(); c++) { if (pitems[c] == _x11.Atoms._NET_WM_STATE_HIDDEN) { state = WindowState.Minimized; break; } if(pitems[c] == _x11.Atoms._NET_WM_STATE_FULLSCREEN) { state = WindowState.FullScreen; break; } if (pitems[c] == _x11.Atoms._NET_WM_STATE_MAXIMIZED_HORZ || pitems[c] == _x11.Atoms._NET_WM_STATE_MAXIMIZED_VERT) { maximized++; if (maximized == 2) { state = WindowState.Maximized; break; } } } XFree(prop); } if (_lastWindowState != state) { _lastWindowState = state; WindowStateChanged?.Invoke(state); } } } RawInputModifiers TranslateModifiers(XModifierMask state) { var rv = default(RawInputModifiers); if (state.HasAllFlags(XModifierMask.Button1Mask)) rv |= RawInputModifiers.LeftMouseButton; if (state.HasAllFlags(XModifierMask.Button2Mask)) rv |= RawInputModifiers.RightMouseButton; if (state.HasAllFlags(XModifierMask.Button3Mask)) rv |= RawInputModifiers.MiddleMouseButton; if (state.HasAllFlags(XModifierMask.Button4Mask)) rv |= RawInputModifiers.XButton1MouseButton; if (state.HasAllFlags(XModifierMask.Button5Mask)) rv |= RawInputModifiers.XButton2MouseButton; if (state.HasAllFlags(XModifierMask.ShiftMask)) rv |= RawInputModifiers.Shift; if (state.HasAllFlags(XModifierMask.ControlMask)) rv |= RawInputModifiers.Control; if (state.HasAllFlags(XModifierMask.Mod1Mask)) rv |= RawInputModifiers.Alt; if (state.HasAllFlags(XModifierMask.Mod4Mask)) rv |= RawInputModifiers.Meta; return rv; } private SystemDecorations _systemDecorations = SystemDecorations.Full; private bool _canResize = true; private const int MaxWindowDimension = 100000; private (Size minSize, Size maxSize) _scaledMinMaxSize = (new Size(1, 1), new Size(double.PositiveInfinity, double.PositiveInfinity)); private (PixelSize minSize, PixelSize maxSize) _minMaxSize = (new PixelSize(1, 1), new PixelSize(MaxWindowDimension, MaxWindowDimension)); private double _scaling = 1; void ScheduleInput(RawInputEventArgs args, ref XEvent xev) { _x11.LastActivityTimestamp = xev.ButtonEvent.time; ScheduleInput(args); } public void ScheduleXI2Input(RawInputEventArgs args) { if (args is RawPointerEventArgs pargs) { if ((pargs.Type == RawPointerEventType.TouchBegin || pargs.Type == RawPointerEventType.TouchUpdate || pargs.Type == RawPointerEventType.LeftButtonDown || pargs.Type == RawPointerEventType.RightButtonDown || pargs.Type == RawPointerEventType.MiddleButtonDown || pargs.Type == RawPointerEventType.NonClientLeftButtonDown) && ActivateTransientChildIfNeeded()) return; if (pargs.Type == RawPointerEventType.TouchEnd && ActivateTransientChildIfNeeded()) pargs.Type = RawPointerEventType.TouchCancel; } ScheduleInput(args); } private void ScheduleInput(RawInputEventArgs args) { if (args is RawPointerEventArgs mouse) mouse.Position = mouse.Position / RenderScaling; if (args is RawDragEvent drag) drag.Location = drag.Location / RenderScaling; _lastEvent = new InputEventContainer() {Event = args}; _inputQueue.Enqueue(_lastEvent); if (_inputQueue.Count == 1) { Dispatcher.UIThread.Post(() => { while (_inputQueue.Count > 0) { Dispatcher.UIThread.RunJobs(DispatcherPriority.Input + 1); var ev = _inputQueue.Dequeue(); Input?.Invoke(ev.Event); } }, DispatcherPriority.Input); } } void MouseEvent(RawPointerEventType type, ref XEvent ev, XModifierMask mods) { var mev = new RawPointerEventArgs( _mouse, (ulong)ev.ButtonEvent.time.ToInt64(), _inputRoot, type, new Point(ev.ButtonEvent.x, ev.ButtonEvent.y), TranslateModifiers(mods)); if(type == RawPointerEventType.Move && _inputQueue.Count>0 && _lastEvent.Event is RawPointerEventArgs ma) if (ma.Type == RawPointerEventType.Move) { _lastEvent.Event = mev; return; } ScheduleInput(mev, ref ev); } void DoPaint() { Paint?.Invoke(new Rect()); } public void Invalidate(Rect rect) { } public IInputRoot InputRoot => _inputRoot; public void SetInputRoot(IInputRoot inputRoot) { _inputRoot = inputRoot; } public void Dispose() { Cleanup(); } void Cleanup() { if (_imeControl != null) { _imeControl.Dispose(); _imeControl = null; _ime = null; } if (_xic != IntPtr.Zero) { XDestroyIC(_xic); _xic = IntPtr.Zero; } if (_handle != IntPtr.Zero) { XDestroyWindow(_x11.Display, _handle); _platform.Windows.Remove(_handle); _platform.XI2?.OnWindowDestroyed(_handle); _handle = IntPtr.Zero; Closed?.Invoke(); _mouse.Dispose(); _touch.Dispose(); } if (_useRenderWindow && _renderHandle != IntPtr.Zero) { _renderHandle = IntPtr.Zero; } } bool ActivateTransientChildIfNeeded() { if (_disabled) { GotInputWhenDisabled?.Invoke(); return true; } return false; } public void SetParent(IWindowImpl parent) { if (parent == null || parent.Handle == null || parent.Handle.Handle == IntPtr.Zero) XDeleteProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_TRANSIENT_FOR); else XSetTransientForHint(_x11.Display, _handle, parent.Handle.Handle); } public void Show(bool activate, bool isDialog) { _wasMappedAtLeastOnce = true; XMapWindow(_x11.Display, _handle); XFlush(_x11.Display); } public void Hide() => XUnmapWindow(_x11.Display, _handle); public Point PointToClient(PixelPoint point) => new Point((point.X - Position.X) / RenderScaling, (point.Y - Position.Y) / RenderScaling); public PixelPoint PointToScreen(Point point) => new PixelPoint( (int)(point.X * RenderScaling + Position.X), (int)(point.Y * RenderScaling + Position.Y)); public void SetSystemDecorations(SystemDecorations enabled) { _systemDecorations = enabled == SystemDecorations.Full ? SystemDecorations.Full : SystemDecorations.None; UpdateMotifHints(); UpdateSizeHints(null); } public void Resize(Size clientSize, PlatformResizeReason reason) => Resize(clientSize, false, reason); public void Move(PixelPoint point) => Position = point; private void MoveResize(PixelPoint position, Size size, double scaling) { Move(position); _scalingOverride = scaling; UpdateScaling(true); Resize(size, true, PlatformResizeReason.Layout); } PixelSize ToPixelSize(Size size) => new PixelSize((int)(size.Width * RenderScaling), (int)(size.Height * RenderScaling)); void Resize(Size clientSize, bool force, PlatformResizeReason reason) { if (!force && clientSize == ClientSize) return; var needImmediatePopupResize = clientSize != ClientSize; var pixelSize = ToPixelSize(clientSize); UpdateSizeHints(pixelSize); XConfigureResizeWindow(_x11.Display, _handle, pixelSize); if (_useRenderWindow) XConfigureResizeWindow(_x11.Display, _renderHandle, pixelSize); XFlush(_x11.Display); if (force || !_wasMappedAtLeastOnce || (_popup && needImmediatePopupResize)) { _realSize = pixelSize; Resized?.Invoke(ClientSize, reason); } } public void CanResize(bool value) { _canResize = value; UpdateMotifHints(); UpdateSizeHints(null); } public void SetCursor(ICursorImpl cursor) { if (cursor == null) XDefineCursor(_x11.Display, _handle, _x11.DefaultCursor); else if (cursor is CursorImpl impl) { XDefineCursor(_x11.Display, _handle, impl.Handle); } } public IPlatformHandle Handle { get; } public PixelPoint Position { get => _position ?? default; set { var changes = new XWindowChanges { x = (int)value.X, y = (int)value.Y }; XConfigureWindow(_x11.Display, _handle, ChangeWindowFlags.CWX | ChangeWindowFlags.CWY, ref changes); XFlush(_x11.Display); if (!_wasMappedAtLeastOnce) { _position = value; PositionChanged?.Invoke(value); } } } public IMouseDevice MouseDevice => _mouse; public TouchDevice TouchDevice => _touch; public IPopupImpl CreatePopup() => _platform.Options.OverlayPopups ? null : new X11Window(_platform, this); public void Activate() { if (_x11.Atoms._NET_ACTIVE_WINDOW != IntPtr.Zero) { SendNetWMMessage(_x11.Atoms._NET_ACTIVE_WINDOW, (IntPtr)1, _x11.LastActivityTimestamp, IntPtr.Zero); } else { XRaiseWindow(_x11.Display, _handle); XSetInputFocus(_x11.Display, _handle, 0, IntPtr.Zero); } } public IScreenImpl Screen => _platform.Screens; public Size MaxAutoSizeHint => _platform.X11Screens.Screens.Select(s => s.Bounds.Size.ToSize(s.PixelDensity)) .OrderByDescending(x => x.Width + x.Height).FirstOrDefault(); void SendNetWMMessage(IntPtr message_type, IntPtr l0, IntPtr? l1 = null, IntPtr? l2 = null, IntPtr? l3 = null, IntPtr? l4 = null) { var xev = new XEvent { ClientMessageEvent = { type = XEventName.ClientMessage, send_event = 1, window = _handle, message_type = message_type, format = 32, ptr1 = l0, ptr2 = l1 ?? IntPtr.Zero, ptr3 = l2 ?? IntPtr.Zero, ptr4 = l3 ?? IntPtr.Zero } }; xev.ClientMessageEvent.ptr4 = l4 ?? IntPtr.Zero; XSendEvent(_x11.Display, _x11.RootWindow, false, new IntPtr((int)(EventMask.SubstructureRedirectMask | EventMask.SubstructureNotifyMask)), ref xev); } void BeginMoveResize(NetWmMoveResize side, PointerPressedEventArgs e) { var pos = GetCursorPos(_x11); XUngrabPointer(_x11.Display, new IntPtr(0)); SendNetWMMessage (_x11.Atoms._NET_WM_MOVERESIZE, (IntPtr) pos.x, (IntPtr) pos.y, (IntPtr) side, (IntPtr) 1, (IntPtr)1); // left button e.Pointer.Capture(null); } public void BeginMoveDrag(PointerPressedEventArgs e) { BeginMoveResize(NetWmMoveResize._NET_WM_MOVERESIZE_MOVE, e); } public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e) { var side = NetWmMoveResize._NET_WM_MOVERESIZE_CANCEL; if (edge == WindowEdge.East) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_RIGHT; if (edge == WindowEdge.North) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOP; if (edge == WindowEdge.South) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOM; if (edge == WindowEdge.West) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_LEFT; if (edge == WindowEdge.NorthEast) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOPRIGHT; if (edge == WindowEdge.NorthWest) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_TOPLEFT; if (edge == WindowEdge.SouthEast) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; if (edge == WindowEdge.SouthWest) side = NetWmMoveResize._NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; BeginMoveResize(side, e); } public void SetTitle(string title) { if (string.IsNullOrEmpty(title)) { XDeleteProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_NAME); } else { var data = Encoding.UTF8.GetBytes(title); fixed (void* pdata = data) { XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_NAME, _x11.Atoms.UTF8_STRING, 8, PropertyMode.Replace, pdata, data.Length); XStoreName(_x11.Display, _handle, title); } } } public void SetWmClass(string wmClass) { var data = Encoding.ASCII.GetBytes(wmClass); fixed (void* pdata = data) { XChangeProperty(_x11.Display, _handle, _x11.Atoms.XA_WM_CLASS, _x11.Atoms.XA_STRING, 8, PropertyMode.Replace, pdata, data.Length); } } public void SetMinMaxSize(Size minSize, Size maxSize) { _scaledMinMaxSize = (minSize, maxSize); var min = new PixelSize( (int)(minSize.Width < 1 ? 1 : minSize.Width * RenderScaling), (int)(minSize.Height < 1 ? 1 : minSize.Height * RenderScaling)); const int maxDim = MaxWindowDimension; var max = new PixelSize( (int)(maxSize.Width > maxDim ? maxDim : Math.Max(min.Width, maxSize.Width * RenderScaling)), (int)(maxSize.Height > maxDim ? maxDim : Math.Max(min.Height, maxSize.Height * RenderScaling))); _minMaxSize = (min, max); UpdateSizeHints(null); } public void SetTopmost(bool value) { ChangeWMAtoms(value, _x11.Atoms._NET_WM_STATE_ABOVE); } public void SetEnabled(bool enable) { _disabled = !enable; } public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint) { } public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints) { } public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight) { } public Action GotInputWhenDisabled { get; set; } public void SetIcon(IWindowIconImpl icon) { if (icon != null) { var data = ((X11IconData)icon).Data; fixed (void* pdata = data) XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_ICON, new IntPtr((int)Atom.XA_CARDINAL), 32, PropertyMode.Replace, pdata, data.Length); } else { XDeleteProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_ICON); } } public void ShowTaskbarIcon(bool value) { ChangeWMAtoms(!value, _x11.Atoms._NET_WM_STATE_SKIP_TASKBAR); } void ChangeWMAtoms(bool enable, params IntPtr[] atoms) { if (atoms.Length != 1 && atoms.Length != 2) throw new ArgumentException(); if (!_mapped) { XGetWindowProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, IntPtr.Zero, new IntPtr(256), false, (IntPtr)Atom.XA_ATOM, out _, out _, out var nitems, out _, out var prop); var ptr = (IntPtr*)prop.ToPointer(); var newAtoms = new HashSet<IntPtr>(); for (var c = 0; c < nitems.ToInt64(); c++) newAtoms.Add(*ptr); XFree(prop); foreach(var atom in atoms) if (enable) newAtoms.Add(atom); else newAtoms.Remove(atom); XChangeProperty(_x11.Display, _handle, _x11.Atoms._NET_WM_STATE, (IntPtr)Atom.XA_ATOM, 32, PropertyMode.Replace, newAtoms.ToArray(), newAtoms.Count); } SendNetWMMessage(_x11.Atoms._NET_WM_STATE, (IntPtr)(enable ? 1 : 0), atoms[0], atoms.Length > 1 ? atoms[1] : IntPtr.Zero, atoms.Length > 2 ? atoms[2] : IntPtr.Zero, atoms.Length > 3 ? atoms[3] : IntPtr.Zero ); } public IPopupPositioner PopupPositioner { get; } public ITopLevelNativeMenuExporter NativeMenuExporter { get; } public INativeControlHostImpl NativeControlHost { get; } public ITextInputMethodImpl TextInputMethod => _ime; public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) => _transparencyHelper.SetTransparencyRequest(transparencyLevel); public void SetWindowManagerAddShadowHint(bool enabled) { } public WindowTransparencyLevel TransparencyLevel => _transparencyHelper.CurrentLevel; public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 0.8, 0.8); public bool NeedsManagedDecorations => false; } }
//------------------------------------------------------------------------- // <copyright file="Grammar.cs"> // Copyright 2008-2010 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Louis DeJardin</author> // <author>John Gietzen</author> //------------------------------------------------------------------------- namespace Spark.Parser { using System.Collections.Generic; /// <summary> /// Contains parse actions shared accross all grammars. /// </summary> public abstract class Grammar { /// <summary> /// Indicates a conjunction (logical and) between two matches. /// </summary> /// <typeparam name="TValue1">The type of the first match.</typeparam> /// <typeparam name="TValue2">The type of the second match.</typeparam> /// <param name="p1">The first requirement in the conjunction.</param> /// <param name="p2">The second requirement in the conjunction.</param> /// <returns>The corresponding ParseAction for this match.</returns> /// <remarks> /// When a match is found, the two results are chained together. /// The first match corresponds to Chain.Left, and the second to Chain.Down. /// </remarks> public static ParseAction<Chain<TValue1, TValue2>> And<TValue1, TValue2>( ParseAction<TValue1> p1, ParseAction<TValue2> p2) { return delegate(Position input) { var r1 = p1(input); if (r1 == null) { return null; } var r2 = p2(r1.Rest); if (r2 == null) { return null; } var chain = new Chain<TValue1, TValue2>( r1.Value, r2.Value); return new ParseResult<Chain<TValue1, TValue2>>( r2.Rest, chain); }; } /// <summary> /// Indicates a disjunction (logical or) between two matches. /// </summary> /// <typeparam name="TValue">The type of the matches.</typeparam> /// <param name="p1">The first option in the disjunction.</param> /// <param name="p2">The second option in the disjunction.</param> /// <returns>The corresponding ParseAction for this match.</returns> public static ParseAction<TValue> Or<TValue>( ParseAction<TValue> p1, ParseAction<TValue> p2) { return input => p1(input) ?? p2(input); } /// <summary> /// Uses the first match, unless the second match is possible at the same location. /// </summary> /// <typeparam name="TValue1">The type of the first match.</typeparam> /// <typeparam name="TValue2">The type of the second match.</typeparam> /// <param name="p1">The first match predicate.</param> /// <param name="p2">The second match predicate.</param> /// <returns>The corresponding ParseAction for this match.</returns> public static ParseAction<TValue1> Unless<TValue1, TValue2>( ParseAction<TValue1> p1, ParseAction<TValue2> p2) { return delegate(Position input) { var r1 = p1(input); if (r1 == null) { return null; } var r2 = p2(input); if (r2 != null) { return null; } return r1; }; } /// <summary> /// Matches a predicate one or zero times. /// </summary> /// <typeparam name="TValue">The type of the match.</typeparam> /// <param name="parse">The match predicate to be used.</param> /// <returns>The corresponding ParseAction for this match.</returns> /// <remarks> /// If the match cannot be performed, the match succeeds and returns the default value of the match type. /// The position of the parse subject is not changed when the match fails. /// </remarks> public static ParseAction<TValue> Opt<TValue>(ParseAction<TValue> parse) { return input => parse(input) ?? new ParseResult<TValue>(input, default(TValue)); } /// <summary> /// Uses the first match, as long as the second match succeeds immediately after the first. /// </summary> /// <typeparam name="TValue">The type of the first match.</typeparam> /// <typeparam name="TValue2">The type of the second match.</typeparam> /// <param name="parse">The match predicate to be used.</param> /// <param name="cond">The match predicate that must match immediately after <paramref name="parse"/>.</param> /// <returns>The corresponding ParseAction for this match.</returns> public static ParseAction<TValue> IfNext<TValue, TValue2>(ParseAction<TValue> parse, ParseAction<TValue2> cond) { return delegate(Position input) { var result = parse(input); if (result == null || cond(result.Rest) == null) { return null; } return result; }; } /// <summary> /// Uses the first match, as long as the second match does not succeed immediately after the first. /// </summary> /// <typeparam name="TValue">The type of the first match.</typeparam> /// <typeparam name="TValue2">The type of the second match.</typeparam> /// <param name="parse">The match predicate to be used.</param> /// <param name="cond">The match predicate that must not match immediately after <paramref name="parse"/>.</param> /// <returns>The corresponding ParseAction for this match.</returns> public static ParseAction<TValue> NotNext<TValue, TValue2>(ParseAction<TValue> parse, ParseAction<TValue2> cond) { return delegate(Position input) { var result = parse(input); if (result == null || cond(result.Rest) != null) { return null; } return result; }; } /// <summary> /// Repeats a match zero or more times. /// </summary> /// <typeparam name="TValue">The type of the match.</typeparam> /// <param name="parse">The match predicate to be repeated.</param> /// <returns>The corresponding ParseAction for this match.</returns> public static ParseAction<IList<TValue>> Rep<TValue>(ParseAction<TValue> parse) { return delegate(Position input) { var list = new List<TValue>(); var rest = input; var result = parse(rest); while (result != null && !rest.IsSamePosition(result.Rest)) { list.Add(result.Value); rest = result.Rest; result = parse(rest); } return new ParseResult<IList<TValue>>(rest, list); }; } /// <summary> /// Repeats a match one or more times. /// </summary> /// <typeparam name="TValue">The type of the match.</typeparam> /// <param name="parse">The match predicate to be repeated.</param> /// <returns>The corresponding ParseAction for this match.</returns> /// <remarks> /// If the match cannot be performed at least once, the entire match fails. /// </remarks> public static ParseAction<IList<TValue>> Rep1<TValue>(ParseAction<TValue> parse) { return delegate(Position input) { var rest = input; var result = parse(rest); if (result == null) { return null; } var list = new List<TValue>(); while (result != null) { rest = result.Rest; list.Add(result.Value); result = parse(rest); } return new ParseResult<IList<TValue>>(rest, list); }; } public static ParseAction<TValue> Paint<TValue>(ParseAction<TValue> parser) { return position => { var result = parser(position); if (result == null) { return null; } return new ParseResult<TValue>(result.Rest.Paint(position, result.Value), result.Value); }; // ${hello[[world]]} // < // > // "hello<world>" } public static ParseAction<TValue> Paint<TValue, TPaintValue>(ParseAction<TValue> parser) where TValue : TPaintValue { return position => { var result = parser(position); if (result == null) { return null; } return new ParseResult<TValue>(result.Rest.Paint<TPaintValue>(position, result.Value), result.Value); }; } public static ParseAction<TValue> Paint<TValue, TPaintValue>(TPaintValue value, ParseAction<TValue> parser) { return position => { var result = parser(position); if (result == null) { return null; } return new ParseResult<TValue>(result.Rest.Paint(position, value), result.Value); }; } } }
using System.Text; namespace Meziantou.Framework.Scheduling; public sealed class YearlyRecurrenceRule : RecurrenceRule { public IList<int>? ByMonthDays { get; set; } public IList<ByDay>? ByWeekDays { get; set; } public IList<Month>? ByMonths { get; set; } //public IList<int> ByWeekNo { get; set; } public IList<int>? ByYearDays { get; set; } protected override IEnumerable<DateTime> GetNextOccurrencesInternal(DateTime startDate) { if (IsEmpty(ByMonthDays) && IsEmpty(ByWeekDays) && IsEmpty(ByMonths) && /*IsEmpty(ByWeekNo) && */IsEmpty(ByYearDays)) { while (true) { yield return startDate; startDate = startDate.AddYears(Interval); } } var startOfYear = Extensions.StartOfYear(startDate, keepTime: true); while (true) { var resultByMonthDays = ResultByMonthDays(startDate, startOfYear); var resultByWeekDays = ResultByWeekDays(startOfYear); var resultByYearDays = ResultByYearDays(startOfYear); var resultByMonths = ResultByMonths(startOfYear); List<DateTime>? resultByWeekNo = null;// ResultByWeekNo(startDate, startOfYear); var result = Intersect(resultByMonths, resultByWeekNo, resultByYearDays, resultByMonthDays, resultByWeekDays); result = FilterBySetPosition(result.Distinct().OrderBy(d => d).ToList(), BySetPositions); foreach (var date in result.Where(d => d >= startDate)) { yield return date; } startOfYear = startOfYear.AddYears(Interval); } } private List<DateTime>? ResultByWeekDays(DateTime startOfYear) { List<DateTime>? result = null; if (!IsEmpty(ByWeekDays)) { result = new List<DateTime>(); if (IsEmpty(ByMonths)) { // 1) Find all dates that match the day of month contraint var potentialResults = new Dictionary<ByDay, IList<DateTime>>(); foreach (var byDay in ByWeekDays) { potentialResults.Add(byDay, new List<DateTime>()); } for (var day = startOfYear; day.Year == startOfYear.Year; day = day.AddDays(1)) { foreach (var byDay in ByWeekDays) { if (byDay.DayOfWeek == day.DayOfWeek) { potentialResults[byDay].Add(day); } } } // 2) Filter by ordinal foreach (var potentialResult in potentialResults) { if (potentialResult.Key.Ordinal.HasValue) { int index; if (potentialResult.Key.Ordinal > 0) { index = potentialResult.Key.Ordinal.Value - 1; } else { index = potentialResult.Value.Count + potentialResult.Key.Ordinal.Value; } if (index >= 0 && index < potentialResult.Value.Count) { result.Add(potentialResult.Value[index]); } } else { result.AddRange(potentialResult.Value); } } } else { for (var dt = startOfYear; dt.Year == startOfYear.Year; dt = dt.AddMonths(1)) { var resultByWeekDaysInMonth = ResultByWeekDaysInMonth(dt, ByWeekDays); if (resultByWeekDaysInMonth != null) { result.AddRange(resultByWeekDaysInMonth); } } } result.Sort(); } return result; } private List<DateTime>? ResultByMonthDays(DateTime startDate, DateTime startOfYear) { List<DateTime>? result = null; var monthDays = ByMonthDays; if (IsEmpty(ByMonthDays) && IsEmpty(ByWeekDays) && /*IsEmpty(ByWeekNo) &&*/ IsEmpty(ByYearDays)) { monthDays = new List<int> { startDate.Day }; } if (!IsEmpty(monthDays)) { result = new List<DateTime>(); for (var i = 0; i < 12; i++) { var startOfMonth = startOfYear.AddMonths(i); var daysInMonth = DateTime.DaysInMonth(startOfMonth.Year, startOfMonth.Month); foreach (var day in monthDays) { if (day >= 1 && day <= daysInMonth) { result.Add(startOfMonth.AddDays(day - 1)); } else if (day <= -1 && day >= -daysInMonth) { result.Add(startOfMonth.AddDays(daysInMonth + day)); } } } result.Sort(); //result = FilterBySetPosition(result, BySetPositions).ToList(); } return result; } private List<DateTime>? ResultByYearDays(DateTime startOfYear) { List<DateTime>? result = null; if (!IsEmpty(ByYearDays)) { result = new List<DateTime>(); var daysInYear = DateTime.IsLeapYear(startOfYear.Year) ? 366 : 365; foreach (var day in ByYearDays) { if (day >= 1 && day <= daysInYear) { result.Add(startOfYear.AddDays(day - 1)); } else if (day <= -1 && day >= -daysInYear) { result.Add(startOfYear.AddDays(daysInYear + day)); } } result.Sort(); //result = FilterBySetPosition(result, BySetPositions).ToList(); } return result; } private List<DateTime>? ResultByMonths(DateTime startOfYear) { List<DateTime>? result = null; if (!IsEmpty(ByMonths)) { result = new List<DateTime>(); foreach (var month in ByMonths.Distinct().OrderBy(_ => _)) { if (month >= Month.January && month <= Month.December) { for (var dt = startOfYear.AddMonths((int)month - 1); dt.Month == (int)month; dt = dt.AddDays(1)) { result.Add(dt); } } } //result.Sort(); //result = FilterBySetPosition(result, BySetPositions).ToList(); } return result; } //private List<DateTime> ResultByWeekNo(DateTime startDate, DateTime startOfYear) //{ // List<DateTime> result = null; // if (!IsEmpty(ByWeekNo)) // { // //result = new List<DateTime>(); // //DateTime week = DateTimeExtensions.FirstDateOfWeekISO8601(startDate.Year, startDate.Month); // ////CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(startDate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday); // //result.Sort(); // //result = FilterBySetPosition(result, BySetPositions).ToList(); // } // return result; //} public override string Text { get { var sb = new StringBuilder(); sb.Append("FREQ=YEARLY"); if (Interval != 1) { sb.Append(";INTERVAL="); sb.Append(Interval); } if (EndDate.HasValue) { sb.Append(";UNTIL="); sb.Append(Utilities.DateTimeToString(EndDate.Value)); } if (Occurrences.HasValue) { sb.Append(";COUNT="); sb.Append(Occurrences.Value); } if (WeekStart != DefaultFirstDayOfWeek) { sb.Append(";WKST="); sb.Append(Utilities.DayOfWeekToString(WeekStart)); } if (!IsEmpty(ByMonths)) { sb.Append(";BYMONTH="); sb.Append(string.Join(",", ByMonths.Cast<int>())); } //if (!IsEmpty(ByWeekNo)) //{ // sb.Append(";BYWEEKNO="); // sb.Append(string.Join(",", ByWeekNo)); //} if (!IsEmpty(ByYearDays)) { sb.Append(";BYYEARDAY="); sb.Append(string.Join(",", ByYearDays)); } if (!IsEmpty(ByMonthDays)) { sb.Append(";BYMONTHDAY="); sb.Append(string.Join(",", ByMonthDays)); } if (!IsEmpty(ByWeekDays)) { sb.Append(";BYDAY="); sb.Append(string.Join(",", ByWeekDays)); } if (!IsEmpty(BySetPositions)) { sb.Append(";BYSETPOS="); sb.Append(string.Join(",", BySetPositions)); } return sb.ToString(); } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using dnlib.DotNet.MD; /* All TypeSig classes: TypeSig base class LeafSig base class for leaf types TypeDefOrRefSig contains a ITypeDefOrRef instance CorLibTypeSig simple corlib types (eg. System.Int32) ClassOrValueTypeSig base class for Class/ValueType element types ValueTypeSig ValueType ClassSig Class GenericSig base class for generic vars GenericVar Generic type parameter GenericMVar Generic method parameter SentinelSig Sentinel FnPtrSig Function pointer sig GenericInstSig Generic instance type (contains a generic type + all generic args) NonLeafSig base class for non-leaf types PtrSig Pointer ByRefSig By ref ArraySigBase Array base class ArraySig Array SZArraySig Single dimension, zero lower limit array (i.e., THETYPE[]) ModifierSig C modifier base class CModReqdSig C required modifier CModOptSig C optional modifier PinnedSig Pinned ValueArraySig Value array (undocumented/not implemented by the CLR so don't use it) ModuleSig Module (undocumented/not implemented by the CLR so don't use it) */ namespace dnlib.DotNet { /// <summary> /// Type sig base class /// </summary> public abstract class TypeSig : IType { uint rid; /// <summary> /// Returns the wrapped element type. Can only be <c>null</c> if it was an invalid sig or /// if it's a <see cref="LeafSig"/> /// </summary> public abstract TypeSig Next { get; } /// <summary> /// Gets the element type /// </summary> public abstract ElementType ElementType { get; } /// <inheritdoc/> public MDToken MDToken => new MDToken(Table.TypeSpec, rid); /// <inheritdoc/> public uint Rid { get => rid; set => rid = value; } /// <inheritdoc/> bool IIsTypeOrMethod.IsMethod => false; /// <inheritdoc/> bool IIsTypeOrMethod.IsType => true; /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters { get { var type = this.RemovePinnedAndModifiers() as GenericInstSig; return type is null ? 0 : type.GenericArguments.Count; } } /// <inheritdoc/> public bool IsValueType { get { var t = this.RemovePinnedAndModifiers(); if (t is null) return false; if (t.ElementType == ElementType.GenericInst) { var gis = (GenericInstSig)t; t = gis.GenericType; if (t is null) return false; } return t.ElementType.IsValueType(); } } /// <inheritdoc/> public bool IsPrimitive => ElementType.IsPrimitive(); /// <inheritdoc/> public string TypeName => FullNameFactory.Name(this, false, null); /// <inheritdoc/> UTF8String IFullName.Name { get => new UTF8String(FullNameFactory.Name(this, false, null)); set => throw new NotSupportedException(); } /// <inheritdoc/> public string ReflectionName => FullNameFactory.Name(this, true, null); /// <inheritdoc/> public string Namespace => FullNameFactory.Namespace(this, false, null); /// <inheritdoc/> public string ReflectionNamespace => FullNameFactory.Namespace(this, true, null); /// <inheritdoc/> public string FullName => FullNameFactory.FullName(this, false, null, null, null, null); /// <inheritdoc/> public string ReflectionFullName => FullNameFactory.FullName(this, true, null, null, null, null); /// <inheritdoc/> public string AssemblyQualifiedName => FullNameFactory.AssemblyQualifiedName(this, null, null); /// <inheritdoc/> public IAssembly DefinitionAssembly => FullNameFactory.DefinitionAssembly(this); /// <inheritdoc/> public IScope Scope => FullNameFactory.Scope(this); /// <inheritdoc/> public ITypeDefOrRef ScopeType => FullNameFactory.ScopeType(this); /// <inheritdoc/> public ModuleDef Module => FullNameFactory.OwnerModule(this); /// <summary> /// <c>true</c> if it's a <see cref="TypeDefOrRefSig"/> /// </summary> public bool IsTypeDefOrRef => this is TypeDefOrRefSig; /// <summary> /// <c>true</c> if it's a <see cref="CorLibTypeSig"/> /// </summary> public bool IsCorLibType => this is CorLibTypeSig; /// <summary> /// <c>true</c> if it's a <see cref="ClassSig"/> /// </summary> public bool IsClassSig => this is ClassSig; /// <summary> /// <c>true</c> if it's a <see cref="ValueTypeSig"/> /// </summary> public bool IsValueTypeSig => this is ValueTypeSig; /// <summary> /// <c>true</c> if it's a <see cref="GenericSig"/> /// </summary> public bool IsGenericParameter => this is GenericSig; /// <summary> /// <c>true</c> if it's a <see cref="GenericVar"/> /// </summary> public bool IsGenericTypeParameter => this is GenericVar; /// <summary> /// <c>true</c> if it's a <see cref="GenericMVar"/> /// </summary> public bool IsGenericMethodParameter => this is GenericMVar; /// <summary> /// <c>true</c> if it's a <see cref="SentinelSig"/> /// </summary> public bool IsSentinel => this is SentinelSig; /// <summary> /// <c>true</c> if it's a <see cref="FnPtrSig"/> /// </summary> public bool IsFunctionPointer => this is FnPtrSig; /// <summary> /// <c>true</c> if it's a <see cref="GenericInstSig"/> /// </summary> public bool IsGenericInstanceType => this is GenericInstSig; /// <summary> /// <c>true</c> if it's a <see cref="PtrSig"/> /// </summary> public bool IsPointer => this is PtrSig; /// <summary> /// <c>true</c> if it's a <see cref="ByRefSig"/> /// </summary> public bool IsByRef => this is ByRefSig; /// <summary> /// <c>true</c> if it's a <see cref="ArraySig"/> or a <see cref="SZArraySig"/> /// </summary> public bool IsSingleOrMultiDimensionalArray => this is ArraySigBase; /// <summary> /// <c>true</c> if it's a <see cref="ArraySig"/> /// </summary> public bool IsArray => this is ArraySig; /// <summary> /// <c>true</c> if it's a <see cref="SZArraySig"/> /// </summary> public bool IsSZArray => this is SZArraySig; /// <summary> /// <c>true</c> if it's a <see cref="ModifierSig"/> /// </summary> public bool IsModifier => this is ModifierSig; /// <summary> /// <c>true</c> if it's a <see cref="CModReqdSig"/> /// </summary> public bool IsRequiredModifier => this is CModReqdSig; /// <summary> /// <c>true</c> if it's a <see cref="CModOptSig"/> /// </summary> public bool IsOptionalModifier => this is CModOptSig; /// <summary> /// <c>true</c> if it's a <see cref="PinnedSig"/> /// </summary> public bool IsPinned => this is PinnedSig; /// <summary> /// <c>true</c> if it's a <see cref="ValueArraySig"/> /// </summary> public bool IsValueArray => this is ValueArraySig; /// <summary> /// <c>true</c> if it's a <see cref="ModuleSig"/> /// </summary> public bool IsModuleSig => this is ModuleSig; /// <summary> /// <c>true</c> if this <see cref="TypeSig"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> public bool ContainsGenericParameter => TypeHelper.ContainsGenericParameter(this); /// <inheritdoc/> public override string ToString() => FullName; } public static partial class Extensions { /// <summary> /// Removes all C optional/required modifiers /// </summary> /// <param name="a">A <see cref="TypeSig"/> instance</param> /// <returns>Input after all modifiers</returns> public static TypeSig RemoveModifiers(this TypeSig a) { if (a is null) return null; while (true) { var modifier = a as ModifierSig; if (modifier is null) return a; a = a.Next; } } /// <summary> /// Removes pinned signature /// </summary> /// <param name="a">The type</param> /// <returns>Input after pinned signature</returns> public static TypeSig RemovePinned(this TypeSig a) { var pinned = a as PinnedSig; if (pinned is null) return a; return pinned.Next; } /// <summary> /// Removes all modifiers and pinned sig /// </summary> /// <param name="a">The type</param> /// <returns>Inputer after modifiers and pinned signature</returns> public static TypeSig RemovePinnedAndModifiers(this TypeSig a) { a = a.RemoveModifiers(); a = a.RemovePinned(); a = a.RemoveModifiers(); return a; } /// <summary> /// Returns a <see cref="TypeDefOrRefSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="TypeDefOrRefSig"/> or <c>null</c> if it's not a /// <see cref="TypeDefOrRefSig"/></returns> public static TypeDefOrRefSig ToTypeDefOrRefSig(this TypeSig type) => type.RemovePinnedAndModifiers() as TypeDefOrRefSig; /// <summary> /// Returns a <see cref="ClassOrValueTypeSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ClassOrValueTypeSig"/> or <c>null</c> if it's not a /// <see cref="ClassOrValueTypeSig"/></returns> public static ClassOrValueTypeSig ToClassOrValueTypeSig(this TypeSig type) => type.RemovePinnedAndModifiers() as ClassOrValueTypeSig; /// <summary> /// Returns a <see cref="ValueTypeSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ValueTypeSig"/> or <c>null</c> if it's not a /// <see cref="ValueTypeSig"/></returns> public static ValueTypeSig ToValueTypeSig(this TypeSig type) => type.RemovePinnedAndModifiers() as ValueTypeSig; /// <summary> /// Returns a <see cref="ClassSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ClassSig"/> or <c>null</c> if it's not a /// <see cref="ClassSig"/></returns> public static ClassSig ToClassSig(this TypeSig type) => type.RemovePinnedAndModifiers() as ClassSig; /// <summary> /// Returns a <see cref="GenericSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericSig"/> or <c>null</c> if it's not a /// <see cref="GenericSig"/></returns> public static GenericSig ToGenericSig(this TypeSig type) => type.RemovePinnedAndModifiers() as GenericSig; /// <summary> /// Returns a <see cref="GenericVar"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericVar"/> or <c>null</c> if it's not a /// <see cref="GenericVar"/></returns> public static GenericVar ToGenericVar(this TypeSig type) => type.RemovePinnedAndModifiers() as GenericVar; /// <summary> /// Returns a <see cref="GenericMVar"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericMVar"/> or <c>null</c> if it's not a /// <see cref="GenericMVar"/></returns> public static GenericMVar ToGenericMVar(this TypeSig type) => type.RemovePinnedAndModifiers() as GenericMVar; /// <summary> /// Returns a <see cref="GenericInstSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericInstSig"/> or <c>null</c> if it's not a /// <see cref="GenericInstSig"/></returns> public static GenericInstSig ToGenericInstSig(this TypeSig type) => type.RemovePinnedAndModifiers() as GenericInstSig; /// <summary> /// Returns a <see cref="PtrSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="PtrSig"/> or <c>null</c> if it's not a /// <see cref="PtrSig"/></returns> public static PtrSig ToPtrSig(this TypeSig type) => type.RemovePinnedAndModifiers() as PtrSig; /// <summary> /// Returns a <see cref="ByRefSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ByRefSig"/> or <c>null</c> if it's not a /// <see cref="ByRefSig"/></returns> public static ByRefSig ToByRefSig(this TypeSig type) => type.RemovePinnedAndModifiers() as ByRefSig; /// <summary> /// Returns a <see cref="ArraySig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ArraySig"/> or <c>null</c> if it's not a /// <see cref="ArraySig"/></returns> public static ArraySig ToArraySig(this TypeSig type) => type.RemovePinnedAndModifiers() as ArraySig; /// <summary> /// Returns a <see cref="SZArraySig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="SZArraySig"/> or <c>null</c> if it's not a /// <see cref="SZArraySig"/></returns> public static SZArraySig ToSZArraySig(this TypeSig type) => type.RemovePinnedAndModifiers() as SZArraySig; /// <summary> /// Gets the next field or <c>null</c> /// </summary> /// <param name="self">this</param> /// <returns></returns> public static TypeSig GetNext(this TypeSig self) => self?.Next; /// <summary> /// Gets the <see cref="TypeSig.IsValueType"/> value or <c>false</c> if /// <paramref name="self"/> is <c>null</c> /// </summary> /// <param name="self">this</param> /// <returns></returns> public static bool GetIsValueType(this TypeSig self) => self is null ? false : self.IsValueType; /// <summary> /// Gets the <see cref="TypeSig.IsPrimitive"/> value or <c>false</c> if /// <paramref name="self"/> is <c>null</c> /// </summary> /// <param name="self">this</param> /// <returns></returns> public static bool GetIsPrimitive(this TypeSig self) => self is null ? false : self.IsPrimitive; /// <summary> /// Gets the element type /// </summary> /// <param name="a">this</param> /// <returns>The element type</returns> public static ElementType GetElementType(this TypeSig a) => a is null ? ElementType.End : a.ElementType; /// <summary> /// Gets the full name of the type /// </summary> /// <param name="a">this</param> /// <returns>Full name of the type</returns> public static string GetFullName(this TypeSig a) => a is null ? string.Empty : a.FullName; /// <summary> /// Gets the name of the type /// </summary> /// <param name="a">this</param> /// <returns>Name of the type</returns> public static string GetName(this TypeSig a) => a is null ? string.Empty : a.TypeName; /// <summary> /// Gets the namespace of the type /// </summary> /// <param name="a">this</param> /// <returns>Namespace of the type</returns> public static string GetNamespace(this TypeSig a) => a is null ? string.Empty : a.Namespace; /// <summary> /// Returns the <see cref="ITypeDefOrRef"/> if it is a <see cref="TypeDefOrRefSig"/>. /// </summary> /// <param name="a">this</param> /// <returns>A <see cref="ITypeDefOrRef"/> or <c>null</c> if none found</returns> public static ITypeDefOrRef TryGetTypeDefOrRef(this TypeSig a) => (a.RemovePinnedAndModifiers() as TypeDefOrRefSig)?.TypeDefOrRef; /// <summary> /// Returns the <see cref="TypeRef"/> if it is a <see cref="TypeDefOrRefSig"/>. /// </summary> /// <param name="a">this</param> /// <returns>A <see cref="TypeRef"/> or <c>null</c> if none found</returns> public static TypeRef TryGetTypeRef(this TypeSig a) => (a.RemovePinnedAndModifiers() as TypeDefOrRefSig)?.TypeRef; /// <summary> /// Returns the <see cref="TypeDef"/> if it is a <see cref="TypeDefOrRefSig"/>. /// Nothing is resolved. /// </summary> /// <param name="a">this</param> /// <returns>A <see cref="TypeDef"/> or <c>null</c> if none found</returns> public static TypeDef TryGetTypeDef(this TypeSig a) => (a.RemovePinnedAndModifiers() as TypeDefOrRefSig)?.TypeDef; /// <summary> /// Returns the <see cref="TypeSpec"/> if it is a <see cref="TypeDefOrRefSig"/>. /// </summary> /// <param name="a">this</param> /// <returns>A <see cref="TypeSpec"/> or <c>null</c> if none found</returns> public static TypeSpec TryGetTypeSpec(this TypeSig a) => (a.RemovePinnedAndModifiers() as TypeDefOrRefSig)?.TypeSpec; } /// <summary> /// Base class for element types that are last in a type sig, ie., /// <see cref="TypeDefOrRefSig"/>, <see cref="GenericSig"/>, <see cref="SentinelSig"/>, /// <see cref="FnPtrSig"/>, <see cref="GenericInstSig"/> /// </summary> public abstract class LeafSig : TypeSig { /// <inheritdoc/> public sealed override TypeSig Next => null; } /// <summary> /// Wraps a <see cref="ITypeDefOrRef"/> /// </summary> public abstract class TypeDefOrRefSig : LeafSig { readonly ITypeDefOrRef typeDefOrRef; /// <summary> /// Gets the the <c>TypeDefOrRef</c> /// </summary> public ITypeDefOrRef TypeDefOrRef => typeDefOrRef; /// <summary> /// Returns <c>true</c> if <see cref="TypeRef"/> != <c>null</c> /// </summary> public bool IsTypeRef => TypeRef is not null; /// <summary> /// Returns <c>true</c> if <see cref="TypeDef"/> != <c>null</c> /// </summary> public bool IsTypeDef => TypeDef is not null; /// <summary> /// Returns <c>true</c> if <see cref="TypeSpec"/> != <c>null</c> /// </summary> public bool IsTypeSpec => TypeSpec is not null; /// <summary> /// Gets the <see cref="TypeRef"/> or <c>null</c> if it's not a <see cref="TypeRef"/> /// </summary> public TypeRef TypeRef => typeDefOrRef as TypeRef; /// <summary> /// Gets the <see cref="TypeDef"/> or <c>null</c> if it's not a <see cref="TypeDef"/> /// </summary> public TypeDef TypeDef => typeDefOrRef as TypeDef; /// <summary> /// Gets the <see cref="TypeSpec"/> or <c>null</c> if it's not a <see cref="TypeSpec"/> /// </summary> public TypeSpec TypeSpec => typeDefOrRef as TypeSpec; /// <summary> /// Constructor /// </summary> /// <param name="typeDefOrRef">A <see cref="TypeRef"/>, <see cref="TypeDef"/> or /// a <see cref="TypeSpec"/></param> protected TypeDefOrRefSig(ITypeDefOrRef typeDefOrRef) => this.typeDefOrRef = typeDefOrRef; } /// <summary> /// A core library type /// </summary> public sealed class CorLibTypeSig : TypeDefOrRefSig { readonly ElementType elementType; /// <summary> /// Gets the element type /// </summary> public override ElementType ElementType => elementType; /// <summary> /// Constructor /// </summary> /// <param name="corType">The type which must be a <see cref="TypeRef"/> or a /// <see cref="TypeDef"/>. <see cref="TypeSpec"/> and <c>null</c> are not allowed.</param> /// <param name="elementType">The type's element type</param> public CorLibTypeSig(ITypeDefOrRef corType, ElementType elementType) : base(corType) { if (!(corType is TypeRef) && !(corType is TypeDef)) throw new ArgumentException("corType must be a TypeDef or a TypeRef. null and TypeSpec are invalid inputs."); this.elementType = elementType; } } /// <summary> /// Base class for class/valuetype element types /// </summary> public abstract class ClassOrValueTypeSig : TypeDefOrRefSig { /// <summary> /// Constructor /// </summary> /// <param name="typeDefOrRef">A <see cref="ITypeDefOrRef"/></param> protected ClassOrValueTypeSig(ITypeDefOrRef typeDefOrRef) : base(typeDefOrRef) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.ValueType"/> /// </summary> public sealed class ValueTypeSig : ClassOrValueTypeSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.ValueType; /// <summary> /// Constructor /// </summary> /// <param name="typeDefOrRef">A <see cref="ITypeDefOrRef"/></param> public ValueTypeSig(ITypeDefOrRef typeDefOrRef) : base(typeDefOrRef) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Class"/> /// </summary> public sealed class ClassSig : ClassOrValueTypeSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.Class; /// <summary> /// Constructor /// </summary> /// <param name="typeDefOrRef">A <see cref="ITypeDefOrRef"/></param> public ClassSig(ITypeDefOrRef typeDefOrRef) : base(typeDefOrRef) { } } /// <summary> /// Generic method/type var base class /// </summary> public abstract class GenericSig : LeafSig { readonly bool isTypeVar; readonly uint number; readonly ITypeOrMethodDef genericParamProvider; /// <summary> /// <c>true</c> if it has an owner <see cref="TypeDef"/> or <see cref="MethodDef"/> /// </summary> public bool HasOwner => genericParamProvider is not null; /// <summary> /// <c>true</c> if it has an owner <see cref="TypeDef"/> (<see cref="OwnerType"/> is /// not <c>null</c>) /// </summary> public bool HasOwnerType => OwnerType is not null; /// <summary> /// <c>true</c> if it has an owner <see cref="MethodDef"/> (<see cref="OwnerMethod"/> is /// not <c>null</c>) /// </summary> public bool HasOwnerMethod => OwnerMethod is not null; /// <summary> /// Gets the owner type or <c>null</c> if the owner is a <see cref="MethodDef"/> or if it /// has no owner. /// </summary> public TypeDef OwnerType => genericParamProvider as TypeDef; /// <summary> /// Gets the owner method or <c>null</c> if the owner is a <see cref="TypeDef"/> or if it /// has no owner. /// </summary> public MethodDef OwnerMethod => genericParamProvider as MethodDef; /// <summary> /// Gets the generic param number /// </summary> public uint Number => number; /// <summary> /// Gets the corresponding <see cref="dnlib.DotNet.GenericParam"/> or <c>null</c> if none exists. /// </summary> public GenericParam GenericParam { get { var gpp = genericParamProvider; if (gpp is null) return null; var gps = gpp.GenericParameters; int count = gps.Count; for (int i = 0; i < count; i++) { var gp = gps[i]; if (gp.Number == number) return gp; } return null; } } /// <summary> /// Constructor /// </summary> /// <param name="isTypeVar"><c>true</c> if it's a <c>Var</c>, <c>false</c> if it's a <c>MVar</c></param> /// <param name="number">Generic param number</param> protected GenericSig(bool isTypeVar, uint number) : this(isTypeVar, number, null) { } /// <summary> /// Constructor /// </summary> /// <param name="isTypeVar"><c>true</c> if it's a <c>Var</c>, <c>false</c> if it's a <c>MVar</c></param> /// <param name="number">Generic param number</param> /// <param name="genericParamProvider">Owner method/type or <c>null</c></param> protected GenericSig(bool isTypeVar, uint number, ITypeOrMethodDef genericParamProvider) { this.isTypeVar = isTypeVar; this.number = number; this.genericParamProvider = genericParamProvider; } /// <summary> /// Returns <c>true</c> if it's a <c>MVar</c> element type /// </summary> public bool IsMethodVar => !isTypeVar; /// <summary> /// Returns <c>true</c> if it's a <c>Var</c> element type /// </summary> public bool IsTypeVar => isTypeVar; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Var"/> /// </summary> public sealed class GenericVar : GenericSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.Var; /// <inheritdoc/> public GenericVar(uint number) : base(true, number) { } /// <inheritdoc/> public GenericVar(int number) : base(true, (uint)number) { } /// <summary> /// Constructor /// </summary> /// <param name="number">Generic parameter number</param> /// <param name="genericParamProvider">Owner type or <c>null</c></param> public GenericVar(uint number, TypeDef genericParamProvider) : base(true, number, genericParamProvider) { } /// <summary> /// Constructor /// </summary> /// <param name="number">Generic parameter number</param> /// <param name="genericParamProvider">Owner type or <c>null</c></param> public GenericVar(int number, TypeDef genericParamProvider) : base(true, (uint)number, genericParamProvider) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.MVar"/> /// </summary> public sealed class GenericMVar : GenericSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.MVar; /// <inheritdoc/> public GenericMVar(uint number) : base(false, number) { } /// <inheritdoc/> public GenericMVar(int number) : base(false, (uint)number) { } /// <summary> /// Constructor /// </summary> /// <param name="number">Generic parameter number</param> /// <param name="genericParamProvider">Owner method or <c>null</c></param> public GenericMVar(uint number, MethodDef genericParamProvider) : base(false, number, genericParamProvider) { } /// <summary> /// Constructor /// </summary> /// <param name="number">Generic parameter number</param> /// <param name="genericParamProvider">Owner method or <c>null</c></param> public GenericMVar(int number, MethodDef genericParamProvider) : base(false, (uint)number, genericParamProvider) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Sentinel"/> /// </summary> public sealed class SentinelSig : LeafSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.Sentinel; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.FnPtr"/> /// </summary> public sealed class FnPtrSig : LeafSig { readonly CallingConventionSig signature; /// <inheritdoc/> public override ElementType ElementType => ElementType.FnPtr; /// <summary> /// Gets the signature /// </summary> public CallingConventionSig Signature => signature; /// <summary> /// Gets the <see cref="MethodSig"/> /// </summary> public MethodSig MethodSig => signature as MethodSig; /// <summary> /// Constructor /// </summary> /// <param name="signature">The method signature</param> public FnPtrSig(CallingConventionSig signature) => this.signature = signature; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.GenericInst"/> /// </summary> public sealed class GenericInstSig : LeafSig { ClassOrValueTypeSig genericType; readonly IList<TypeSig> genericArgs; /// <inheritdoc/> public override ElementType ElementType => ElementType.GenericInst; /// <summary> /// Gets the generic type /// </summary> public ClassOrValueTypeSig GenericType { get => genericType; set => genericType = value; } /// <summary> /// Gets the generic arguments (it's never <c>null</c>) /// </summary> public IList<TypeSig> GenericArguments => genericArgs; /// <summary> /// Default constructor /// </summary> public GenericInstSig() => genericArgs = new List<TypeSig>(); /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> public GenericInstSig(ClassOrValueTypeSig genericType) { this.genericType = genericType; genericArgs = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArgCount">Number of generic arguments</param> public GenericInstSig(ClassOrValueTypeSig genericType, uint genArgCount) { this.genericType = genericType; genericArgs = new List<TypeSig>((int)genArgCount); } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArgCount">Number of generic arguments</param> public GenericInstSig(ClassOrValueTypeSig genericType, int genArgCount) : this(genericType, (uint)genArgCount) { } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArg1">Generic argument #1</param> public GenericInstSig(ClassOrValueTypeSig genericType, TypeSig genArg1) { this.genericType = genericType; genericArgs = new List<TypeSig> { genArg1 }; } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArg1">Generic argument #1</param> /// <param name="genArg2">Generic argument #2</param> public GenericInstSig(ClassOrValueTypeSig genericType, TypeSig genArg1, TypeSig genArg2) { this.genericType = genericType; genericArgs = new List<TypeSig> { genArg1, genArg2 }; } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArg1">Generic argument #1</param> /// <param name="genArg2">Generic argument #2</param> /// <param name="genArg3">Generic argument #3</param> public GenericInstSig(ClassOrValueTypeSig genericType, TypeSig genArg1, TypeSig genArg2, TypeSig genArg3) { this.genericType = genericType; genericArgs = new List<TypeSig> { genArg1, genArg2, genArg3 }; } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArgs">Generic arguments</param> public GenericInstSig(ClassOrValueTypeSig genericType, params TypeSig[] genArgs) { this.genericType = genericType; genericArgs = new List<TypeSig>(genArgs); } /// <summary> /// Constructor /// </summary> /// <param name="genericType">The generic type</param> /// <param name="genArgs">Generic arguments</param> public GenericInstSig(ClassOrValueTypeSig genericType, IList<TypeSig> genArgs) { this.genericType = genericType; genericArgs = new List<TypeSig>(genArgs); } } /// <summary> /// Base class of non-leaf element types /// </summary> public abstract class NonLeafSig : TypeSig { readonly TypeSig nextSig; /// <inheritdoc/> public sealed override TypeSig Next => nextSig; /// <summary> /// Constructor /// </summary> /// <param name="nextSig">Next sig</param> protected NonLeafSig(TypeSig nextSig) => this.nextSig = nextSig; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Ptr"/> /// </summary> public sealed class PtrSig : NonLeafSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.Ptr; /// <summary> /// Constructor /// </summary> /// <param name="nextSig">The next element type</param> public PtrSig(TypeSig nextSig) : base(nextSig) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.ByRef"/> /// </summary> public sealed class ByRefSig : NonLeafSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.ByRef; /// <summary> /// Constructor /// </summary> /// <param name="nextSig">The next element type</param> public ByRefSig(TypeSig nextSig) : base(nextSig) { } } /// <summary> /// Array base class /// </summary> public abstract class ArraySigBase : NonLeafSig { /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> protected ArraySigBase(TypeSig arrayType) : base(arrayType) { } /// <summary> /// <c>true</c> if it's a multi-dimensional array (i.e., <see cref="ArraySig"/>), /// and <c>false</c> if it's a single-dimensional array (i.e., <see cref="SZArraySig"/>) /// </summary> /// <seealso cref="IsSingleDimensional"/> public bool IsMultiDimensional => ElementType == ElementType.Array; /// <summary> /// <c>true</c> if it's a single-dimensional array (i.e., <see cref="SZArraySig"/>), /// and <c>false</c> if it's a multi-dimensional array (i.e., <see cref="ArraySig"/>) /// </summary> /// <see cref="IsMultiDimensional"/> public bool IsSingleDimensional => ElementType == ElementType.SZArray; /// <summary> /// Gets/sets the rank (number of dimensions). This can only be set if /// <see cref="IsMultiDimensional"/> is <c>true</c> /// </summary> public abstract uint Rank { get; set; } /// <summary> /// Gets all sizes. If it's a <see cref="SZArraySig"/>, then it will be an empty temporary /// list that is re-created every time this method is called. /// </summary> /// <returns>A list of sizes</returns> public abstract IList<uint> GetSizes(); /// <summary> /// Gets all lower bounds. If it's a <see cref="SZArraySig"/>, then it will be an empty /// temporary list that is re-created every time this method is called. /// </summary> /// <returns>A list of lower bounds</returns> public abstract IList<int> GetLowerBounds(); } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Array"/> /// </summary> /// <seealso cref="SZArraySig"/> public sealed class ArraySig : ArraySigBase { uint rank; readonly IList<uint> sizes; readonly IList<int> lowerBounds; /// <inheritdoc/> public override ElementType ElementType => ElementType.Array; /// <summary> /// Gets/sets the rank (max value is <c>0x1FFFFFFF</c>) /// </summary> public override uint Rank { get => rank; set => rank = value; } /// <summary> /// Gets all sizes (max elements is <c>0x1FFFFFFF</c>) /// </summary> public IList<uint> Sizes => sizes; /// <summary> /// Gets all lower bounds (max elements is <c>0x1FFFFFFF</c>) /// </summary> public IList<int> LowerBounds => lowerBounds; /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> public ArraySig(TypeSig arrayType) : base(arrayType) { sizes = new List<uint>(); lowerBounds = new List<int>(); } /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> /// <param name="rank">Array rank</param> public ArraySig(TypeSig arrayType, uint rank) : base(arrayType) { this.rank = rank; sizes = new List<uint>(); lowerBounds = new List<int>(); } /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> /// <param name="rank">Array rank</param> public ArraySig(TypeSig arrayType, int rank) : this(arrayType, (uint)rank) { } /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> /// <param name="rank">Array rank</param> /// <param name="sizes">Sizes list. <c>This instance will be the owner of this list.</c></param> /// <param name="lowerBounds">Lower bounds list. <c>This instance will be the owner of this list.</c></param> public ArraySig(TypeSig arrayType, uint rank, IEnumerable<uint> sizes, IEnumerable<int> lowerBounds) : base(arrayType) { this.rank = rank; this.sizes = new List<uint>(sizes); this.lowerBounds = new List<int>(lowerBounds); } /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> /// <param name="rank">Array rank</param> /// <param name="sizes">Sizes list. <c>This instance will be the owner of this list.</c></param> /// <param name="lowerBounds">Lower bounds list. <c>This instance will be the owner of this list.</c></param> public ArraySig(TypeSig arrayType, int rank, IEnumerable<uint> sizes, IEnumerable<int> lowerBounds) : this(arrayType, (uint)rank, sizes, lowerBounds) { } /// <summary> /// Constructor /// </summary> /// <param name="arrayType">Array type</param> /// <param name="rank">Array rank</param> /// <param name="sizes">Sizes list. <c>This instance will be the owner of this list.</c></param> /// <param name="lowerBounds">Lower bounds list. <c>This instance will be the owner of this list.</c></param> internal ArraySig(TypeSig arrayType, uint rank, IList<uint> sizes, IList<int> lowerBounds) : base(arrayType) { this.rank = rank; this.sizes = sizes; this.lowerBounds = lowerBounds; } /// <inheritdoc/> public override IList<uint> GetSizes() => sizes; /// <inheritdoc/> public override IList<int> GetLowerBounds() => lowerBounds; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.SZArray"/> (single dimension, zero lower bound array) /// </summary> /// <seealso cref="ArraySig"/> public sealed class SZArraySig : ArraySigBase { /// <inheritdoc/> public override ElementType ElementType => ElementType.SZArray; /// <inheritdoc/> public override uint Rank { get => 1; set => throw new NotSupportedException(); } /// <summary> /// Constructor /// </summary> /// <param name="nextSig">The next element type</param> public SZArraySig(TypeSig nextSig) : base(nextSig) { } /// <inheritdoc/> public override IList<uint> GetSizes() => Array2.Empty<uint>(); /// <inheritdoc/> public override IList<int> GetLowerBounds() => Array2.Empty<int>(); } /// <summary> /// Base class for modifier type sigs /// </summary> public abstract class ModifierSig : NonLeafSig { readonly ITypeDefOrRef modifier; /// <summary> /// Returns the modifier type /// </summary> public ITypeDefOrRef Modifier => modifier; /// <summary> /// Constructor /// </summary> /// <param name="modifier">Modifier type</param> /// <param name="nextSig">The next element type</param> protected ModifierSig(ITypeDefOrRef modifier, TypeSig nextSig) : base(nextSig) => this.modifier = modifier; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.CModReqd"/> /// </summary> public sealed class CModReqdSig : ModifierSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.CModReqd; /// <inheritdoc/> public CModReqdSig(ITypeDefOrRef modifier, TypeSig nextSig) : base(modifier, nextSig) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.CModOpt"/> /// </summary> public sealed class CModOptSig : ModifierSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.CModOpt; /// <inheritdoc/> public CModOptSig(ITypeDefOrRef modifier, TypeSig nextSig) : base(modifier, nextSig) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Pinned"/> /// </summary> public sealed class PinnedSig : NonLeafSig { /// <inheritdoc/> public override ElementType ElementType => ElementType.Pinned; /// <summary> /// Constructor /// </summary> /// <param name="nextSig">The next element type</param> public PinnedSig(TypeSig nextSig) : base(nextSig) { } } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.ValueArray"/> /// </summary> public sealed class ValueArraySig : NonLeafSig { uint size; /// <inheritdoc/> public override ElementType ElementType => ElementType.ValueArray; /// <summary> /// Gets/sets the size /// </summary> public uint Size { get => size; set => size = value; } /// <summary> /// Constructor /// </summary> /// <param name="nextSig">The next element type</param> /// <param name="size">Size of the array</param> public ValueArraySig(TypeSig nextSig, uint size) : base(nextSig) => this.size = size; } /// <summary> /// Represents a <see cref="dnlib.DotNet.ElementType.Module"/> /// </summary> public sealed class ModuleSig : NonLeafSig { uint index; /// <inheritdoc/> public override ElementType ElementType => ElementType.Module; /// <summary> /// Gets/sets the index /// </summary> public uint Index { get => index; set => index = value; } /// <summary> /// Constructor /// </summary> /// <param name="index">Index</param> /// <param name="nextSig">The next element type</param> public ModuleSig(uint index, TypeSig nextSig) : base(nextSig) => this.index = index; } }
//Copyright 2010 Microsoft Corporation // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. namespace System.Data.Services.Client { using System; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Resources; using System.Security.Permissions; using System.Text; using System.Threading; [AttributeUsage(AttributeTargets.All)] internal sealed class TextResDescriptionAttribute : DescriptionAttribute { private bool replaced = false; public TextResDescriptionAttribute(string description) : base(description) { } public override string Description { get { if (!replaced) { replaced = true; DescriptionValue = TextRes.GetString(base.Description); } return base.Description; } } } [AttributeUsage(AttributeTargets.All)] internal sealed class TextResCategoryAttribute : CategoryAttribute { public TextResCategoryAttribute(string category) : base(category) { } protected override string GetLocalizedString(string value) { return TextRes.GetString(value); } } internal sealed class TextRes { internal const string BatchStream_MissingBoundary = "BatchStream_MissingBoundary"; internal const string BatchStream_ContentExpected = "BatchStream_ContentExpected"; internal const string BatchStream_ContentUnexpected = "BatchStream_ContentUnexpected"; internal const string BatchStream_GetMethodNotSupportedInChangeset = "BatchStream_GetMethodNotSupportedInChangeset"; internal const string BatchStream_InvalidBatchFormat = "BatchStream_InvalidBatchFormat"; internal const string BatchStream_InvalidDelimiter = "BatchStream_InvalidDelimiter"; internal const string BatchStream_MissingEndChangesetDelimiter = "BatchStream_MissingEndChangesetDelimiter"; internal const string BatchStream_InvalidHeaderValueSpecified = "BatchStream_InvalidHeaderValueSpecified"; internal const string BatchStream_InvalidContentLengthSpecified = "BatchStream_InvalidContentLengthSpecified"; internal const string BatchStream_OnlyGETOperationsCanBeSpecifiedInBatch = "BatchStream_OnlyGETOperationsCanBeSpecifiedInBatch"; internal const string BatchStream_InvalidOperationHeaderSpecified = "BatchStream_InvalidOperationHeaderSpecified"; internal const string BatchStream_InvalidHttpMethodName = "BatchStream_InvalidHttpMethodName"; internal const string BatchStream_MoreDataAfterEndOfBatch = "BatchStream_MoreDataAfterEndOfBatch"; internal const string BatchStream_InternalBufferRequestTooSmall = "BatchStream_InternalBufferRequestTooSmall"; internal const string BatchStream_InvalidMethodHeaderSpecified = "BatchStream_InvalidMethodHeaderSpecified"; internal const string BatchStream_InvalidHttpVersionSpecified = "BatchStream_InvalidHttpVersionSpecified"; internal const string BatchStream_InvalidNumberOfHeadersAtOperationStart = "BatchStream_InvalidNumberOfHeadersAtOperationStart"; internal const string BatchStream_MissingOrInvalidContentEncodingHeader = "BatchStream_MissingOrInvalidContentEncodingHeader"; internal const string BatchStream_InvalidNumberOfHeadersAtChangeSetStart = "BatchStream_InvalidNumberOfHeadersAtChangeSetStart"; internal const string BatchStream_MissingContentTypeHeader = "BatchStream_MissingContentTypeHeader"; internal const string BatchStream_InvalidContentTypeSpecified = "BatchStream_InvalidContentTypeSpecified"; internal const string Batch_ExpectedContentType = "Batch_ExpectedContentType"; internal const string Batch_ExpectedResponse = "Batch_ExpectedResponse"; internal const string Batch_IncompleteResponseCount = "Batch_IncompleteResponseCount"; internal const string Batch_UnexpectedContent = "Batch_UnexpectedContent"; internal const string Context_BaseUri = "Context_BaseUri"; internal const string Context_CannotConvertKey = "Context_CannotConvertKey"; internal const string Context_TrackingExpectsAbsoluteUri = "Context_TrackingExpectsAbsoluteUri"; internal const string Context_LinkResourceInsertFailure = "Context_LinkResourceInsertFailure"; internal const string Context_InternalError = "Context_InternalError"; internal const string Context_BatchExecuteError = "Context_BatchExecuteError"; internal const string Context_EntitySetName = "Context_EntitySetName"; internal const string Context_MissingEditLinkInResponseBody = "Context_MissingEditLinkInResponseBody"; internal const string Context_MissingSelfLinkInResponseBody = "Context_MissingSelfLinkInResponseBody"; internal const string Context_MissingEditMediaLinkInResponseBody = "Context_MissingEditMediaLinkInResponseBody"; internal const string Content_EntityWithoutKey = "Content_EntityWithoutKey"; internal const string Content_EntityIsNotEntityType = "Content_EntityIsNotEntityType"; internal const string Context_EntityNotContained = "Context_EntityNotContained"; internal const string Context_EntityAlreadyContained = "Context_EntityAlreadyContained"; internal const string Context_DifferentEntityAlreadyContained = "Context_DifferentEntityAlreadyContained"; internal const string Context_DidNotOriginateAsync = "Context_DidNotOriginateAsync"; internal const string Context_AsyncAlreadyDone = "Context_AsyncAlreadyDone"; internal const string Context_OperationCanceled = "Context_OperationCanceled"; internal const string Context_NoLoadWithInsertEnd = "Context_NoLoadWithInsertEnd"; internal const string Context_NoRelationWithInsertEnd = "Context_NoRelationWithInsertEnd"; internal const string Context_NoRelationWithDeleteEnd = "Context_NoRelationWithDeleteEnd"; internal const string Context_RelationAlreadyContained = "Context_RelationAlreadyContained"; internal const string Context_RelationNotRefOrCollection = "Context_RelationNotRefOrCollection"; internal const string Context_AddLinkCollectionOnly = "Context_AddLinkCollectionOnly"; internal const string Context_AddRelatedObjectCollectionOnly = "Context_AddRelatedObjectCollectionOnly"; internal const string Context_AddRelatedObjectSourceDeleted = "Context_AddRelatedObjectSourceDeleted"; internal const string Context_SetLinkReferenceOnly = "Context_SetLinkReferenceOnly"; internal const string Context_NoContentTypeForMediaLink = "Context_NoContentTypeForMediaLink"; internal const string Context_BatchNotSupportedForMediaLink = "Context_BatchNotSupportedForMediaLink"; internal const string Context_UnexpectedZeroRawRead = "Context_UnexpectedZeroRawRead"; internal const string Context_VersionNotSupported = "Context_VersionNotSupported"; internal const string Context_ChildResourceExists = "Context_ChildResourceExists"; internal const string Context_EntityNotMediaLinkEntry = "Context_EntityNotMediaLinkEntry"; internal const string Context_MLEWithoutSaveStream = "Context_MLEWithoutSaveStream"; internal const string Context_SetSaveStreamOnMediaEntryProperty = "Context_SetSaveStreamOnMediaEntryProperty"; internal const string Context_SetSaveStreamWithoutEditMediaLink = "Context_SetSaveStreamWithoutEditMediaLink"; internal const string Collection_NullCollectionReference = "Collection_NullCollectionReference"; internal const string ClientType_MissingOpenProperty = "ClientType_MissingOpenProperty"; internal const string Clienttype_MultipleOpenProperty = "Clienttype_MultipleOpenProperty"; internal const string ClientType_MissingProperty = "ClientType_MissingProperty"; internal const string ClientType_KeysMustBeSimpleTypes = "ClientType_KeysMustBeSimpleTypes"; internal const string ClientType_KeysOnDifferentDeclaredType = "ClientType_KeysOnDifferentDeclaredType"; internal const string ClientType_MissingMimeTypeProperty = "ClientType_MissingMimeTypeProperty"; internal const string ClientType_MissingMediaEntryProperty = "ClientType_MissingMediaEntryProperty"; internal const string ClientType_NoSettableFields = "ClientType_NoSettableFields"; internal const string ClientType_MultipleImplementationNotSupported = "ClientType_MultipleImplementationNotSupported"; internal const string ClientType_NullOpenProperties = "ClientType_NullOpenProperties"; internal const string ClientType_CollectionOfNonEntities = "ClientType_CollectionOfNonEntities"; internal const string ClientType_Ambiguous = "ClientType_Ambiguous"; internal const string ClientType_UnsupportedType = "ClientType_UnsupportedType"; internal const string DataServiceException_GeneralError = "DataServiceException_GeneralError"; internal const string Deserialize_GetEnumerator = "Deserialize_GetEnumerator"; internal const string Deserialize_Current = "Deserialize_Current"; internal const string Deserialize_MixedTextWithComment = "Deserialize_MixedTextWithComment"; internal const string Deserialize_ExpectingSimpleValue = "Deserialize_ExpectingSimpleValue"; internal const string Deserialize_NotApplicationXml = "Deserialize_NotApplicationXml"; internal const string Deserialize_MismatchAtomLinkLocalSimple = "Deserialize_MismatchAtomLinkLocalSimple"; internal const string Deserialize_MismatchAtomLinkFeedPropertyNotCollection = "Deserialize_MismatchAtomLinkFeedPropertyNotCollection"; internal const string Deserialize_MismatchAtomLinkEntryPropertyIsCollection = "Deserialize_MismatchAtomLinkEntryPropertyIsCollection"; internal const string Deserialize_UnknownMimeTypeSpecified = "Deserialize_UnknownMimeTypeSpecified"; internal const string Deserialize_ExpectedEmptyMediaLinkEntryContent = "Deserialize_ExpectedEmptyMediaLinkEntryContent"; internal const string Deserialize_ContentPlusPropertiesNotAllowed = "Deserialize_ContentPlusPropertiesNotAllowed"; internal const string Deserialize_NoLocationHeader = "Deserialize_NoLocationHeader"; internal const string Deserialize_ServerException = "Deserialize_ServerException"; internal const string Deserialize_MissingIdElement = "Deserialize_MissingIdElement"; internal const string EpmClientType_PropertyIsComplex = "EpmClientType_PropertyIsComplex"; internal const string EpmClientType_PropertyIsPrimitive = "EpmClientType_PropertyIsPrimitive"; internal const string EpmSourceTree_InvalidSourcePath = "EpmSourceTree_InvalidSourcePath"; internal const string EpmSourceTree_DuplicateEpmAttrsWithSameSourceName = "EpmSourceTree_DuplicateEpmAttrsWithSameSourceName"; internal const string EpmSourceTree_InaccessiblePropertyOnType = "EpmSourceTree_InaccessiblePropertyOnType"; internal const string EpmTargetTree_InvalidTargetPath = "EpmTargetTree_InvalidTargetPath"; internal const string EpmTargetTree_AttributeInMiddle = "EpmTargetTree_AttributeInMiddle"; internal const string EpmTargetTree_DuplicateEpmAttrsWithSameTargetName = "EpmTargetTree_DuplicateEpmAttrsWithSameTargetName"; internal const string EntityPropertyMapping_EpmAttribute = "EntityPropertyMapping_EpmAttribute"; internal const string EntityPropertyMapping_TargetNamespaceUriNotValid = "EntityPropertyMapping_TargetNamespaceUriNotValid"; internal const string HttpProcessUtility_ContentTypeMissing = "HttpProcessUtility_ContentTypeMissing"; internal const string HttpProcessUtility_MediaTypeMissingValue = "HttpProcessUtility_MediaTypeMissingValue"; internal const string HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter = "HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter"; internal const string HttpProcessUtility_MediaTypeRequiresSlash = "HttpProcessUtility_MediaTypeRequiresSlash"; internal const string HttpProcessUtility_MediaTypeRequiresSubType = "HttpProcessUtility_MediaTypeRequiresSubType"; internal const string HttpProcessUtility_MediaTypeUnspecified = "HttpProcessUtility_MediaTypeUnspecified"; internal const string HttpProcessUtility_EncodingNotSupported = "HttpProcessUtility_EncodingNotSupported"; internal const string HttpProcessUtility_EscapeCharWithoutQuotes = "HttpProcessUtility_EscapeCharWithoutQuotes"; internal const string HttpProcessUtility_EscapeCharAtEnd = "HttpProcessUtility_EscapeCharAtEnd"; internal const string HttpProcessUtility_ClosingQuoteNotFound = "HttpProcessUtility_ClosingQuoteNotFound"; internal const string MaterializeFromAtom_CountNotPresent = "MaterializeFromAtom_CountNotPresent"; internal const string MaterializeFromAtom_CountFormatError = "MaterializeFromAtom_CountFormatError"; internal const string MaterializeFromAtom_TopLevelLinkNotAvailable = "MaterializeFromAtom_TopLevelLinkNotAvailable"; internal const string MaterializeFromAtom_CollectionKeyNotPresentInLinkTable = "MaterializeFromAtom_CollectionKeyNotPresentInLinkTable"; internal const string MaterializeFromAtom_GetNestLinkForFlatCollection = "MaterializeFromAtom_GetNestLinkForFlatCollection"; internal const string Serializer_NullKeysAreNotSupported = "Serializer_NullKeysAreNotSupported"; internal const string Util_EmptyString = "Util_EmptyString"; internal const string Util_EmptyArray = "Util_EmptyArray"; internal const string Util_NullArrayElement = "Util_NullArrayElement"; internal const string ALinq_UnsupportedExpression = "ALinq_UnsupportedExpression"; internal const string ALinq_CouldNotConvert = "ALinq_CouldNotConvert"; internal const string ALinq_MethodNotSupported = "ALinq_MethodNotSupported"; internal const string ALinq_UnaryNotSupported = "ALinq_UnaryNotSupported"; internal const string ALinq_BinaryNotSupported = "ALinq_BinaryNotSupported"; internal const string ALinq_ConstantNotSupported = "ALinq_ConstantNotSupported"; internal const string ALinq_TypeBinaryNotSupported = "ALinq_TypeBinaryNotSupported"; internal const string ALinq_ConditionalNotSupported = "ALinq_ConditionalNotSupported"; internal const string ALinq_ParameterNotSupported = "ALinq_ParameterNotSupported"; internal const string ALinq_MemberAccessNotSupported = "ALinq_MemberAccessNotSupported"; internal const string ALinq_LambdaNotSupported = "ALinq_LambdaNotSupported"; internal const string ALinq_NewNotSupported = "ALinq_NewNotSupported"; internal const string ALinq_MemberInitNotSupported = "ALinq_MemberInitNotSupported"; internal const string ALinq_ListInitNotSupported = "ALinq_ListInitNotSupported"; internal const string ALinq_NewArrayNotSupported = "ALinq_NewArrayNotSupported"; internal const string ALinq_InvocationNotSupported = "ALinq_InvocationNotSupported"; internal const string ALinq_QueryOptionsOnlyAllowedOnLeafNodes = "ALinq_QueryOptionsOnlyAllowedOnLeafNodes"; internal const string ALinq_CantExpand = "ALinq_CantExpand"; internal const string ALinq_CantCastToUnsupportedPrimitive = "ALinq_CantCastToUnsupportedPrimitive"; internal const string ALinq_CantNavigateWithoutKeyPredicate = "ALinq_CantNavigateWithoutKeyPredicate"; internal const string ALinq_CanOnlyApplyOneKeyPredicate = "ALinq_CanOnlyApplyOneKeyPredicate"; internal const string ALinq_CantTranslateExpression = "ALinq_CantTranslateExpression"; internal const string ALinq_TranslationError = "ALinq_TranslationError"; internal const string ALinq_CantAddQueryOption = "ALinq_CantAddQueryOption"; internal const string ALinq_CantAddDuplicateQueryOption = "ALinq_CantAddDuplicateQueryOption"; internal const string ALinq_CantAddAstoriaQueryOption = "ALinq_CantAddAstoriaQueryOption"; internal const string ALinq_CantAddQueryOptionStartingWithDollarSign = "ALinq_CantAddQueryOptionStartingWithDollarSign"; internal const string ALinq_CantReferToPublicField = "ALinq_CantReferToPublicField"; internal const string ALinq_QueryOptionsOnlyAllowedOnSingletons = "ALinq_QueryOptionsOnlyAllowedOnSingletons"; internal const string ALinq_QueryOptionOutOfOrder = "ALinq_QueryOptionOutOfOrder"; internal const string ALinq_CannotAddCountOption = "ALinq_CannotAddCountOption"; internal const string ALinq_CannotAddCountOptionConflict = "ALinq_CannotAddCountOptionConflict"; internal const string ALinq_ProjectionOnlyAllowedOnLeafNodes = "ALinq_ProjectionOnlyAllowedOnLeafNodes"; internal const string ALinq_ProjectionCanOnlyHaveOneProjection = "ALinq_ProjectionCanOnlyHaveOneProjection"; internal const string ALinq_ProjectionMemberAssignmentMismatch = "ALinq_ProjectionMemberAssignmentMismatch"; internal const string ALinq_ExpressionNotSupportedInProjectionToEntity = "ALinq_ExpressionNotSupportedInProjectionToEntity"; internal const string ALinq_ExpressionNotSupportedInProjection = "ALinq_ExpressionNotSupportedInProjection"; internal const string ALinq_CannotConstructKnownEntityTypes = "ALinq_CannotConstructKnownEntityTypes"; internal const string ALinq_CannotCreateConstantEntity = "ALinq_CannotCreateConstantEntity"; internal const string ALinq_PropertyNamesMustMatchInProjections = "ALinq_PropertyNamesMustMatchInProjections"; internal const string ALinq_CanOnlyProjectTheLeaf = "ALinq_CanOnlyProjectTheLeaf"; internal const string ALinq_CannotProjectWithExplicitExpansion = "ALinq_CannotProjectWithExplicitExpansion"; internal const string DSKAttribute_MustSpecifyAtleastOnePropertyName = "DSKAttribute_MustSpecifyAtleastOnePropertyName"; internal const string HttpWeb_Internal = "HttpWeb_Internal"; internal const string HttpWeb_InternalArgument = "HttpWeb_InternalArgument"; internal const string HttpWebRequest_Aborted = "HttpWebRequest_Aborted"; internal const string DataServiceCollection_LoadRequiresTargetCollectionObserved = "DataServiceCollection_LoadRequiresTargetCollectionObserved"; internal const string DataServiceCollection_CannotStopTrackingChildCollection = "DataServiceCollection_CannotStopTrackingChildCollection"; internal const string DataServiceCollection_DataServiceQueryCanNotBeEnumerated = "DataServiceCollection_DataServiceQueryCanNotBeEnumerated"; internal const string DataServiceCollection_OperationForTrackedOnly = "DataServiceCollection_OperationForTrackedOnly"; internal const string DataServiceCollection_CannotDetermineContextFromItems = "DataServiceCollection_CannotDetermineContextFromItems"; internal const string DataServiceCollection_InsertIntoTrackedButNotLoadedCollection = "DataServiceCollection_InsertIntoTrackedButNotLoadedCollection"; internal const string DataServiceCollection_MultipleLoadAsyncOperationsAtTheSameTime = "DataServiceCollection_MultipleLoadAsyncOperationsAtTheSameTime"; internal const string DataServiceCollection_LoadAsyncNoParamsWithoutParentEntity = "DataServiceCollection_LoadAsyncNoParamsWithoutParentEntity"; internal const string DataServiceCollection_LoadAsyncRequiresDataServiceQuery = "DataServiceCollection_LoadAsyncRequiresDataServiceQuery"; internal const string DataBinding_DataServiceCollectionArgumentMustHaveEntityType = "DataBinding_DataServiceCollectionArgumentMustHaveEntityType"; internal const string DataBinding_CollectionPropertySetterValueHasObserver = "DataBinding_CollectionPropertySetterValueHasObserver"; internal const string DataBinding_CollectionChangedUnknownAction = "DataBinding_CollectionChangedUnknownAction"; internal const string DataBinding_BindingOperation_DetachedSource = "DataBinding_BindingOperation_DetachedSource"; internal const string DataBinding_BindingOperation_ArrayItemNull = "DataBinding_BindingOperation_ArrayItemNull"; internal const string DataBinding_BindingOperation_ArrayItemNotEntity = "DataBinding_BindingOperation_ArrayItemNotEntity"; internal const string DataBinding_Util_UnknownEntitySetName = "DataBinding_Util_UnknownEntitySetName"; internal const string DataBinding_EntityAlreadyInCollection = "DataBinding_EntityAlreadyInCollection"; internal const string DataBinding_NotifyPropertyChangedNotImpl = "DataBinding_NotifyPropertyChangedNotImpl"; internal const string DataBinding_ComplexObjectAssociatedWithMultipleEntities = "DataBinding_ComplexObjectAssociatedWithMultipleEntities"; internal const string AtomParser_FeedUnexpected = "AtomParser_FeedUnexpected"; internal const string AtomParser_PagingLinkOutsideOfFeed = "AtomParser_PagingLinkOutsideOfFeed"; internal const string AtomParser_ManyFeedCounts = "AtomParser_ManyFeedCounts"; internal const string AtomParser_FeedCountNotUnderFeed = "AtomParser_FeedCountNotUnderFeed"; internal const string AtomParser_UnexpectedContentUnderExpandedLink = "AtomParser_UnexpectedContentUnderExpandedLink"; internal const string AtomMaterializer_CannotAssignNull = "AtomMaterializer_CannotAssignNull"; internal const string AtomMaterializer_DuplicatedNextLink = "AtomMaterializer_DuplicatedNextLink"; internal const string AtomMaterializer_EntryIntoCollectionMismatch = "AtomMaterializer_EntryIntoCollectionMismatch"; internal const string AtomMaterializer_EntryToAccessIsNull = "AtomMaterializer_EntryToAccessIsNull"; internal const string AtomMaterializer_EntryToInitializeIsNull = "AtomMaterializer_EntryToInitializeIsNull"; internal const string AtomMaterializer_ProjectEntityTypeMismatch = "AtomMaterializer_ProjectEntityTypeMismatch"; internal const string AtomMaterializer_LinksMissingHref = "AtomMaterializer_LinksMissingHref"; internal const string AtomMaterializer_PropertyMissing = "AtomMaterializer_PropertyMissing"; internal const string AtomMaterializer_PropertyMissingFromEntry = "AtomMaterializer_PropertyMissingFromEntry"; internal const string AtomMaterializer_PropertyNotExpectedEntry = "AtomMaterializer_PropertyNotExpectedEntry"; internal const string DataServiceQuery_EnumerationNotSupportedInSL = "DataServiceQuery_EnumerationNotSupportedInSL"; static TextRes loader = null; ResourceManager resources; internal TextRes() { resources = new System.Resources.ResourceManager("System.Data.Services.Client", this.GetType().Assembly); } private static TextRes GetLoader() { if (loader == null) { TextRes sr = new TextRes(); Interlocked.CompareExchange(ref loader, sr, null); } return loader; } private static CultureInfo Culture { get { return null; } } public static ResourceManager Resources { get { return GetLoader().resources; } } public static string GetString(string name, params object[] args) { TextRes sys = GetLoader(); if (sys == null) return null; string res = sys.resources.GetString(name, TextRes.Culture); if (args != null && args.Length > 0) { for (int i = 0; i < args.Length; i ++) { String value = args[i] as String; if (value != null && value.Length > 1024) { args[i] = value.Substring(0, 1024 - 3) + "..."; } } return String.Format(CultureInfo.CurrentCulture, res, args); } else { return res; } } public static string GetString(string name) { TextRes sys = GetLoader(); if (sys == null) return null; return sys.resources.GetString(name, TextRes.Culture); } public static string GetString(string name, out bool usedFallback) { usedFallback = false; return GetString(name); } public static object GetObject(string name) { TextRes sys = GetLoader(); if (sys == null) return null; return sys.resources.GetObject(name, TextRes.Culture); } } }
using System.Collections.Generic; using System.Linq; using Content.Shared.Acts; using Content.Shared.Alert; using Content.Shared.Buckle.Components; using Content.Shared.DragDrop; using Content.Shared.Interaction; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.Buckle.Components { [RegisterComponent] [ComponentReference(typeof(SharedStrapComponent))] public sealed class StrapComponent : SharedStrapComponent, IInteractHand, ISerializationHooks, IDestroyAct { [Dependency] private readonly IEntityManager _entityManager = default!; private readonly HashSet<EntityUid> _buckledEntities = new(); /// <summary> /// The angle in degrees to rotate the player by when they get strapped /// </summary> [ViewVariables] [DataField("rotation")] private int _rotation; /// <summary> /// The size of the strap which is compared against when buckling entities /// </summary> [ViewVariables] [DataField("size")] private int _size = 100; private int _occupiedSize; /// <summary> /// The buckled entity will be offset by this amount from the center of the strap object. /// If this offset it too big, it will be clamped to <see cref="MaxBuckleDistance"/> /// </summary> [DataField("buckleOffset", required: false)] private Vector2 _buckleOffset = Vector2.Zero; private bool _enabled = true; /// <summary> /// If disabled, nothing can be buckled on this object, and it will unbuckle anything that's already buckled /// </summary> public bool Enabled { get => _enabled; set { _enabled = value; if (_enabled == value) return; RemoveAll(); } } /// <summary> /// The distance above which a buckled entity will be automatically unbuckled. /// Don't change it unless you really have to /// </summary> [DataField("maxBuckleDistance", required: false)] public float MaxBuckleDistance = 0.1f; /// <summary> /// You can specify the offset the entity will have after unbuckling. /// </summary> [DataField("unbuckleOffset", required: false)] public Vector2 UnbuckleOffset = Vector2.Zero; /// <summary> /// Gets and clamps the buckle offset to MaxBuckleDistance /// </summary> public Vector2 BuckleOffset => Vector2.Clamp( _buckleOffset, Vector2.One * -MaxBuckleDistance, Vector2.One * MaxBuckleDistance); /// <summary> /// The entity that is currently buckled here, synced from <see cref="BuckleComponent.BuckledTo"/> /// </summary> public IReadOnlyCollection<EntityUid> BuckledEntities => _buckledEntities; /// <summary> /// The change in position to the strapped mob /// </summary> [DataField("position")] public StrapPosition Position { get; } = StrapPosition.None; /// <summary> /// The sound to be played when a mob is buckled /// </summary> [ViewVariables] [DataField("buckleSound")] public SoundSpecifier BuckleSound { get; } = new SoundPathSpecifier("/Audio/Effects/buckle.ogg"); /// <summary> /// The sound to be played when a mob is unbuckled /// </summary> [ViewVariables] [DataField("unbuckleSound")] public SoundSpecifier UnbuckleSound { get; } = new SoundPathSpecifier("/Audio/Effects/unbuckle.ogg"); /// <summary> /// ID of the alert to show when buckled /// </summary> [ViewVariables] [DataField("buckledAlertType")] public AlertType BuckledAlertType { get; } = AlertType.Buckled; /// <summary> /// The sum of the sizes of all the buckled entities in this strap /// </summary> [ViewVariables] public int OccupiedSize => _occupiedSize; /// <summary> /// Checks if this strap has enough space for a new occupant. /// </summary> /// <param name="buckle">The new occupant</param> /// <returns>true if there is enough space, false otherwise</returns> public bool HasSpace(BuckleComponent buckle) { return OccupiedSize + buckle.Size <= _size; } /// <summary> /// DO NOT CALL THIS DIRECTLY. /// Adds a buckled entity. Called from <see cref="BuckleComponent.TryBuckle"/> /// </summary> /// <param name="buckle">The component to add</param> /// <param name="force"> /// Whether or not to check if the strap has enough space /// </param> /// <returns>True if added, false otherwise</returns> public bool TryAdd(BuckleComponent buckle, bool force = false) { if (!Enabled) return false; if (!force && !HasSpace(buckle)) { return false; } if (!_buckledEntities.Add(buckle.Owner)) { return false; } _occupiedSize += buckle.Size; if(_entityManager.TryGetComponent<AppearanceComponent>(buckle.Owner, out var appearanceComponent)) appearanceComponent.SetData(StrapVisuals.RotationAngle, _rotation); // Update the visuals of the strap object if (IoCManager.Resolve<IEntityManager>().TryGetComponent<AppearanceComponent>(Owner, out var appearance)) { appearance.SetData("StrapState", true); } return true; } /// <summary> /// Removes a buckled entity. /// Called from <see cref="BuckleComponent.TryUnbuckle"/> /// </summary> /// <param name="buckle">The component to remove</param> public void Remove(BuckleComponent buckle) { if (_buckledEntities.Remove(buckle.Owner)) { if (IoCManager.Resolve<IEntityManager>().TryGetComponent<AppearanceComponent>(Owner, out var appearance)) { appearance.SetData("StrapState", false); } _occupiedSize -= buckle.Size; } } protected override void OnRemove() { base.OnRemove(); RemoveAll(); } void IDestroyAct.OnDestroy(DestructionEventArgs eventArgs) { RemoveAll(); } private void RemoveAll() { var entManager = IoCManager.Resolve<IEntityManager>(); foreach (var entity in _buckledEntities.ToArray()) { if (entManager.TryGetComponent<BuckleComponent>(entity, out var buckle)) { buckle.TryUnbuckle(entity, true); } } _buckledEntities.Clear(); _occupiedSize = 0; } public override ComponentState GetComponentState() { return new StrapComponentState(Position); } bool IInteractHand.InteractHand(InteractHandEventArgs eventArgs) { var entManager = IoCManager.Resolve<IEntityManager>(); if (!entManager.TryGetComponent<BuckleComponent>(eventArgs.User, out var buckle)) { return false; } return buckle.ToggleBuckle(eventArgs.User, Owner); } public override bool DragDropOn(DragDropEvent eventArgs) { var entManager = IoCManager.Resolve<IEntityManager>(); if (!entManager.TryGetComponent(eventArgs.Dragged, out BuckleComponent? buckleComponent)) return false; return buckleComponent.TryBuckle(eventArgs.User, Owner); } } }
/***************************************************************************\ * * File: WindowsEditBoxRange.cs * * Description: * ITextRangeProvider interface for WindowsEditBox * * Revision History: * 3/01/04: a-davidj created. * * Copyright (C) 2004 by Microsoft Corporation. All rights reserved. * \***************************************************************************/ // PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Input; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows.Automation.Text; using System.ComponentModel; using MS.Win32; namespace MS.Internal.AutomationProxies { // TERMINOLOGY: Win32 Edit controls use the term "index" to mean a character position. // For example the EM_LINEINDEX message converts a line number to it's starting character position. // Perhaps not the best choice but we use it to be consistent. internal class WindowsEditBoxRange : ITextRangeProvider { //------------------------------------------------------ // // Constructor // //------------------------------------------------------ internal WindowsEditBoxRange(WindowsEditBox provider, int start, int end) { if (start < 0 || end < start) { // i'm throwing an invalid operation exception rather than an argument exception because // clients never call this constructor directly. it always happens as a result of some // other operation, e.g. cloning an existing TextPatternRange. throw new InvalidOperationException(SR.Get(SRID.InvalidTextRangeOffset,GetType().FullName)); } Debug.Assert(provider != null); _provider = provider; _start = start; _end = end; } //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods ITextRangeProvider ITextRangeProvider.Clone() { return new WindowsEditBoxRange(_provider, Start, End); } bool ITextRangeProvider.Compare(ITextRangeProvider range) { // TextPatternRange already verifies the other range comes from the same element before forwarding so we only need to worry about // whether the endpoints are identical. WindowsEditBoxRange editRange = (WindowsEditBoxRange)range; return editRange.Start == Start && editRange.End == End; } int ITextRangeProvider.CompareEndpoints(TextPatternRangeEndpoint endpoint, ITextRangeProvider targetRange, TextPatternRangeEndpoint targetEndpoint) { // TextPatternRange already verifies the other range comes from the same element before forwarding so we only need to worry about // comparing the endpoints. WindowsEditBoxRange editRange = (WindowsEditBoxRange)targetRange; int e1 = (endpoint == TextPatternRangeEndpoint.Start) ? Start : End; int e2 = (targetEndpoint == TextPatternRangeEndpoint.Start) ? editRange.Start : editRange.End; return e1 - e2; } void ITextRangeProvider.ExpandToEnclosingUnit(TextUnit unit) { Misc.SetFocus(_provider._hwnd); switch (unit) { case TextUnit.Character: // if it is a degenerate range then expand it to be one character. // otherwise, leave it as it is. if (Start == End) { int moved; End = MoveEndpointForward(End, TextUnit.Character, 1, out moved); } break; case TextUnit.Word: { // this works same as paragraph except we look for word boundaries instead of paragraph boundaries. // get the text so we can figure out where the boundaries are string text = _provider.GetText(); ValidateEndpoints(); #if WCP_NLS_ENABLED // use the same word breaker that Avalon Text uses. WordBreaker breaker = new WordBreaker(); TextContainer container = new TextContainer(text); // if the starting point of the range is not already at a word break // then move it backwards to the nearest word break. TextNavigator startNavigator = new TextNavigator(Start, container); if (!breaker.IsAtWordBreak(startNavigator)) { breaker.MoveToPreviousWordBreak(startNavigator); Start = startNavigator.Position; } // if the range is degenerate or the ending point of the range is not already at a word break // then move it forwards to the nearest word break. TextNavigator endNavigator = new TextNavigator(End, container); if (Start==End || !breaker.IsAtWordBreak(endNavigator)) { breaker.MoveToNextWordBreak(endNavigator); End = endNavigator.Position; } #else // move start left until we reach a word boundary. for (; !AtWordBoundary(text, Start); Start--) ; // move end right until we reach word boundary (different from Start). End = Math.Min(Math.Max(End, Start + 1), text.Length); for (; !AtWordBoundary(text, End); End++) ; #endif } break; case TextUnit.Line: { if (_provider.GetLineCount() != 1) { int startLine = _provider.LineFromChar(Start); int endLine = _provider.LineFromChar(End); MoveTo(_provider.LineIndex(startLine), _provider.LineIndex(endLine + 1)); } else { MoveTo(0, _provider.GetTextLength()); } } break; case TextUnit.Paragraph: { // this works same as paragraph except we look for word boundaries instead of paragraph boundaries. // get the text so we can figure out where the boundaries are string text = _provider.GetText(); ValidateEndpoints(); // move start left until we reach a paragraph boundary. for (; !AtParagraphBoundary(text, Start); Start--); // move end right until we reach a paragraph boundary (different from Start). End = Math.Min(Math.Max(End, Start + 1), text.Length); for (; !AtParagraphBoundary(text, End); End++); } break; case TextUnit.Format: case TextUnit.Page: case TextUnit.Document: MoveTo(0, _provider.GetTextLength()); break; //break; default: throw new System.ComponentModel.InvalidEnumArgumentException("unit", (int)unit, typeof(TextUnit)); } } ITextRangeProvider ITextRangeProvider.FindAttribute(int attributeId, object val, bool backwards) { AutomationTextAttribute attribute = AutomationTextAttribute.LookupById(attributeId); // generic controls are plain text so if the attribute matches then it matches over the whole range. // To workaround the conversion that Marshaling of COM-interop did. object targetAttribute = GetAttributeValue(attribute); if (targetAttribute is Enum) { targetAttribute = (int)targetAttribute; } return val.Equals(targetAttribute) ? new WindowsEditBoxRange(_provider, Start, End) : null; } ITextRangeProvider ITextRangeProvider.FindText(string text, bool backwards, bool ignoreCase) { // PerSharp/PreFast will flag this as warning 6507/56507: Prefer 'string.IsNullOrEmpty(text)' over checks for null and/or emptiness. // A null string is not should throw an ArgumentNullException while an empty string should throw an ArgumentException. // Therefore we can not use IsNullOrEmpty() here, suppress the warning. #pragma warning suppress 6507 if (text == null) { throw new ArgumentNullException("text"); } #pragma warning suppress 6507 if (text.Length == 0) { throw new ArgumentException(SR.Get(SRID.InvalidParameter)); } // get the text of the range string rangeText = _provider.GetText(); ValidateEndpoints(); rangeText = rangeText.Substring(Start, Length); // if we are ignoring case then convert everything to lowercase if (ignoreCase) { rangeText = rangeText.ToLower(System.Globalization.CultureInfo.InvariantCulture); text = text.ToLower(System.Globalization.CultureInfo.InvariantCulture); } // do a case-sensitive search for the text inside the range. int i = backwards ? rangeText.LastIndexOf(text, StringComparison.Ordinal) : rangeText.IndexOf(text, StringComparison.Ordinal); // if the text was found then create a new range covering the found text. return i >= 0 ? new WindowsEditBoxRange(_provider, Start + i, Start + i + text.Length) : null; } object ITextRangeProvider.GetAttributeValue(int attributeId) { AutomationTextAttribute attribute = AutomationTextAttribute.LookupById(attributeId); return GetAttributeValue(attribute); } double[] ITextRangeProvider.GetBoundingRectangles() { // Return zero rectangles for a degenerate range. We don't return an empty, // but properly positioned, rectangle for degenerate ranges because // there is ambiguity at line breaks and some international scenarios. if (IsDegenerate) { return new double[0]; } // we'll need to have the text eventually (so we can measure characters) so get it up // front so we can check the endpoints before proceeding. string text = _provider.GetText(); ValidateEndpoints(); // get the mapping from client coordinates to screen coordinates NativeMethods.Win32Point w32point; w32point.x = 0; w32point.y = 0; if (!Misc.MapWindowPoints(_provider.WindowHandle, IntPtr.Zero, ref w32point, 1)) { return new double[0]; } Point mapClientToScreen = new Point(w32point.x, w32point.y); // clip the rectangles to the edit control's formatting rectangle Rect clippingRectangle = _provider.GetRect(); // we accumulate rectangles onto a list ArrayList rects; if (_provider.IsMultiline) { rects = GetMultilineBoundingRectangles(text, mapClientToScreen, clippingRectangle); } else { // single line edit control rects = new ArrayList(1); // figure out the rectangle for this one line Point startPoint = _provider.PosFromChar(Start); Point endPoint = _provider.PosFromCharUR(End - 1, text); Rect rect = new Rect(startPoint.X, startPoint.Y, endPoint.X - startPoint.X, clippingRectangle.Height); rect.Intersect(clippingRectangle); // use the rectangle if it is non-empty. if (rect.Width > 0 && rect.Height > 0) // r.Empty is true only if both width & height are zero. Duh! { rect.Offset(mapClientToScreen.X, mapClientToScreen.Y); rects.Add(rect); } } // convert the list of rectangles into an array for returning Rect[] rectArray = new Rect[rects.Count]; rects.CopyTo(rectArray); return Misc.RectArrayToDoubleArray(rectArray); } IRawElementProviderSimple ITextRangeProvider.GetEnclosingElement() { return _provider; } string ITextRangeProvider.GetText(int maxLength) { if (maxLength < 0) maxLength = End; string text = _provider.GetText(); ValidateEndpoints(); return text.Substring(Start, maxLength >= 0 ? Math.Min(Length, maxLength) : Length); } int ITextRangeProvider.Move(TextUnit unit, int count) { Misc.SetFocus(_provider._hwnd); // positive count means move forward. negative count means move backwards. int moved = 0; if (count > 0) { // If the range is non-degenerate then we need to collapse the range. // (See the discussion of Count for ITextRange::Move) if (!IsDegenerate) { // If the count is greater than zero, collapse the range at its end point Start = End; } // move the degenerate range forward by the number of units int m; int start = Start; Start = MoveEndpointForward(Start, unit, count, out m); // if the start did not change then no move was done. if (start != Start) { moved = m; } } else if (count < 0) { // If the range is non-degenerate then we need to collapse the range. if (!IsDegenerate) { // If the count is less than zero, collapse the range at the starting point End = Start; } // move the degenerate range backward by the number of units int m; int end = End; End = MoveEndpointBackward(End, unit, count, out m); // if the end did not change then no move was done. if (end != End) { moved = m; } } else { // moving zero of any unit has no effect. moved = 0; } return moved; } int ITextRangeProvider.MoveEndpointByUnit(TextPatternRangeEndpoint endpoint, TextUnit unit, int count) { Misc.SetFocus(_provider._hwnd); // positive count means move forward. negative count means move backwards. int moved = 0; bool moveStart = endpoint == TextPatternRangeEndpoint.Start; int start = Start; int end = End; if (count > 0) { if (moveStart) { Start = MoveEndpointForward(Start, unit, count, out moved); // if the start did not change then no move was done. if (start == Start) { moved = 0; } } else { End = MoveEndpointForward(End, unit, count, out moved); // if the end did not change then no move was done. if (end == End) { moved = 0; } } } else if (count < 0) { if (moveStart) { Start = MoveEndpointBackward(Start, unit, count, out moved); // if the start did not change then no move was done. if (start == Start) { moved = 0; } } else { End = MoveEndpointBackward(End, unit, count, out moved); // if the end did not change then no move was done. if (end == End) { moved = 0; } } } else { // moving zero of any unit has no effect. moved = 0; } return moved; } void ITextRangeProvider.MoveEndpointByRange(TextPatternRangeEndpoint endpoint, ITextRangeProvider targetRange, TextPatternRangeEndpoint targetEndpoint) { Misc.SetFocus(_provider._hwnd); // TextPatternRange already verifies the other range comes from the same element before forwarding so we only need to worry // about the endpoints. WindowsEditBoxRange editRange = (WindowsEditBoxRange)targetRange; int e = (targetEndpoint == TextPatternRangeEndpoint.Start) ? editRange.Start : editRange.End; if (endpoint == TextPatternRangeEndpoint.Start) { Start = e; } else { End = e; } } void ITextRangeProvider.Select() { Misc.SetFocus(_provider._hwnd); _provider.SetSel(Start, End); } void ITextRangeProvider.AddToSelection() { throw new InvalidOperationException(); } void ITextRangeProvider.RemoveFromSelection() { throw new InvalidOperationException(); } void ITextRangeProvider.ScrollIntoView(bool alignToTop) { Misc.SetFocus(_provider._hwnd); // Scroll into view is handled differently depending on whether // it is a multi-line control or not. if (_provider.IsMultiline) { int newFirstLine; if (alignToTop) { newFirstLine = _provider.LineFromChar(Start); } else { newFirstLine = Math.Max(0, _provider.LineFromChar(End) - _provider.LinesPerPage() + 1); } _provider.LineScroll(Start, newFirstLine - _provider.GetFirstVisibleLine()); } else if (_provider.IsScrollable) { Misc.SetFocus(_provider._hwnd); int visibleStart; int visibleEnd; _provider.GetVisibleRangePoints(out visibleStart, out visibleEnd); if (Misc.IsReadingRTL(_provider._hwnd)) { short key = UnsafeNativeMethods.VK_LEFT; if (Start > visibleStart) { key = UnsafeNativeMethods.VK_RIGHT; } while (Start > visibleStart || Start < visibleEnd) { Input.SendKeyboardInputVK(key, true); _provider.GetVisibleRangePoints(out visibleStart, out visibleEnd); } } else { short key = UnsafeNativeMethods.VK_RIGHT; if (Start < visibleStart) { key = UnsafeNativeMethods.VK_LEFT; } while (Start < visibleStart || Start > visibleEnd) { Input.SendKeyboardInputVK(key, true); _provider.GetVisibleRangePoints(out visibleStart, out visibleEnd); } } } } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties IRawElementProviderSimple[] ITextRangeProvider.GetChildren() { // we don't have any children so return an empty array return new IRawElementProviderSimple[0]; } #endregion Public Properties //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // returns true iff index identifies a paragraph boundary within text. private static bool AtParagraphBoundary(string text, int index) { return index <= 0 || index >= text.Length || (text[index - 1]=='\n') && (text[index]!='\n'); } #if !WCP_NLS_ENABLED // returns true iff index identifies a word boundary within text. // following richedit & word precedent the boundaries are at the leading edge of the word // so the span of a word includes trailing whitespace. private static bool AtWordBoundary(string text, int index) { // NOTE: this is a heuristic word break detector that matches RichEdit behavior pretty well for // English prose. It is a placeholder until we put in something with real wordbreaking // intelligence based on the System.NaturalLanguage DLL. // we are at a word boundary if we are at the beginning or end of the text if (index <= 0 || index >= text.Length) { return true; } if( AtParagraphBoundary(text, index)) { return true; } char ch1 = text[index - 1]; char ch2 = text[index]; // an apostrophe does *not* break a word if it follows or precedes characters if ((char.IsLetterOrDigit(ch1) && IsApostrophe(ch2)) || (IsApostrophe(ch1) && char.IsLetterOrDigit(ch2) && index >= 2 && char.IsLetterOrDigit(text[index - 2]))) { return false; } // the following transitions mark boundaries. // note: these are constructed to include trailing whitespace. return (char.IsWhiteSpace(ch1) && !char.IsWhiteSpace(ch2)) || (char.IsLetterOrDigit(ch1) && !char.IsLetterOrDigit(ch2)) || (!char.IsLetterOrDigit(ch1) && char.IsLetterOrDigit(ch2)) || (char.IsPunctuation(ch1) && char.IsWhiteSpace(ch2)); } private static bool IsApostrophe(char ch) { return ch == '\'' || ch == (char)0x2019; // Unicode Right Single Quote Mark } #endif // a big pseudo-switch statement based on the attribute private object GetAttributeValue(AutomationTextAttribute attribute) { object rval; if (attribute == TextPattern.BackgroundColorAttribute) { rval = GetBackgroundColor(); } else if (attribute == TextPattern.CapStyleAttribute) { rval = GetCapStyle(_provider.WindowStyle); } else if (attribute == TextPattern.FontNameAttribute) { rval = GetFontName(_provider.GetLogfont()); } else if (attribute == TextPattern.FontSizeAttribute) { rval = GetFontSize(_provider.GetLogfont()); } else if (attribute == TextPattern.FontWeightAttribute) { rval = GetFontWeight(_provider.GetLogfont()); } else if (attribute == TextPattern.ForegroundColorAttribute) { rval = GetForegroundColor(); } else if (attribute == TextPattern.HorizontalTextAlignmentAttribute) { rval = GetHorizontalTextAlignment(_provider.WindowStyle); } else if (attribute == TextPattern.IsItalicAttribute) { rval = GetItalic(_provider.GetLogfont()); } else if (attribute == TextPattern.IsReadOnlyAttribute) { rval = GetReadOnly(); } else if (attribute == TextPattern.StrikethroughStyleAttribute) { rval = GetStrikethroughStyle(_provider.GetLogfont()); } else if (attribute == TextPattern.UnderlineStyleAttribute) { rval = GetUnderlineStyle(_provider.GetLogfont()); } else { rval = AutomationElement.NotSupported; } return rval; } // helper function to accumulate a list of bounding rectangles for a potentially mult-line range private ArrayList GetMultilineBoundingRectangles(string text, Point mapClientToScreen, Rect clippingRectangle) { // remember the line height int height = Math.Abs(_provider.GetLogfont().lfHeight);; // get the starting and ending lines for the range. int start = Start; int end = End; int startLine = _provider.LineFromChar(start); int endLine = _provider.LineFromChar(end - 1); // adjust the start based on the first visible line int firstVisibleLine = _provider.GetFirstVisibleLine(); if (firstVisibleLine > startLine) { startLine = firstVisibleLine; start = _provider.LineIndex(startLine); } // adjust the end based on the last visible line int lastVisibleLine = firstVisibleLine + _provider.LinesPerPage() - 1; if (lastVisibleLine < endLine) { endLine = lastVisibleLine; end = _provider.LineIndex(endLine) - 1; } // adding a rectangle for each line ArrayList rects = new ArrayList(Math.Max(endLine - startLine + 1, 0)); int nextLineIndex = _provider.LineIndex(startLine); for (int i = startLine; i <= endLine; i++) { // determine the starting coordinate on this line Point startPoint; if (i == startLine) { startPoint = _provider.PosFromChar(start); } else { startPoint = _provider.PosFromChar(nextLineIndex); } // determine the ending coordinate on this line Point endPoint; if (i == endLine) { endPoint = _provider.PosFromCharUR(end-1, text); } else { nextLineIndex = _provider.LineIndex(i + 1); endPoint = _provider.PosFromChar(nextLineIndex - 1); } // add a bounding rectangle for this line if it is nonempty Rect rect = new Rect(startPoint.X, startPoint.Y, endPoint.X - startPoint.X, height); rect.Intersect(clippingRectangle); if (rect.Width > 0 && rect.Height > 0) // r.Empty is true only if both width & height are zero. Duh! { rect.Offset(mapClientToScreen.X, mapClientToScreen.Y); rects.Add(rect); } } return rects; } // returns the value of the corresponding text attribute private static object GetHorizontalTextAlignment(int style) { if (Misc.IsBitSet(style, NativeMethods.ES_CENTER)) { return HorizontalTextAlignment.Centered; } else if (Misc.IsBitSet(style, NativeMethods.ES_RIGHT)) { return HorizontalTextAlignment.Right; } else { return HorizontalTextAlignment.Left; } } // returns the value of the corresponding text attribute private static object GetCapStyle(int style) { return Misc.IsBitSet(style, NativeMethods.ES_UPPERCASE) ? CapStyle.AllCap : CapStyle.None; } // returns the value of the corresponding text attribute private object GetReadOnly() { return _provider.IsReadOnly(); } // returns the value of the corresponding text attribute private static object GetBackgroundColor() { // NOTE! it is possible for parents of edit controls to change the background color by responding // to WM_CTLCOLOREDIT however we have decided not to handle that case. return SafeNativeMethods.GetSysColor(NativeMethods.COLOR_WINDOW); } // returns the value of the corresponding text attribute private static object GetFontName(NativeMethods.LOGFONT logfont) { return logfont.lfFaceName; } // returns the value of the corresponding text attribute private static object GetFontSize(NativeMethods.LOGFONT logfont) { // note: this assumes integral point sizes. violating this assumption would confuse the user // because they set something to 7 point but reports that it is, say 7.2 point, due to the rounding. IntPtr hdc = Misc.GetDC(IntPtr.Zero); if (hdc == IntPtr.Zero) { return null; } int lpy = UnsafeNativeMethods.GetDeviceCaps(hdc, NativeMethods.LOGPIXELSY); Misc.ReleaseDC(IntPtr.Zero, hdc); return Math.Round((double)(-logfont.lfHeight) * 72 / lpy); } // returns the value of the corresponding text attribute private static object GetFontWeight(NativeMethods.LOGFONT logfont) { return logfont.lfWeight; } // returns the value of the corresponding text attribute private static object GetForegroundColor() { // NOTE! it is possible for parents of edit controls to change the text color by responding // to WM_CTLCOLOREDIT however we have decided not to handle that case. return SafeNativeMethods.GetSysColor(NativeMethods.COLOR_WINDOWTEXT); } // returns the value of the corresponding text attribute private static object GetItalic(NativeMethods.LOGFONT logfont) { return logfont.lfItalic != 0; } // returns the value of the corresponding text attribute private static object GetStrikethroughStyle(NativeMethods.LOGFONT logfont) { return logfont.lfStrikeOut != 0 ? TextDecorationLineStyle.Single : TextDecorationLineStyle.None; } // returns the value of the corresponding text attribute private static object GetUnderlineStyle(NativeMethods.LOGFONT logfont) { return logfont.lfUnderline != 0 ? TextDecorationLineStyle.Single : TextDecorationLineStyle.None; } // moves an endpoint forward a certain number of units. // the endpoint is just an index into the text so it could represent either // the endpoint. private int MoveEndpointForward(int index, TextUnit unit, int count, out int moved) { switch (unit) { case TextUnit.Character: { int limit = _provider.GetTextLength() ; ValidateEndpoints(); moved = Math.Min(count, limit - index); index = index + moved; index = index > limit ? limit : index; } break; case TextUnit.Word: { string text = _provider.GetText(); ValidateEndpoints(); #if WCP_NLS_ENABLED // use the same word breaker as Avalon Text. WordBreaker breaker = new WordBreaker(); TextContainer container = new TextContainer(text); TextNavigator navigator = new TextNavigator(index, container); // move forward one word break for each count for (moved = 0; moved < count && index < text.Length; moved++) { if (!breaker.MoveToNextWordBreak(navigator)) break; } index = navigator.Position; #else for (moved = 0; moved < count && index < text.Length; moved++) { for (index++; !AtWordBoundary(text, index); index++) ; } #endif } break; case TextUnit.Line: { // figure out what line we are on. if we are in the middle of a line and // are moving left then we'll round up to the next line so that we move // to the beginning of the current line. int line = _provider.LineFromChar(index); // limit the number of lines moved to the number of lines available to move // Note lineMax is always >= 1. int lineMax = _provider.GetLineCount(); moved = Math.Min(count, lineMax - line - 1); if (moved > 0) { // move the endpoint to the beginning of the destination line. index = _provider.LineIndex(line + moved); } else if (moved == 0 && lineMax == 1) { // There is only one line so get the text length as endpoint index = _provider.GetTextLength(); moved = 1; } } break; case TextUnit.Paragraph: { // just like moving words but we look for paragraph boundaries instead of // word boundaries. string text = _provider.GetText(); ValidateEndpoints(); for (moved = 0; moved < count && index < text.Length; moved++) { for (index++; !AtParagraphBoundary(text, index); index++) ; } } break; case TextUnit.Format: case TextUnit.Page: case TextUnit.Document: { // since edit controls are plain text moving one uniform format unit will // take us all the way to the end of the document, just like // "pages" and document. int limit = _provider.GetTextLength(); ValidateEndpoints(); // we'll move 1 format unit if we aren't already at the end of the // document. Otherwise, we won't move at all. moved = index < limit ? 1 : 0; index = limit; } break; default: throw new System.ComponentModel.InvalidEnumArgumentException("unit", (int)unit, typeof(TextUnit)); } return index; } // moves an endpoint backward a certain number of units. // the endpoint is just an index into the text so it could represent either // the endpoint. private int MoveEndpointBackward(int index, TextUnit unit, int count, out int moved) { switch (unit) { case TextUnit.Character: { int limit = _provider.GetTextLength(); ValidateEndpoints(); int oneBasedIndex = index + 1; moved = Math.Max(count, -oneBasedIndex); index = index + moved; index = index < 0 ? 0 : index; } break; case TextUnit.Word: { string text = _provider.GetText(); ValidateEndpoints(); #if WCP_NLS_ENABLED // use the same word breaker as Avalon Text. WordBreaker breaker = new WordBreaker(); TextContainer container = new TextContainer(text); TextNavigator navigator = new TextNavigator(index, container); // move backward one word break for each count for (moved = 0; moved > count && index > 0; moved--) { if (!breaker.MoveToPreviousWordBreak(navigator)) break; } index = navigator.Position; #else for (moved = 0; moved > count && index > 0; moved--) { for (index--; !AtWordBoundary(text, index); index--) ; } #endif } break; case TextUnit.Line: { // Note count < 0. // Get 1-based line. int line = _provider.LineFromChar(index) + 1; int lineMax = _provider.GetLineCount(); // Truncate the count to the number of available lines. int actualCount = Math.Max(count, -line); moved = actualCount; if (actualCount == -line) { // We are moving by the maximum number of possible lines, // so we know the resulting index will be 0. index = 0; // If a line other than the first consists of only "\r\n", // you can move backwards past this line and the position changes, // hence this is counted. The first line is special, though: // if it is empty, and you move say from the second line back up // to the first, you cannot move further; however if the first line // is nonempty, you can move from the end of the first line to its // beginning! This latter move is counted, but if the first line // is empty, it is not counted. // Recalculate the value of "moved". // The first line is empty if it consists only of // a line separator sequence. bool firstLineEmpty = ((lineMax > 1 && _provider.LineIndex(1) == _lineSeparator.Length) || lineMax == 0); if (moved < 0 && firstLineEmpty) { ++moved; } } else // actualCount > -line { // Move the endpoint to the beginning of the following line, // then back by the line separator length to get to the end // of the previous line, since the Edit control has // no method to get the character index of the end // of a line directly. index = _provider.LineIndex(line + actualCount) - _lineSeparator.Length; } } break; case TextUnit.Paragraph: { // just like moving words but we look for paragraph boundaries instead of // word boundaries. string text = _provider.GetText(); ValidateEndpoints(); for (moved = 0; moved > count && index > 0; moved--) { for (index--; !AtParagraphBoundary(text, index); index--) ; } } break; case TextUnit.Format: case TextUnit.Page: case TextUnit.Document: { // since edit controls are plain text moving one uniform format unit will // take us all the way to the beginning of the document, just like // "pages" and document. // we'll move 1 format unit if we aren't already at the beginning of the // document. Otherwise, we won't move at all. moved = index > 0 ? -1 : 0; index = 0; } break; default: throw new System.ComponentModel.InvalidEnumArgumentException("unit", (int)unit, typeof(TextUnit)); } return index; } // method to set both endpoints simultaneously private void MoveTo(int start, int end) { if (start < 0 || end < start) { throw new InvalidOperationException(SR.Get(SRID.InvalidTextRangeOffset,GetType().FullName)); } _start = start; _end = end; } private void ValidateEndpoints() { int limit = _provider.GetTextLength(); if (Start > limit || End > limit) { throw new InvalidOperationException(SR.Get(SRID.InvalidRangeEndpoint,GetType().FullName)); } } #endregion Private Methods //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ #region Private Properties private bool IsDegenerate { get { // strictly only needs to be == since never should _start>_end. return _start >= _end; } } private int End { get { return _end; } set { // ensure that we never accidentally get a negative index if (value < 0) { throw new InvalidOperationException(SR.Get(SRID.InvalidTextRangeOffset,GetType().FullName)); } // ensure that end never moves before start if (value < _start) { _start = value; } _end = value; } } private int Length { get { return _end - _start; } } private int Start { get { return _start; } set { // ensure that we never accidentally get a negative index if (value < 0) { throw new InvalidOperationException(SR.Get(SRID.InvalidTextRangeOffset,GetType().FullName)); } // ensure that start never moves after end if (value > _end) { _end = value; } _start = value; } } #endregion Private Properties //------------------------------------------------------ // // Static Methods // //------------------------------------------------------ #region Static Methods #endregion Static Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private WindowsEditBox _provider; private int _start; private int _end; // Edit controls always use "\r\n" as the line separator, not "\n". private const string _lineSeparator = "\r\n"; // This string is a non-localizable string #endregion Private Fields } }
// PathFilter.cs // // Copyright 2005 John Reilly // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. #if ZIPLIB using System; using System.IO; namespace ICSharpCode.SharpZipLib.Core { /// <summary> /// PathFilter filters directories and files using a form of <see cref="System.Text.RegularExpressions.Regex">regular expressions</see> /// by full path name. /// See <see cref="NameFilter">NameFilter</see> for more detail on filtering. /// </summary> internal class PathFilter : IScanFilter { #region Constructors /// <summary> /// Initialise a new instance of <see cref="PathFilter"></see>. /// </summary> /// <param name="filter">The <see cref="NameFilter">filter</see> expression to apply.</param> public PathFilter(string filter) { nameFilter_ = new NameFilter(filter); } #endregion #region IScanFilter Members /// <summary> /// Test a name to see if it matches the filter. /// </summary> /// <param name="name">The name to test.</param> /// <returns>True if the name matches, false otherwise.</returns> /// <remarks><see cref="Path.GetFullPath(string)"/> is used to get the full path before matching.</remarks> public virtual bool IsMatch(string name) { bool result = false; if ( name != null ) { string cooked = (name.Length > 0) ? Path.GetFullPath(name) : ""; result = nameFilter_.IsMatch(cooked); } return result; } #endregion #region Instance Fields NameFilter nameFilter_; #endregion } /// <summary> /// ExtendedPathFilter filters based on name, file size, and the last write time of the file. /// </summary> /// <remarks>Provides an example of how to customise filtering.</remarks> internal class ExtendedPathFilter : PathFilter { #region Constructors /// <summary> /// Initialise a new instance of ExtendedPathFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minSize">The minimum file size to include.</param> /// <param name="maxSize">The maximum file size to include.</param> public ExtendedPathFilter(string filter, long minSize, long maxSize) : base(filter) { MinSize = minSize; MaxSize = maxSize; } /// <summary> /// Initialise a new instance of ExtendedPathFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minDate">The minimum <see cref="DateTime"/> to include.</param> /// <param name="maxDate">The maximum <see cref="DateTime"/> to include.</param> public ExtendedPathFilter(string filter, DateTime minDate, DateTime maxDate) : base(filter) { MinDate = minDate; MaxDate = maxDate; } /// <summary> /// Initialise a new instance of ExtendedPathFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minSize">The minimum file size to include.</param> /// <param name="maxSize">The maximum file size to include.</param> /// <param name="minDate">The minimum <see cref="DateTime"/> to include.</param> /// <param name="maxDate">The maximum <see cref="DateTime"/> to include.</param> public ExtendedPathFilter(string filter, long minSize, long maxSize, DateTime minDate, DateTime maxDate) : base(filter) { MinSize = minSize; MaxSize = maxSize; MinDate = minDate; MaxDate = maxDate; } #endregion #region IScanFilter Members /// <summary> /// Test a filename to see if it matches the filter. /// </summary> /// <param name="name">The filename to test.</param> /// <returns>True if the filter matches, false otherwise.</returns> /// <exception cref="System.IO.FileNotFoundException">The <see paramref="fileName"/> doesnt exist</exception> public override bool IsMatch(string name) { bool result = base.IsMatch(name); if ( result ) { FileInfo fileInfo = new FileInfo(name); result = (MinSize <= fileInfo.Length) && (MaxSize >= fileInfo.Length) && (MinDate <= fileInfo.LastWriteTime) && (MaxDate >= fileInfo.LastWriteTime) ; } return result; } #endregion #region Properties /// <summary> /// Get/set the minimum size/length for a file that will match this filter. /// </summary> /// <remarks>The default value is zero.</remarks> /// <exception cref="ArgumentOutOfRangeException">value is less than zero; greater than <see cref="MaxSize"/></exception> public long MinSize { get { return minSize_; } set { if ( (value < 0) || (maxSize_ < value) ) { throw new ArgumentOutOfRangeException("value"); } minSize_ = value; } } /// <summary> /// Get/set the maximum size/length for a file that will match this filter. /// </summary> /// <remarks>The default value is <see cref="System.Int64.MaxValue"/></remarks> /// <exception cref="ArgumentOutOfRangeException">value is less than zero or less than <see cref="MinSize"/></exception> public long MaxSize { get { return maxSize_; } set { if ( (value < 0) || (minSize_ > value) ) { throw new ArgumentOutOfRangeException("value"); } maxSize_ = value; } } /// <summary> /// Get/set the minimum <see cref="DateTime"/> value that will match for this filter. /// </summary> /// <remarks>Files with a LastWrite time less than this value are excluded by the filter.</remarks> public DateTime MinDate { get { return minDate_; } set { if ( value > maxDate_ ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("value"); #else throw new ArgumentOutOfRangeException("value", "Exceeds MaxDate"); #endif } minDate_ = value; } } /// <summary> /// Get/set the maximum <see cref="DateTime"/> value that will match for this filter. /// </summary> /// <remarks>Files with a LastWrite time greater than this value are excluded by the filter.</remarks> public DateTime MaxDate { get { return maxDate_; } set { if ( minDate_ > value ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("value"); #else throw new ArgumentOutOfRangeException("value", "Exceeds MinDate"); #endif } maxDate_ = value; } } #endregion #region Instance Fields long minSize_; long maxSize_ = long.MaxValue; DateTime minDate_ = DateTime.MinValue; DateTime maxDate_ = DateTime.MaxValue; #endregion } /// <summary> /// NameAndSizeFilter filters based on name and file size. /// </summary> /// <remarks>A sample showing how filters might be extended.</remarks> [Obsolete("Use ExtendedPathFilter instead")] internal class NameAndSizeFilter : PathFilter { /// <summary> /// Initialise a new instance of NameAndSizeFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minSize">The minimum file size to include.</param> /// <param name="maxSize">The maximum file size to include.</param> public NameAndSizeFilter(string filter, long minSize, long maxSize) : base(filter) { MinSize = minSize; MaxSize = maxSize; } /// <summary> /// Test a filename to see if it matches the filter. /// </summary> /// <param name="name">The filename to test.</param> /// <returns>True if the filter matches, false otherwise.</returns> public override bool IsMatch(string name) { bool result = base.IsMatch(name); if ( result ) { FileInfo fileInfo = new FileInfo(name); long length = fileInfo.Length; result = (MinSize <= length) && (MaxSize >= length); } return result; } /// <summary> /// Get/set the minimum size for a file that will match this filter. /// </summary> public long MinSize { get { return minSize_; } set { if ( (value < 0) || (maxSize_ < value) ) { throw new ArgumentOutOfRangeException("value"); } minSize_ = value; } } /// <summary> /// Get/set the maximum size for a file that will match this filter. /// </summary> public long MaxSize { get { return maxSize_; } set { if ( (value < 0) || (minSize_ > value) ) { throw new ArgumentOutOfRangeException("value"); } maxSize_ = value; } } #region Instance Fields long minSize_; long maxSize_ = long.MaxValue; #endregion } } #endif
#region "Copyright" /* FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER */ #endregion #region "References" using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SageFrame.Web; using SageFrame.SageBannner.SettingInfo; using SageFrame.Web.Utilities; using SageFrame.SageBannner.Controller; using SageFrame.SageBannner.Info; using System.Text; using SageFrame.Web.Common.SEO; #endregion public partial class Modules_Sage_Banner_ViewBanner : BaseAdministrationUserControl { #region Variables public string Auto_Direction = ""; public bool Auto_Slide; public bool Caption; public int DisplaySlideQty; public bool InfiniteLoop; public bool NumericPager; public bool EnableControl = false; public int Pause_Time; public bool RandomStart; public int Speed; public string BannerId = ""; public string TransitionMode = ""; public int UserModuleId; public int PortalId; public string SageURL = ""; public string Extension; string modulePath = string.Empty; public int bannerCount = 0; public string Fullpath = string.Empty; #endregion protected void Page_Load(object sender, EventArgs e) { Extension = SageFrameSettingKeys.PageExtension; SageURL = string.Format("{0}{1}", Request.ApplicationPath == "/" ? "" : Request.ApplicationPath, SageURL); UserModuleId = Int32.Parse(SageUserModuleID); PortalId = GetPortalID; modulePath = ResolveUrl(this.AppRelativeTemplateSourceDirectory); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "globalVariables", " var SageBannerServicePath='" + ResolveUrl(modulePath) + "';", true); IncludeJS(); IncludeCss(); EnableControl = true; Fullpath = !IsParent ? SageURL + "/portal/" + GetPortalSEOName : SageURL; GetBannerSetting(); } private void GetBannerSetting() { SageBannerSettingInfo obj = GetSageBannerSettingList(GetPortalID, Int32.Parse(SageUserModuleID)); Auto_Slide = obj.Auto_Slide; Caption = obj.Caption; InfiniteLoop = obj.InfiniteLoop; NumericPager = obj.NumericPager; Pause_Time = obj.Pause_Time; RandomStart = obj.RandomStart; EnableControl = obj.EnableControl; Speed = obj.Speed; TransitionMode = obj.TransitionMode; BannerId = obj.BannerToUse; GetBannerImages(int.Parse(BannerId), UserModuleId, PortalId, GetCurrentCulture()); } private void IncludeCss() { IncludeCss("SageResponsiveBanner", "/Modules/Sage_Banner/css/bx_styles.css", "/Modules/Sage_Banner/css/Module.css"); } private void IncludeJS() { IncludeJs("Sage_Banner", "/Modules/Sage_Banner/js/jquery.bxslider.js"); IncludeJs("Sage_Banner", "/Modules/Sage_Banner/js/picturefill.js", "/Modules/Sage_Banner/js/matchmedia.js"); IncludeJs("Sage_Banner", "/Modules/Sage_Banner/js/SageBannerView.js"); } public SageBannerSettingInfo GetSageBannerSettingList(int PortalID, int UserModuleID) { try { SageBannerController objc = new SageBannerController(); return objc.GetSageBannerSettingList(PortalID, UserModuleID, GetCurrentCulture()); } catch (Exception ex) { throw ex; } } public void GetBannerImages(int BannerID, int UserModuleID, int PortalID, string CultureCode) { try { List<SageBannerInfo> objSageBannerLst = new List<SageBannerInfo>(); SageBannerController obj = new SageBannerController(); objSageBannerLst = obj.GetBannerImages(BannerID, UserModuleID, PortalID, CultureCode); StringBuilder elem = new StringBuilder(); elem.Append("<ul id=\"sfSlider\">"); if (objSageBannerLst.Count > 0) { foreach (SageBannerInfo banner in objSageBannerLst) { if (banner.ImagePath.Length == 0) { elem.Append("<li>"); elem.Append(banner.HTMLBodyText); elem.Append("</li>"); } else { string target = "#"; string readmoreLink = "#"; if (banner.LinkToImage != string.Empty) { readmoreLink = banner.LinkToImage; target = "_blank"; } else if (banner.ReadMorePage != string.Empty) { readmoreLink = Fullpath + banner.ReadMorePage + Extension; } else { readmoreLink = Fullpath + banner.ReadMorePage + Extension; } elem.Append("<li style=\"position:relative; display:none;\">"); elem.Append("<div class='bannerImageWrapper'>"); elem.Append("<div class='sfImageholder'>"); //Responsive Images elem.Append("<div data-alt=\"SageFrame Banner Images\" data-picture=\"\">"); elem.Append("<div data-media=\"(min-width: 0px)\" data-src="); elem.Append(ResolveUrl(modulePath)); elem.Append("images/ThumbNail/Small/"); elem.Append(banner.ImagePath); elem.Append("></div>"); elem.Append("<div data-media=\"(min-width: 320px)\" data-src="); elem.Append(ResolveUrl(modulePath)); elem.Append("images/ThumbNail/Medium/"); elem.Append(banner.ImagePath); elem.Append("></div>"); elem.Append("<div data-media=\"(min-width: 768px)\" data-src="); elem.Append(ResolveUrl(modulePath)); elem.Append("images/ThumbNail/Large/"); elem.Append(banner.ImagePath); elem.Append("></div>"); elem.Append("<div data-media=\"(min-width: 960px)\" data-src="); elem.Append(ResolveUrl(modulePath)); elem.Append("images/ThumbNail/Default/"); elem.Append(banner.ImagePath); elem.Append("></div>"); //elem.Append("<noscript><img alt=\"Sageframe Bannner Images\" src=\""); //elem.Append(ResolveUrl(modulePath)); //elem.Append("images/ThumbNail/Default/"); //elem.Append(banner.ImagePath); //elem.Append("/></noscript>"); elem.Append("</div>"); elem.Append("</div>"); SEOHelper seoHelper = new SEOHelper(); string unwantedTag = seoHelper.RemoveUnwantedHTMLTAG(banner.Description); if (banner.Description != null && banner.Description.Trim() != string.Empty && banner.Description.Trim() != "" && unwantedTag.Trim().Length > 0) { elem.Append("<div class='sfBannerDesc'><p>"); elem.Append(banner.Description + "</p>"); elem.Append("<a target=\" " + target + " \" class='sfReadmore' href=\""); elem.Append(readmoreLink); elem.Append("\">"); elem.Append("<span>"); elem.Append(banner.ReadButtonText); elem.Append("</span></a></div></div></li>"); } else { elem.Append("</li>"); } } } bannerCount++; } else { bannerCount = 0; elem.Append("No Banner To Display"); } elem.Append("</ul>"); sageSlider.Text = elem.ToString(); } catch (Exception ex) { ProcessException(ex); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleRealTimeEmulation.SampleRealTimeEmulationPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleRealTimeEmulation { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Windows; using Ecng.Collections; using Ecng.Common; using Ecng.Serialization; using Ecng.Xaml; using MoreLinq; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Testing; using StockSharp.BusinessEntities; using StockSharp.Configuration; using StockSharp.Localization; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Xaml; using StockSharp.Xaml.Charting; public partial class MainWindow { private readonly SynchronizedList<Candle> _buffer = new SynchronizedList<Candle>(); private readonly ChartCandleElement _candlesElem; private readonly LogManager _logManager; private CandleManager _candleManager; private CandleSeries _candleSeries; private RealTimeEmulationTrader<IMessageAdapter> _connector; private bool _isConnected; private Security _security; private CandleSeries _tempCandleSeries; // used to determine if chart settings have changed and new chart is needed private const string _settingsFile = "connection.xml"; private readonly BasketMessageAdapter _realAdapter = new BasketMessageAdapter(new MillisecondIncrementalIdGenerator()); public MainWindow() { InitializeComponent(); CandleSettingsEditor.Settings = new CandleSeries { CandleType = typeof(TimeFrameCandle), Arg = TimeSpan.FromMinutes(5), }; CandleSettingsEditor.SettingsChanged += CandleSettingsChanged; _logManager = new LogManager(); _logManager.Listeners.Add(new GuiLogListener(Log)); var area = new ChartArea(); Chart.Areas.Add(area); _candlesElem = new ChartCandleElement(); area.Elements.Add(_candlesElem); InitConnector(); GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles); } private void InitConnector() { _connector?.Dispose(); try { if (File.Exists(_settingsFile)) _realAdapter.Load(new XmlSerializer<SettingsStorage>().Deserialize(_settingsFile)); _realAdapter.InnerAdapters.ForEach(a => a.RemoveTransactionalSupport()); } catch { } _connector = new RealTimeEmulationTrader<IMessageAdapter>(_realAdapter); _logManager.Sources.Add(_connector); _connector.EmulationAdapter.Emulator.Settings.TimeZone = TimeHelper.Est; _connector.EmulationAdapter.Emulator.Settings.ConvertTime = true; SecurityPicker.SecurityProvider = new FilterableSecurityProvider(_connector); SecurityPicker.MarketDataProvider = _connector; _candleManager = new CandleManager(_connector); _logManager.Sources.Add(_connector); // clear password for security reason //Password.Clear(); // subscribe on connection successfully event _connector.Connected += () => { // update gui labels this.GuiAsync(() => { ChangeConnectStatus(true); }); }; // subscribe on disconnection event _connector.Disconnected += () => { // update gui labels this.GuiAsync(() => { ChangeConnectStatus(false); }); }; // subscribe on connection error event _connector.ConnectionError += error => this.GuiAsync(() => { // update gui labels ChangeConnectStatus(false); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); _connector.NewMarketDepth += OnDepth; _connector.MarketDepthChanged += OnDepth; _connector.NewPortfolio += PortfolioGrid.Portfolios.Add; _connector.NewPosition += PortfolioGrid.Positions.Add; _connector.NewOrder += OrderGrid.Orders.Add; _connector.NewMyTrade += TradeGrid.Trades.Add; // subscribe on error of order registration event _connector.OrderRegisterFailed += OrderGrid.AddRegistrationFail; _candleManager.Processing += (s, candle) => { if (candle.State == CandleStates.Finished) _buffer.Add(candle); }; _connector.MassOrderCancelFailed += (transId, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716)); // subscribe on error event _connector.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event _connector.MarketDataSubscriptionFailed += (security, msg, error) => { if (error == null) return; this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security))); }; } private void CandleSettingsChanged() { if (_tempCandleSeries == CandleSettingsEditor.Settings || _candleSeries == null) return; _tempCandleSeries = CandleSettingsEditor.Settings.Clone(); SecurityPicker_OnSecuritySelected(SecurityPicker.SelectedSecurity); } protected override void OnClosing(CancelEventArgs e) { if (_connector != null) _connector.Dispose(); base.OnClosing(e); } private void SettingsClick(object sender, RoutedEventArgs e) { if (_realAdapter.Configure(this)) new XmlSerializer<SettingsStorage>().Serialize(_realAdapter.Save(), _settingsFile); InitConnector(); } private void ConnectClick(object sender, RoutedEventArgs e) { if (!_isConnected) { ConnectBtn.IsEnabled = false; _connector.Connect(); } else { _connector.Disconnect(); } } private void OnDepth(MarketDepth depth) { if (depth.Security != _security) return; DepthControl.UpdateDepth(depth); } private void ChangeConnectStatus(bool isConnected) { // set flag (connection is established or not) _isConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; ConnectBtn.IsEnabled = true; Find.IsEnabled = _isConnected; } private void ProcessCandles() { foreach (var candle in _buffer.SyncGet(c => c.CopyAndClear())) Chart.Draw(_candlesElem, candle); } private void SecurityPicker_OnSecuritySelected(Security security) { if (security == null) return; if (_candleSeries != null) _candleManager.Stop(_candleSeries); // give back series memory _security = security; Chart.Reset(new[] { _candlesElem }); _connector.RegisterMarketDepth(security); _connector.RegisterTrades(security); _connector.RegisterSecurity(security); _candleSeries = new CandleSeries(CandleSettingsEditor.Settings.CandleType, security, CandleSettingsEditor.Settings.Arg); _candleManager.Start(_candleSeries); } private void NewOrder_OnClick(object sender, RoutedEventArgs e) { OrderGrid_OrderRegistering(); } private void OrderGrid_OrderRegistering() { var newOrder = new OrderWindow { Order = new Order { Security = _security }, SecurityProvider = _connector, MarketDataProvider = _connector, Portfolios = new PortfolioDataSource(_connector), }; if (newOrder.ShowModal(this)) _connector.RegisterOrder(newOrder.Order); } private void OrderGrid_OnOrderCanceling(IEnumerable<Order> orders) { orders.ForEach(_connector.CancelOrder); } private void OrderGrid_OnOrderReRegistering(Order order) { var window = new OrderWindow { Title = LocalizedStrings.Str2976Params.Put(order.TransactionId), SecurityProvider = _connector, MarketDataProvider = _connector, Portfolios = new PortfolioDataSource(_connector), Order = order.ReRegisterClone(newVolume: order.Balance) }; if (window.ShowModal(this)) _connector.ReRegisterOrder(order, window.Order); } private void FindClick(object sender, RoutedEventArgs e) { var wnd = new SecurityLookupWindow { Criteria = new Security { Code = "AAPL" } }; if (!wnd.ShowModal(this)) return; _connector.LookupSecurities(wnd.Criteria); } } }
// The MIT License (MIT) // // CoreTweet - A .NET Twitter Library supporting Twitter API 1.1 // Copyright (c) 2013-2015 CoreTweet Development Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using CoreTweet.Core; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CoreTweet.Streaming { /// <summary> /// Provides disconnect codes in Twitter Streaming API. /// </summary> public enum DisconnectCode { /// <summary> /// The feed was shutdown (possibly a machine restart) /// </summary> Shutdown = 1, /// <summary> /// The same endpoint was connected too many times. /// </summary> DuplicateStream, /// <summary> /// Control streams was used to close a stream (applies to sitestreams). /// </summary> ControlRequest, /// <summary> /// The client was reading too slowly and was disconnected by the server. /// </summary> Stall, /// <summary> /// The client appeared to have initiated a disconnect. /// </summary> Normal, /// <summary> /// An oauth token was revoked for a user (applies to site and userstreams). /// </summary> TokenRevoked, /// <summary> /// The same credentials were used to connect a new stream and the oldest was disconnected. /// </summary> AdminLogout, /// <summary> /// <para>Reserved for internal use.</para> /// <para>Will not be delivered to external clients.</para> /// </summary> Reserved, /// <summary> /// The stream connected with a negative count parameter and was disconnected after all backfill was delivered. /// </summary> MaxMessageLimit, /// <summary> /// An internal issue disconnected the stream. /// </summary> StreamException, /// <summary> /// An internal issue disconnected the stream. /// </summary> BrokerStall, /// <summary> /// <para>The host the stream was connected to became overloaded and streams were disconnected to balance load.</para> /// <para>Reconnect as usual.</para> /// </summary> ShedLoad } /// <summary> /// Provides event codes in Twitter Streaming API. /// </summary> public enum EventCode { /// <summary> /// The user revokes his access token. /// </summary> AccessRevoked, /// <summary> /// The user blocks a user. /// </summary> Block, /// <summary> /// The user unblocks a user. /// </summary> Unblock, /// <summary> /// The user favorites a Tweet. /// </summary> Favorite, /// <summary> /// The user unfavorites a Tweet. /// </summary> Unfavorite, /// <summary> /// The user follows a user. /// </summary> Follow, /// <summary> /// The user unfollows a user. /// </summary> Unfollow, /// <summary> /// The user creates a List. /// </summary> ListCreated, /// <summary> /// The user destroys a List. /// </summary> ListDestroyed, /// <summary> /// The user updates a List. /// </summary> ListUpdated, /// <summary> /// The user adds a user to a List. /// </summary> ListMemberAdded, /// <summary> /// The user removes a user from a List. /// </summary> ListMemberRemoved, /// <summary> /// The user subscribes a List. /// </summary> ListUserSubscribed, /// <summary> /// The user unsubscribes a List. /// </summary> ListUserUnsubscribed, /// <summary> /// The user updates a List. /// </summary> UserUpdate, /// <summary> /// The user mutes a user. /// </summary> Mute, /// <summary> /// The user unmutes a user. /// </summary> Unmute, /// <summary> /// The user favorites a retweet. /// </summary> FavoritedRetweet, /// <summary> /// The user retweets a retweet. /// </summary> RetweetedRetweet, /// <summary> /// The user quotes a Tweet. /// </summary> QuotedTweet } /// <summary> /// Provides message types in Twitter Streaming API. /// </summary> public enum MessageType { /// <summary> /// The message indicates the Tweet has been deleted. /// </summary> DeleteStatus, /// <summary> /// The message indicates the Direct Message has been deleted. /// </summary> DeleteDirectMessage, /// <summary> /// The message indicates that geolocated data must be stripped from a range of Tweets. /// </summary> ScrubGeo, /// <summary> /// The message indicates that the indicated tweet has had their content withheld. /// </summary> StatusWithheld, /// <summary> /// The message indicates that indicated user has had their content withheld. /// </summary> UserWithheld, /// <summary> /// The message indicates that the user has been deleted. /// </summary> UserDelete, /// <summary> /// The message indicates that the user has canceled the deletion. /// </summary> //TODO: need investigation UserUndelete, /// <summary> /// The message indicates that the user has been suspended. /// </summary> UserSuspend, /// <summary> /// The message indicates that the streams may be shut down for a variety of reasons. /// </summary> Disconnect, /// <summary> /// <para>The message indicates the current health of the connection.</para> /// <para>This can be only sent when connected to a stream using the stall_warnings parameter.</para> /// </summary> Warning, /// <summary> /// The message is about non-Tweet events. /// </summary> Event, /// <summary> /// <para>The message is sent to identify the target of each message.</para> /// <para>In Site Streams, an additional wrapper is placed around every message, except for blank keep-alive lines.</para> /// </summary> Envelopes, /// <summary> /// The message is a new Tweet. /// </summary> Create, /// <summary> /// The message is a new Direct Message. /// </summary> DirectMesssage, /// <summary> /// <para>The message is a list of the user's friends.</para> /// <para>Twitter sends a preamble before starting regular message delivery upon establishing a User Stream connection.</para> /// </summary> Friends, /// <summary> /// The message indicates that a filtered stream has matched more Tweets than its current rate limit allows to be delivered. /// </summary> Limit, /// <summary> /// The message is sent to modify the Site Streams connection without reconnecting. /// </summary> Control, /// <summary> /// The message is in raw JSON format. /// </summary> RawJson } /// <summary> /// Represents a streaming message. This class is an abstract class. /// </summary> public abstract class StreamingMessage : CoreBase { /// <summary> /// Gets the type of the message. /// </summary> public MessageType Type { get { return GetMessageType(); } } /// <summary> /// Gets or sets the raw JSON. /// </summary> public string Json { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected abstract MessageType GetMessageType(); /// <summary> /// Converts the JSON to a <see cref="StreamingMessage"/> object. /// </summary> /// <param name="x">The JSON value.</param> /// <returns>The <see cref="StreamingMessage"/> object.</returns> public static StreamingMessage Parse(string x) { try { var j = JObject.Parse(x); StreamingMessage m; if(j["text"] != null) m = StatusMessage.Parse(j); else if(j["direct_message"] != null) m = CoreBase.Convert<DirectMessageMessage>(x); else if(j["friends"] != null) m = CoreBase.Convert<FriendsMessage>(x); else if(j["event"] != null) m = EventMessage.Parse(j); else if(j["for_user"] != null) m = EnvelopesMessage.Parse(j); else if(j["control"] != null) m = CoreBase.Convert<ControlMessage>(x); else m = ExtractRoot(j); m.Json = x; return m; } catch(ParsingException) { throw; } catch(Exception e) { throw new ParsingException("on streaming, cannot parse the json", x, e); } } static StreamingMessage ExtractRoot(JObject jo) { JToken jt; if(jo.TryGetValue("disconnect", out jt)) return jt.ToObject<DisconnectMessage>(); else if(jo.TryGetValue("warning", out jt)) return jt.ToObject<WarningMessage>(); else if(jo.TryGetValue("control", out jt)) return jt.ToObject<ControlMessage>(); else if(jo.TryGetValue("delete", out jt)) { JToken status; DeleteMessage id; if (((JObject)jt).TryGetValue("status", out status)) { id = status.ToObject<DeleteMessage>(); id.messageType = MessageType.DeleteStatus; } else { id = jt["direct_message"].ToObject<DeleteMessage>(); id.messageType = MessageType.DeleteDirectMessage; } var timestamp = jt["timestamp_ms"]; if (timestamp != null) id.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp)); return id; } else if(jo.TryGetValue("scrub_geo", out jt)) { return jt.ToObject<ScrubGeoMessage>(); } else if(jo.TryGetValue("limit", out jt)) { return jt.ToObject<LimitMessage>(); } else if(jo.TryGetValue("status_withheld", out jt)) { return jt.ToObject<StatusWithheldMessage>(); } else if(jo.TryGetValue("user_withheld", out jt)) { return jt.ToObject<UserWithheldMessage>(); } else if(jo.TryGetValue("user_delete", out jt)) { var m = jt.ToObject<UserMessage>(); m.messageType = MessageType.UserDelete; return m; } else if(jo.TryGetValue("user_undelete", out jt)) { var m = jt.ToObject<UserMessage>(); m.messageType = MessageType.UserUndelete; return m; } else if(jo.TryGetValue("user_suspend", out jt)) { // user_suspend doesn't have 'timestamp_ms' field var m = jt.ToObject<UserMessage>(); m.messageType = MessageType.UserSuspend; return m; } else throw new ParsingException("on streaming, cannot parse the json: unsupported type", jo.ToString(Formatting.Indented), null); } } /// <summary> /// Represents a streaming message containing a timestamp. /// </summary> public abstract class TimestampMessage : StreamingMessage { /// <summary> /// Gets or sets the timestamp. /// </summary> [JsonProperty("timestamp_ms")] [JsonConverter(typeof(TimestampConverter))] public DateTimeOffset Timestamp { get; set; } } /// <summary> /// Represents a status message. /// </summary> public class StatusMessage : TimestampMessage { /// <summary> /// Gets or sets the status. /// </summary> public Status Status { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Create; } internal static StatusMessage Parse(JObject j) { var m = new StatusMessage() { Status = j.ToObject<Status>() }; var timestamp = j["timestamp_ms"]; if (timestamp != null) m.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp)); return m; } } /// <summary> /// Represents a Direct message message. /// </summary> public class DirectMessageMessage : StreamingMessage { /// <summary> /// The direct message. /// </summary> /// <value>The direct message.</value> [JsonProperty("direct_message")] public DirectMessage DirectMessage { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.DirectMesssage; } } /// <summary> /// Represents a message contains ids of friends. /// </summary> [JsonObject] public class FriendsMessage : StreamingMessage,IEnumerable<long> { /// <summary> /// Gets or sets the ids of friends. /// </summary> [JsonProperty("friends")] public long[] Friends { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Friends; } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An IEnumerator object that can be used to iterate through the collection.</returns> public IEnumerator<long> GetEnumerator() { return ((IEnumerable<long>)Friends).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return Friends.GetEnumerator(); } } /// <summary> /// Represents the message with the rate limit. /// </summary> public class LimitMessage : TimestampMessage { /// <summary> /// Gets or sets a total count of the number of undelivered Tweets since the connection was opened. /// </summary> [JsonProperty("track")] public int Track { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Limit; } } /// <summary> /// Represents a delete message of a status or a direct message. /// </summary> public class DeleteMessage : TimestampMessage { /// <summary> /// Gets or sets the ID. /// </summary> [JsonProperty("id")] public long Id { get; set; } /// <summary> /// Gets or sets the ID of the user. /// </summary> [JsonProperty("user_id")] public long UserId { get; set; } internal MessageType messageType { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return messageType; } } /// <summary> /// Represents a scrub-get message. /// </summary> public class ScrubGeoMessage : TimestampMessage { /// <summary> /// Gets or sets the ID of the user. /// </summary> [JsonProperty("user_id")] public long UserId { get; set; } /// <summary> /// Gets or sets the ID of the status. /// </summary> //TODO: improve this comment [JsonProperty("up_to_status_id")] public long UpToStatusId { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.ScrubGeo; } } /// <summary> /// Represents a withheld message. /// </summary> public class UserWithheldMessage : TimestampMessage { /// <summary> /// Gets or sets the ID. /// </summary> [JsonProperty("id")] public long Id { get; set; } /// <summary> /// Gets or sets the withhelds in countries. /// </summary> [JsonProperty("withheld_in_countries")] public string[] WithheldInCountries { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.UserWithheld; } } /// <summary> /// Represents a withheld message. /// </summary> public class StatusWithheldMessage : TimestampMessage { /// <summary> /// Gets or sets the ID. /// </summary> [JsonProperty("id")] public long Id { get; set; } /// <summary> /// Gets or sets the ID of the user. /// </summary> [JsonProperty("user_id")] public long UserId { get; set; } /// <summary> /// Gets or sets the withhelds in countries. /// </summary> [JsonProperty("withheld_in_countries")] public string[] WithheldInCountries { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.StatusWithheld; } } /// <summary> /// Represents a message contains the ID of an user. /// </summary> public class UserMessage : TimestampMessage { /// <summary> /// Gets or sets the ID of the user. /// </summary> [JsonProperty("id")] public long Id { get; set; } internal MessageType messageType { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return messageType; } } /// <summary> /// Represents the message published when Twitter disconnects the stream. /// </summary> public class DisconnectMessage : StreamingMessage { /// <summary> /// Gets or sets the disconnect code. /// </summary> [JsonProperty("code")] public DisconnectCode Code { get; set; } /// <summary> /// Gets or sets the stream name of current stream. /// </summary> [JsonProperty("stream_name")] public string StreamName { get; set; } /// <summary> /// Gets or sets the human readable message of the reason. /// </summary> [JsonProperty("reason")] public string Reason { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Disconnect; } } /// <summary> /// Represents a warning message. /// </summary> public class WarningMessage : TimestampMessage { /// <summary> /// Gets or sets the warning code. /// </summary> [JsonProperty("code")] public string Code { get; set; } /// <summary> /// Gets or sets the warning message. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Gets or sets the percentage of the stall messages /// </summary> [JsonProperty("percent_full")] public int? PercentFull { get; set; } /// <summary> /// Gets or sets the target user ID. /// </summary> [JsonProperty("user_id")] public long? UserId { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Warning; } } /// <summary> /// Provides the event target type. /// </summary> public enum EventTargetType { /// <summary> /// The event is about a List. /// </summary> List, /// <summary> /// The event is about a Tweet. /// </summary> Status, /// <summary> /// The event is that the user revoked his access token. /// </summary> AccessRevocation, /// <summary> /// The event is unknown. /// </summary> Null } /// <summary> /// Represents a revoked token. /// </summary> public class AccessRevocation { /// <summary> /// The client application. /// </summary> [JsonProperty("client_application")] public ClientApplication ClientApplication { get; set; } /// <summary> /// The revoked access token. /// </summary> [JsonProperty("token")] public string Token { get; set; } } /// <summary> /// Represents a client application. /// </summary> public class ClientApplication { /// <summary> /// Gets or sets the URL of the application's publicly accessible home page. /// </summary> [JsonProperty("url")] public string Url { get; set; } /// <summary> /// Gets or sets the ID. /// </summary> [JsonProperty("id")] public long Id { get; set; } // int is better? /// <summary> /// Gets or sets the consumer key. /// </summary> [JsonProperty("consumer_key")] public string ConsumerKey { get; set; } /// <summary> /// Gets or sets the application name. /// </summary> [JsonProperty("name")] public string Name { get; set; } } /// <summary> /// Represents an event message. /// </summary> public class EventMessage : StreamingMessage { /// <summary> /// Gets or sets the target user. /// </summary> public User Target { get; set; } /// <summary> /// Gets or sets the source. /// </summary> public User Source { get; set; } /// <summary> /// Gets or sets the event code. /// </summary> public EventCode Event { get; set; } /// <summary> /// Gets or sets the type of target. /// </summary> public EventTargetType TargetType { get; set; } /// <summary> /// Gets or sets the target status. /// </summary> public Status TargetStatus { get; set; } /// <summary> /// Gets or sets the target List. /// </summary> public CoreTweet.List TargetList { get; set; } /// <summary> /// Gets or sets the target access token. /// </summary> public AccessRevocation TargetToken { get; set; } /// <summary> /// Gets or sets the time when the event happened. /// </summary> public DateTimeOffset CreatedAt { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Event; } internal static EventMessage Parse(JObject j) { var e = new EventMessage(); e.Target = j["target"].ToObject<User>(); e.Source = j["source"].ToObject<User>(); e.Event = (EventCode)Enum.Parse(typeof(EventCode), ((string)j["event"]) .Replace("objectType", "") .Replace("_",""), true); e.CreatedAt = DateTimeOffset.ParseExact((string)j["created_at"], "ddd MMM dd HH:mm:ss K yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AllowWhiteSpaces); var eventstr = (string)j["event"]; e.TargetType = eventstr.Contains("list") ? EventTargetType.List : (eventstr.Contains("favorite") || e.Event == EventCode.RetweetedRetweet) ? EventTargetType.Status : e.Event == EventCode.AccessRevoked ? EventTargetType.AccessRevocation : EventTargetType.Null; switch(e.TargetType) { case EventTargetType.Status: e.TargetStatus = j["target_object"].ToObject<Status>(); break; case EventTargetType.List: e.TargetList = j["target_object"].ToObject<CoreTweet.List>(); break; case EventTargetType.AccessRevocation: e.TargetToken = j["target_object"].ToObject<AccessRevocation>(); break; } return e; } } /// <summary> /// Provides an envelopes message. /// </summary> public class EnvelopesMessage : StreamingMessage { /// <summary> /// Gets or sets the ID of the user. /// </summary> public long ForUser { get; set; } /// <summary> /// Gets or sets the message. /// </summary> public StreamingMessage Message { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Envelopes; } internal static EnvelopesMessage Parse(JObject j) { return new EnvelopesMessage() { ForUser = (long)j["for_user"], Message = StreamingMessage.Parse(j["message"].ToString(Formatting.None)) }; } } /// <summary> /// Represents a control message. /// </summary> public class ControlMessage : StreamingMessage { /// <summary> /// Gets or sets the URI. /// </summary> [JsonProperty("control_uri")] public string ControlUri { get; set; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.Control; } } /// <summary> /// Represents a raw JSON message. This message means an exception was thrown when parsing. /// </summary> public class RawJsonMessage : StreamingMessage { /// <summary> /// Gets the exception when parsing. /// </summary> public ParsingException Exception { get; private set; } internal static RawJsonMessage Create(string json, ParsingException exception) { return new RawJsonMessage { Json = json, Exception = exception }; } /// <summary> /// Gets the type of the message. /// </summary> /// <returns>The type of the message.</returns> protected override MessageType GetMessageType() { return MessageType.RawJson; } } }
// Copyright 2013 Benjamin Burns // // 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. // Class to do simple (string) comparison of properties. Properties can // have sub-properties, and comparisons can be strung together, sort of. // There's not really an order of operation, phrases are just parsed // left to right. // // The idea is to make a filter, and then test an object -- pass it through // the filter. True or false will be returned depending on whether the object // had matching properties and values. // // There are several different methods of value comparison. // - Exactly match all property value(s) // - Exactly match any property value(s) // - Property contains a substring of all property value(s) // - Property contains a substring of at least one of the property value(s) // /// <example> /// FilterClause clause = new FilterClause(); /// /// FilterNode authorNode = new FilterNode(clause); /// authorNode.PropertyName = "Author"; /// /// FilterValuePair agencyValue = new FilterValuePair(authorNode); /// agencyValue.Comparer = FilterValueComparer.ExactlyMatchAll; /// agencyValue.PropertyName = "Name"; /// /// agencyValue.AddValue("Frank"); /// /// authorNode.SetChild(agencyValue); /// /// FilterValuePair bookValue = new FilterValuePair(clause); /// bookValue.Comparer = FilterValueComparer.ExactlyMatchAll; /// bookValue.PropertyName = "Books"; /// bookValue.AddValues("Gone With the Wind", "Back With the Tide"); /// /// clause.Left = authorNode; /// clause.Operator = FilterOperator.Intersect; /// clause.Right = bookValue; /// /// bool b = clause.Test(obj); /// /// // will compare object obj to a filter such that /// // a property "Author" has a property "Name" which has a value "Frank" /// // AND /// // the same object has a property "Books" containing both values "Gone With the Wind" and "Back With the Tide" /// /// </example> // Ben Burns // July 26, 2013 using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Reflection; namespace Toolbox.Filter { /// <summary> /// How to compare a property to a value or values /// </summary> public enum FilterValueComparer { Unknown, /// <summary> /// Contains at least one of the specified values, exactly. /// </summary> ExactlyMatchAny, /// <summary> /// Contains all of the specified values, but not necessarily in the same order. The values must match exactly. /// </summary> ExactlyMatchAll, /// <summary> /// Text compare looking to see if at least one of the values is a sub-string. /// </summary> ContainsAny, /// <summary> /// Text comparing looking to see if all of the values are found as a sub-string. /// </summary> ContainsAll, } /// <summary> /// How to apply multiple filtering criteria /// </summary> public enum FilterOperator { Unknown, /// <summary> /// Union. Similar to logical OR /// </summary> Union, /// <summary> /// Intersect. Similar to logical AND /// </summary> Intersect // not supported: /* XOR */ /* NOT */ } /// <summary> /// Helper to convert the enums to strings /// </summary> public static class FilterEnumExtensions { /// <summary> /// Converts the enum operators into "logical" operators /// </summary> /// <param name="fo"></param> /// <returns></returns> public static string ToShortString(this FilterOperator fo) { switch (fo) { case FilterOperator.Intersect: return "&&"; case FilterOperator.Union: return "||"; default: return "unknown"; } } /// <summary> /// Converts the enum comparison descriptor into text /// </summary> /// <param name="fc"></param> /// <returns></returns> public static string ToShortString(this FilterValueComparer fc) { switch (fc) { case FilterValueComparer.ExactlyMatchAny: return "exactly at least one of"; case FilterValueComparer.ExactlyMatchAll: return "=="; case FilterValueComparer.ContainsAny: return "contains at least one sub-string"; case FilterValueComparer.ContainsAll: return "contains all sub-strings"; default: return "unknown"; } } } /// <summary> /// Abstract base class /// </summary> public abstract class FilterGrammarBase { #region Fields /// <summary> /// Describes what type of structure the object is, related to the syntax. /// </summary> /// <remarks> /// Similar to "noun, verb, adjective, adverb, pronoun" etc /// </remarks> private readonly FilterGrammar grammarObject; #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="grammarType"></param> protected FilterGrammarBase(FilterGrammar grammarType) { this.grammarObject = grammarType; } #endregion #region Properties /// <summary> /// Returns the parent of the current node /// </summary> public FilterGrammarBase Parent { get; private set; } /// <summary> /// Returns whether the node has a parent /// </summary> public bool HasParent { get { return this.Parent != null; } } #endregion #region Methods /// <summary> /// Returns whether the part is well-formed /// </summary> /// <returns></returns> public abstract bool IsValid(); /// <summary> /// Test whether the filter matches a given object /// </summary> /// <param name="o"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public abstract bool Test(object o, bool ignoreCase = true); /// <summary> /// Throws specific exceptions depending on validation errors /// </summary> public abstract void Validate(); /// <summary> /// Quickly determines type /// </summary> /// <remarks> /// Without using reflection /// </remarks> /// <returns></returns> public bool IsValuePair() { return (this.grammarObject == FilterGrammar.Value); } /// <summary> /// Quickly determines type /// </summary> /// <<remarks> /// Without using reflection /// </remarks> /// <returns></returns> public bool IsClause() { return (this.grammarObject == FilterGrammar.Clause); } /// <summary> /// Quickly determines type /// </summary> /// <remarks> /// Without using reflection /// </remarks> /// <returns></returns> public bool IsTreeBranch() { return (this.grammarObject == FilterGrammar.TreeBranch); } /// <summary> /// Helper function. 1) Controls what can access setting the parent. 2) avoids null checks everywhere /// </summary> /// <param name="node"></param> /// <param name="parent"></param> protected static void SetParent(FilterGrammarBase node, FilterGrammarBase parent) { if (node == null) return; // nothing to do if the parent is already the parent if (Object.ReferenceEquals(node.Parent, parent)) return; // make sure the parent node isn't already in the tree if (FilterGrammarBase.IsAncestor(node, parent)) throw new RecursiveTree("Can not attache parent node, infinite loop detected"); if (FilterGrammarBase.IsAncestor(parent, node)) throw new RecursiveTree("Can not attache parent node, infinite loop detected"); node.Parent = parent; } /// <summary> /// Need a way to check for infinite loops. /// </summary> /// <param name="node">Base node</param> /// <param name="ancestorCheck">Node to search for in relation to the base node</param> protected static bool IsAncestor(FilterGrammarBase node, FilterGrammarBase ancestorCheck) { if (node == null || ancestorCheck == null) return false; FilterGrammarBase p = node.Parent as FilterGrammarBase; while (p != null) { if (Object.ReferenceEquals(p, ancestorCheck)) return true; p = p.Parent; } return false; } #endregion #region Enums /// <summary> /// Type of structure within the filter sentence /// </summary> protected enum FilterGrammar { Unknown, Value, Clause, TreeBranch } #endregion } /// <summary> /// Abstract base class for nodes /// </summary> public abstract class FilterNodeBase : FilterGrammarBase { #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="fg"></param> protected FilterNodeBase(FilterGrammar fg) : base(fg) { } #endregion #region Properties /// <summary> /// Name of property to match /// </summary> public string PropertyName { get; set; } #endregion #region Methods /// <summary> /// Test whether the filter matches a given object /// </summary> /// <param name="o"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public abstract override bool Test(object o, bool ignoreCase); /// <summary> /// Returns whether the part is well-formed /// </summary> /// <returns></returns> public abstract override bool IsValid(); /// <summary> /// Throws specific exceptions depending on validation errors /// </summary> public abstract override void Validate(); #endregion } /// <summary> /// A basic node. Can have a child of either another node, /// or a value pair /// </summary> public class FilterNode : FilterNodeBase { #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="parent"></param> public FilterNode(FilterGrammarBase parent = null) : base(FilterGrammar.TreeBranch) { FilterGrammarBase.SetParent(this, parent); SetChild(null); } #endregion #region Properties /// <summary> /// Returns the child of the current node /// </summary> public FilterNodeBase Child { get; private set; } /// <summary> /// Returns whether the node has a child /// </summary> public bool HasChild { get { return this.Child != null; } } #endregion #region Methods /// <summary> /// Returns whether the part is well-formed /// </summary> /// <returns></returns> public override bool IsValid() { if (String.IsNullOrEmpty(this.PropertyName)) return false; return this.HasChild; } /// <summary> /// ToString /// </summary> /// <returns></returns> public override string ToString() { string result = ""; if (string.IsNullOrEmpty(this.PropertyName)) result += "(Propertyname empty)"; else result += this.PropertyName; if (this.HasChild) { result += " > " + this.Child.ToString(); } return result; } /// <summary> /// Sets the child node /// </summary> /// <param name="c"></param> public void SetChild(FilterNodeBase c) { if (this.Child == c) return; // otherwise, unlink existing child FilterNode currentChild = this.Child as FilterNode; if (currentChild != null) this.RemoveChild(); this.Child = c; FilterGrammarBase.SetParent(this.Child, this); } /// <summary> /// Test whether the filter matches a given object /// </summary> /// <param name="o">Object to apply property/values to</param> /// <param name="ignoreCase">Wether to ignore case in string compare</param> /// <returns></returns> public override bool Test(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) throw new NullReferenceException("Object to match against must not be null."); if (!this.IsValid()) this.Validate(); PropertyInfo p = o.GetType().GetProperty(this.PropertyName); if (p == null) return false; var v = p.GetValue(o, null); return this.Child.Test(v, ignoreCase); } /// <summary> /// Helper function to elucidate the exact nature of validation failure /// </summary> public override void Validate() { if (String.IsNullOrEmpty(this.PropertyName)) throw new MissingProperty("The filter tree node does not have a property to compare against"); if (!this.HasChild) throw new MissingChild("The filter tree node does not have a child/values"); } /// <summary> /// Recursively removes child nodes /// </summary> private void RemoveChild() { if (!this.HasChild) return; FilterNode c = this.Child as FilterNode; if (c == null) return; c.RemoveChild(); c = null; } #endregion } /// <summary> /// Contains values associated with a property /// </summary> public class FilterValuePair : FilterNodeBase { #region Fields /// <summary> /// Value or values of property to match /// </summary> private List<string> propertyValues; #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="parent"></param> public FilterValuePair(FilterGrammarBase parent = null) : base(FilterGrammar.Value) { FilterGrammarBase.SetParent(this, parent); this.propertyValues = new List<string>(); } #endregion #region Properties /// <summary> /// Value or values of property to match /// </summary> public ReadOnlyCollection<string> PropertyValues { get { return this.propertyValues.AsReadOnly(); } } /// <summary> /// How to compare values to the property /// </summary> public FilterValueComparer Comparer { get; set; } #endregion #region Methods /// <summary> /// Returns whether the part is well-formed /// </summary> /// <returns></returns> public override bool IsValid() { if (String.IsNullOrEmpty(this.PropertyName)) return false; if (this.propertyValues == null) return false; if (this.propertyValues.Count < 1) return false; if (this.Comparer == FilterValueComparer.Unknown) return false; return true; } /// <summary> /// ToString /// </summary> /// <returns></returns> public override string ToString() { string result = ""; if (string.IsNullOrEmpty(this.PropertyName)) result += "(Propertyname empty)"; else result += this.PropertyName; result += " " + this.Comparer.ToShortString() + " "; if (this.propertyValues.Count > 1) result += "("; else result += "\""; result += String.Join(",", this.propertyValues); if (this.propertyValues.Count > 1) result += ")"; else result += "\""; return result; } /// <summary> /// Shorthand to add value /// </summary> /// <param name="s"></param> public void AddValue(string s) { if (!String.IsNullOrEmpty(s)) this.propertyValues.Add(s); } /// <summary> /// Shorthand to add values /// </summary> /// <param name="ls"></param> public void AddValues(List<String> ls) { if (ls == null) return; if (ls.Count < 1) return; foreach (string s in ls) if (!String.IsNullOrEmpty(s)) this.propertyValues.Add(s); } /// <summary> /// Shorthand to add values /// </summary> /// <param name="ls"></param> public void AddValues(params string[] ls) { if (ls == null) return; if (ls.Length < 1) return; foreach (string s in ls) if (!String.IsNullOrEmpty(s)) this.propertyValues.Add(s); } /// <summary> /// Test whether the filter matches a given object /// </summary> /// <param name="o">Object to apply property/values to</param> /// <param name="ignoreCase">Wether to ignore case in string compare</param> /// <returns></returns> public override bool Test(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) throw new NullReferenceException("Object to match against must not be null."); if (!this.IsValid()) this.Validate(); PropertyInfo p = o.GetType().GetProperty(this.PropertyName); if (p == null) return false; var v = p.GetValue(o, null); switch (this.Comparer) { case FilterValueComparer.ExactlyMatchAny: return ContainsAnyExact(v); case FilterValueComparer.ExactlyMatchAll: return ContainsAllExact(v); case FilterValueComparer.ContainsAny: return ContainsAnySubString(v); case FilterValueComparer.ContainsAll: return ContainsAllSubString(v); case FilterValueComparer.Unknown: /* fall through */ default: return false; } } /// <summary> /// Helper function to elucidate the exact nature of validation failure /// </summary> public override void Validate() { if (String.IsNullOrEmpty(this.PropertyName)) throw new MissingProperty("The value pair does not have a property to compare against"); if (this.propertyValues == null) throw new MissingValue("The value pair does not have any values"); if (this.propertyValues.Count < 1) throw new MissingValue("The value pair does not have any values"); if (this.Comparer == FilterValueComparer.Unknown) throw new BadOperator("The value pair operator is invalid: " + this.Comparer.ToString()); } /// <summary> /// Helper function. Searches property values for any values, exactly. /// </summary> /// <param name="o"></param> /// <returns></returns> private bool ContainsAnyExact(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) return false; if (o is IEnumerable && !(o is String)) { var en = ((IEnumerable)o).GetEnumerator(); while (en.MoveNext()) { foreach (string s in this.propertyValues) { // just need to find one value ... if (String.Compare(en.Current.ToString(), s, ignoreCase) == 0) return true; } } return false; } // could be a string else { foreach (string s in this.propertyValues) { // just need to find one value ... if (String.Compare(o.ToString(), s, ignoreCase) == 0) return true; } } return false; } /// <summary> /// Helper function. Searches property values to match all values, exactly. /// </summary> /// <param name="o"></param> /// <param name="ignoreCase"></param> /// <returns></returns> private bool ContainsAllExact(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) return false; if (o is IEnumerable && !(o is String)) { var en = ((IEnumerable)o).GetEnumerator(); // copy list of values List<string> itemsLeftToMatch = new List<string>(this.propertyValues); while (en.MoveNext()) { foreach (string s in itemsLeftToMatch) { if (String.Compare(en.Current.ToString(), s, ignoreCase) == 0) { // everytime a value matches, remove it from the list itemsLeftToMatch.Remove(en.Current.ToString()); break; } } } // as long as all the values were found, it's a match if (itemsLeftToMatch.Count > 0) return false; return true; } // could be a string. else { // should have at least one property value set ... foreach (string s in this.propertyValues) { // if it's not found, fail if (String.Compare(o.ToString(), s, ignoreCase) != 0) return false; } return true; } } /// <summary> /// Helper function. Searches property values for sub-strings of any values. /// </summary> /// <param name="o"></param> /// <param name="ignoreCase"></param> /// <returns></returns> private bool ContainsAnySubString(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) return false; if (o is IEnumerable && !(o is String)) { var en = ((IEnumerable)o).GetEnumerator(); while (en.MoveNext()) { foreach (string s in this.propertyValues) { // just need to find one value ... if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(en.Current.ToString(), s, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) > -1) return true; } } return false; } // could be a string else { foreach (string s in this.propertyValues) { // just need to find one value ... if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(o.ToString(), s, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) > -1) return true; } } return false; } /// <summary> /// Helper function. Searches property for sub-strings of all values. /// </summary> /// <param name="o"></param> /// <param name="ignoreCase"></param> /// <returns></returns> private bool ContainsAllSubString(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) return false; if (o is IEnumerable && !(o is String)) { var en = ((IEnumerable)o).GetEnumerator(); // copy list of values List<string> itemsLeftToMatch = new List<string>(this.propertyValues); while (en.MoveNext()) { foreach (string s in itemsLeftToMatch) { if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(o.ToString(), s, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) > -1) { // everytime a value matches, remove it from the list itemsLeftToMatch.Remove(en.Current.ToString()); break; } } } // as long as all the values were found, it's a match if (itemsLeftToMatch.Count > 0) return false; return true; } // could be a string. else { // should have at least one property value set ... foreach (string s in this.propertyValues) { // if it's not found, fail if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(o.ToString(), s, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == -1) return false; } return true; } } #endregion } /// <summary> /// Basic filter sentence is built with this. Can contain members of the same type. /// </summary> public class FilterClause : FilterGrammarBase { #region Fields private FilterGrammarBase left; private FilterGrammarBase right; #endregion #region Constructors public FilterClause() : base(FilterGrammar.Clause) { } #endregion #region Properties /// <summary> /// Left hand side. Required /// </summary> public FilterGrammarBase Left { get { return this.left; } set { // unlink old parent, then set the new one FilterGrammarBase.SetParent(this.left, null); this.left = value; FilterGrammarBase.SetParent(this.left, this); } } /// <summary> /// Operator to relate left and right hand side. Only required /// if right hand side is set. /// </summary> public FilterOperator Operator { get; set; } /// <summary> /// Right hand side. Related to left hand side via operator. /// </summary> public FilterGrammarBase Right { get { return this.right; } set { // unlink old parent, then set the new one FilterGrammarBase.SetParent(this.right, null); this.right = value; FilterGrammarBase.SetParent(this.right, this); } } #endregion #region Methods /// <summary> /// Returns whether the part is well-formed /// </summary> /// <returns></returns> public override bool IsValid() { if (this.Left == null) return false; if (this.Left.IsClause()) if (this.Left.IsValid() == false) return false; // don't need an operator unless there's a right hand side if (this.Right != null) { if (this.Operator == FilterOperator.Unknown) return false; } // don't need a right hand side unless there's an operator if (this.Operator != FilterOperator.Unknown) { if (this.Right == null) return false; if (this.Right.IsClause()) if (this.Right.IsValid() == false) return false; } return true; } /// <summary> /// ToString /// </summary> /// <returns></returns> public override string ToString() { string result = ""; if (!this.IsValid()) return result; result += this.Left.ToString(); if (this.Right != null) { result += " " + this.Operator.ToShortString() + " "; result += this.Right.ToString(); } return result; } /// <summary> /// Test whether the filter matches a given object /// </summary> /// <param name="o">Object to apply property/values to</param> /// <param name="ignoreCase">Wether to ignore case in string compare</param> /// <returns></returns> public override bool Test(object o, bool ignoreCase = true) { if (Object.Equals(o, null)) throw new NullReferenceException("Object to match against must not be null."); if (!this.IsValid()) this.Validate(); // check if there's only a left hand side... if (this.Right == null) { return this.Left.Test(o, ignoreCase); } // else, there's a right hand side as well switch (this.Operator) { case FilterOperator.Intersect: return this.Left.Test(o, ignoreCase) && this.Right.Test(o, ignoreCase); case FilterOperator.Union: return this.Left.Test(o, ignoreCase) || this.Right.Test(o, ignoreCase); case FilterOperator.Unknown: /* fall through */ default: throw new ArgumentException("Unsupported operator: " + this.Operator.ToString()); } } /// <summary> /// Helper function to elucidate the exact nature of validation failure /// </summary> public override void Validate() { if (this.Left == null) throw new MissingChild("The clause is missing the left side phrase"); if (this.Left.IsValid() == false) this.Left.Validate(); // don't need an operator unless there's a right hand side if (this.Right != null) { if (this.Operator == FilterOperator.Unknown) throw new BadOperator("The clause operator is invalid"); } // don't need a right hand side unless there's an operator if (this.Operator != FilterOperator.Unknown) { if (this.Right == null) throw new MissingChild("The operator is set, but the clause is missing the right side phrase"); if (this.Right.IsValid() == false) this.Right.Validate(); } } #endregion } /// <summary> /// Generic filter grammar exception /// </summary> [Serializable] public class MalFormedExpression : Exception { public MalFormedExpression() { } public MalFormedExpression(string message) : base(message) { } public MalFormedExpression(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// Exception for missing child node /// </summary> [Serializable] public class MissingChild : MalFormedExpression { public MissingChild() { } public MissingChild(string message) : base(message) { } public MissingChild(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// Exception for bad property name /// </summary> [Serializable] public class MissingProperty : MalFormedExpression { public MissingProperty() { } public MissingProperty(string message) : base(message) { } public MissingProperty(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// Exception for lack of values /// </summary> [Serializable] public class MissingValue : MalFormedExpression { public MissingValue() { } public MissingValue(string message) : base(message) { } public MissingValue(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// Exception for operator /// </summary> [Serializable] public class BadOperator : MalFormedExpression { public BadOperator() { } public BadOperator(string message) : base(message) { } public BadOperator(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// Exception for family tree /// </summary> [Serializable] public class RecursiveTree : MalFormedExpression { public RecursiveTree() { } public RecursiveTree(string message) : base(message) { } public RecursiveTree(string message, Exception innerException) : base(message, innerException) { } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using System.Linq; using UnityEngine; namespace Newtonsoft.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { private JsonContract _rootContract; private readonly List<object> _serializeStack = new List<object>(); private JsonSerializerProxy _internalSerializer; public JsonSerializerInternalWriter(JsonSerializer serializer) : base(serializer) { } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { if (jsonWriter == null) throw new ArgumentNullException("jsonWriter"); if (objectType != null) _rootContract = Serializer._contractResolver.ResolveContract(objectType); SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null); } private JsonSerializerProxy GetInternalSerializer() { if (_internalSerializer == null) _internalSerializer = new JsonSerializerProxy(this); return _internalSerializer; } private JsonContract GetContractSafe(object value) { if (value == null) return null; return Serializer._contractResolver.ResolveContract(value.GetType()); } private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (contract.TypeCode == PrimitiveTypeCode.Bytes) { // if type name handling is enabled then wrap the base64 byte string in an object with the type name bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty); if (includeTypeDetails) { writer.WriteStartObject(); WriteTypeProperty(writer, contract.CreatedType); writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false); JsonWriter.WriteValue(writer, contract.TypeCode, value); writer.WriteEndObject(); return; } } JsonWriter.WriteValue(writer, contract.TypeCode, value); } private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null) { writer.WriteNull(); return; } JsonConverter converter; if ((((converter = (member != null) ? member.Converter : null) != null) || ((converter = (containerProperty != null) ? containerProperty.ItemConverter : null) != null) || ((converter = (containerContract != null) ? containerContract.ItemConverter : null) != null) || ((converter = valueContract.Converter) != null) || ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) || ((converter = valueContract.InternalConverter) != null)) && converter.CanWrite) { SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty); return; } switch (valueContract.ContractType) { case JsonContractType.Object: SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.Array: JsonArrayContract arrayContract = (JsonArrayContract) valueContract; if (!arrayContract.IsMultidimensionalArray) SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty); else SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty); break; case JsonContractType.Primitive: SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.String: SerializeString(writer, value, (JsonStringContract)valueContract); break; case JsonContractType.Dictionary: JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) valueContract; SerializeDictionary(writer, (value is IDictionary) ? (IDictionary) value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty); break; case JsonContractType.Dynamic: SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.Linq: ((JToken) value).WriteTo(writer, Serializer.Converters.ToArray()); break; } } private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) { bool? isReference = null; // value could be coming from a dictionary or array and not have a property if (property != null) isReference = property.IsReference; if (isReference == null && containerProperty != null) isReference = containerProperty.ItemIsReference; if (isReference == null && collectionContract != null) isReference = collectionContract.ItemIsReference; if (isReference == null) isReference = contract.IsReference; return isReference; } private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (value == null) return false; if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) return false; bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty); if (isReference == null) { if (valueContract.ContractType == JsonContractType.Array) isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); else isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); } if (!isReference.Value) return false; return Serializer.GetReferenceResolver().IsReferenced(this, value); } private bool ShouldWriteProperty(object memberValue, JsonProperty property) { if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && memberValue == null) return false; if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())) return false; return true; } private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) return true; ReferenceLoopHandling? referenceLoopHandling = null; if (property != null) referenceLoopHandling = property.ReferenceLoopHandling; if (referenceLoopHandling == null && containerProperty != null) referenceLoopHandling = containerProperty.ItemReferenceLoopHandling; if (referenceLoopHandling == null && containerContract != null) referenceLoopHandling = containerContract.ItemReferenceLoopHandling; if (_serializeStack.IndexOf(value) != -1) { string message = "Self referencing loop detected"; if (property != null) message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName); message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()); var selfRef = (value is Vector2 || value is Vector3 || value is Vector4 || value is Color || value is Color32) ? ReferenceLoopHandling.Ignore : referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling); switch (selfRef) { case ReferenceLoopHandling.Error: throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); case ReferenceLoopHandling.Ignore: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null); return false; case ReferenceLoopHandling.Serialize: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null); return true; } } return true; } private void WriteReference(JsonWriter writer, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null); writer.WriteStartObject(); writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false); writer.WriteValue(reference); writer.WriteEndObject(); } private string GetReference(JsonWriter writer, object value) { try { string reference = Serializer.GetReferenceResolver().GetReference(this, value); return reference; } catch (Exception ex) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex); } } internal static bool TryConvertToString(object value, Type type, out string s) { if (value is Guid || value is Uri || value is TimeSpan) { s = value.ToString(); return true; } if (value is Type) { s = ((Type)value).AssemblyQualifiedName; return true; } s = null; return false; } private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) { OnSerializing(writer, contract, value); string s; TryConvertToString(value, contract.UnderlyingType, out s); writer.WriteValue(s); OnSerialized(writer, contract, value); } private void OnSerializing(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); contract.InvokeOnSerializing(value, Serializer._context); } private void OnSerialized(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); contract.InvokeOnSerialized(value, Serializer._context); } private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; try { object memberValue; JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) continue; property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } if (contract.ExtensionDataGetter != null) { IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value); if (extensionData != null) { foreach (KeyValuePair<object, object> e in extensionData) { JsonContract keyContract = GetContractSafe(e.Key); JsonContract valueContract = GetContractSafe(e.Value); bool escape; string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape); if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName); WriteReference(writer, e.Value); } else { if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member)) continue; writer.WritePropertyName(propertyName); SerializeValue(writer, e.Value, valueContract, null, contract, member); } } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); memberValue = property.ValueProvider.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, property)) { if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); WriteReference(writer, memberValue); return false; } if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) return false; if (memberValue == null) { JsonObjectContract objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default; if (resolvedRequired == Required.Always) throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); } return true; } } memberContract = null; memberValue = null; return false; } private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { writer.WriteStartObject(); bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); if (isReference) { WriteReferenceIdProperty(writer, contract.UnderlyingType, value); } if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty)) { WriteTypeProperty(writer, contract.UnderlyingType); } } private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null); writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false); writer.WriteValue(reference); } private void WriteTypeProperty(JsonWriter writer, Type type) { string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null); writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false); writer.WriteValue(typeName); } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag) { return ((value & flag) == flag); } private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) { return ((value & flag) == flag); } private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) return; _serializeStack.Add(value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); converter.WriteJson(writer, value, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); _serializeStack.RemoveAt(_serializeStack.Count - 1); } } private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { IWrappedCollection wrappedCollection = values as IWrappedCollection; object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values; OnSerializing(writer, contract, underlyingList); _serializeStack.Add(underlyingList); bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty); writer.WriteStartArray(); int initialDepth = writer.Top; int index = 0; // note that an error in the IEnumerable won't be caught foreach (object value in values) { try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } finally { index++; } } writer.WriteEndArray(); if (hasWrittenMetadataObject) writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingList); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, values); _serializeStack.Add(values); bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty); SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]); if (hasWrittenMetadataObject) writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, values); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } writer.WriteStartArray(); for (int i = 0; i < values.GetLength(dimension); i++) { newIndices[dimension] = i; bool isTopLevel = (newIndices.Length == values.Rank); if (isTopLevel) { object value = values.GetValue(newIndices); try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth + 1); else throw; } } else { SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices); } } writer.WriteEndArray(); } private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty); bool writeMetadataObject = isReference || includeTypeDetails; if (writeMetadataObject) { writer.WriteStartObject(); if (isReference) { WriteReferenceIdProperty(writer, contract.UnderlyingType, values); } if (includeTypeDetails) { WriteTypeProperty(writer, values.GetType()); } writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false); } if (contract.ItemContract == null) contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof (object)); return writeMetadataObject; } private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; // only write non-dynamic properties that have an explicit attribute if (property.HasMemberAttribute) { try { object memberValue; JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) continue; property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } } foreach (string memberName in value.GetDynamicMemberNames()) { object memberValue; if (contract.TryGetMember(value, memberName, out memberValue)) { try { JsonContract valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) continue; if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member)) { string resolvedPropertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(memberName) : memberName; writer.WritePropertyName(resolvedPropertyName); SerializeValue(writer, memberValue, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } private bool ShouldWriteDynamicProperty(object memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) return false; if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) && (memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType())))) return false; return true; } private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { TypeNameHandling resolvedTypeNameHandling = ((member != null) ? member.TypeNameHandling : null) ?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null) ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null) ?? Serializer._typeNameHandling; if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag)) return true; // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default) if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto)) { if (member != null) { if (contract.UnderlyingType != member.PropertyContract.CreatedType) return true; } else if (containerContract != null) { if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType) return true; } else if (_rootContract != null && _serializeStack.Count == 1) { if (contract.UnderlyingType != _rootContract.CreatedType) return true; } } return false; } private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { IWrappedDictionary wrappedDictionary = values as IWrappedDictionary; object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); _serializeStack.Add(underlyingDictionary); WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); if (contract.ItemContract == null) contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); if (contract.KeyContract == null) contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); int initialDepth = writer.Top; foreach (DictionaryEntry entry in values) { bool escape; string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape); propertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(propertyName) : propertyName; try { object value = entry.Value; JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName, escape); WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) continue; writer.WritePropertyName(propertyName, escape); SerializeValue(writer, value, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); } private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) { string propertyName; if (contract.ContractType == JsonContractType.Primitive) { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable) { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable) { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } else { escape = true; return Convert.ToString(name, CultureInfo.InvariantCulture); } } else if (TryConvertToString(name, name.GetType(), out propertyName)) { escape = true; return propertyName; } else { escape = true; return name.ToString(); } } private void HandleError(JsonWriter writer, int initialDepth) { ClearErrorContext(); if (writer.WriteState == WriteState.Property) writer.WriteNull(); while (writer.Top > initialDepth) { writer.WriteEnd(); } } private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target) { if (property.ShouldSerialize == null) return true; bool shouldSerialize = property.ShouldSerialize(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null); return shouldSerialize; } private bool IsSpecified(JsonWriter writer, JsonProperty property, object target) { if (property.GetIsSpecified == null) return true; bool isSpecified = property.GetIsSpecified(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null); return isSpecified; } } } #endif
// 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! namespace Google.Cloud.Dataplex.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedMetadataServiceClientSnippets { /// <summary>Snippet for CreateEntity</summary> public void CreateEntityRequestObject() { // Snippet: CreateEntity(CreateEntityRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) CreateEntityRequest request = new CreateEntityRequest { ParentAsZoneName = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"), Entity = new Entity(), ValidateOnly = false, }; // Make the request Entity response = metadataServiceClient.CreateEntity(request); // End snippet } /// <summary>Snippet for CreateEntityAsync</summary> public async Task CreateEntityRequestObjectAsync() { // Snippet: CreateEntityAsync(CreateEntityRequest, CallSettings) // Additional: CreateEntityAsync(CreateEntityRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) CreateEntityRequest request = new CreateEntityRequest { ParentAsZoneName = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"), Entity = new Entity(), ValidateOnly = false, }; // Make the request Entity response = await metadataServiceClient.CreateEntityAsync(request); // End snippet } /// <summary>Snippet for CreateEntity</summary> public void CreateEntity() { // Snippet: CreateEntity(string, Entity, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]"; Entity entity = new Entity(); // Make the request Entity response = metadataServiceClient.CreateEntity(parent, entity); // End snippet } /// <summary>Snippet for CreateEntityAsync</summary> public async Task CreateEntityAsync() { // Snippet: CreateEntityAsync(string, Entity, CallSettings) // Additional: CreateEntityAsync(string, Entity, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]"; Entity entity = new Entity(); // Make the request Entity response = await metadataServiceClient.CreateEntityAsync(parent, entity); // End snippet } /// <summary>Snippet for CreateEntity</summary> public void CreateEntityResourceNames() { // Snippet: CreateEntity(ZoneName, Entity, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) ZoneName parent = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"); Entity entity = new Entity(); // Make the request Entity response = metadataServiceClient.CreateEntity(parent, entity); // End snippet } /// <summary>Snippet for CreateEntityAsync</summary> public async Task CreateEntityResourceNamesAsync() { // Snippet: CreateEntityAsync(ZoneName, Entity, CallSettings) // Additional: CreateEntityAsync(ZoneName, Entity, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) ZoneName parent = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"); Entity entity = new Entity(); // Make the request Entity response = await metadataServiceClient.CreateEntityAsync(parent, entity); // End snippet } /// <summary>Snippet for UpdateEntity</summary> public void UpdateEntityRequestObject() { // Snippet: UpdateEntity(UpdateEntityRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) UpdateEntityRequest request = new UpdateEntityRequest { Entity = new Entity(), ValidateOnly = false, }; // Make the request Entity response = metadataServiceClient.UpdateEntity(request); // End snippet } /// <summary>Snippet for UpdateEntityAsync</summary> public async Task UpdateEntityRequestObjectAsync() { // Snippet: UpdateEntityAsync(UpdateEntityRequest, CallSettings) // Additional: UpdateEntityAsync(UpdateEntityRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) UpdateEntityRequest request = new UpdateEntityRequest { Entity = new Entity(), ValidateOnly = false, }; // Make the request Entity response = await metadataServiceClient.UpdateEntityAsync(request); // End snippet } /// <summary>Snippet for DeleteEntity</summary> public void DeleteEntityRequestObject() { // Snippet: DeleteEntity(DeleteEntityRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) DeleteEntityRequest request = new DeleteEntityRequest { EntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), Etag = "", }; // Make the request metadataServiceClient.DeleteEntity(request); // End snippet } /// <summary>Snippet for DeleteEntityAsync</summary> public async Task DeleteEntityRequestObjectAsync() { // Snippet: DeleteEntityAsync(DeleteEntityRequest, CallSettings) // Additional: DeleteEntityAsync(DeleteEntityRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) DeleteEntityRequest request = new DeleteEntityRequest { EntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), Etag = "", }; // Make the request await metadataServiceClient.DeleteEntityAsync(request); // End snippet } /// <summary>Snippet for DeleteEntity</summary> public void DeleteEntity() { // Snippet: DeleteEntity(string, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; // Make the request metadataServiceClient.DeleteEntity(name); // End snippet } /// <summary>Snippet for DeleteEntityAsync</summary> public async Task DeleteEntityAsync() { // Snippet: DeleteEntityAsync(string, CallSettings) // Additional: DeleteEntityAsync(string, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; // Make the request await metadataServiceClient.DeleteEntityAsync(name); // End snippet } /// <summary>Snippet for DeleteEntity</summary> public void DeleteEntityResourceNames() { // Snippet: DeleteEntity(EntityName, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) EntityName name = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); // Make the request metadataServiceClient.DeleteEntity(name); // End snippet } /// <summary>Snippet for DeleteEntityAsync</summary> public async Task DeleteEntityResourceNamesAsync() { // Snippet: DeleteEntityAsync(EntityName, CallSettings) // Additional: DeleteEntityAsync(EntityName, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) EntityName name = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); // Make the request await metadataServiceClient.DeleteEntityAsync(name); // End snippet } /// <summary>Snippet for GetEntity</summary> public void GetEntityRequestObject() { // Snippet: GetEntity(GetEntityRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) GetEntityRequest request = new GetEntityRequest { EntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), View = GetEntityRequest.Types.EntityView.Unspecified, }; // Make the request Entity response = metadataServiceClient.GetEntity(request); // End snippet } /// <summary>Snippet for GetEntityAsync</summary> public async Task GetEntityRequestObjectAsync() { // Snippet: GetEntityAsync(GetEntityRequest, CallSettings) // Additional: GetEntityAsync(GetEntityRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) GetEntityRequest request = new GetEntityRequest { EntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), View = GetEntityRequest.Types.EntityView.Unspecified, }; // Make the request Entity response = await metadataServiceClient.GetEntityAsync(request); // End snippet } /// <summary>Snippet for GetEntity</summary> public void GetEntity() { // Snippet: GetEntity(string, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; // Make the request Entity response = metadataServiceClient.GetEntity(name); // End snippet } /// <summary>Snippet for GetEntityAsync</summary> public async Task GetEntityAsync() { // Snippet: GetEntityAsync(string, CallSettings) // Additional: GetEntityAsync(string, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; // Make the request Entity response = await metadataServiceClient.GetEntityAsync(name); // End snippet } /// <summary>Snippet for GetEntity</summary> public void GetEntityResourceNames() { // Snippet: GetEntity(EntityName, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) EntityName name = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); // Make the request Entity response = metadataServiceClient.GetEntity(name); // End snippet } /// <summary>Snippet for GetEntityAsync</summary> public async Task GetEntityResourceNamesAsync() { // Snippet: GetEntityAsync(EntityName, CallSettings) // Additional: GetEntityAsync(EntityName, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) EntityName name = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); // Make the request Entity response = await metadataServiceClient.GetEntityAsync(name); // End snippet } /// <summary>Snippet for ListEntities</summary> public void ListEntitiesRequestObject() { // Snippet: ListEntities(ListEntitiesRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) ListEntitiesRequest request = new ListEntitiesRequest { ParentAsZoneName = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"), View = ListEntitiesRequest.Types.EntityView.Unspecified, Filter = "", }; // Make the request PagedEnumerable<ListEntitiesResponse, Entity> response = metadataServiceClient.ListEntities(request); // Iterate over all response items, lazily performing RPCs as required foreach (Entity item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListEntitiesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Entity item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Entity> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Entity item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEntitiesAsync</summary> public async Task ListEntitiesRequestObjectAsync() { // Snippet: ListEntitiesAsync(ListEntitiesRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) ListEntitiesRequest request = new ListEntitiesRequest { ParentAsZoneName = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"), View = ListEntitiesRequest.Types.EntityView.Unspecified, Filter = "", }; // Make the request PagedAsyncEnumerable<ListEntitiesResponse, Entity> response = metadataServiceClient.ListEntitiesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Entity item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListEntitiesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Entity item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Entity> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Entity item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEntities</summary> public void ListEntities() { // Snippet: ListEntities(string, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]"; // Make the request PagedEnumerable<ListEntitiesResponse, Entity> response = metadataServiceClient.ListEntities(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Entity item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListEntitiesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Entity item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Entity> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Entity item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEntitiesAsync</summary> public async Task ListEntitiesAsync() { // Snippet: ListEntitiesAsync(string, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]"; // Make the request PagedAsyncEnumerable<ListEntitiesResponse, Entity> response = metadataServiceClient.ListEntitiesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Entity item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListEntitiesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Entity item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Entity> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Entity item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEntities</summary> public void ListEntitiesResourceNames() { // Snippet: ListEntities(ZoneName, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) ZoneName parent = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"); // Make the request PagedEnumerable<ListEntitiesResponse, Entity> response = metadataServiceClient.ListEntities(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Entity item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListEntitiesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Entity item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Entity> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Entity item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEntitiesAsync</summary> public async Task ListEntitiesResourceNamesAsync() { // Snippet: ListEntitiesAsync(ZoneName, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) ZoneName parent = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]"); // Make the request PagedAsyncEnumerable<ListEntitiesResponse, Entity> response = metadataServiceClient.ListEntitiesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Entity item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListEntitiesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Entity item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Entity> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Entity item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for CreatePartition</summary> public void CreatePartitionRequestObject() { // Snippet: CreatePartition(CreatePartitionRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) CreatePartitionRequest request = new CreatePartitionRequest { ParentAsEntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), Partition = new Partition(), ValidateOnly = false, }; // Make the request Partition response = metadataServiceClient.CreatePartition(request); // End snippet } /// <summary>Snippet for CreatePartitionAsync</summary> public async Task CreatePartitionRequestObjectAsync() { // Snippet: CreatePartitionAsync(CreatePartitionRequest, CallSettings) // Additional: CreatePartitionAsync(CreatePartitionRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) CreatePartitionRequest request = new CreatePartitionRequest { ParentAsEntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), Partition = new Partition(), ValidateOnly = false, }; // Make the request Partition response = await metadataServiceClient.CreatePartitionAsync(request); // End snippet } /// <summary>Snippet for CreatePartition</summary> public void CreatePartition() { // Snippet: CreatePartition(string, Partition, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; Partition partition = new Partition(); // Make the request Partition response = metadataServiceClient.CreatePartition(parent, partition); // End snippet } /// <summary>Snippet for CreatePartitionAsync</summary> public async Task CreatePartitionAsync() { // Snippet: CreatePartitionAsync(string, Partition, CallSettings) // Additional: CreatePartitionAsync(string, Partition, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; Partition partition = new Partition(); // Make the request Partition response = await metadataServiceClient.CreatePartitionAsync(parent, partition); // End snippet } /// <summary>Snippet for CreatePartition</summary> public void CreatePartitionResourceNames() { // Snippet: CreatePartition(EntityName, Partition, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) EntityName parent = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); Partition partition = new Partition(); // Make the request Partition response = metadataServiceClient.CreatePartition(parent, partition); // End snippet } /// <summary>Snippet for CreatePartitionAsync</summary> public async Task CreatePartitionResourceNamesAsync() { // Snippet: CreatePartitionAsync(EntityName, Partition, CallSettings) // Additional: CreatePartitionAsync(EntityName, Partition, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) EntityName parent = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); Partition partition = new Partition(); // Make the request Partition response = await metadataServiceClient.CreatePartitionAsync(parent, partition); // End snippet } /// <summary>Snippet for DeletePartition</summary> public void DeletePartitionRequestObject() { // Snippet: DeletePartition(DeletePartitionRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) DeletePartitionRequest request = new DeletePartitionRequest { PartitionName = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"), }; // Make the request metadataServiceClient.DeletePartition(request); // End snippet } /// <summary>Snippet for DeletePartitionAsync</summary> public async Task DeletePartitionRequestObjectAsync() { // Snippet: DeletePartitionAsync(DeletePartitionRequest, CallSettings) // Additional: DeletePartitionAsync(DeletePartitionRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) DeletePartitionRequest request = new DeletePartitionRequest { PartitionName = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"), }; // Make the request await metadataServiceClient.DeletePartitionAsync(request); // End snippet } /// <summary>Snippet for DeletePartition</summary> public void DeletePartition() { // Snippet: DeletePartition(string, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]/partitions/[PARTITION]"; // Make the request metadataServiceClient.DeletePartition(name); // End snippet } /// <summary>Snippet for DeletePartitionAsync</summary> public async Task DeletePartitionAsync() { // Snippet: DeletePartitionAsync(string, CallSettings) // Additional: DeletePartitionAsync(string, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]/partitions/[PARTITION]"; // Make the request await metadataServiceClient.DeletePartitionAsync(name); // End snippet } /// <summary>Snippet for DeletePartition</summary> public void DeletePartitionResourceNames() { // Snippet: DeletePartition(PartitionName, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) PartitionName name = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"); // Make the request metadataServiceClient.DeletePartition(name); // End snippet } /// <summary>Snippet for DeletePartitionAsync</summary> public async Task DeletePartitionResourceNamesAsync() { // Snippet: DeletePartitionAsync(PartitionName, CallSettings) // Additional: DeletePartitionAsync(PartitionName, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) PartitionName name = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"); // Make the request await metadataServiceClient.DeletePartitionAsync(name); // End snippet } /// <summary>Snippet for GetPartition</summary> public void GetPartitionRequestObject() { // Snippet: GetPartition(GetPartitionRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) GetPartitionRequest request = new GetPartitionRequest { PartitionName = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"), }; // Make the request Partition response = metadataServiceClient.GetPartition(request); // End snippet } /// <summary>Snippet for GetPartitionAsync</summary> public async Task GetPartitionRequestObjectAsync() { // Snippet: GetPartitionAsync(GetPartitionRequest, CallSettings) // Additional: GetPartitionAsync(GetPartitionRequest, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) GetPartitionRequest request = new GetPartitionRequest { PartitionName = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"), }; // Make the request Partition response = await metadataServiceClient.GetPartitionAsync(request); // End snippet } /// <summary>Snippet for GetPartition</summary> public void GetPartition() { // Snippet: GetPartition(string, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]/partitions/[PARTITION]"; // Make the request Partition response = metadataServiceClient.GetPartition(name); // End snippet } /// <summary>Snippet for GetPartitionAsync</summary> public async Task GetPartitionAsync() { // Snippet: GetPartitionAsync(string, CallSettings) // Additional: GetPartitionAsync(string, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]/partitions/[PARTITION]"; // Make the request Partition response = await metadataServiceClient.GetPartitionAsync(name); // End snippet } /// <summary>Snippet for GetPartition</summary> public void GetPartitionResourceNames() { // Snippet: GetPartition(PartitionName, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) PartitionName name = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"); // Make the request Partition response = metadataServiceClient.GetPartition(name); // End snippet } /// <summary>Snippet for GetPartitionAsync</summary> public async Task GetPartitionResourceNamesAsync() { // Snippet: GetPartitionAsync(PartitionName, CallSettings) // Additional: GetPartitionAsync(PartitionName, CancellationToken) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) PartitionName name = PartitionName.FromProjectLocationLakeZoneEntityPartition("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]", "[PARTITION]"); // Make the request Partition response = await metadataServiceClient.GetPartitionAsync(name); // End snippet } /// <summary>Snippet for ListPartitions</summary> public void ListPartitionsRequestObject() { // Snippet: ListPartitions(ListPartitionsRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) ListPartitionsRequest request = new ListPartitionsRequest { ParentAsEntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), Filter = "", }; // Make the request PagedEnumerable<ListPartitionsResponse, Partition> response = metadataServiceClient.ListPartitions(request); // Iterate over all response items, lazily performing RPCs as required foreach (Partition item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPartitionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Partition item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Partition> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Partition item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPartitionsAsync</summary> public async Task ListPartitionsRequestObjectAsync() { // Snippet: ListPartitionsAsync(ListPartitionsRequest, CallSettings) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) ListPartitionsRequest request = new ListPartitionsRequest { ParentAsEntityName = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"), Filter = "", }; // Make the request PagedAsyncEnumerable<ListPartitionsResponse, Partition> response = metadataServiceClient.ListPartitionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Partition item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPartitionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Partition item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Partition> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Partition item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPartitions</summary> public void ListPartitions() { // Snippet: ListPartitions(string, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; // Make the request PagedEnumerable<ListPartitionsResponse, Partition> response = metadataServiceClient.ListPartitions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Partition item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPartitionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Partition item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Partition> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Partition item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPartitionsAsync</summary> public async Task ListPartitionsAsync() { // Snippet: ListPartitionsAsync(string, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]"; // Make the request PagedAsyncEnumerable<ListPartitionsResponse, Partition> response = metadataServiceClient.ListPartitionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Partition item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPartitionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Partition item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Partition> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Partition item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPartitions</summary> public void ListPartitionsResourceNames() { // Snippet: ListPartitions(EntityName, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create(); // Initialize request argument(s) EntityName parent = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); // Make the request PagedEnumerable<ListPartitionsResponse, Partition> response = metadataServiceClient.ListPartitions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Partition item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPartitionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Partition item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Partition> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Partition item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPartitionsAsync</summary> public async Task ListPartitionsResourceNamesAsync() { // Snippet: ListPartitionsAsync(EntityName, string, int?, CallSettings) // Create client MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync(); // Initialize request argument(s) EntityName parent = EntityName.FromProjectLocationLakeZoneEntity("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]", "[ENTITY]"); // Make the request PagedAsyncEnumerable<ListPartitionsResponse, Partition> response = metadataServiceClient.ListPartitionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Partition item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPartitionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Partition item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Partition> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Partition item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
using System; using System.Collections; using System.IO; using System.Web.UI.WebControls; using Cuyahoga.Core.Domain; using Cuyahoga.Web.Admin.UI; using Cuyahoga.Web.UI; using Cuyahoga.Web.Util; namespace Cuyahoga.Web.Admin { /// <summary> /// Summary description for TemplateEdit. /// </summary> public class TemplateEdit : AdminBasePage { private Template _activeTemplate; protected TextBox txtName; protected RequiredFieldValidator rfvName; protected TextBox txtPath; protected RequiredFieldValidator rfvPath; protected Button btnSave; protected DropDownList ddlCss; protected TextBox txtBasePath; protected RequiredFieldValidator rfvBasePath; protected DropDownList ddlTemplateControls; protected Button btnBack; protected Button btnVerifyBasePath; protected Label lblTemplateControlWarning; protected Label lblCssWarning; protected Panel pnlPlaceholders; protected Repeater rptPlaceholders; protected Button btnDelete; private void Page_Load(object sender, EventArgs e) { this.Title = "Edit template"; if (Context.Request.QueryString["TemplateId"] != null) { if (Int32.Parse(Context.Request.QueryString["TemplateId"]) == -1) { this._activeTemplate = new Template(); } else { this._activeTemplate = (Template)base.CoreRepository.GetObjectById(typeof(Template) , Int32.Parse(Context.Request.QueryString["TemplateId"])); this.pnlPlaceholders.Visible = true; } if (! this.IsPostBack) { BindTemplateControls(); BindTemplateUserControls(); BindCss(); if (this._activeTemplate.Id != -1) { BindPlaceholders(); } } } } private void BindTemplateControls() { this.txtName.Text = this._activeTemplate.Name; this.txtBasePath.Text = this._activeTemplate.BasePath; this.btnDelete.Visible = (this._activeTemplate.Id > 0 && base.CoreRepository.GetNodesByTemplate(this._activeTemplate).Count <= 0); this.btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?')"); } private void BindTemplateUserControls() { this.ddlTemplateControls.Items.Clear(); string physicalTemplateDir = Context.Server.MapPath( UrlHelper.GetApplicationPath() + this._activeTemplate.BasePath); DirectoryInfo dir = new DirectoryInfo(physicalTemplateDir); if (dir.Exists) { FileInfo[] templateControls = dir.GetFiles("*.ascx"); if (templateControls.Length == 0 && this.IsPostBack) { this.lblTemplateControlWarning.Visible = true; this.lblTemplateControlWarning.Text = "No template user controls found at the [base path] location."; } else { foreach (FileInfo templateControlFile in templateControls) { this.ddlTemplateControls.Items.Add(templateControlFile.Name); } ListItem li = this.ddlTemplateControls.Items.FindByValue(this._activeTemplate.TemplateControl); if (li != null) { li.Selected = true; } } } } private void BindCss() { this.ddlCss.Items.Clear(); string physicalCssDir = Context.Server.MapPath( UrlHelper.GetApplicationPath() + this._activeTemplate.BasePath + "/Css"); DirectoryInfo dir = new DirectoryInfo(physicalCssDir); if (dir.Exists) { FileInfo[] cssSheets = dir.GetFiles("*.css"); if (cssSheets.Length == 0 && this.IsPostBack) { this.lblCssWarning.Visible = true; this.lblCssWarning.Text = "No stylesheet files found at the [base path]/Css location."; } else { foreach (FileInfo css in cssSheets) { this.ddlCss.Items.Add(css.Name); } ListItem li = this.ddlCss.Items.FindByValue(this._activeTemplate.Css); if (li != null) { li.Selected = true; } } } else { this.lblCssWarning.Visible = true; this.lblCssWarning.Text = "The location for the stylesheets ([base path]/Css) could not be found."; } } private void BindPlaceholders() { // Load template control first. string templateControlPath = UrlHelper.GetApplicationPath() + this._activeTemplate.Path; if (File.Exists(Server.MapPath(templateControlPath))) { BaseTemplate templateControl = (BaseTemplate) this.Page.LoadControl(templateControlPath); this.rptPlaceholders.DataSource = templateControl.Containers; this.rptPlaceholders.DataBind(); } else { ShowError("Unable to load the template control " + templateControlPath); } } private void CheckBasePath() { if (this._activeTemplate.BasePath.Trim() == String.Empty) { ShowError("The base path can not be empty."); } else { string physicalBasePath = Context.Server.MapPath( UrlHelper.GetApplicationPath() + this._activeTemplate.BasePath); if (! Directory.Exists(physicalBasePath)) { ShowError("The base path you entered could not be found on the server."); } else { BindTemplateUserControls(); BindCss(); } } } private void SaveTemplate() { try { if (this._activeTemplate.Id == -1) { base.CoreRepository.SaveObject(this._activeTemplate); Context.Response.Redirect("Templates.aspx"); } else { base.CoreRepository.UpdateObject(this._activeTemplate); ShowMessage("Template saved"); } } catch (Exception ex) { ShowError(ex.Message); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnVerifyBasePath.Click += new System.EventHandler(this.btnVerifyBasePath_Click); this.rptPlaceholders.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptPlaceholders_ItemDataBound); this.rptPlaceholders.ItemCommand += new System.Web.UI.WebControls.RepeaterCommandEventHandler(this.rptPlaceholders_ItemCommand); this.btnSave.Click += new System.EventHandler(this.btnSave_Click); this.btnBack.Click += new System.EventHandler(this.btnCancel_Click); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void btnSave_Click(object sender, EventArgs e) { if (this.IsValid) { if (this.ddlTemplateControls.SelectedIndex == -1 || this.ddlCss.SelectedIndex == -1) { ShowError("No template control or css selected."); } else { this._activeTemplate.Name = this.txtName.Text; this._activeTemplate.BasePath = this.txtBasePath.Text; this._activeTemplate.TemplateControl = this.ddlTemplateControls.SelectedValue; this._activeTemplate.Css = this.ddlCss.SelectedValue; SaveTemplate(); } } } private void btnDelete_Click(object sender, EventArgs e) { if (this._activeTemplate.Id > 0) { try { base.CoreRepository.DeleteObject(this._activeTemplate); Context.Response.Redirect("Templates.aspx"); } catch (Exception ex) { ShowError(ex.Message); } } } private void btnCancel_Click(object sender, EventArgs e) { Context.Response.Redirect("Templates.aspx"); } private void btnVerifyBasePath_Click(object sender, EventArgs e) { this._activeTemplate.BasePath = this.txtBasePath.Text; CheckBasePath(); } private void rptPlaceholders_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { DictionaryEntry entry = (DictionaryEntry)e.Item.DataItem; string placeholder = entry.Key.ToString(); Label lblPlaceholder = e.Item.FindControl("lblPlaceholder") as Label; HyperLink hplSection = e.Item.FindControl("hplSection") as HyperLink; HyperLink hplAttachSection = e.Item.FindControl("hplAttachSection") as HyperLink; LinkButton lbtDetachSection = e.Item.FindControl("lbtDetachSection") as LinkButton; lblPlaceholder.Text = placeholder; // Find an attached section Section section = this._activeTemplate.Sections[placeholder] as Section; if (section != null) { hplSection.Text = section.Title; hplSection.NavigateUrl = "~/Admin/SectionEdit.aspx?SectionId=" + section.Id; hplSection.Visible = true; hplAttachSection.Visible = false; lbtDetachSection.Visible = true; lbtDetachSection.Attributes.Add("onclick", "return confirm(\"Are you sure?\");"); lbtDetachSection.CommandArgument = placeholder; } else { hplSection.Visible = false; hplAttachSection.Visible = true; hplAttachSection.NavigateUrl = String.Format("~/Admin/TemplateSection.aspx?TemplateId={0}&Placeholder={1}" , this._activeTemplate.Id, placeholder); lbtDetachSection.Visible = false; } } } private void rptPlaceholders_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "detach") { string placeholder = e.CommandArgument.ToString(); this._activeTemplate.Sections.Remove(placeholder); try { base.CoreRepository.UpdateObject(this._activeTemplate); ShowMessage(String.Format("Section in Placeholder {0} detached", placeholder)); BindPlaceholders(); } catch (Exception ex) { ShowError(ex.Message); } } } } }
using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IIntegrationPartnerApi { #region Synchronous Operations /// <summary> /// Get an integrationPartner by id /// </summary> /// <remarks> /// Returns the integrationPartner identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>IntegrationPartner</returns> IntegrationPartner GetIntegrationPartnerById (string integrationPartnerId); /// <summary> /// Get an integrationPartner by id /// </summary> /// <remarks> /// Returns the integrationPartner identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>ApiResponse of IntegrationPartner</returns> ApiResponse<IntegrationPartner> GetIntegrationPartnerByIdWithHttpInfo (string integrationPartnerId); /// <summary> /// Search integrationPartners /// </summary> /// <remarks> /// Returns the list of integrationPartners that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;IntegrationPartner&gt;</returns> List<IntegrationPartner> GetIntegrationPartnerBySearchText (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search integrationPartners /// </summary> /// <remarks> /// Returns the list of integrationPartners that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;IntegrationPartner&gt;</returns> ApiResponse<List<IntegrationPartner>> GetIntegrationPartnerBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Get an integrationPartner by id /// </summary> /// <remarks> /// Returns the integrationPartner identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>Task of IntegrationPartner</returns> System.Threading.Tasks.Task<IntegrationPartner> GetIntegrationPartnerByIdAsync (string integrationPartnerId); /// <summary> /// Get an integrationPartner by id /// </summary> /// <remarks> /// Returns the integrationPartner identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>Task of ApiResponse (IntegrationPartner)</returns> System.Threading.Tasks.Task<ApiResponse<IntegrationPartner>> GetIntegrationPartnerByIdAsyncWithHttpInfo (string integrationPartnerId); /// <summary> /// Search integrationPartners /// </summary> /// <remarks> /// Returns the list of integrationPartners that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;IntegrationPartner&gt;</returns> System.Threading.Tasks.Task<List<IntegrationPartner>> GetIntegrationPartnerBySearchTextAsync (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search integrationPartners /// </summary> /// <remarks> /// Returns the list of integrationPartners that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;IntegrationPartner&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<IntegrationPartner>>> GetIntegrationPartnerBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class IntegrationPartnerApi : IIntegrationPartnerApi { /// <summary> /// Initializes a new instance of the <see cref="IntegrationPartnerApi"/> class. /// </summary> /// <returns></returns> public IntegrationPartnerApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="IntegrationPartnerApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public IntegrationPartnerApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Get an integrationPartner by id Returns the integrationPartner identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>IntegrationPartner</returns> public IntegrationPartner GetIntegrationPartnerById (string integrationPartnerId) { ApiResponse<IntegrationPartner> localVarResponse = GetIntegrationPartnerByIdWithHttpInfo(integrationPartnerId); return localVarResponse.Data; } /// <summary> /// Get an integrationPartner by id Returns the integrationPartner identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>ApiResponse of IntegrationPartner</returns> public ApiResponse< IntegrationPartner > GetIntegrationPartnerByIdWithHttpInfo (string integrationPartnerId) { // verify the required parameter 'integrationPartnerId' is set if (integrationPartnerId == null) throw new ApiException(400, "Missing required parameter 'integrationPartnerId' when calling IntegrationPartnerApi->GetIntegrationPartnerById"); var localVarPath = "/beta/integrationPartner/{integrationPartnerId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (integrationPartnerId != null) localVarPathParams.Add("integrationPartnerId", Configuration.ApiClient.ParameterToString(integrationPartnerId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerById: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<IntegrationPartner>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (IntegrationPartner) Configuration.ApiClient.Deserialize(localVarResponse, typeof(IntegrationPartner))); } /// <summary> /// Get an integrationPartner by id Returns the integrationPartner identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>Task of IntegrationPartner</returns> public async System.Threading.Tasks.Task<IntegrationPartner> GetIntegrationPartnerByIdAsync (string integrationPartnerId) { ApiResponse<IntegrationPartner> localVarResponse = await GetIntegrationPartnerByIdAsyncWithHttpInfo(integrationPartnerId); return localVarResponse.Data; } /// <summary> /// Get an integrationPartner by id Returns the integrationPartner identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="integrationPartnerId">Id of integrationPartner to be returned.</param> /// <returns>Task of ApiResponse (IntegrationPartner)</returns> public async System.Threading.Tasks.Task<ApiResponse<IntegrationPartner>> GetIntegrationPartnerByIdAsyncWithHttpInfo (string integrationPartnerId) { // verify the required parameter 'integrationPartnerId' is set if (integrationPartnerId == null) throw new ApiException(400, "Missing required parameter 'integrationPartnerId' when calling GetIntegrationPartnerById"); var localVarPath = "/beta/integrationPartner/{integrationPartnerId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (integrationPartnerId != null) localVarPathParams.Add("integrationPartnerId", Configuration.ApiClient.ParameterToString(integrationPartnerId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerById: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<IntegrationPartner>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (IntegrationPartner) Configuration.ApiClient.Deserialize(localVarResponse, typeof(IntegrationPartner))); } /// <summary> /// Search integrationPartners Returns the list of integrationPartners that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;IntegrationPartner&gt;</returns> public List<IntegrationPartner> GetIntegrationPartnerBySearchText (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<IntegrationPartner>> localVarResponse = GetIntegrationPartnerBySearchTextWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search integrationPartners Returns the list of integrationPartners that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;IntegrationPartner&gt;</returns> public ApiResponse< List<IntegrationPartner> > GetIntegrationPartnerBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/beta/integrationPartner/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerBySearchText: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<List<IntegrationPartner>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<IntegrationPartner>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<IntegrationPartner>))); } /// <summary> /// Search integrationPartners Returns the list of integrationPartners that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;IntegrationPartner&gt;</returns> public async System.Threading.Tasks.Task<List<IntegrationPartner>> GetIntegrationPartnerBySearchTextAsync (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<IntegrationPartner>> localVarResponse = await GetIntegrationPartnerBySearchTextAsyncWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search integrationPartners Returns the list of integrationPartners that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;IntegrationPartner&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<IntegrationPartner>>> GetIntegrationPartnerBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/beta/integrationPartner/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerBySearchText: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetIntegrationPartnerBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<List<IntegrationPartner>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<IntegrationPartner>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<IntegrationPartner>))); } } }
using UnityEditor; using UnityEngine; using System; using System.Collections.Generic; using System.IO; using PlayFab.PfEditor.Json; namespace PlayFab.PfEditor { [InitializeOnLoad] public static partial class PlayFabEditorHelper { #region EDITOR_STRINGS public static string EDEX_VERSION_TEMPLATE = "namespace PlayFab.PfEditor { public static partial class PlayFabEditorHelper { public static string EDEX_VERSION = \"{sdkVersion}\"; } }\n"; public static string EDEX_NAME = "PlayFab_EditorExtensions"; public static string EDEX_ROOT = Application.dataPath + "/PlayFabEditorExtensions/Editor"; public static string DEV_API_ENDPOINT = "https://editor.playfabapi.com"; public static string TITLE_ENDPOINT = ".playfabapi.com"; public static string GAMEMANAGER_URL = "https://developer.playfab.com"; public static string PLAYFAB_SETTINGS_TYPENAME = "PlayFabSettings"; public static string PLAYFAB_EDEX_MAINFILE = "PlayFabEditor.cs"; public static string SDK_DOWNLOAD_PATH = "/Resources/PlayFabUnitySdk.unitypackage"; public static string EDEX_UPGRADE_PATH = "/Resources/PlayFabUnityEditorExtensions.unitypackage"; public static string EDEX_PACKAGES_PATH = "/Resources/MostRecentPackage.unitypackage"; public static string CLOUDSCRIPT_FILENAME = ".CloudScript.js"; //prefixed with a '.' to exclude this code from Unity's compiler public static string CLOUDSCRIPT_PATH = EDEX_ROOT + "/Resources/" + CLOUDSCRIPT_FILENAME; public static string ADMIN_API = "ENABLE_PLAYFABADMIN_API"; public static string SERVER_API = "ENABLE_PLAYFABSERVER_API"; public static string CLIENT_API = "DISABLE_PLAYFABCLIENT_API"; public static string DEBUG_REQUEST_TIMING = "PLAYFAB_REQUEST_TIMING"; public static string DISABLE_IDFA = "DISABLE_IDFA"; public static Dictionary<string, string> FLAG_LABELS = new Dictionary<string, string> { { CLIENT_API, "ENABLE CLIENT API" }, { SERVER_API, "ENABLE SERVER API" }, { ADMIN_API, "ENABLE ADMIN API" }, { DEBUG_REQUEST_TIMING, "ENABLE REQUEST TIMES" }, { DISABLE_IDFA, "DISABLE IDFA" }, }; public static Dictionary<string, bool> FLAG_INVERSION = new Dictionary<string, bool> { { CLIENT_API, true }, { SERVER_API, false }, { ADMIN_API, false }, { DEBUG_REQUEST_TIMING, false }, { DISABLE_IDFA, false }, }; public static string DEFAULT_SDK_LOCATION = "Assets/PlayFabSdk"; public static string STUDIO_OVERRIDE = "_OVERRIDE_"; public static string MSG_SPIN_BLOCK = "{\"useSpinner\":true, \"blockUi\":true }"; #endregion private static GUISkin _uiStyle; public static GUISkin uiStyle { get { if (_uiStyle != null) return _uiStyle; _uiStyle = GetUiStyle(); return _uiStyle; } } static PlayFabEditorHelper() { // scan for changes to the editor folder / structure. if (uiStyle == null) { string[] rootFiles = new string[0]; bool relocatedEdEx = false; _uiStyle = null; try { if (PlayFabEditorDataService.EnvDetails != null && !string.IsNullOrEmpty(PlayFabEditorDataService.EnvDetails.edexPath)) EDEX_ROOT = PlayFabEditorDataService.EnvDetails.edexPath; rootFiles = Directory.GetDirectories(EDEX_ROOT); } catch { if (rootFiles.Length == 0) { // this probably means the editor folder was moved. // see if we can locate the moved root and reload the assets var movedRootFiles = Directory.GetFiles(Application.dataPath, PLAYFAB_EDEX_MAINFILE, SearchOption.AllDirectories); if (movedRootFiles.Length > 0) { relocatedEdEx = true; EDEX_ROOT = movedRootFiles[0].Substring(0, movedRootFiles[0].LastIndexOf(PLAYFAB_EDEX_MAINFILE) - 1); PlayFabEditorDataService.EnvDetails.edexPath = EDEX_ROOT; PlayFabEditorDataService.SaveEnvDetails(); } } } finally { if (relocatedEdEx && rootFiles.Length == 0) { Debug.Log("Found new EdEx root: " + EDEX_ROOT); } else if (rootFiles.Length == 0) { Debug.Log("Could not relocate the PlayFab Editor Extension"); EDEX_ROOT = string.Empty; } } } } private static GUISkin GetUiStyle() { var searchRoot = string.IsNullOrEmpty(EDEX_ROOT) ? Application.dataPath : EDEX_ROOT; var pfGuiPaths = Directory.GetFiles(searchRoot, "PlayFabStyles.guiskin", SearchOption.AllDirectories); foreach (var eachPath in pfGuiPaths) { var loadPath = eachPath.Substring(eachPath.LastIndexOf("Assets/")); return (GUISkin)AssetDatabase.LoadAssetAtPath(loadPath, typeof(GUISkin)); } return null; } public static void SharedErrorCallback(EditorModels.PlayFabError error) { PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error.GenerateErrorReport()); } public static void SharedErrorCallback(string error) { PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error); } public static EditorModels.PlayFabError GeneratePlayFabError(string json, object customData = null) { JsonObject errorDict = null; Dictionary<string, List<string>> errorDetails = null; try { //deserialize the error errorDict = JsonWrapper.DeserializeObject<JsonObject>(json, PlayFabEditorUtil.ApiSerializerStrategy); if (errorDict.ContainsKey("errorDetails")) { var ed = JsonWrapper.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString()); errorDetails = ed; } } catch (Exception e) { return new EditorModels.PlayFabError() { ErrorMessage = e.Message }; } //create new error object return new EditorModels.PlayFabError { HttpCode = errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400, HttpStatus = errorDict.ContainsKey("status") ? (string)errorDict["status"] : "BadRequest", Error = errorDict.ContainsKey("errorCode") ? (EditorModels.PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"]) : EditorModels.PlayFabErrorCode.ServiceUnavailable, ErrorMessage = errorDict.ContainsKey("errorMessage") ? (string)errorDict["errorMessage"] : string.Empty, ErrorDetails = errorDetails, CustomData = customData ?? new object() }; } #region unused, but could be useful /// <summary> /// Tool to create a color background texture /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="col"></param> /// <returns>Texture2D</returns> public static Texture2D MakeTex(int width, int height, Color col) { var pix = new Color[width * height]; for (var i = 0; i < pix.Length; i++) pix[i] = col; var result = new Texture2D(width, height); result.SetPixels(pix); result.Apply(); return result; } public static Vector3 GetColorVector(int colorValue) { return new Vector3((colorValue / 255f), (colorValue / 255f), (colorValue / 255f)); } #endregion } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Viewport transformer - simple orthogonal conversions from world coordinates // to screen (device) ones. // //---------------------------------------------------------------------------- using System; namespace MatterHackers.Agg.Transform { //----------------------------------------------------------trans_viewport public sealed class Viewport { private double m_world_x1; private double m_world_y1; private double m_world_x2; private double m_world_y2; private double m_device_x1; private double m_device_y1; private double m_device_x2; private double m_device_y2; private aspect_ratio_e m_aspect; private bool m_is_valid; private double m_align_x; private double m_align_y; private double m_wx1; private double m_wy1; private double m_wx2; private double m_wy2; private double m_dx1; private double m_dy1; private double m_kx; private double m_ky; public enum aspect_ratio_e { aspect_ratio_stretch, aspect_ratio_meet, aspect_ratio_slice }; //------------------------------------------------------------------- public Viewport() { m_world_x1 = (0.0); m_world_y1 = (0.0); m_world_x2 = (1.0); m_world_y2 = (1.0); m_device_x1 = (0.0); m_device_y1 = (0.0); m_device_x2 = (1.0); m_device_y2 = (1.0); m_aspect = aspect_ratio_e.aspect_ratio_stretch; m_is_valid = (true); m_align_x = (0.5); m_align_y = (0.5); m_wx1 = (0.0); m_wy1 = (0.0); m_wx2 = (1.0); m_wy2 = (1.0); m_dx1 = (0.0); m_dy1 = (0.0); m_kx = (1.0); m_ky = (1.0); } //------------------------------------------------------------------- public void preserve_aspect_ratio(double alignx, double aligny, aspect_ratio_e aspect) { m_align_x = alignx; m_align_y = aligny; m_aspect = aspect; update(); } //------------------------------------------------------------------- public void device_viewport(double x1, double y1, double x2, double y2) { m_device_x1 = x1; m_device_y1 = y1; m_device_x2 = x2; m_device_y2 = y2; update(); } //------------------------------------------------------------------- public void world_viewport(double x1, double y1, double x2, double y2) { m_world_x1 = x1; m_world_y1 = y1; m_world_x2 = x2; m_world_y2 = y2; update(); } //------------------------------------------------------------------- public void device_viewport(out double x1, out double y1, out double x2, out double y2) { x1 = m_device_x1; y1 = m_device_y1; x2 = m_device_x2; y2 = m_device_y2; } //------------------------------------------------------------------- public void world_viewport(out double x1, out double y1, out double x2, out double y2) { x1 = m_world_x1; y1 = m_world_y1; x2 = m_world_x2; y2 = m_world_y2; } //------------------------------------------------------------------- public void world_viewport_actual(out double x1, out double y1, out double x2, out double y2) { x1 = m_wx1; y1 = m_wy1; x2 = m_wx2; y2 = m_wy2; } //------------------------------------------------------------------- public bool is_valid() { return m_is_valid; } public double align_x() { return m_align_x; } public double align_y() { return m_align_y; } public aspect_ratio_e aspect_ratio() { return m_aspect; } //------------------------------------------------------------------- public void transform(ref double x, ref double y) { x = (x - m_wx1) * m_kx + m_dx1; y = (y - m_wy1) * m_ky + m_dy1; } //------------------------------------------------------------------- public void transform_scale_only(ref double x, ref double y) { x *= m_kx; y *= m_ky; } //------------------------------------------------------------------- public void inverse_transform(ref double x, ref double y) { x = (x - m_dx1) / m_kx + m_wx1; y = (y - m_dy1) / m_ky + m_wy1; } //------------------------------------------------------------------- public void inverse_transform_scale_only(ref double x, ref double y) { x /= m_kx; y /= m_ky; } //------------------------------------------------------------------- public double device_dx() { return m_dx1 - m_wx1 * m_kx; } public double device_dy() { return m_dy1 - m_wy1 * m_ky; } //------------------------------------------------------------------- public double scale_x() { return m_kx; } //------------------------------------------------------------------- public double scale_y() { return m_ky; } //------------------------------------------------------------------- public double scale() { return (m_kx + m_ky) * 0.5; } //------------------------------------------------------------------- public Affine to_affine() { Affine mtx = Affine.NewTranslation(-m_wx1, -m_wy1); mtx *= Affine.NewScaling(m_kx, m_ky); mtx *= Affine.NewTranslation(m_dx1, m_dy1); return mtx; } //------------------------------------------------------------------- public Affine to_affine_scale_only() { return Affine.NewScaling(m_kx, m_ky); } private void update() { double epsilon = 1e-30; if (Math.Abs(m_world_x1 - m_world_x2) < epsilon || Math.Abs(m_world_y1 - m_world_y2) < epsilon || Math.Abs(m_device_x1 - m_device_x2) < epsilon || Math.Abs(m_device_y1 - m_device_y2) < epsilon) { m_wx1 = m_world_x1; m_wy1 = m_world_y1; m_wx2 = m_world_x1 + 1.0; m_wy2 = m_world_y2 + 1.0; m_dx1 = m_device_x1; m_dy1 = m_device_y1; m_kx = 1.0; m_ky = 1.0; m_is_valid = false; return; } double world_x1 = m_world_x1; double world_y1 = m_world_y1; double world_x2 = m_world_x2; double world_y2 = m_world_y2; double device_x1 = m_device_x1; double device_y1 = m_device_y1; double device_x2 = m_device_x2; double device_y2 = m_device_y2; if (m_aspect != aspect_ratio_e.aspect_ratio_stretch) { double d; m_kx = (device_x2 - device_x1) / (world_x2 - world_x1); m_ky = (device_y2 - device_y1) / (world_y2 - world_y1); if ((m_aspect == aspect_ratio_e.aspect_ratio_meet) == (m_kx < m_ky)) { d = (world_y2 - world_y1) * m_ky / m_kx; world_y1 += (world_y2 - world_y1 - d) * m_align_y; world_y2 = world_y1 + d; } else { d = (world_x2 - world_x1) * m_kx / m_ky; world_x1 += (world_x2 - world_x1 - d) * m_align_x; world_x2 = world_x1 + d; } } m_wx1 = world_x1; m_wy1 = world_y1; m_wx2 = world_x2; m_wy2 = world_y2; m_dx1 = device_x1; m_dy1 = device_y1; m_kx = (device_x2 - device_x1) / (world_x2 - world_x1); m_ky = (device_y2 - device_y1) / (world_y2 - world_y1); m_is_valid = true; } }; }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.Compilation.ClientBuildManager.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.Compilation { sealed public partial class ClientBuildManager : MarshalByRefObject, IDisposable { #region Methods and constructors public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir) { } public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir, ClientBuildManagerParameter parameter) { } public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir) { } public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir, ClientBuildManagerParameter parameter, System.ComponentModel.TypeDescriptionProvider typeDescriptionProvider) { } public void CompileApplicationDependencies() { } public void CompileFile(string virtualPath) { } public void CompileFile(string virtualPath, ClientBuildManagerCallback callback) { } public System.Web.Hosting.IRegisteredObject CreateObject(Type type, bool failIfExists) { return default(System.Web.Hosting.IRegisteredObject); } public string GenerateCode(string virtualPath, string virtualFileString, out System.Collections.IDictionary linePragmasTable) { linePragmasTable = default(System.Collections.IDictionary); return default(string); } public System.CodeDom.CodeCompileUnit GenerateCodeCompileUnit(string virtualPath, string virtualFileString, out Type codeDomProviderType, out System.CodeDom.Compiler.CompilerParameters compilerParameters, out System.Collections.IDictionary linePragmasTable) { codeDomProviderType = default(Type); compilerParameters = default(System.CodeDom.Compiler.CompilerParameters); linePragmasTable = default(System.Collections.IDictionary); return default(System.CodeDom.CodeCompileUnit); } public System.CodeDom.CodeCompileUnit GenerateCodeCompileUnit(string virtualPath, out Type codeDomProviderType, out System.CodeDom.Compiler.CompilerParameters compilerParameters, out System.Collections.IDictionary linePragmasTable) { codeDomProviderType = default(Type); compilerParameters = default(System.CodeDom.Compiler.CompilerParameters); linePragmasTable = default(System.Collections.IDictionary); return default(System.CodeDom.CodeCompileUnit); } public string[] GetAppDomainShutdownDirectories() { return default(string[]); } public System.Collections.IDictionary GetBrowserDefinitions() { return default(System.Collections.IDictionary); } public void GetCodeDirectoryInformation(string virtualCodeDir, out Type codeDomProviderType, out System.CodeDom.Compiler.CompilerParameters compilerParameters, out string generatedFilesDir) { codeDomProviderType = default(Type); compilerParameters = default(System.CodeDom.Compiler.CompilerParameters); generatedFilesDir = default(string); } public Type GetCompiledType(string virtualPath) { return default(Type); } public void GetCompilerParameters(string virtualPath, out Type codeDomProviderType, out System.CodeDom.Compiler.CompilerParameters compilerParameters) { codeDomProviderType = default(Type); compilerParameters = default(System.CodeDom.Compiler.CompilerParameters); } public string GetGeneratedFileVirtualPath(string filePath) { return default(string); } public string GetGeneratedSourceFile(string virtualPath) { return default(string); } public string[] GetTopLevelAssemblyReferences(string virtualPath) { return default(string[]); } public string[] GetVirtualCodeDirectories() { return default(string[]); } public override Object InitializeLifetimeService() { return default(Object); } public bool IsCodeAssembly(string assemblyName) { return default(bool); } public void PrecompileApplication() { } public void PrecompileApplication(ClientBuildManagerCallback callback) { } public void PrecompileApplication(ClientBuildManagerCallback callback, bool forceCleanBuild) { } void System.IDisposable.Dispose() { } public bool Unload() { return default(bool); } #endregion #region Properties and indexers public string CodeGenDir { get { return default(string); } } public bool IsHostCreated { get { return default(bool); } } #endregion #region Events public event BuildManagerHostUnloadEventHandler AppDomainShutdown { add { } remove { } } public event EventHandler AppDomainStarted { add { } remove { } } public event BuildManagerHostUnloadEventHandler AppDomainUnloaded { add { } remove { } } #endregion } }
using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Ocelot.Middleware; using Ocelot.Middleware.Multiplexer; using Shouldly; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; namespace Ocelot.AcceptanceTests { public class AggregateTests : IDisposable { private readonly Steps _steps; private string _downstreamPathOne; private string _downstreamPathTwo; private readonly ServiceHandler _serviceHandler; public AggregateTests() { _serviceHandler = new ServiceHandler(); _steps = new Steps(); } [Fact] public void should_fix_issue_597() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key1data/{userid}", UpstreamHttpMethod = new List<string> {"Get"}, DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 8571 } }, Key = "key1" }, new FileReRoute { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key2data/{userid}", UpstreamHttpMethod = new List<string> {"Get"}, DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 8571 } }, Key = "key2" }, new FileReRoute { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key3data/{userid}", UpstreamHttpMethod = new List<string> {"Get"}, DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 8571 } }, Key = "key3" }, new FileReRoute { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key4data/{userid}", UpstreamHttpMethod = new List<string> {"Get"}, DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 8571 } }, Key = "key4" }, }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { ReRouteKeys = new List<string>{ "key1", "key2", "key3", "key4" }, UpstreamPathTemplate = "/EmpDetail/IN/{userid}" }, new FileAggregateReRoute { ReRouteKeys = new List<string>{ "key1", "key2", }, UpstreamPathTemplate = "/EmpDetail/US/{userid}" } }, GlobalConfiguration = new FileGlobalConfiguration { RequestIdKey = "CorrelationID" } }; var expected = "{\"key1\":some_data,\"key2\":some_data}"; this.Given(x => x.GivenServiceIsRunning("http://localhost:8571", 200, "some_data")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/EmpDetail/US/1")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe(expected)) .BDDfy(); } [Fact] public void should_return_response_200_with_advanced_aggregate_configs() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51889, } }, UpstreamPathTemplate = "/Comments", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Comments" }, new FileReRoute { DownstreamPathTemplate = "/users/{userId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 54030, } }, UpstreamPathTemplate = "/UserDetails", UpstreamHttpMethod = new List<string> { "Get" }, Key = "UserDetails" }, new FileReRoute { DownstreamPathTemplate = "/posts/{postId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51887, } }, UpstreamPathTemplate = "/PostDetails", UpstreamHttpMethod = new List<string> { "Get" }, Key = "PostDetails" } }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { UpstreamPathTemplate = "/", UpstreamHost = "localhost", ReRouteKeys = new List<string> { "Comments", "UserDetails", "PostDetails" }, ReRouteKeysConfig = new List<AggregateReRouteConfig>() { new AggregateReRouteConfig(){ReRouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"}, new AggregateReRouteConfig(){ReRouteKey = "PostDetails",JsonPath = "$[*].postId",Parameter = "postId"} }, } } }; var userDetailsResponseContent = @"{""id"":1,""firstName"":""abolfazl"",""lastName"":""rajabpour""}"; var postDetailsResponseContent = @"{""id"":1,""title"":""post1""}"; var commentsResponseContent = @"[{""id"":1,""writerId"":1,""postId"":2,""text"":""text1""},{""id"":2,""writerId"":1,""postId"":2,""text"":""text2""}]"; var expected = "{\"Comments\":" + commentsResponseContent + ",\"UserDetails\":" + userDetailsResponseContent + ",\"PostDetails\":" + postDetailsResponseContent + "}"; this.Given(x => x.GivenServiceOneIsRunning("http://localhost:51889", "/", 200, commentsResponseContent)) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:54030", "/users/1", 200, userDetailsResponseContent)) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:51887", "/posts/2", 200, postDetailsResponseContent)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe(expected)) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_user_defined_aggregate() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51885, } }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Laura" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51886, } }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Tom" } }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { UpstreamPathTemplate = "/", UpstreamHost = "localhost", ReRouteKeys = new List<string> { "Laura", "Tom" }, Aggregator = "FakeDefinedAggregator" } } }; var expected = "Bye from Laura, Bye from Tom"; this.Given(x => x.GivenServiceOneIsRunning("http://localhost:51885", "/", 200, "{Hello from Laura}")) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:51886", "/", 200, "{Hello from Tom}")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningWithSpecficAggregatorsRegisteredInDi<FakeDefinedAggregator, FakeDepdendency>()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe(expected)) .And(x => ThenTheDownstreamUrlPathShouldBe("/", "/")) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51875, } }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Laura" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 52476, } }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Tom" } }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { UpstreamPathTemplate = "/", UpstreamHost = "localhost", ReRouteKeys = new List<string> { "Laura", "Tom" } } } }; var expected = "{\"Laura\":{Hello from Laura},\"Tom\":{Hello from Tom}}"; this.Given(x => x.GivenServiceOneIsRunning("http://localhost:51875", "/", 200, "{Hello from Laura}")) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:52476", "/", 200, "{Hello from Tom}")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe(expected)) .And(x => ThenTheDownstreamUrlPathShouldBe("/", "/")) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_one_service_404() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51881, } }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Laura" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51889, } }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Tom" } }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { UpstreamPathTemplate = "/", UpstreamHost = "localhost", ReRouteKeys = new List<string> { "Laura", "Tom" } } } }; var expected = "{\"Laura\":,\"Tom\":{Hello from Tom}}"; this.Given(x => x.GivenServiceOneIsRunning("http://localhost:51881", "/", 404, "")) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:51889", "/", 200, "{Hello from Tom}")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe(expected)) .And(x => ThenTheDownstreamUrlPathShouldBe("/", "/")) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_both_service_404() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51883, } }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Laura" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51884, } }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Tom" } }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { UpstreamPathTemplate = "/", UpstreamHost = "localhost", ReRouteKeys = new List<string> { "Laura", "Tom" } } } }; var expected = "{\"Laura\":,\"Tom\":}"; this.Given(x => x.GivenServiceOneIsRunning("http://localhost:51883", "/", 404, "")) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:51884", "/", 404, "")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe(expected)) .And(x => ThenTheDownstreamUrlPathShouldBe("/", "/")) .BDDfy(); } [Fact] public void should_be_thread_safe() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51878, } }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Laura" }, new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51880, } }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List<string> { "Get" }, Key = "Tom" } }, Aggregates = new List<FileAggregateReRoute> { new FileAggregateReRoute { UpstreamPathTemplate = "/", UpstreamHost = "localhost", ReRouteKeys = new List<string> { "Laura", "Tom" } } } }; this.Given(x => x.GivenServiceOneIsRunning("http://localhost:51878", "/", 200, "{Hello from Laura}")) .Given(x => x.GivenServiceTwoIsRunning("http://localhost:51880", "/", 200, "{Hello from Tom}")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIMakeLotsOfDifferentRequestsToTheApiGateway()) .And(x => ThenTheDownstreamUrlPathShouldBe("/", "/")) .BDDfy(); } private void GivenServiceIsRunning(string baseUrl, int statusCode, string responseBody) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, async context => { context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); }); } private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statusCode, string responseBody) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => { _downstreamPathOne = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; if (_downstreamPathOne != basePath) { context.Response.StatusCode = statusCode; await context.Response.WriteAsync("downstream path didnt match base path"); } else { context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); } }); } private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statusCode, string responseBody) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => { _downstreamPathTwo = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; if (_downstreamPathTwo != basePath) { context.Response.StatusCode = statusCode; await context.Response.WriteAsync("downstream path didnt match base path"); } else { context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); } }); } internal void ThenTheDownstreamUrlPathShouldBe(string expectedDownstreamPathOne, string expectedDownstreamPath) { _downstreamPathOne.ShouldBe(expectedDownstreamPathOne); _downstreamPathTwo.ShouldBe(expectedDownstreamPath); } public void Dispose() { _serviceHandler.Dispose(); _steps.Dispose(); } } public class FakeDepdendency { } public class FakeDefinedAggregator : IDefinedAggregator { private readonly FakeDepdendency _dep; public FakeDefinedAggregator(FakeDepdendency dep) { _dep = dep; } public async Task<DownstreamResponse> Aggregate(List<DownstreamContext> responses) { var one = await responses[0].DownstreamResponse.Content.ReadAsStringAsync(); var two = await responses[1].DownstreamResponse.Content.ReadAsStringAsync(); var merge = $"{one}, {two}"; merge = merge.Replace("Hello", "Bye").Replace("{", "").Replace("}", ""); var headers = responses.SelectMany(x => x.DownstreamResponse.Headers).ToList(); return new DownstreamResponse(new StringContent(merge), HttpStatusCode.OK, headers, "some reason"); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // This class represents the Default COM+ binder. // // namespace System { using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; //Marked serializable even though it has no state. [Serializable] internal partial class DefaultBinder : Binder { // This method is passed a set of methods and must choose the best // fit. The methods all have the same number of arguments and the object // array args. On exit, this method will choice the best fit method // and coerce the args to match that method. By match, we mean all primitive // arguments are exact matchs and all object arguments are exact or subclasses // of the target. If the target OR is an interface, the object must implement // that interface. There are a couple of exceptions // thrown when a method cannot be returned. If no method matchs the args and // ArgumentException is thrown. If multiple methods match the args then // an AmbiguousMatchException is thrown. // // The most specific match will be selected. // [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref Object[] args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state) { if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match"); Contract.EndContractBlock(); MethodBase[] candidates = (MethodBase[]) match.Clone(); int i; int j; state = null; #region Map named parameters to candidate parameter postions // We are creating an paramOrder array to act as a mapping // between the order of the args and the actual order of the // parameters in the method. This order may differ because // named parameters (names) may change the order. If names // is not provided, then we assume the default mapping (0,1,...) int[][] paramOrder = new int[candidates.Length][]; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; if (names == null) { // Default mapping for (j = 0; j < args.Length; j++) paramOrder[i][j] = j; } else { // Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method // doesn't have a name that matchs one of the named parameters so we don't consider it any further. if (!CreateParamOrder(paramOrder[i], par, names)) candidates[i] = null; } } #endregion Type[] paramArrayTypes = new Type[candidates.Length]; Type[] argTypes = new Type[args.Length]; #region Cache the type of the provided arguments // object that contain a null are treated as if they were typeless (but match either object // references or value classes). We mark this condition by placing a null in the argTypes array. for (i = 0; i < args.Length; i++) { if (args[i] != null) { argTypes[i] = args[i].GetType(); } } #endregion // Find the method that matches... int CurIdx = 0; bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0); Type paramArrayType = null; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) { paramArrayType = null; // If we have named parameters then we may have a hole in the candidates array. if (candidates[i] == null) continue; // Validate the parameters. ParameterInfo[] par = candidates[i].GetParametersNoCopy(); #region Match method by parameter count if (par.Length == 0) { #region No formal parameters if (args.Length != 0) { if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) continue; } // This is a valid routine so we move it up the candidates list. paramOrder[CurIdx] = paramOrder[i]; candidates[CurIdx++] = candidates[i]; continue; #endregion } else if (par.Length > args.Length) { #region Shortage of provided parameters // If the number of parameters is greater than the number of args then // we are in the situation were we may be using default values. for (j = args.Length; j < par.Length - 1; j++) { if (par[j].DefaultValue == System.DBNull.Value) break; } if (j != par.Length - 1) continue; if (par[j].DefaultValue == System.DBNull.Value) { if (!par[j].ParameterType.IsArray) continue; if (!par[j].IsDefined(typeof(ParamArrayAttribute), true)) continue; paramArrayType = par[j].ParameterType.GetElementType(); } #endregion } else if (par.Length < args.Length) { #region Excess provided parameters // test for the ParamArray case int lastArgPos = par.Length - 1; if (!par[lastArgPos].ParameterType.IsArray) continue; if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)) continue; if (paramOrder[i][lastArgPos] != lastArgPos) continue; paramArrayType = par[lastArgPos].ParameterType.GetElementType(); #endregion } else { #region Test for paramArray, save paramArray type int lastArgPos = par.Length - 1; if (par[lastArgPos].ParameterType.IsArray && par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true) && paramOrder[i][lastArgPos] == lastArgPos) { if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos])) paramArrayType = par[lastArgPos].ParameterType.GetElementType(); } #endregion } #endregion Type pCls = null; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type for (j = 0; j < argsToCheck; j++) { #region Classic argument coersion checks // get the formal type pCls = par[j].ParameterType; if (pCls.IsByRef) pCls = pCls.GetElementType(); // the type is the same if (pCls == argTypes[paramOrder[i][j]]) continue; // a default value is available if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing) continue; // the argument was null, so it matches with everything if (args[paramOrder[i][j]] == null) continue; // the type is Object, so it will match everything if (pCls == typeof(Object)) continue; // now do a "classic" type check if (pCls.IsPrimitive) { if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]],(RuntimeType)pCls)) { break; } } else { if (argTypes[paramOrder[i][j]] == null) continue; if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]])) { if (argTypes[paramOrder[i][j]].IsCOMObject) { if (pCls.IsInstanceOfType(args[paramOrder[i][j]])) continue; } break; } } #endregion } if (paramArrayType != null && j == par.Length - 1) { #region Check that excess arguments can be placed in the param array for (; j < args.Length; j++) { if (paramArrayType.IsPrimitive) { if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType)) break; } else { if (argTypes[j] == null) continue; if (!paramArrayType.IsAssignableFrom(argTypes[j])) { if (argTypes[j].IsCOMObject) { if (paramArrayType.IsInstanceOfType(args[j])) continue; } break; } } } #endregion } #endregion if (j == args.Length) { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; paramArrayTypes[CurIdx] = paramArrayType; candidates[CurIdx++] = candidates[i]; #endregion } } #endregion // If we didn't find a method if (CurIdx == 0) throw new MissingMethodException(Environment.GetResourceString("MissingMember")); if (CurIdx == 1) { #region Found only one method if (names != null) { state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null); ReorderParams(paramOrder[0],args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parms = candidates[0].GetParametersNoCopy(); if (parms.Length == args.Length) { if (paramArrayTypes[0] != null) { Object[] objs = new Object[parms.Length]; int lastPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parms.Length > args.Length) { Object[] objs = new Object[parms.Length]; for (i=0;i<args.Length;i++) objs[i] = args[i]; for (;i<parms.Length - 1;i++) objs[i] = parms[i].DefaultValue; if (paramArrayTypes[0] != null) objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[0], 0); // create an empty array for the else objs[i] = parms[i].DefaultValue; args = objs; } else { if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parms.Length]; int paramArrayPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } #endregion return candidates[0]; } int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin], candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { ambig = true; } else if (newMin == 2) { currentMin = i; ambig = false; } #endregion } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); // Reorder (if needed) if (names != null) { state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null); ReorderParams(paramOrder[currentMin], args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) { Object[] objs = new Object[parameters.Length]; int lastPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parameters.Length > args.Length) { Object[] objs = new Object[parameters.Length]; for (i=0;i<args.Length;i++) objs[i] = args[i]; for (;i<parameters.Length - 1;i++) objs[i] = parameters[i].DefaultValue; if (paramArrayTypes[currentMin] != null) { objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0); } else { objs[i] = parameters[i].DefaultValue; } args = objs; } else { if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parameters.Length]; int paramArrayPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } return candidates[currentMin]; } // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field [System.Security.SecuritySafeCritical] // auto-generated public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo) { if (match == null) { throw new ArgumentNullException("match"); } int i; // Find the method that match... int CurIdx = 0; Type valueType = null; FieldInfo[] candidates = (FieldInfo[]) match.Clone(); // If we are a FieldSet, then use the value's type to disambiguate if ((bindingAttr & BindingFlags.SetField) != 0) { valueType = value.GetType(); for (i=0;i<candidates.Length;i++) { Type pCls = candidates[i].FieldType; if (pCls == valueType) { candidates[CurIdx++] = candidates[i]; continue; } if (value == Empty.Value) { // the object passed in was null which would match any non primitive non value type if (pCls.IsClass) { candidates[CurIdx++] = candidates[i]; continue; } } if (pCls == typeof(Object)) { candidates[CurIdx++] = candidates[i]; continue; } if (pCls.IsPrimitive) { if (CanConvertPrimitiveObjectToType(value,(RuntimeType)pCls)) { candidates[CurIdx++] = candidates[i]; continue; } } else { if (pCls.IsAssignableFrom(valueType)) { candidates[CurIdx++] = candidates[i]; continue; } } } if (CurIdx == 0) throw new MissingFieldException(Environment.GetResourceString("MissingField")); if (CurIdx == 1) return candidates[0]; } // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; for (i=1;i<CurIdx;i++) { int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; } } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers) { int i; int j; Type[] realTypes = new Type[types.Length]; for (i=0;i<types.Length;i++) { realTypes[i] = types[i].UnderlyingSystemType; if (!(realTypes[i] is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"types"); } types = realTypes; // We don't automatically jump out on exact match. if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match"); MethodBase[] candidates = (MethodBase[]) match.Clone(); // Find all the methods that can be described by the types parameter. // Remove all of them that cannot. int CurIdx = 0; for (i=0;i<candidates.Length;i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); if (par.Length != types.Length) continue; for (j=0;j<types.Length;j++) { Type pCls = par[j].ParameterType; if (pCls == types[j]) continue; if (pCls == typeof(Object)) continue; if (pCls.IsPrimitive) { if (!(types[j].UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(types[j])) break; } } if (j == types.Length) candidates[CurIdx++] = candidates[i]; } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[types.Length]; for (i=0;i<types.Length;i++) paramOrder[i] = i; for (i=1;i<CurIdx;i++) { int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; currentMin = i; } } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // Given a set of properties that match the base criteria, select one. [System.Security.SecuritySafeCritical] // auto-generated public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType, Type[] indexes,ParameterModifier[] modifiers) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null && !Contract.ForAll(indexes, delegate(Type t) { return t != null; })) { Exception e; // Written this way to pass the Code Contracts style requirements. #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) e = new NullReferenceException(); else #endif e = new ArgumentNullException("indexes"); throw e; } if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match"); Contract.EndContractBlock(); PropertyInfo[] candidates = (PropertyInfo[]) match.Clone(); int i,j = 0; // Find all the properties that can be described by type indexes parameter int CurIdx = 0; int indexesLength = (indexes != null) ? indexes.Length : 0; for (i=0;i<candidates.Length;i++) { if (indexes != null) { ParameterInfo[] par = candidates[i].GetIndexParameters(); if (par.Length != indexesLength) continue; for (j=0;j<indexesLength;j++) { Type pCls = par[j]. ParameterType; // If the classes exactly match continue if (pCls == indexes[j]) continue; if (pCls == typeof(Object)) continue; if (pCls.IsPrimitive) { if (!(indexes[j].UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(indexes[j])) break; } } } if (j == indexesLength) { if (returnType != null) { if (candidates[i].PropertyType.IsPrimitive) { if (!(returnType.UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType,(RuntimeType)candidates[i].PropertyType.UnderlyingSystemType)) continue; } else { if (!candidates[i].PropertyType.IsAssignableFrom(returnType)) continue; } } candidates[CurIdx++] = candidates[i]; } } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the properties looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[indexesLength]; for (i=0;i<indexesLength;i++) paramOrder[i] = i; for (i=1;i<CurIdx;i++) { int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType,returnType); if (newMin == 0 && indexes != null) newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(), paramOrder, null, candidates[i].GetIndexParameters(), paramOrder, null, indexes, null); if (newMin == 0) { newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; } if (newMin == 2) { ambig = false; currentMin = i; } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // ChangeType // The default binder doesn't support any change type functionality. // This is because the default is built into the low level invoke code. public override Object ChangeType(Object value,Type type,CultureInfo cultureInfo) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ChangeType")); } public override void ReorderArgumentArray(ref Object[] args, Object state) { BinderState binderState = (BinderState)state; ReorderParams(binderState.m_argsMap, args); if (binderState.m_isParamArray) { int paramArrayPos = args.Length - 1; if (args.Length == binderState.m_originalSize) args[paramArrayPos] = ((Object[])args[paramArrayPos])[0]; else { // must be args.Length < state.originalSize Object[] newArgs = new Object[args.Length]; Array.Copy(args, 0, newArgs, 0, paramArrayPos); for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) { newArgs[i] = ((Object[])args[paramArrayPos])[j]; } args = newArgs; } } else { if (args.Length > binderState.m_originalSize) { Object[] newArgs = new Object[binderState.m_originalSize]; Array.Copy(args, 0, newArgs, 0, binderState.m_originalSize); args = newArgs; } } } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static MethodBase ExactBinding(MethodBase[] match,Type[] types,ParameterModifier[] modifiers) { if (match==null) throw new ArgumentNullException("match"); Contract.EndContractBlock(); MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; for (int i=0;i<match.Length;i++) { ParameterInfo[] par = match[i].GetParametersNoCopy(); if (par.Length == 0) { continue; } int j; for (j=0;j<types.Length;j++) { Type pCls = par[j]. ParameterType; // If the classes exactly match continue if (!pCls.Equals(types[j])) break; } if (j < types.Length) continue; // Add the exact match to the array of exact matches. aExactMatches[cExactMatches] = match[i]; cExactMatches++; } if (cExactMatches == 0) return null; if (cExactMatches == 1) return aExactMatches[0]; return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches); } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match,Type returnType,Type[] types,ParameterModifier[] modifiers) { if (match==null) throw new ArgumentNullException("match"); Contract.EndContractBlock(); PropertyInfo bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i=0;i<match.Length;i++) { ParameterInfo[] par = match[i].GetIndexParameters(); int j; for (j=0;j<typesLength;j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls != types[j]) break; } if (j < typesLength) continue; if (returnType != null && returnType != match[i].PropertyType) continue; if (bestMatch != null) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); bestMatch = match[i]; } return bestMatch; } private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) return 2; if (paramArrayType2 != null && paramArrayType1 == null) return 1; // now either p1 and p2 both use params or neither does. bool p1Less = false; bool p2Less = false; for (int i = 0; i < types.Length; i++) { if (args != null && args[i] == Type.Missing) continue; Type c1, c2; // If a param array is present, then either // the user re-ordered the parameters in which case // the argument to the param array is either an array // in which case the params is conceptually ignored and so paramArrayType1 == null // or the argument to the param array is a single element // in which case paramOrder[i] == p1.Length - 1 for that element // or the user did not re-order the parameters in which case // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) // so any index >= p.Length - 1 is being put in the param array if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1) c1 = paramArrayType1; else c1 = p1[paramOrder1[i]].ParameterType; if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1) c2 = paramArrayType2; else c2 = p2[paramOrder2[i]].ParameterType; if (c1 == c2) continue; switch (FindMostSpecificType(c1, c2, types[i])) { case 0: return 0; case 1: p1Less = true; break; case 2: p2Less = true; break; } } // Two way p1Less and p2Less can be equal. All the arguments are the // same they both equal false, otherwise there were things that both // were the most specific type on.... if (p1Less == p2Less) { // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), // let's see which one has the most matches without using the params array (the longer one wins). if (!p1Less && args != null) { if (p1.Length > p2.Length) { return 1; } else if (p2.Length > p1.Length) { return 2; } } return 0; } else { return (p1Less == true) ? 1 : 2; } } [System.Security.SecuritySafeCritical] // auto-generated private static int FindMostSpecificType(Type c1, Type c2, Type t) { // If the two types are exact move on... if (c1 == c2) return 0; if (c1 == t) return 1; if (c2 == t) return 2; bool c1FromC2; bool c2FromC1; if (c1.IsByRef || c2.IsByRef) { if (c1.IsByRef && c2.IsByRef) { c1 = c1.GetElementType(); c2 = c2.GetElementType(); } else if (c1.IsByRef) { if (c1.GetElementType() == c2) return 2; c1 = c1.GetElementType(); } else { if (c2.GetElementType() == c1) return 1; c2 = c2.GetElementType(); } } if (c1.IsPrimitive && c2.IsPrimitive) { c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1); c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2); } else { c1FromC2 = c1.IsAssignableFrom(c2); c2FromC1 = c2.IsAssignableFrom(c1); } if (c1FromC2 == c2FromC1) return 0; if (c1FromC2) { return 2; } else { return 1; } } private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, MethodBase m2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args); // If the match was not ambigous then return the result. if (res != 0) return res; // Check to see if the methods have the exact same name and signature. if (CompareMethodSigAndName(m1, m2)) { // Determine the depth of the declaring types for both methods. int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) { return 2; } else { return 1; } } // The match is ambigous. return 0; } private static int FindMostSpecificField(FieldInfo cur1,FieldInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2"); return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } private static int FindMostSpecificProperty(PropertyInfo cur1,PropertyInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2) { ParameterInfo[] params1 = m1.GetParametersNoCopy(); ParameterInfo[] params2 = m2.GetParametersNoCopy(); if (params1.Length != params2.Length) return false; int numParams = params1.Length; for (int i = 0; i < numParams; i++) { if (params1[i].ParameterType != params2[i].ParameterType) return false; } return true; } internal static int GetHierarchyDepth(Type t) { int depth = 0; Type currentType = t; do { depth++; currentType = currentType.BaseType; } while (currentType != null); return depth; } internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int deepestHierarchy = 0; MethodBase methWithDeepestHierarchy = null; for (int i = 0; i < cMatches; i++) { // Calculate the depth of the hierarchy of the declaring type of the // current method. int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType); // The two methods have the same name, signature, and hierarchy depth. // This can only happen if at least one is vararg or generic. if (currentHierarchyDepth == deepestHierarchy) { throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); } // Check to see if this method is on the most derived class. if (currentHierarchyDepth > deepestHierarchy) { deepestHierarchy = currentHierarchyDepth; methWithDeepestHierarchy = match[i]; } } return methWithDeepestHierarchy; } #if !MONO // CanConvertPrimitive // This will determine if the source can be converted to the target type [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target); // CanConvertPrimitiveObjectToType // This method will determine if the primitive object can be converted // to a type. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type); #endif // This method will sort the vars array into the mapping order stored // in the paramOrder array. private static void ReorderParams(int[] paramOrder,Object[] vars) { object[] varsCopy = new object[vars.Length]; for (int i = 0; i < vars.Length; i ++) varsCopy[i] = vars[i]; for (int i = 0; i < vars.Length; i ++) vars[i] = varsCopy[paramOrder[i]]; } // This method will create the mapping between the Parameters and the underlying // data based upon the names array. The names array is stored in the same order // as the values and maps to the parameters of the method. We store the mapping // from the parameters to the names in the paramOrder array. All parameters that // don't have matching names are then stored in the array in order. private static bool CreateParamOrder(int[] paramOrder,ParameterInfo[] pars,String[] names) { bool[] used = new bool[pars.Length]; // Mark which parameters have not been found in the names list for (int i=0;i<pars.Length;i++) paramOrder[i] = -1; // Find the parameters with names. for (int i=0;i<names.Length;i++) { int j; for (j=0;j<pars.Length;j++) { if (names[i].Equals(pars[j].Name)) { paramOrder[j] = i; used[i] = true; break; } } // This is an error condition. The name was not found. This // method must not match what we sent. if (j == pars.Length) return false; } // Now we fill in the holes with the parameters that are unused. int pos = 0; for (int i=0;i<pars.Length;i++) { if (paramOrder[i] == -1) { for (;pos<pars.Length;pos++) { if (!used[pos]) { paramOrder[i] = pos; pos++; break; } } } } return true; } internal class BinderState { internal int[] m_argsMap; internal int m_originalSize; internal bool m_isParamArray; internal BinderState(int[] argsMap, int originalSize, bool isParamArray) { m_argsMap = argsMap; m_originalSize = originalSize; m_isParamArray = isParamArray; } } } }
//--------------------------------------------------------------------- // <copyright file="EdmNavigationProperty.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.Collections.Generic; namespace Microsoft.OData.Edm.Library { /// <summary> /// Represents an EDM navigation property. /// </summary> public sealed class EdmNavigationProperty : EdmProperty, IEdmNavigationProperty { private readonly IEdmReferentialConstraint referentialConstraint; private readonly bool containsTarget; private readonly EdmOnDeleteAction onDelete; private EdmNavigationProperty partner; private EdmNavigationProperty( IEdmEntityType declaringType, string name, IEdmTypeReference type, IEnumerable<IEdmStructuralProperty> dependentProperties, IEnumerable<IEdmStructuralProperty> principalProperties, bool containsTarget, EdmOnDeleteAction onDelete) : base(declaringType, name, type) { this.containsTarget = containsTarget; this.onDelete = onDelete; if (dependentProperties != null) { this.referentialConstraint = EdmReferentialConstraint.Create(dependentProperties, principalProperties); } } /// <summary> /// Gets the kind of this property. /// </summary> public override EdmPropertyKind PropertyKind { get { return EdmPropertyKind.Navigation; } } /// <summary> /// Gets a value indicating whether the navigation target is contained inside the navigation source. /// </summary> public bool ContainsTarget { get { return this.containsTarget; } } /// <summary> /// Gets the referential constraint for this navigation, returning null if this is the principal end or if there is no referential constraint. /// </summary> public IEdmReferentialConstraint ReferentialConstraint { get { return this.referentialConstraint; } } /// <summary> /// Gets the entity type that this navigation property belongs to. /// </summary> public IEdmEntityType DeclaringEntityType { get { return (IEdmEntityType)this.DeclaringType; } } /// <summary> /// Gets the action to take when an instance of the declaring type is deleted. /// </summary> public EdmOnDeleteAction OnDelete { get { return this.onDelete; } } /// <summary> /// Gets the partner of this navigation property. /// </summary> public IEdmNavigationProperty Partner { get { return this.partner; } } /// <summary> /// Creates a navigation property from the given information. /// </summary> /// <param name="declaringType">The type that declares this property.</param> /// <param name="propertyInfo">Information to create the navigation property.</param> /// <returns>Created navigation property.</returns> public static EdmNavigationProperty CreateNavigationProperty(IEdmEntityType declaringType, EdmNavigationPropertyInfo propertyInfo) { EdmUtil.CheckArgumentNull(propertyInfo, "propertyInfo"); EdmUtil.CheckArgumentNull(propertyInfo.Name, "propertyInfo.Name"); EdmUtil.CheckArgumentNull(propertyInfo.Target, "propertyInfo.Target"); return new EdmNavigationProperty( declaringType, propertyInfo.Name, CreateNavigationPropertyType(propertyInfo.Target, propertyInfo.TargetMultiplicity, "propertyInfo.TargetMultiplicity"), propertyInfo.DependentProperties, propertyInfo.PrincipalProperties, propertyInfo.ContainsTarget, propertyInfo.OnDelete); } /// <summary> /// Creates two navigation properties representing an association between two entity types. /// </summary> /// <param name="propertyInfo">Information to create the navigation property.</param> /// <param name="partnerInfo">Information to create the partner navigation property.</param> /// <returns>Created navigation property.</returns> public static EdmNavigationProperty CreateNavigationPropertyWithPartner(EdmNavigationPropertyInfo propertyInfo, EdmNavigationPropertyInfo partnerInfo) { EdmUtil.CheckArgumentNull(propertyInfo, "propertyInfo"); EdmUtil.CheckArgumentNull(propertyInfo.Name, "propertyInfo.Name"); EdmUtil.CheckArgumentNull(propertyInfo.Target, "propertyInfo.Target"); EdmUtil.CheckArgumentNull(partnerInfo, "partnerInfo"); EdmUtil.CheckArgumentNull(partnerInfo.Name, "partnerInfo.Name"); EdmUtil.CheckArgumentNull(partnerInfo.Target, "partnerInfo.Target"); EdmNavigationProperty end1 = new EdmNavigationProperty( partnerInfo.Target, propertyInfo.Name, CreateNavigationPropertyType(propertyInfo.Target, propertyInfo.TargetMultiplicity, "propertyInfo.TargetMultiplicity"), propertyInfo.DependentProperties, propertyInfo.PrincipalProperties, propertyInfo.ContainsTarget, propertyInfo.OnDelete); EdmNavigationProperty end2 = new EdmNavigationProperty( propertyInfo.Target, partnerInfo.Name, CreateNavigationPropertyType(partnerInfo.Target, partnerInfo.TargetMultiplicity, "partnerInfo.TargetMultiplicity"), partnerInfo.DependentProperties, partnerInfo.PrincipalProperties, partnerInfo.ContainsTarget, partnerInfo.OnDelete); end1.partner = end2; end2.partner = end1; return end1; } /// <summary> /// Creates two navigation properties representing an association between two entity types. /// </summary> /// <param name="propertyName">Navigation property name.</param> /// <param name="propertyType">Type of the navigation property.</param> /// <param name="dependentProperties">Dependent properties of the navigation source.</param> /// <param name="principalProperties">Principal properties of the navigation source.</param> /// <param name="containsTarget">A value indicating whether the navigation source logically contains the navigation target.</param> /// <param name="onDelete">Action to take upon deletion of an instance of the navigation source.</param> /// <param name="partnerPropertyName">Navigation partner property name.</param> /// <param name="partnerPropertyType">Type of the navigation partner property.</param> /// <param name="partnerDependentProperties">Dependent properties of the navigation target.</param> /// <param name="partnerPrincipalProperties">Principal properties of the navigation target.</param> /// <param name="partnerContainsTarget">A value indicating whether the navigation target logically contains the navigation source.</param> /// <param name="partnerOnDelete">Action to take upon deletion of an instance of the navigation target.</param> /// <returns>Navigation property.</returns> public static EdmNavigationProperty CreateNavigationPropertyWithPartner( string propertyName, IEdmTypeReference propertyType, IEnumerable<IEdmStructuralProperty> dependentProperties, IEnumerable<IEdmStructuralProperty> principalProperties, bool containsTarget, EdmOnDeleteAction onDelete, string partnerPropertyName, IEdmTypeReference partnerPropertyType, IEnumerable<IEdmStructuralProperty> partnerDependentProperties, IEnumerable<IEdmStructuralProperty> partnerPrincipalProperties, bool partnerContainsTarget, EdmOnDeleteAction partnerOnDelete) { EdmUtil.CheckArgumentNull(propertyName, "propertyName"); EdmUtil.CheckArgumentNull(propertyType, "propertyType"); EdmUtil.CheckArgumentNull(partnerPropertyName, "partnerPropertyName"); EdmUtil.CheckArgumentNull(partnerPropertyType, "partnerPropertyType"); IEdmEntityType declaringType = GetEntityType(partnerPropertyType); if (declaringType == null) { throw new ArgumentException(Strings.Constructable_EntityTypeOrCollectionOfEntityTypeExpected, "partnerPropertyType"); } IEdmEntityType partnerDeclaringType = GetEntityType(propertyType); if (partnerDeclaringType == null) { throw new ArgumentException(Strings.Constructable_EntityTypeOrCollectionOfEntityTypeExpected, "propertyType"); } EdmNavigationProperty end1 = new EdmNavigationProperty( declaringType, propertyName, propertyType, dependentProperties, principalProperties, containsTarget, onDelete); EdmNavigationProperty end2 = new EdmNavigationProperty( partnerDeclaringType, partnerPropertyName, partnerPropertyType, partnerDependentProperties, partnerPrincipalProperties, partnerContainsTarget, partnerOnDelete); end1.partner = end2; end2.partner = end1; return end1; } private static IEdmEntityType GetEntityType(IEdmTypeReference type) { IEdmEntityType entityType = null; if (type.IsEntity()) { entityType = (IEdmEntityType)type.Definition; } else if (type.IsCollection()) { type = ((IEdmCollectionType)type.Definition).ElementType; if (type.IsEntity()) { entityType = (IEdmEntityType)type.Definition; } } return entityType; } private static IEdmTypeReference CreateNavigationPropertyType(IEdmEntityType entityType, EdmMultiplicity multiplicity, string multiplicityParameterName) { switch (multiplicity) { case EdmMultiplicity.ZeroOrOne: return new EdmEntityTypeReference(entityType, true); case EdmMultiplicity.One: return new EdmEntityTypeReference(entityType, false); case EdmMultiplicity.Many: return EdmCoreModel.GetCollection(new EdmEntityTypeReference(entityType, false)); default: throw new ArgumentOutOfRangeException(multiplicityParameterName, Strings.UnknownEnumVal_Multiplicity(multiplicity)); } } } }
//------------------------------------------------------------------------------ // <copyright // file="StyleCopCmdTaskTest.cs" // company="Schley Andrew Kutz"> // Copyright (c) Schley Andrew Kutz. All rights reserved. // </copyright> // <authors> // <author>Schley Andrew Kutz</author> // </authors> //------------------------------------------------------------------------------ /******************************************************************************* * Copyright (c) 2008, Schley Andrew Kutz <sakutz@gmail.com> * 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 Schley Andrew Kutz 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 Net.SF.StyleCopCmd.Core.Test { using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using NAnt.Core; using NUnit.Framework; /// <summary> /// A test fixture for the StyleCopCmdTask class. /// </summary> [TestFixture] public class StyleCopCmdTaskTest { #region NantSettingsXml /// <summary> /// The NAnt configuration XML /// </summary> private const string NantConfigXml = @"<configuration> <nant> <frameworks> <platform name=""win32"" default=""auto""> <task-assemblies> <!-- include NAnt task assemblies --> <include name=""*Tasks.dll"" /> <!-- include NAnt test assemblies --> <include name=""*Tests.dll"" /> <!-- include framework-neutral assemblies --> <include name=""extensions/common/neutral/**/*.dll"" /> <!-- exclude Microsoft.NET specific task assembly --> <exclude name=""NAnt.MSNetTasks.dll"" /> <!-- exclude Microsoft.NET specific test assembly --> <exclude name=""NAnt.MSNet.Tests.dll"" /> </task-assemblies> <framework name=""net-3.5"" family=""net"" version=""2.0"" description=""Microsoft .NET Framework 3.5"" sdkdirectory=""${path::combine(sdkInstallRoot, 'bin')}"" frameworkdirectory=""${path::combine(installRoot, 'v3.5')}"" frameworkassemblydirectory=""${path::combine(installRoot, 'v2.0.50727')}"" clrversion=""2.0.50727"" > <runtime> <probing-paths> <directory name=""lib/net/2.0"" /> <directory name=""lib/net/neutral"" /> <directory name=""lib/common/2.0"" /> <directory name=""lib/common/neutral"" /> </probing-paths> <modes> <strict> <environment> <variable name=""COMPLUS_VERSION"" value=""v2.0.50727"" /> </environment> </strict> </modes> </runtime> <reference-assemblies basedir=""${path::combine(installRoot, 'v2.0.50727')}""> <include name=""Accessibility.dll"" /> <include name=""mscorlib.dll"" /> <include name=""Microsoft.Build.Utilities.dll"" /> <include name=""Microsoft.Vsa.dll"" /> <include name=""Microsoft.VisualBasic.dll"" /> <include name=""Microsoft.VisualBasic.Compatibility.dll"" /> <include name=""Microsoft.VisualBasic.Compatibility.Data.dll"" /> <include name=""System.Configuration.dll"" /> <include name=""System.Configuration.Install.dll"" /> <include name=""System.Data.dll"" /> <include name=""System.Data.OracleClient.dll"" /> <include name=""System.Data.SqlXml.dll"" /> <include name=""System.Deployment.dll"" /> <include name=""System.Design.dll"" /> <include name=""System.DirectoryServices.dll"" /> <include name=""System.dll"" /> <include name=""System.Drawing.Design.dll"" /> <include name=""System.Drawing.dll"" /> <include name=""System.EnterpriseServices.dll"" /> <include name=""System.Management.dll"" /> <include name=""System.Messaging.dll"" /> <include name=""System.Runtime.Remoting.dll"" /> <include name=""System.Runtime.Serialization.Formatters.Soap.dll"" /> <include name=""System.Security.dll"" /> <include name=""System.ServiceProcess.dll"" /> <include name=""System.Transactions.dll"" /> <include name=""System.Web.dll"" /> <include name=""System.Web.Mobile.dll"" /> <include name=""System.Web.RegularExpressions.dll"" /> <include name=""System.Web.Services.dll"" /> <include name=""System.Windows.Forms.dll"" /> <include name=""System.Xml.dll"" /> </reference-assemblies> <reference-assemblies basedir=""${environment::get-folder-path('ProgramFiles')}/Reference Assemblies/Microsoft/Framework/v3.5""> <include name=""Microsoft.Build.Engine.dll"" /> <include name=""Microsoft.Build.Framework.dll"" /> <include name=""System.AddIn.Contract.dll"" /> <include name=""System.AddIn.dll"" /> <include name=""System.Core.dll"" /> <include name=""System.Data.DataSetExtensions.dll"" /> <include name=""System.Data.Linq.dll"" /> <include name=""System.DirectoryServices.AccountManagement.dll"" /> <include name=""System.Management.Instrumentation.dll"" /> <include name=""System.Net.dll"" /> <include name=""System.ServiceModel.Web.dll"" /> <include name=""System.Web.Extensions.Design.dll"" /> <include name=""System.Web.Extensions.dll"" /> <include name=""System.Windows.Presentation.dll"" /> <include name=""System.WorkflowServices.dll"" /> <include name=""System.Xml.Linq.dll"" /> </reference-assemblies> <reference-assemblies basedir=""${environment::get-folder-path('ProgramFiles')}/Reference Assemblies/Microsoft/Framework/v3.0""> <include name=""System.IdentityModel.dll"" /> <include name=""System.IdentityModel.Selectors.dll"" /> <include name=""System.IO.Log.dll"" /> <include name=""System.Printing.dll"" /> <include name=""System.Runtime.Serialization.dll"" /> <include name=""System.ServiceModel.dll"" /> <include name=""System.Speech.dll"" /> <include name=""System.Workflow.Activities.dll"" /> <include name=""System.Workflow.ComponentModel.dll"" /> <include name=""System.Workflow.Runtime.dll"" /> <include name=""WindowsBase.dll"" /> </reference-assemblies> <task-assemblies> <!-- include MS.NET version-neutral assemblies --> <include name=""extensions/net/neutral/**/*.dll"" /> <!-- include MS.NET 2.0 specific assemblies --> <include name=""extensions/net/2.0/**/*.dll"" /> <!-- include MS.NET specific task assembly --> <include name=""NAnt.MSNetTasks.dll"" /> <!-- include MS.NET specific test assembly --> <include name=""NAnt.MSNet.Tests.dll"" /> <!-- include .NET 2.0 specific assemblies --> <include name=""extensions/common/2.0/**/*.dll"" /> </task-assemblies> <tool-paths> <directory name=""${path::combine(sdkInstallRoot, 'bin')}"" /> <directory name=""${path::combine(installRoot, 'v3.5')}"" /> <directory name=""${path::combine(installRoot, 'v2.0.50727')}"" /> </tool-paths> <project> <property name=""installRoot"" value=""C:\WINDOWS\Microsoft.NET\Framework\"" /> <property name=""sdkInstallRoot"" value=""C:\Program Files\Microsoft SDKs\Windows\v6.1\"" /> <!--<readregistry property=""installRoot"" key=""SOFTWARE\Microsoft\.NETFramework\InstallRoot"" hive=""LocalMachine"" /> <readregistry property=""sdkInstallRoot"" key=""SOFTWARE\Microsoft\Microsoft SDKs\Windows\v6.1\WinSDKNetFxTools\InstallationFolder"" hive=""LocalMachine"" failonerror=""false"" />--> <property name=""frameworkDirectoryV35"" value=""${path::combine(installRoot, 'v3.5')}"" /> <fail if=""${not(directory::exists(frameworkDirectoryV35))}"">The Framework directory for .NET 3.5 does not exist.</fail> <property name=""referenceV35"" value=""${environment::get-folder-path('ProgramFiles')}/Reference Assemblies/Microsoft/Framework/v3.5"" /> <fail if=""${not(directory::exists(referenceV35))}"">The Reference Assemblies directory for .NET 3.5 does not exist.</fail> </project> <tasks> <task name=""csc""> <attribute name=""exename"">${path::combine(frameworkDirectoryV35,'csc.exe')}</attribute> <attribute name=""supportsnowarnlist"">true</attribute> <attribute name=""supportswarnaserrorlist"">true</attribute> <attribute name=""supportskeycontainer"">true</attribute> <attribute name=""supportskeyfile"">true</attribute> <attribute name=""supportsdelaysign"">true</attribute> <attribute name=""supportsplatform"">true</attribute> <attribute name=""supportslangversion"">true</attribute> </task> <task name=""vbc""> <attribute name=""exename"">${path::combine(frameworkDirectoryV35,'vbc.exe')}</attribute> <attribute name=""supportsdocgeneration"">true</attribute> <attribute name=""supportsnostdlib"">true</attribute> <attribute name=""supportsnowarnlist"">true</attribute> <attribute name=""supportskeycontainer"">true</attribute> <attribute name=""supportskeyfile"">true</attribute> <attribute name=""supportsdelaysign"">true</attribute> <attribute name=""supportsplatform"">true</attribute> <attribute name=""supportswarnaserrorlist"">true</attribute> </task> <task name=""jsc""> <attribute name=""supportsplatform"">true</attribute> </task> <task name=""vjc""> <attribute name=""supportsnowarnlist"">true</attribute> <attribute name=""supportskeycontainer"">true</attribute> <attribute name=""supportskeyfile"">true</attribute> <attribute name=""supportsdelaysign"">true</attribute> </task> <task name=""resgen""> <attribute name=""supportsassemblyreferences"">true</attribute> <attribute name=""supportsexternalfilereferences"">true</attribute> </task> <task name=""al""> <attribute name=""exename"">${path::combine(sdkInstallRoot, 'bin/al.exe')}</attribute> </task> <task name=""delay-sign""> <attribute name=""exename"">sn</attribute> </task> <task name=""license""> <attribute name=""exename"">lc</attribute> <attribute name=""supportsassemblyreferences"">true</attribute> </task> </tasks> </framework> </platform> </frameworks> <properties> <!-- properties defined here are accessible to all build files --> <!-- <property name=""foo"" value = ""bar"" readonly=""false"" /> --> </properties> </nant> </configuration>"; #endregion /// <summary> /// The NAnt .config file. /// </summary> private static readonly XmlDocument NAntConfigXmlDoc = new XmlDocument(); /// <summary> /// The path to the root solution. /// </summary> private string rootSolutionPath = string.Empty; /// <summary> /// The path to the test solution. /// </summary> private string testSolutionPath = string.Empty; /// <summary> /// The path to the output XML file. /// </summary> private string outputXmlPath = string.Empty; /// <summary> /// The path to the XSL file. /// </summary> private string transformFilePath = string.Empty; /// <summary> /// Sets up this test fixture. /// </summary> [SetUp] public void SetUp() { // Load the NAnt configuration file. NAntConfigXmlDoc.LoadXml(NantConfigXml); this.rootSolutionPath = GetRootSolutionPath(); this.transformFilePath = this.rootSolutionPath + @"\inc\StyleCopReport.xsl"; this.testSolutionPath = this.rootSolutionPath + @"\test\Net.SF.StyleCopCmd.Core.Test" + @"\data\StyleCopTestProject"; this.outputXmlPath = this.rootSolutionPath + @"\test\Net.SF.StyleCopCmd.Core.Test" + @"\build\StyleCopReport.xml"; } /// <summary> /// Tests the Initialize method. /// </summary> [Test] public void InitializeTest() { var format = @"<project name=""StyleCopCmdTest""> <styleCopCmd outputXmlFile=""{0}"" transformFile=""{1}"" ignorePatterns=""AssemblyInfo\.cs,GlobalSuppressions\.cs""> <solutionFiles> <include name=""{2}/*.sln"" /> </solutionFiles> <addinDirectories> <include name=""{3}/test/Net.SF.StyleCopCmd.Core.Test/build"" /> </addinDirectories> </styleCopCmd> </project>"; // Create the NAnt XML document for the project. var xmldoc = this.CreateNAntXmlDocument(format); // Create a NAnt project. var p = CreateNAntProject(xmldoc); // Load the StyleCopCmd.Core assembly into the project. LoadStyleCopCmdTask(p); // Get the StyleCopCmd task. var t = CreateTask(p); Assert.AreEqual( this.outputXmlPath, t.OutputXmlFile); Assert.AreEqual( @"AssemblyInfo\.cs,GlobalSuppressions\.cs", t.IgnorePatterns); Assert.AreEqual( 1, t.SolutionFiles.FileNames.Count); } /// <summary> /// Tests the ExecuteTask method. /// </summary> [Test] public void ExecuteTaskTest() { var format = @"<project name=""StyleCopCmdTest""> <styleCopCmd outputXmlFile=""{0}"" transformFile=""{1}"" recursionEnabled=""true"" ignorePatterns=""AssemblyInfo\.cs,GlobalSuppressions\.cs""> <solutionFiles> <include name=""{2}/*.sln"" /> </solutionFiles> <addinDirectories> <include name=""{3}/test/Net.SF.StyleCopCmd.Core.Test/build"" /> </addinDirectories> </styleCopCmd> </project>"; // Create the NAnt XML document for the project. var xmldoc = this.CreateNAntXmlDocument(format); // Create a NAnt project. var p = CreateNAntProject(xmldoc); // Load the StyleCopCmd.Core assembly into the project. LoadStyleCopCmdTask(p); // Get the StyleCopCmd task. var t = CreateTask(p); t.Execute(); } /// <summary>Creates a StyleCopCmd task.</summary> /// <param name="project">The project to create the task from.</param> /// <returns>A StyleCopCmd task.</returns> private static StyleCopCmdTask CreateTask(Project project) { if (project.Document.DocumentElement == null) { throw new XmlException("DocumentElement is null"); } var el = project.Document.DocumentElement.ChildNodes[0]; var nt = (StyleCopCmdTask) project.CreateTask(el); return nt; } /// <summary> /// Creates a NAnt project. /// </summary> /// <param name="projectXmlDoc"> /// The XML document to create the project from. /// </param> /// <returns>A NAnt Proejct.</returns> private static Project CreateNAntProject(XmlDocument projectXmlDoc) { if (NAntConfigXmlDoc.DocumentElement == null) { throw new XmlException("DocumentElement is null"); } // Create a NAnt project. var p = new Project( projectXmlDoc, Level.Info, 0, NAntConfigXmlDoc.DocumentElement.ChildNodes[0]); return p; } /// <summary> /// Load any custom tasks into the given project from the /// StyleCopCmd.Core assembly. /// </summary> /// <param name="project"> /// The project to load the custom tasks into. /// </param> private static void LoadStyleCopCmdTask(Project project) { if (project.Document.DocumentElement == null) { throw new XmlException("DocumentElement is null"); } // Add an echo task to the project's document root to output // the result of the task load operation. var et = project.Document.CreateElement("echo"); et.Attributes.Append(project.Document.CreateAttribute("message")); project.Document.DocumentElement.AppendChild(et); // Load the custom tasks. TypeFactory.ScanAssembly( Assembly.GetAssembly(typeof(StyleCopCmdTask)), project.CreateTask(et)); } /// <summary> /// Gets the path to the root solution. /// </summary> /// <returns> /// The path to the root solution. /// </returns> private static string GetRootSolutionPath() { var d = new DirectoryInfo("."); // Move backwards to the root of the solution. while (d != null) { // Is the solution in this directory? if (d.GetFiles().FirstOrDefault(f => f.Extension == ".sln") != null) { break; } d = d.Parent; } return d == null ? null : d.FullName; } /// <summary> /// Creates a NAnt XML project document. /// </summary> /// <param name="format">The XML format pattern to use.</param> /// <returns>A new XML document.</returns> private XmlDocument CreateNAntXmlDocument(string format) { var xml = string.Format( CultureInfo.CurrentCulture, format, this.outputXmlPath, this.transformFilePath, this.testSolutionPath, this.rootSolutionPath); var xmldoc = new XmlDocument(); xmldoc.LoadXml(xml); return xmldoc; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Messages; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbNtRename Request /// </summary> public class SmbNtRenameRequestPacket : SmbSingleRequestPacket { #region Fields private SMB_COM_NT_RENAME_Request_SMB_Parameters smbParameters; private SMB_COM_NT_RENAME_Request_SMB_Data smbData; #endregion #region Properties /// <summary> /// get or set the Smb_Parameters:SMB_COM_NT_RENAME_Request_SMB_Parameters /// </summary> public SMB_COM_NT_RENAME_Request_SMB_Parameters SmbParameters { get { return this.smbParameters; } set { this.smbParameters = value; } } /// <summary> /// get or set the Smb_Data:SMB_COM_NT_RENAME_Request_SMB_Data /// </summary> public SMB_COM_NT_RENAME_Request_SMB_Data SmbData { get { return this.smbData; } set { this.smbData = value; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbNtRenameRequestPacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbNtRenameRequestPacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbNtRenameRequestPacket(SmbNtRenameRequestPacket packet) : base(packet) { this.InitDefaultValue(); this.smbParameters.WordCount = packet.SmbParameters.WordCount; this.smbParameters.SearchAttributes = packet.SmbParameters.SearchAttributes; this.smbParameters.InformationLevel = packet.SmbParameters.InformationLevel; this.smbParameters.Reserved = packet.SmbParameters.Reserved; this.smbData.ByteCount = packet.SmbData.ByteCount; this.smbData.BufferFormat1 = packet.SmbData.BufferFormat1; if (packet.smbData.OldFileName != null) { this.smbData.OldFileName = new byte[packet.smbData.OldFileName.Length]; Array.Copy(packet.smbData.OldFileName, this.smbData.OldFileName, packet.smbData.OldFileName.Length); } else { this.smbData.OldFileName = new byte[0]; } this.smbData.BufferFormat2 = packet.SmbData.BufferFormat2; if (packet.smbData.NewFileName != null) { this.smbData.NewFileName = new byte[packet.smbData.NewFileName.Length]; Array.Copy(packet.smbData.NewFileName, this.smbData.NewFileName, packet.smbData.NewFileName.Length); } else { this.smbData.NewFileName = new byte[0]; } } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbNtRenameRequestPacket(this); } /// <summary> /// encode the SmbParameters /// </summary> protected override void EncodeParameters() { this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>( CifsMessageUtils.ToBytes<SMB_COM_NT_RENAME_Request_SMB_Parameters>(this.smbParameters)); } /// <summary> /// decode the SmbData /// </summary> protected override void EncodeData() { this.smbDataBlock.ByteCount = this.SmbData.ByteCount; this.smbDataBlock.Bytes = new byte[this.smbDataBlock.ByteCount]; using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<byte>(this.SmbData.BufferFormat1); if (this.SmbData.OldFileName != null) { channel.WriteBytes(this.SmbData.OldFileName); } channel.Write<byte>(this.SmbData.BufferFormat2); if (this.SmbData.NewFileName != null) { channel.WriteBytes(this.SmbData.NewFileName); } channel.EndWriteGroup(); } } } /// <summary> /// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters. /// </summary> protected override void DecodeParameters() { this.smbParameters = TypeMarshal.ToStruct<SMB_COM_NT_RENAME_Request_SMB_Parameters>( TypeMarshal.ToBytes(this.smbParametersBlock)); } /// <summary> /// to decode the smb data: from the general SmbDada to the concrete Smb Data. /// </summary> protected override void DecodeData() { using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock))) { using (Channel channel = new Channel(null, memoryStream)) { this.smbData.ByteCount = channel.Read<ushort>(); this.smbData.BufferFormat1 = channel.Read<byte>(); this.smbData.OldFileName = CifsMessageUtils.ReadNullTerminatedString(channel, (this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE); this.smbData.BufferFormat2 = channel.Read<byte>(); this.smbData.NewFileName = CifsMessageUtils.ReadNullTerminatedString(channel, (this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE); } } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { this.smbData.OldFileName = new byte[0]; this.smbData.NewFileName = new byte[0]; } #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Implements the algorithm for distributing loop indices to parallel loop workers // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Threading; using System.Diagnostics; #pragma warning disable 0420 namespace System.Threading.Tasks { /// <summary> /// Represents an index range /// </summary> internal struct IndexRange { // the From and To values for this range. These do not change. internal long _nFromInclusive; internal long _nToExclusive; // The shared index, stored as the offset from nFromInclusive. Using an offset rather than the actual // value saves us from overflows that can happen due to multiple workers racing to increment this. // All updates to this field need to be interlocked. internal volatile Box<long> _nSharedCurrentIndexOffset; // to be set to 1 by the worker that finishes this range. It's OK to do a non-interlocked write here. internal int _bRangeFinished; } /// <summary> /// The RangeWorker struct wraps the state needed by a task that services the parallel loop /// </summary> internal struct RangeWorker { // reference to the IndexRange array allocated by the range manager internal readonly IndexRange[] _indexRanges; // index of the current index range that this worker is grabbing chunks from internal int _nCurrentIndexRange; // the step for this loop. Duplicated here for quick access (rather than jumping to rangemanager) internal long _nStep; // increment value is the current amount that this worker will use // to increment the shared index of the range it's working on internal long _nIncrementValue; // the increment value is doubled each time this worker finds work, and is capped at this value internal readonly long _nMaxIncrementValue; internal bool IsInitialized { get { return _indexRanges != null; } } /// <summary> /// Initializes a RangeWorker struct /// </summary> internal RangeWorker(IndexRange[] ranges, int nInitialRange, long nStep) { _indexRanges = ranges; _nCurrentIndexRange = nInitialRange; _nStep = nStep; _nIncrementValue = nStep; _nMaxIncrementValue = Parallel.DEFAULT_LOOP_STRIDE * nStep; } /// <summary> /// Implements the core work search algorithm that will be used for this range worker. /// </summary> /// /// Usage pattern is: /// 1) the thread associated with this rangeworker calls FindNewWork /// 2) if we return true, the worker uses the nFromInclusiveLocal and nToExclusiveLocal values /// to execute the sequential loop /// 3) if we return false it means there is no more work left. It's time to quit. /// internal bool FindNewWork(out long nFromInclusiveLocal, out long nToExclusiveLocal) { // since we iterate over index ranges circularly, we will use the // count of visited ranges as our exit condition int numIndexRangesToVisit = _indexRanges.Length; do { // local snap to save array access bounds checks in places where we only read fields IndexRange currentRange = _indexRanges[_nCurrentIndexRange]; if (currentRange._bRangeFinished == 0) { if (_indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset == null) { Interlocked.CompareExchange(ref _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset, new Box<long>(0), null); } // this access needs to be on the array slot long nMyOffset = Interlocked.Add(ref _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset.Value, _nIncrementValue) - _nIncrementValue; if (currentRange._nToExclusive - currentRange._nFromInclusive > nMyOffset) { // we found work nFromInclusiveLocal = currentRange._nFromInclusive + nMyOffset; nToExclusiveLocal = nFromInclusiveLocal + _nIncrementValue; // Check for going past end of range, or wrapping if ((nToExclusiveLocal > currentRange._nToExclusive) || (nToExclusiveLocal < currentRange._nFromInclusive)) { nToExclusiveLocal = currentRange._nToExclusive; } // We will double our unit of increment until it reaches the maximum. if (_nIncrementValue < _nMaxIncrementValue) { _nIncrementValue *= 2; if (_nIncrementValue > _nMaxIncrementValue) { _nIncrementValue = _nMaxIncrementValue; } } return true; } else { // this index range is completed, mark it so that others can skip it quickly Interlocked.Exchange(ref _indexRanges[_nCurrentIndexRange]._bRangeFinished, 1); } } // move on to the next index range, in circular order. _nCurrentIndexRange = (_nCurrentIndexRange + 1) % _indexRanges.Length; numIndexRangesToVisit--; } while (numIndexRangesToVisit > 0); // we've visited all index ranges possible => there's no work remaining nFromInclusiveLocal = 0; nToExclusiveLocal = 0; return false; } /// <summary> /// 32 bit integer version of FindNewWork. Assumes the ranges were initialized with 32 bit values. /// </summary> internal bool FindNewWork32(out int nFromInclusiveLocal32, out int nToExclusiveLocal32) { long nFromInclusiveLocal; long nToExclusiveLocal; bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal); Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) && (nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue)); // convert to 32 bit before returning nFromInclusiveLocal32 = (int)nFromInclusiveLocal; nToExclusiveLocal32 = (int)nToExclusiveLocal; return bRetVal; } } /// <summary> /// Represents the entire loop operation, keeping track of workers and ranges. /// </summary> /// /// The usage pattern is: /// 1) The Parallel loop entry function (ForWorker) creates an instance of this class /// 2) Every thread joining to service the parallel loop calls RegisterWorker to grab a /// RangeWorker struct to wrap the state it will need to find and execute work, /// and they keep interacting with that struct until the end of the loop internal class RangeManager { internal readonly IndexRange[] _indexRanges; internal int _nCurrentIndexRangeToAssign; internal long _nStep; /// <summary> /// Initializes a RangeManager with the given loop parameters, and the desired number of outer ranges /// </summary> internal RangeManager(long nFromInclusive, long nToExclusive, long nStep, int nNumExpectedWorkers) { _nCurrentIndexRangeToAssign = 0; _nStep = nStep; // Our signed math breaks down w/ nNumExpectedWorkers == 1. So change it to 2. if (nNumExpectedWorkers == 1) nNumExpectedWorkers = 2; // // calculate the size of each index range // ulong uSpan = (ulong)(nToExclusive - nFromInclusive); ulong uRangeSize = uSpan / (ulong)nNumExpectedWorkers; // rough estimate first uRangeSize -= uRangeSize % (ulong)nStep; // snap to multiples of nStep // otherwise index range transitions will derail us from nStep if (uRangeSize == 0) { uRangeSize = (ulong)nStep; } // // find the actual number of index ranges we will need // Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue); int nNumRanges = (int)(uSpan / uRangeSize); if (uSpan % uRangeSize != 0) { nNumRanges++; } // Convert to signed so the rest of the logic works. // Should be fine so long as uRangeSize < Int64.MaxValue, which we guaranteed by setting #workers >= 2. long nRangeSize = (long)uRangeSize; // allocate the array of index ranges _indexRanges = new IndexRange[nNumRanges]; long nCurrentIndex = nFromInclusive; for (int i = 0; i < nNumRanges; i++) { // the fromInclusive of the new index range is always on nCurrentIndex _indexRanges[i]._nFromInclusive = nCurrentIndex; _indexRanges[i]._nSharedCurrentIndexOffset = null; _indexRanges[i]._bRangeFinished = 0; // now increment it to find the toExclusive value for our range nCurrentIndex += nRangeSize; // detect integer overflow or range overage and snap to nToExclusive if (nCurrentIndex < nCurrentIndex - nRangeSize || nCurrentIndex > nToExclusive) { // this should only happen at the last index Debug.Assert(i == nNumRanges - 1); nCurrentIndex = nToExclusive; } // now that the end point of the new range is calculated, assign it. _indexRanges[i]._nToExclusive = nCurrentIndex; } } /// <summary> /// The function that needs to be called by each new worker thread servicing the parallel loop /// in order to get a RangeWorker struct that wraps the state for finding and executing indices /// </summary> internal RangeWorker RegisterNewWorker() { Debug.Assert(_indexRanges != null && _indexRanges.Length != 0); int nInitialRange = (Interlocked.Increment(ref _nCurrentIndexRangeToAssign) - 1) % _indexRanges.Length; return new RangeWorker(_indexRanges, nInitialRange, _nStep); } } } #pragma warning restore 0420
/* Copyright(c) 2009, Stefan Simek Copyright(c) 2016, Vladyslav Taranov MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using TriAxis.RunSharp; namespace TriAxis.RunSharp.Tests { [TestFixture] public class _11_OperatorOverloading : TestBase { [Test] public void TestGenComplex() { TestingFacade.GetTestsForGenerator(GenComplex, @">>> GEN TriAxis.RunSharp.Tests.11_OperatorOverloading.GenComplex === RUN TriAxis.RunSharp.Tests.11_OperatorOverloading.GenComplex First complex number: 2 + 3i Second complex number: 3 + 4i The sum of the two numbers: 5 + 7i <<< END TriAxis.RunSharp.Tests.11_OperatorOverloading.GenComplex ").RunAll(); } // example based on the MSDN Operator Overloading Sample (complex.cs) public static void GenComplex(AssemblyGen ag) { var st = ag.StaticFactory; var exp = ag.ExpressionFactory; ITypeMapper m = ag.TypeMapper; TypeGen Complex = ag.Public.Struct("Complex"); { FieldGen real = Complex.Public.Field(typeof(int), "real"); FieldGen imaginary = Complex.Public.Field(typeof(int), "imaginary"); CodeGen g = Complex.Public.Constructor() .Parameter(typeof(int), "real") .Parameter(typeof(int), "imaginary") ; { g.Assign(real, g.Arg("real")); g.Assign(imaginary, g.Arg("imaginary")); } // Declare which operator to overload (+), the types // that can be added (two Complex objects), and the // return type (Complex): g = Complex.Operator(Operator.Add, Complex, Complex, "c1", Complex, "c2"); { var c1 = g.Arg("c1"); var c2 = g.Arg("c2"); g.Return(exp.New(Complex, c1.Field("real") + c2.Field("real"), c1.Field("imaginary") + c2.Field("imaginary"))); } // Override the ToString method to display an complex number in the suitable format: g = Complex.Public.Override.Method(typeof(string), "ToString"); { g.Return(st.Invoke(typeof(string), "Format", "{0} + {1}i", real, imaginary)); } g = Complex.Public.Static.Method(typeof(void), "Main"); { var num1 = g.Local(exp.New(Complex, 2, 3)); var num2 = g.Local(exp.New(Complex, 3, 4)); // Add two Complex objects (num1 and num2) through the // overloaded plus operator: var sum = g.Local(num1 + num2); // Print the numbers and the sum using the overriden ToString method: g.WriteLine("First complex number: {0}", num1); g.WriteLine("Second complex number: {0}", num2); g.WriteLine("The sum of the two numbers: {0}", sum); } } } [Test] public void TestGenDbBool() { TestingFacade.GetTestsForGenerator(GenDbBool, @">>> GEN TriAxis.RunSharp.Tests.11_OperatorOverloading.GenDbBool === RUN TriAxis.RunSharp.Tests.11_OperatorOverloading.GenDbBool !DBBool.True = DBBool.False !DBBool.Null = DBBool.Null DBBool.True & DBBool.Null = DBBool.Null DBBool.True | DBBool.Null = DBBool.True b is not definitely true <<< END TriAxis.RunSharp.Tests.11_OperatorOverloading.GenDbBool ").RunAll(); } // example based on the MSDN Operator Overloading Sample (dbbool.cs) public static void GenDbBool(AssemblyGen ag) { var st = ag.StaticFactory; var exp = ag.ExpressionFactory; ITypeMapper m = ag.TypeMapper; TypeGen DBBool = ag.Public.Struct("DBBool"); { // Private field that stores -1, 0, 1 for dbFalse, dbNull, dbTrue: FieldGen value = DBBool.Field(typeof(int), "value"); // Private constructor. The value parameter must be -1, 0, or 1: CodeGen g = DBBool.Constructor().Parameter(typeof(int), "value"); { g.Assign(value, g.Arg("value")); } // The three possible DBBool values: FieldGen dbNull = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbNull", exp.New(DBBool, 0)); FieldGen dbFalse = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbFalse", exp.New(DBBool, -1)); FieldGen dbTrue = DBBool.Public.Static.ReadOnly.Field(DBBool, "dbTrue", exp.New(DBBool, 1)); // Implicit conversion from bool to DBBool. Maps true to // DBBool.dbTrue and false to DBBool.dbFalse: g = DBBool.ImplicitConversionFrom(typeof(bool), "x"); { var x = g.Arg("x"); g.Return(x.Conditional(dbTrue, dbFalse)); } // Explicit conversion from DBBool to bool. Throws an // exception if the given DBBool is dbNull, otherwise returns // true or false: g = DBBool.ExplicitConversionTo(typeof(bool), "x"); { var x = g.Arg("x"); g.If(x.Field("value") == 0); { g.Throw(exp.New(typeof(InvalidOperationException))); } g.End(); g.Return(x.Field("value") > 0); } // Equality operator. Returns dbNull if either operand is dbNull, // otherwise returns dbTrue or dbFalse: g = DBBool.Operator(Operator.Equality, DBBool, DBBool, "x", DBBool, "y"); { var x = g.Arg("x"); var y = g.Arg("y"); g.If(x.Field("value") == 0 || y.Field("value") == 0); { g.Return(dbNull); } g.End(); g.Return((x.Field("value") == y.Field("value")).Conditional(dbTrue, dbFalse)); } // Inequality operator. Returns dbNull if either operand is // dbNull, otherwise returns dbTrue or dbFalse: g = DBBool.Operator(Operator.Inequality, DBBool, DBBool, "x", DBBool, "y"); { var x = g.Arg("x"); var y = g.Arg("y"); g.If(x.Field("value") == 0 || y.Field("value") == 0); { g.Return(dbNull); } g.End(); g.Return((x.Field("value") != y.Field("value")).Conditional(dbTrue, dbFalse)); } // Logical negation operator. Returns dbTrue if the operand is // dbFalse, dbNull if the operand is dbNull, or dbFalse if the // operand is dbTrue: g = DBBool.Operator(Operator.LogicalNot, DBBool, DBBool, "x"); { var x = g.Arg("x"); g.Return(exp.New(DBBool, -x.Field("value"))); } // Logical AND operator. Returns dbFalse if either operand is // dbFalse, dbNull if either operand is dbNull, otherwise dbTrue: g = DBBool.Operator(Operator.And, DBBool, DBBool, "x", DBBool, "y"); { var x = g.Arg("x"); var y = g.Arg("y"); g.Return(exp.New(DBBool, (x.Field("value") < y.Field("value")).Conditional(x.Field("value"), y.Field("value")))); } // Logical OR operator. Returns dbTrue if either operand is // dbTrue, dbNull if either operand is dbNull, otherwise dbFalse: g = DBBool.Operator(Operator.Or, DBBool, DBBool, "x", DBBool, "y"); { var x = g.Arg("x"); var y = g.Arg("y"); g.Return(exp.New(DBBool, (x.Field("value") > y.Field("value")).Conditional(x.Field("value"), y.Field("value")))); } // Definitely true operator. Returns true if the operand is // dbTrue, false otherwise: g = DBBool.Operator(Operator.True, typeof(bool), DBBool, "x"); { var x = g.Arg("x"); g.Return(x.Field("value") > 0); } // Definitely false operator. Returns true if the operand is // dbFalse, false otherwise: g = DBBool.Operator(Operator.False, typeof(bool), DBBool, "x"); { var x = g.Arg("x"); g.Return(x.Field("value") < 0); } // Overload the conversion from DBBool to string: g = DBBool.ImplicitConversionTo(typeof(string), "x"); { var x = g.Arg("x"); g.Return((x.Field("value") > 0).Conditional("dbTrue", (x.Field("value") < 0).Conditional("dbFalse", "dbNull"))); } // Override the Object.Equals(object o) method: g = DBBool.Public.Override.Method(typeof(bool), "Equals").Parameter(typeof(object), "o"); { g.Try(); { g.Return((g.This() == g.Arg("o").Cast(DBBool)).Cast(typeof(bool))); } g.CatchAll(); { g.Return(false); } g.End(); } // Override the Object.GetHashCode() method: g = DBBool.Public.Override.Method(typeof(int), "GetHashCode"); { g.Return(value); } // Override the ToString method to convert DBBool to a string: g = DBBool.Public.Override.Method(typeof(string), "ToString"); { g.Switch(value); { g.Case(-1); g.Return("DBBool.False"); g.Case(0); g.Return("DBBool.Null"); g.Case(1); g.Return("DBBool.True"); g.DefaultCase(); g.Throw(exp.New(typeof(InvalidOperationException))); } g.End(); } } TypeGen Test = ag.Class("Test"); { CodeGen g = Test.Public.Static.Method(typeof(void), "Main"); { var a = g.Local(DBBool); var b = g.Local(DBBool); g.Assign(a, st.Field(DBBool, "dbTrue")); g.Assign(b, st.Field(DBBool, "dbNull")); g.WriteLine("!{0} = {1}", a, !a); g.WriteLine("!{0} = {1}", b, !b); g.WriteLine("{0} & {1} = {2}", a, b, a & b); g.WriteLine("{0} | {1} = {2}", a, b, a | b); // Invoke the true operator to determine the Boolean // value of the DBBool variable: g.If(b); { g.WriteLine("b is definitely true"); } g.Else(); { g.WriteLine("b is not definitely true"); } g.End(); } } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System.Threading; using NLog.Common; using NLog.Targets.Wrappers; using Xunit; public class AsyncRequestQueueTests : NLogTestBase { [Fact] public void AsyncRequestQueueWithDiscardBehaviorTest() { var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Discard); Assert.Equal(3, queue.RequestLimit); Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, queue.OnOverflow); Assert.Equal(0, queue.RequestCount); queue.Enqueue(ev1); Assert.Equal(1, queue.RequestCount); queue.Enqueue(ev2); Assert.Equal(2, queue.RequestCount); queue.Enqueue(ev3); Assert.Equal(3, queue.RequestCount); queue.Enqueue(ev4); Assert.Equal(3, queue.RequestCount); AsyncLogEventInfo[] logEventInfos = queue.DequeueBatch(10); Assert.Equal(0, queue.RequestCount); // ev1 is lost Assert.Same(logEventInfos[0].LogEvent, ev2.LogEvent); Assert.Same(logEventInfos[1].LogEvent, ev3.LogEvent); Assert.Same(logEventInfos[2].LogEvent, ev4.LogEvent); Assert.Same(logEventInfos[0].Continuation, ev2.Continuation); Assert.Same(logEventInfos[1].Continuation, ev3.Continuation); Assert.Same(logEventInfos[2].Continuation, ev4.Continuation); } [Fact] public void AsyncRequestQueueWithGrowBehaviorTest() { var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Grow); Assert.Equal(3, queue.RequestLimit); Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, queue.OnOverflow); Assert.Equal(0, queue.RequestCount); queue.Enqueue(ev1); Assert.Equal(1, queue.RequestCount); queue.Enqueue(ev2); Assert.Equal(2, queue.RequestCount); queue.Enqueue(ev3); Assert.Equal(3, queue.RequestCount); queue.Enqueue(ev4); Assert.Equal(4, queue.RequestCount); AsyncLogEventInfo[] logEventInfos = queue.DequeueBatch(10); int result = logEventInfos.Length; Assert.Equal(4, result); Assert.Equal(0, queue.RequestCount); // ev1 is lost Assert.Same(logEventInfos[0].LogEvent, ev1.LogEvent); Assert.Same(logEventInfos[1].LogEvent, ev2.LogEvent); Assert.Same(logEventInfos[2].LogEvent, ev3.LogEvent); Assert.Same(logEventInfos[3].LogEvent, ev4.LogEvent); Assert.Same(logEventInfos[0].Continuation, ev1.Continuation); Assert.Same(logEventInfos[1].Continuation, ev2.Continuation); Assert.Same(logEventInfos[2].Continuation, ev3.Continuation); Assert.Same(logEventInfos[3].Continuation, ev4.Continuation); } [Fact] public void AsyncRequestQueueWithBlockBehavior() { var queue = new AsyncRequestQueue(10, AsyncTargetWrapperOverflowAction.Block); ManualResetEvent producerFinished = new ManualResetEvent(false); int pushingEvent = 0; ThreadPool.QueueUserWorkItem( s => { // producer thread for (int i = 0; i < 1000; ++i) { AsyncLogEventInfo logEvent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); logEvent.LogEvent.Message = "msg" + i; // Console.WriteLine("Pushing event {0}", i); pushingEvent = i; queue.Enqueue(logEvent); } producerFinished.Set(); }); // consumer thread AsyncLogEventInfo[] logEventInfos; int total = 0; while (total < 500) { int left = 500 - total; logEventInfos = queue.DequeueBatch(left); int got = logEventInfos.Length; Assert.True(got <= queue.RequestLimit); total += got; } Thread.Sleep(500); // producer is blocked on trying to push event #510 Assert.Equal(510, pushingEvent); queue.DequeueBatch(1); total++; Thread.Sleep(500); // producer is now blocked on trying to push event #511 Assert.Equal(511, pushingEvent); while (total < 1000) { int left = 1000 - total; logEventInfos = queue.DequeueBatch(left); int got = logEventInfos.Length; Assert.True(got <= queue.RequestLimit); total += got; } // producer should now finish producerFinished.WaitOne(); } [Fact] public void AsyncRequestQueueClearTest() { var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { }); var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Grow); Assert.Equal(3, queue.RequestLimit); Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, queue.OnOverflow); Assert.Equal(0, queue.RequestCount); queue.Enqueue(ev1); Assert.Equal(1, queue.RequestCount); queue.Enqueue(ev2); Assert.Equal(2, queue.RequestCount); queue.Enqueue(ev3); Assert.Equal(3, queue.RequestCount); queue.Enqueue(ev4); Assert.Equal(4, queue.RequestCount); queue.Clear(); Assert.Equal(0, queue.RequestCount); AsyncLogEventInfo[] logEventInfos; logEventInfos = queue.DequeueBatch(10); int result = logEventInfos.Length; Assert.Equal(0, result); Assert.Equal(0, queue.RequestCount); } } }
// Copyright (C) 2015 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if UNITY_IOS using System; using System.Collections.Generic; using System.Runtime.InteropServices; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { internal class BannerClient : IBannerClient, IDisposable { private IntPtr bannerViewPtr; private IntPtr bannerClientPtr; #region Banner callback types internal delegate void GADUAdViewDidReceiveAdCallback(IntPtr bannerClient); internal delegate void GADUAdViewDidFailToReceiveAdWithErrorCallback( IntPtr bannerClient, string error); internal delegate void GADUAdViewWillPresentScreenCallback(IntPtr bannerClient); internal delegate void GADUAdViewDidDismissScreenCallback(IntPtr bannerClient); internal delegate void GADUAdViewWillLeaveApplicationCallback(IntPtr bannerClient); #endregion public event EventHandler<EventArgs> OnAdLoaded; public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad; public event EventHandler<EventArgs> OnAdOpening; public event EventHandler<EventArgs> OnAdClosed; public event EventHandler<EventArgs> OnAdLeavingApplication; // This property should be used when setting the bannerViewPtr. private IntPtr BannerViewPtr { get { return this.bannerViewPtr; } set { Externs.GADURelease(this.bannerViewPtr); this.bannerViewPtr = value; } } #region IBannerClient implementation // Creates a banner view. public void CreateBannerView(string adUnitId, AdSize adSize, AdPosition position) { this.bannerClientPtr = (IntPtr)GCHandle.Alloc(this); if (adSize.IsSmartBanner) { this.BannerViewPtr = Externs.GADUCreateSmartBannerView( this.bannerClientPtr, adUnitId, (int)position); } else { this.BannerViewPtr = Externs.GADUCreateBannerView( this.bannerClientPtr, adUnitId, adSize.Width, adSize.Height, (int)position); } Externs.GADUSetBannerCallbacks( this.BannerViewPtr, AdViewDidReceiveAdCallback, AdViewDidFailToReceiveAdWithErrorCallback, AdViewWillPresentScreenCallback, AdViewDidDismissScreenCallback, AdViewWillLeaveApplicationCallback); } // Loads an ad. public void LoadAd(AdRequest request) { IntPtr requestPtr = Utils.BuildAdRequest(request); Externs.GADURequestBannerAd(this.BannerViewPtr, requestPtr); Externs.GADURelease(requestPtr); } // Displays the banner view on the screen. public void ShowBannerView() { Externs.GADUShowBannerView(this.BannerViewPtr); } // Hides the banner view from the screen. public void HideBannerView() { Externs.GADUHideBannerView(this.BannerViewPtr); } // Destroys the banner view. public void DestroyBannerView() { Externs.GADURemoveBannerView(this.BannerViewPtr); this.BannerViewPtr = IntPtr.Zero; } public void Dispose() { this.DestroyBannerView(); ((GCHandle)this.bannerClientPtr).Free(); } ~BannerClient() { this.Dispose(); } #endregion #region Banner callback methods [MonoPInvokeCallback(typeof(GADUAdViewDidReceiveAdCallback))] private static void AdViewDidReceiveAdCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdLoaded != null) { client.OnAdLoaded(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAdViewDidFailToReceiveAdWithErrorCallback))] private static void AdViewDidFailToReceiveAdWithErrorCallback( IntPtr bannerClient, string error) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdFailedToLoad != null) { AdFailedToLoadEventArgs args = new AdFailedToLoadEventArgs() { Message = error }; client.OnAdFailedToLoad(client, args); } } [MonoPInvokeCallback(typeof(GADUAdViewWillPresentScreenCallback))] private static void AdViewWillPresentScreenCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdOpening != null) { client.OnAdOpening(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAdViewDidDismissScreenCallback))] private static void AdViewDidDismissScreenCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdClosed != null) { client.OnAdClosed(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAdViewWillLeaveApplicationCallback))] private static void AdViewWillLeaveApplicationCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdLeavingApplication != null) { client.OnAdLeavingApplication(client, EventArgs.Empty); } } private static BannerClient IntPtrToBannerClient(IntPtr bannerClient) { GCHandle handle = (GCHandle)bannerClient; return handle.Target as BannerClient; } #endregion } } #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.Buffers; using System.Collections.Generic; using System.Runtime.ConstrainedExecution; using System.Threading; namespace System.IO.Enumeration { public unsafe abstract partial class FileSystemEnumerator<TResult> : CriticalFinalizerObject, IEnumerator<TResult> { // The largest supported path on Unix is 4K bytes of UTF-8 (most only support 1K) private const int StandardBufferSize = 4096; private readonly string _originalRootDirectory; private readonly string _rootDirectory; private readonly EnumerationOptions _options; private readonly object _lock = new object(); private string _currentPath; private IntPtr _directoryHandle; private bool _lastEntryFound; private Queue<string> _pending; private Interop.Sys.DirectoryEntry _entry; private TResult _current; // Used for creating full paths private char[] _pathBuffer; // Used to get the raw entry data private byte[] _entryBuffer; private void Init() { // We need to initialize the directory handle up front to ensure // we immediately throw IO exceptions for missing directory/etc. _directoryHandle = CreateDirectoryHandle(_rootDirectory); if (_directoryHandle == IntPtr.Zero) _lastEntryFound = true; _currentPath = _rootDirectory; try { _pathBuffer = ArrayPool<char>.Shared.Rent(StandardBufferSize); int size = Interop.Sys.GetReadDirRBufferSize(); _entryBuffer = size > 0 ? ArrayPool<byte>.Shared.Rent(size) : null; } catch { // Close the directory handle right away if we fail to allocate CloseDirectoryHandle(); throw; } } private bool InternalContinueOnError(Interop.ErrorInfo info, bool ignoreNotFound = false) => (ignoreNotFound && IsDirectoryNotFound(info)) || (_options.IgnoreInaccessible && IsAccessError(info)) || ContinueOnError(info.RawErrno); private static bool IsDirectoryNotFound(Interop.ErrorInfo info) => info.Error == Interop.Error.ENOTDIR || info.Error == Interop.Error.ENOENT; private static bool IsAccessError(Interop.ErrorInfo info) => info.Error == Interop.Error.EACCES || info.Error == Interop.Error.EBADF || info.Error == Interop.Error.EPERM; private IntPtr CreateDirectoryHandle(string path, bool ignoreNotFound = false) { IntPtr handle = Interop.Sys.OpenDir(path); if (handle == IntPtr.Zero) { Interop.ErrorInfo info = Interop.Sys.GetLastErrorInfo(); if (InternalContinueOnError(info, ignoreNotFound)) { return IntPtr.Zero; } throw Interop.GetExceptionForIoErrno(info, path, isDirectory: true); } return handle; } private void CloseDirectoryHandle() { IntPtr handle = Interlocked.Exchange(ref _directoryHandle, IntPtr.Zero); if (handle != IntPtr.Zero) Interop.Sys.CloseDir(handle); } public bool MoveNext() { if (_lastEntryFound) return false; FileSystemEntry entry = default; lock (_lock) { if (_lastEntryFound) return false; // If HAVE_READDIR_R is defined for the platform FindNextEntry depends on _entryBuffer being fixed since // _entry will point to a string in the middle of the array. If the array is not fixed GC can move it after // the native call and _entry will point to a bogus file name. fixed (byte* entryBufferPtr = _entryBuffer) { do { FindNextEntry(entryBufferPtr, _entryBuffer == null ? 0 : _entryBuffer.Length); if (_lastEntryFound) return false; FileAttributes attributes = FileSystemEntry.Initialize( ref entry, _entry, _currentPath, _rootDirectory, _originalRootDirectory, new Span<char>(_pathBuffer)); bool isDirectory = (attributes & FileAttributes.Directory) != 0; bool isSpecialDirectory = false; if (isDirectory) { // Subdirectory found if (_entry.Name[0] == '.' && (_entry.Name[1] == 0 || (_entry.Name[1] == '.' && _entry.Name[2] == 0))) { // "." or "..", don't process unless the option is set if (!_options.ReturnSpecialDirectories) continue; isSpecialDirectory = true; } } if (!isSpecialDirectory && _options.AttributesToSkip != 0) { if ((_options.AttributesToSkip & FileAttributes.ReadOnly) != 0) { // ReadOnly is the only attribute that requires hitting entry.Attributes (which hits the disk) attributes = entry.Attributes; } if ((_options.AttributesToSkip & attributes) != 0) { continue; } } if (isDirectory && !isSpecialDirectory) { if (_options.RecurseSubdirectories && ShouldRecurseIntoEntry(ref entry)) { // Recursion is on and the directory was accepted, Queue it if (_pending == null) _pending = new Queue<string>(); _pending.Enqueue(Path.Join(_currentPath, entry.FileName)); } } if (ShouldIncludeEntry(ref entry)) { _current = TransformEntry(ref entry); return true; } } while (true); } } } private unsafe void FindNextEntry() { fixed (byte* entryBufferPtr = _entryBuffer) { FindNextEntry(entryBufferPtr, _entryBuffer == null ? 0 : _entryBuffer.Length); } } private unsafe void FindNextEntry(byte* entryBufferPtr, int bufferLength) { int result = Interop.Sys.ReadDirR(_directoryHandle, entryBufferPtr, bufferLength, out _entry); switch (result) { case -1: // End of directory DirectoryFinished(); break; case 0: // Success break; default: // Error if (InternalContinueOnError(new Interop.ErrorInfo(result))) { DirectoryFinished(); break; } else { throw Interop.GetExceptionForIoErrno(new Interop.ErrorInfo(result), _currentPath, isDirectory: true); } } } private bool DequeueNextDirectory() { // In Windows we open handles before we queue them, not after. If we fail to create the handle // but are ok with it (IntPtr.Zero), we don't queue them. Unix can't handle having a lot of // open handles, so we open after the fact. // // Doing the same on Windows would create a performance hit as we would no longer have the context // of the parent handle to open from. Keeping the parent handle open would increase the amount of // data we're maintaining, the number of active handles (they're not infinite), and the length // of time we have handles open (preventing some actions such as renaming/deleting/etc.). _directoryHandle = IntPtr.Zero; while (_directoryHandle == IntPtr.Zero) { if (_pending == null || _pending.Count == 0) return false; _currentPath = _pending.Dequeue(); _directoryHandle = CreateDirectoryHandle(_currentPath, ignoreNotFound: true); } return true; } private void InternalDispose(bool disposing) { // It is possible to fail to allocate the lock, but the finalizer will still run if (_lock != null) { lock (_lock) { _lastEntryFound = true; _pending = null; CloseDirectoryHandle(); if (_pathBuffer != null) ArrayPool<char>.Shared.Return(_pathBuffer); _pathBuffer = null; if (_entryBuffer != null) ArrayPool<byte>.Shared.Return(_entryBuffer); _entryBuffer = null; } } Dispose(disposing); } } }
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 frmBlockTestCode { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmBlockTestCode() : base() { KeyPress += frmBlockTestCode_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); Form_Initialize_Renamed(); } //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.Timer Timer1; public System.Windows.Forms.Button Command2; public System.Windows.Forms.Button Command1; public Microsoft.VisualBasic.Compatibility.VB6.DriveListBox Drive1; public System.Windows.Forms.CheckBox chkFields; public System.Windows.Forms.TextBox txtFields; private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _lblLabels_0; public System.Windows.Forms.Label _lblLabels_1; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.Label _lbl_5; //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //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(frmBlockTestCode)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.Timer1 = new System.Windows.Forms.Timer(components); this.Command2 = new System.Windows.Forms.Button(); this.Command1 = new System.Windows.Forms.Button(); //Me.Drive1 = New Microsoft.VisualBasic.Compatibility.VB6.DriveListBox this.chkFields = new System.Windows.Forms.CheckBox(); this.txtFields = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this._lblLabels_0 = new System.Windows.Forms.Label(); this._lblLabels_1 = new System.Windows.Forms.Label(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._lbl_5 = new System.Windows.Forms.Label(); //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "4MEAT Registration"; this.ClientSize = new System.Drawing.Size(345, 120); this.Location = new System.Drawing.Point(73, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmBlockTestCode"; this.Timer1.Interval = 1; this.Timer1.Enabled = true; this.Command2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Command2.Text = "Close CD Tray and Register"; this.Command2.Size = new System.Drawing.Size(151, 19); this.Command2.Location = new System.Drawing.Point(184, 256); this.Command2.TabIndex = 10; this.Command2.BackColor = System.Drawing.SystemColors.Control; this.Command2.CausesValidation = true; this.Command2.Enabled = true; this.Command2.ForeColor = System.Drawing.SystemColors.ControlText; this.Command2.Cursor = System.Windows.Forms.Cursors.Default; this.Command2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command2.TabStop = true; this.Command2.Name = "Command2"; this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Command1.Text = "Open"; this.Command1.Size = new System.Drawing.Size(59, 19); this.Command1.Location = new System.Drawing.Point(216, 280); this.Command1.TabIndex = 8; this.Command1.BackColor = System.Drawing.SystemColors.Control; this.Command1.CausesValidation = true; this.Command1.Enabled = true; this.Command1.ForeColor = System.Drawing.SystemColors.ControlText; this.Command1.Cursor = System.Windows.Forms.Cursors.Default; this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command1.TabStop = true; this.Command1.Name = "Command1"; //Me.Drive1.Enabled = False //Me.Drive1.Size = New System.Drawing.Size(111, 21) //Me.Drive1.Location = New System.Drawing.Point(64, 256) //Me.Drive1.TabIndex = 7 //Me.Drive1.BackColor = System.Drawing.SystemColors.Window //Me.Drive1.CausesValidation = True //Me.Drive1.ForeColor = System.Drawing.SystemColors.WindowText //Me.Drive1.Cursor = System.Windows.Forms.Cursors.Default //Me.Drive1.TabStop = True //Me.Drive1.Visible = True //Me.Drive1.Name = "Drive1" this.chkFields.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkFields.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkFields.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.chkFields.Text = "Manual :"; this.chkFields.ForeColor = System.Drawing.SystemColors.WindowText; this.chkFields.Size = new System.Drawing.Size(68, 17); this.chkFields.Location = new System.Drawing.Point(264, 231); this.chkFields.TabIndex = 2; this.chkFields.CausesValidation = true; this.chkFields.Enabled = true; this.chkFields.Cursor = System.Windows.Forms.Cursors.Default; this.chkFields.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkFields.Appearance = System.Windows.Forms.Appearance.Normal; this.chkFields.TabStop = true; this.chkFields.CheckState = System.Windows.Forms.CheckState.Unchecked; this.chkFields.Visible = true; this.chkFields.Name = "chkFields"; this.txtFields.AutoSize = false; this.txtFields.BackColor = System.Drawing.Color.White; this.txtFields.Font = new System.Drawing.Font("Arial", 12f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.txtFields.Size = new System.Drawing.Size(270, 27); this.txtFields.ImeMode = System.Windows.Forms.ImeMode.Disable; this.txtFields.Location = new System.Drawing.Point(64, 76); this.txtFields.TabIndex = 1; this.txtFields.AcceptsReturn = true; this.txtFields.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtFields.CausesValidation = true; this.txtFields.Enabled = true; this.txtFields.ForeColor = System.Drawing.SystemColors.WindowText; this.txtFields.HideSelection = true; this.txtFields.ReadOnly = false; this.txtFields.MaxLength = 0; this.txtFields.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtFields.Multiline = false; this.txtFields.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtFields.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtFields.TabStop = true; this.txtFields.Visible = true; this.txtFields.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFields.Name = "txtFields"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(345, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 6; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.TabIndex = 5; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "N&ext"; this.cmdClose.Size = new System.Drawing.Size(81, 29); this.cmdClose.Location = new System.Drawing.Point(256, 2); this.cmdClose.TabIndex = 4; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_0.BackColor = System.Drawing.Color.Transparent; this._lblLabels_0.Text = "CD Drive :"; this._lblLabels_0.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_0.Size = new System.Drawing.Size(49, 13); this._lblLabels_0.Location = new System.Drawing.Point(8, 258); this._lblLabels_0.TabIndex = 9; this._lblLabels_0.Enabled = true; this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_0.UseMnemonic = true; this._lblLabels_0.Visible = true; this._lblLabels_0.AutoSize = true; this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_0.Name = "_lblLabels_0"; this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_1.BackColor = System.Drawing.Color.Transparent; this._lblLabels_1.Text = "CD Key :"; this._lblLabels_1.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblLabels_1.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_1.Size = new System.Drawing.Size(51, 16); this._lblLabels_1.Location = new System.Drawing.Point(8, 79); this._lblLabels_1.TabIndex = 0; this._lblLabels_1.Enabled = true; this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_1.UseMnemonic = true; this._lblLabels_1.Visible = true; this._lblLabels_1.AutoSize = true; this._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_1.Name = "_lblLabels_1"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(338, 49); this._Shape1_2.Location = new System.Drawing.Point(4, 64); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Text = "Please type in your 4MEAT CD Key. [ without dashes ]"; this._lbl_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_5.Size = new System.Drawing.Size(333, 21); this._lbl_5.Location = new System.Drawing.Point(6, 48); this._lbl_5.TabIndex = 3; this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_5.Enabled = true; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.UseMnemonic = true; this._lbl_5.Visible = true; this._lbl_5.AutoSize = false; this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_5.Name = "_lbl_5"; this.Controls.Add(Command2); this.Controls.Add(Command1); //Me.Controls.Add(Drive1) this.Controls.Add(chkFields); this.Controls.Add(txtFields); this.Controls.Add(picButtons); this.Controls.Add(_lblLabels_0); this.Controls.Add(_lblLabels_1); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.Controls.Add(_lbl_5); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdCancel); this.picButtons.Controls.Add(cmdClose); //Me.lbl.SetIndex(_lbl_5, CType(5, Short)) //Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short)) //Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short)) this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.1434 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.ProviderControls { public partial class SmarterMail50_EditDomain { /// <summary> /// lblCatchAll control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblCatchAll; /// <summary> /// ddlCatchAllAccount control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlCatchAllAccount; /// <summary> /// AdvancedSettingsPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel AdvancedSettingsPanel; /// <summary> /// secFeatures control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secFeatures; /// <summary> /// FeaturesPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel FeaturesPanel; /// <summary> /// featuresSection control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ProviderControls.SmarterMail50_EditDomain_Features featuresSection; /// <summary> /// secSharing control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secSharing; /// <summary> /// SharingPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel SharingPanel; /// <summary> /// sharingSection control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ProviderControls.SmarterMail50_EditDomain_Sharing sharingSection; /// <summary> /// secThrottling control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secThrottling; /// <summary> /// ThrottlingPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel ThrottlingPanel; /// <summary> /// throttlingSection control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ProviderControls.SmarterMail50_EditDomain_Throttling throttlingSection; /// <summary> /// secLimits control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secLimits; /// <summary> /// LimitsPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel LimitsPanel; /// <summary> /// lblDomainDiskSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblDomainDiskSpace; /// <summary> /// txtSize control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtSize; /// <summary> /// valDomainDiskSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valDomainDiskSpace; /// <summary> /// reqValDiskSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValDiskSpace; /// <summary> /// lblDomainAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblDomainAliases; /// <summary> /// txtDomainAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtDomainAliases; /// <summary> /// valDomainAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valDomainAliases; /// <summary> /// reqValDomainAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValDomainAliases; /// <summary> /// lblUserQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblUserQuota; /// <summary> /// txtUser control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtUser; /// <summary> /// valUser control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valUser; /// <summary> /// reqValUser control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValUser; /// <summary> /// lblUserAliasesQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblUserAliasesQuota; /// <summary> /// txtUserAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtUserAliases; /// <summary> /// valUserAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valUserAliases; /// <summary> /// reqValUserAliases control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValUserAliases; /// <summary> /// lblMailingListsQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblMailingListsQuota; /// <summary> /// txtMailingLists control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtMailingLists; /// <summary> /// valMailingLists control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valMailingLists; /// <summary> /// reqValMailingLists control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValMailingLists; /// <summary> /// lblPopRetreivalAccounts control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblPopRetreivalAccounts; /// <summary> /// txtPopRetreivalAccounts control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPopRetreivalAccounts; /// <summary> /// valPopRetreivalAccounts control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valPopRetreivalAccounts; /// <summary> /// reqPopRetreivalAccounts control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqPopRetreivalAccounts; /// <summary> /// lblMessageSizeQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblMessageSizeQuota; /// <summary> /// txtMessageSize control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtMessageSize; /// <summary> /// valMessageSize control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valMessageSize; /// <summary> /// reqValMessageSize control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValMessageSize; /// <summary> /// lblRecipientsPerMessageQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblRecipientsPerMessageQuota; /// <summary> /// txtRecipientsPerMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtRecipientsPerMessage; /// <summary> /// valRecipientsPerMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator valRecipientsPerMessage; /// <summary> /// reqValRecipientsPerMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator reqValRecipientsPerMessage; } }
using BaseHarvest = Landis.Harvest; using Edu.Wisc.Forest.Flel.Util; using Landis.Extensions.BiomassHarvest; using NUnit.Framework; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace Landis.Tests.BiomassHarvest { [TestFixture] public class ParametersParser_Test { private Species.IDataset speciesDataset; private const int startTime = 1950; private const int endTime = 2400; private ParametersParser parser; private LineReader reader; //--------------------------------------------------------------------- [TestFixtureSetUp] public void Init() { Species.DatasetParser speciesParser = new Species.DatasetParser(); reader = OpenFile("Species.txt"); try { speciesDataset = speciesParser.Parse(reader); } finally { reader.Close(); } parser = new ParametersParser(speciesDataset, startTime, endTime); } //--------------------------------------------------------------------- [TestFixtureTearDown] public void TearDown() { // Unsubscribe from the event (static ctor of parser class // subscribes to the event) PartialThinning.ReadAgeOrRangeEvent -= ParametersParser.AgeOrRangeWasRead; } //--------------------------------------------------------------------- private FileLineReader OpenFile(string filename) { string path = Data.MakeInputPath(filename); return Landis.Data.OpenTextFile(path); } //--------------------------------------------------------------------- private BaseHarvest.IParameters ParseFile(string filename) { try { reader = OpenFile(filename); return parser.Parse(reader); } finally { reader.Close(); } } //--------------------------------------------------------------------- private string GetFileAssociatedWithTest(StackFrame currentTest) { // Get the name of the input file associated with the test that's // currently running. The file's name is "{test}.txt". MethodBase testMethod = currentTest.GetMethod(); string testName = testMethod.Name; string filename = testName + ".txt"; return filename; } //--------------------------------------------------------------------- private BaseHarvest.IParameters ParseGoodFile(string filename) { BaseHarvest.IParameters parameters = ParseFile(filename); Assert.IsNotNull(parameters); Assert.IsNotNull(parser.RoundedRepeatIntervals); Assert.AreEqual(1, parser.RoundedRepeatIntervals.Count); AssertAreEqual(new BaseHarvest.RoundedInterval(15, 20, 37), parser.RoundedRepeatIntervals[0]); return parameters; } //--------------------------------------------------------------------- [Test] public void GoodFile() { string filename = GetFileAssociatedWithTest(new StackFrame(0)); ParseGoodFile(filename); } //--------------------------------------------------------------------- [Test] public void GoodFile_BiomassMaps() { string filename = GetFileAssociatedWithTest(new StackFrame(0)); BaseHarvest.IParameters baseHarvestParams = ParseGoodFile(filename); IParameters parameters = baseHarvestParams as IParameters; Assert.IsNotNull(parameters); Assert.IsNotNull(parameters.BiomassMapNames); } //--------------------------------------------------------------------- private void AssertAreEqual(BaseHarvest.RoundedInterval expected, BaseHarvest.RoundedInterval actual) { Assert.AreEqual(expected.Original, actual.Original); Assert.AreEqual(expected.Adjusted, actual.Adjusted); Assert.AreEqual(expected.LineNumber, actual.LineNumber); } //--------------------------------------------------------------------- private void TryParse(string filename) { int? errorLineNum = Testing.FindErrorMarker(Data.MakeInputPath(filename)); try { reader = OpenFile(filename); BaseHarvest.IParameters parameters = parser.Parse(reader); } catch (System.Exception e) { Data.Output.WriteLine(); Data.Output.WriteLine(e.Message.Replace(Data.Directory, Data.DirPlaceholder)); LineReaderException lrExc = e as LineReaderException; if (lrExc != null && errorLineNum.HasValue) Assert.AreEqual(errorLineNum.Value, lrExc.LineNumber); throw; } finally { reader.Close(); } } //--------------------------------------------------------------------- private void TryParseFileAssociatedWithTest() { // This line: // // string filename = GetFileAssociatedWithTest(new StackFrame(1)); // // doesn't work with the release configuration. MethodBase testMethod = new StackFrame(1).GetMethod(); string testName = testMethod.Name; string filename = testName + ".txt"; TryParse(filename); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void LandisData_WrongValue() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Timestep_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Timestep_Negative() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void ManagementAreas_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void ManagementAreas_Empty() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void ManagementAreas_Whitespace() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Stands_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Stands_Empty() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Stands_Whitespace() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Prescription_NameMissing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Prescription_NameRepeated() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void StandRanking_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void StandRanking_Unknown() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_Empty() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_SpeciesUnknown() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_SpeciesRepeated() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_RankMissing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_RankBad() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_RankMoreThanMax() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_AgeMissing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_AgeBad() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_AgeTooBig() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_AgeNegative() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EconomicRankTable_Extra() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void RankingRequirement_MinAge_TooBig() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void RankingRequirement_MaxAge_Negative() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void RankingRequirement_MaxLessThanMin() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_MissingValue() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Unknown() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Complete_Extra() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_CompleteSpread_NoSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_CompleteSpread_BadSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_CompleteSpread_Negative() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_CompleteSpread_Extra() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_TargetSize_NoSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_TargetSize_BadSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_TargetSize_Negative() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_TargetSize_NotImplemented() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_TargetSize_Extra() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_NoPercentage() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_BadPercentage() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_PercentageTooBig() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_NoSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_BadSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_NegativeSize() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_Extra() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SiteSelection_Patch_NotImplemented() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_Unknown() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_None() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_UnknownSpecies() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_RepeatedSpecies() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_JustSpecies() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_ExtraAfterAll() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_Nis0() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_NisMissing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_NisBad() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_ExtraAfter1OverN() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_Age0() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_AgeBad() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_NoStart() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_NoEnd() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_StartBad() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_Start0() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_StartAfterEnd() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_EndBad() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_EndTooBig() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_AgeRepeated() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_AgeInRange() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_RangesOverlap() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void CohortSelection_SpeciesList_RangeContainsAge() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Plant_NoSpecies() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Plant_UnknownSpecies() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void Plant_RepeatedSpecies() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void SingleRepeat_NoCohortsRemoved() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void MultipleRepeat_CohortsRemoved() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_MgmtArea_CodeTooBig() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_MgmtArea_NegativeCode() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Prescription_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Prescription_AppliedTwice() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Prescription_Unknown() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Area_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Area_Negative() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Area_TooBig() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_BeginTime_BeforeScenarioStart() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_BeginTime_AfterScenarioEnd() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_EndTime_BeforeBeginTime() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_EndTime_AfterScenarioEnd() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void HarvestImpl_Extra() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void PrescriptionMaps_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void PrescriptionMaps_NoTimestep() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void BiomassMaps_NoTimestep() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EventLog_Missing() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EventLog_Empty() { TryParseFileAssociatedWithTest(); } //--------------------------------------------------------------------- [Test] [ExpectedException(typeof(LineReaderException))] public void EventLog_Whitespace() { TryParseFileAssociatedWithTest(); } } }
namespace Kinare.FormSystem.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class Initial_Migration : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), ImpersonatorUserId = c.Long(), ImpersonatorTenantId = c.Int(), CustomData = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true) .Index(t => t.EditionId); CreateTable( "dbo.AbpEditions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguages", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 10), DisplayName = c.String(nullable: false, maxLength: 64), Icon = c.String(maxLength: 128), IsDisabled = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguageTexts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), LanguageName = c.String(nullable: false, maxLength: 10), Source = c.String(nullable: false, maxLength: 128), Key = c.String(nullable: false, maxLength: 256), Value = c.String(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), ParentId = c.Long(), Code = c.String(nullable: false, maxLength: 95), DisplayName = c.String(nullable: false, maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), Description = c.String(), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), AuthenticationSource = c.String(maxLength: 64), UserName = c.String(nullable: false, maxLength: 32), TenantId = c.Int(), EmailAddress = c.String(nullable: false, maxLength: 256), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), EmailConfirmationCode = c.String(maxLength: 328), PasswordResetCode = c.String(maxLength: 328), LockoutEndDateUtc = c.DateTime(), AccessFailedCount = c.Int(nullable: false), IsLockoutEnabled = c.Boolean(nullable: false), PhoneNumber = c.String(), IsPhoneNumberConfirmed = c.Boolean(nullable: false), SecurityStamp = c.String(), IsTwoFactorEnabled = c.Boolean(nullable: false), IsEmailConfirmed = c.Boolean(nullable: false), IsActive = c.Boolean(nullable: false), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserClaims", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), EditionId = c.Int(), Name = c.String(nullable: false, maxLength: 128), TenancyName = c.String(nullable: false, maxLength: 64), ConnectionString = c.String(maxLength: 1024), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpEditions", t => t.EditionId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.EditionId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserAccounts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), UserLinkId = c.Long(), UserName = c.String(), EmailAddress = c.String(), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.TenantId }) .Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), TenantNotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); CreateTable( "dbo.AbpUserOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), OrganizationUnitId = c.Long(nullable: false), IsDeleted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserOrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits"); DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions"); DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpTenants", new[] { "EditionId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUserClaims", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpFeatures", new[] { "EditionId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserOrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLoginAttempts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserAccounts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLogins", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserClaims", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotificationSubscriptions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpLanguageTexts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpLanguages", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpEditions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpFeatures", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpBackgroundJobs"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.Collections; using System.Globalization; using System.Text; using System.IO; using System.Diagnostics; internal sealed partial class Parser { private SchemaType _schemaType; private XmlNameTable _nameTable; private SchemaNames _schemaNames; private ValidationEventHandler _eventHandler; private XmlNamespaceManager _namespaceManager; private XmlReader _reader; private PositionInfo _positionInfo; private bool _isProcessNamespaces; private int _schemaXmlDepth = 0; private int _markupDepth; private SchemaBuilder _builder; private XmlSchema _schema; private SchemaInfo _xdrSchema; private XmlResolver _xmlResolver = null; //to be used only by XDRBuilder //xs:Annotation perf fix private XmlDocument _dummyDocument; private bool _processMarkup; private XmlNode _parentNode; private XmlNamespaceManager _annotationNSManager; private string _xmlns; //Whitespace check for text nodes private XmlCharType _xmlCharType = XmlCharType.Instance; public Parser(SchemaType schemaType, XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler) { _schemaType = schemaType; _nameTable = nameTable; _schemaNames = schemaNames; _eventHandler = eventHandler; _xmlResolver = System.Xml.XmlConfiguration.XmlReaderSection.CreateDefaultResolver(); _processMarkup = true; _dummyDocument = new XmlDocument(); } public SchemaType Parse(XmlReader reader, string targetNamespace) { StartParsing(reader, targetNamespace); while (ParseReaderNode() && reader.Read()) { } return FinishParsing(); } public void StartParsing(XmlReader reader, string targetNamespace) { _reader = reader; _positionInfo = PositionInfo.GetPositionInfo(reader); _namespaceManager = reader.NamespaceManager; if (_namespaceManager == null) { _namespaceManager = new XmlNamespaceManager(_nameTable); _isProcessNamespaces = true; } else { _isProcessNamespaces = false; } while (reader.NodeType != XmlNodeType.Element && reader.Read()) { } _markupDepth = int.MaxValue; _schemaXmlDepth = reader.Depth; SchemaType rootType = _schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI); string code; if (!CheckSchemaRoot(rootType, out code)) { throw new XmlSchemaException(code, reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition); } if (_schemaType == SchemaType.XSD) { _schema = new XmlSchema(); _schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute); _builder = new XsdBuilder(reader, _namespaceManager, _schema, _nameTable, _schemaNames, _eventHandler); } else { Debug.Assert(_schemaType == SchemaType.XDR); _xdrSchema = new SchemaInfo(); _xdrSchema.SchemaType = SchemaType.XDR; _builder = new XdrBuilder(reader, _namespaceManager, _xdrSchema, targetNamespace, _nameTable, _schemaNames, _eventHandler); ((XdrBuilder)_builder).XmlResolver = _xmlResolver; } } private bool CheckSchemaRoot(SchemaType rootType, out string code) { code = null; if (_schemaType == SchemaType.None) { _schemaType = rootType; } switch (rootType) { case SchemaType.XSD: if (_schemaType != SchemaType.XSD) { code = SR.Sch_MixSchemaTypes; return false; } break; case SchemaType.XDR: if (_schemaType == SchemaType.XSD) { code = SR.Sch_XSDSchemaOnly; return false; } else if (_schemaType != SchemaType.XDR) { code = SR.Sch_MixSchemaTypes; return false; } break; case SchemaType.DTD: //Did not detect schema type that can be parsed by this parser case SchemaType.None: code = SR.Sch_SchemaRootExpected; if (_schemaType == SchemaType.XSD) { code = SR.Sch_XSDSchemaRootExpected; } return false; default: Debug.Assert(false); break; } return true; } public SchemaType FinishParsing() { return _schemaType; } public XmlSchema XmlSchema { get { return _schema; } } internal XmlResolver XmlResolver { set { _xmlResolver = value; } } public SchemaInfo XdrSchema { get { return _xdrSchema; } } public bool ParseReaderNode() { if (_reader.Depth > _markupDepth) { if (_processMarkup) { ProcessAppInfoDocMarkup(false); } return true; } else if (_reader.NodeType == XmlNodeType.Element) { if (_builder.ProcessElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI)) { _namespaceManager.PushScope(); if (_reader.MoveToFirstAttribute()) { do { _builder.ProcessAttribute(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _reader.Value); if (Ref.Equal(_reader.NamespaceURI, _schemaNames.NsXmlNs) && _isProcessNamespaces) { _namespaceManager.AddNamespace(_reader.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); // get back to the element } _builder.StartChildren(); if (_reader.IsEmptyElement) { _namespaceManager.PopScope(); _builder.EndChildren(); if (_reader.Depth == _schemaXmlDepth) { return false; // done } } else if (!_builder.IsContentParsed()) { //AppInfo and Documentation _markupDepth = _reader.Depth; _processMarkup = true; if (_annotationNSManager == null) { _annotationNSManager = new XmlNamespaceManager(_nameTable); _xmlns = _nameTable.Add("xmlns"); } ProcessAppInfoDocMarkup(true); } } else if (!_reader.IsEmptyElement) { //UnsupportedElement in that context _markupDepth = _reader.Depth; _processMarkup = false; //Hack to not process unsupported elements } } else if (_reader.NodeType == XmlNodeType.Text) { //Check for whitespace if (!_xmlCharType.IsOnlyWhitespace(_reader.Value)) { _builder.ProcessCData(_reader.Value); } } else if (_reader.NodeType == XmlNodeType.EntityReference || _reader.NodeType == XmlNodeType.SignificantWhitespace || _reader.NodeType == XmlNodeType.CDATA) { _builder.ProcessCData(_reader.Value); } else if (_reader.NodeType == XmlNodeType.EndElement) { if (_reader.Depth == _markupDepth) { if (_processMarkup) { Debug.Assert(_parentNode != null); XmlNodeList list = _parentNode.ChildNodes; XmlNode[] markup = new XmlNode[list.Count]; for (int i = 0; i < list.Count; i++) { markup[i] = list[i]; } _builder.ProcessMarkup(markup); _namespaceManager.PopScope(); _builder.EndChildren(); } _markupDepth = int.MaxValue; } else { _namespaceManager.PopScope(); _builder.EndChildren(); } if (_reader.Depth == _schemaXmlDepth) { return false; // done } } return true; } private void ProcessAppInfoDocMarkup(bool root) { //First time reader is positioned on AppInfo or Documentation element XmlNode currentNode = null; switch (_reader.NodeType) { case XmlNodeType.Element: _annotationNSManager.PushScope(); currentNode = LoadElementNode(root); // Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute // was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form // although it does not change the semantic meaning of the schema. // Since it is as a breaking change and Dev10 needs to maintain the backward compatibility, this fix is being reverted. // if (reader.IsEmptyElement) { // annotationNSManager.PopScope(); // } break; case XmlNodeType.Text: currentNode = _dummyDocument.CreateTextNode(_reader.Value); goto default; case XmlNodeType.SignificantWhitespace: currentNode = _dummyDocument.CreateSignificantWhitespace(_reader.Value); goto default; case XmlNodeType.CDATA: currentNode = _dummyDocument.CreateCDataSection(_reader.Value); goto default; case XmlNodeType.EntityReference: currentNode = _dummyDocument.CreateEntityReference(_reader.Name); goto default; case XmlNodeType.Comment: currentNode = _dummyDocument.CreateComment(_reader.Value); goto default; case XmlNodeType.ProcessingInstruction: currentNode = _dummyDocument.CreateProcessingInstruction(_reader.Name, _reader.Value); goto default; case XmlNodeType.EndEntity: break; case XmlNodeType.Whitespace: break; case XmlNodeType.EndElement: _annotationNSManager.PopScope(); _parentNode = _parentNode.ParentNode; break; default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc Debug.Assert(currentNode != null); Debug.Assert(_parentNode != null); _parentNode.AppendChild(currentNode); break; } } private XmlElement LoadElementNode(bool root) { Debug.Assert(_reader.NodeType == XmlNodeType.Element); XmlReader r = _reader; bool fEmptyElement = r.IsEmptyElement; XmlElement element = _dummyDocument.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); element.IsEmpty = fEmptyElement; if (root) { _parentNode = element; } else { XmlAttributeCollection attributes = element.Attributes; if (r.MoveToFirstAttribute()) { do { if (Ref.Equal(r.NamespaceURI, _schemaNames.NsXmlNs)) { //Namespace Attribute _annotationNSManager.AddNamespace(r.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } XmlAttribute attr = LoadAttributeNode(); attributes.Append(attr); } while (r.MoveToNextAttribute()); } r.MoveToElement(); string ns = _annotationNSManager.LookupNamespace(r.Prefix); if (ns == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } else if (ns.Length == 0) { //string.Empty prefix is mapped to string.Empty NS by default string elemNS = _namespaceManager.LookupNamespace(r.Prefix); if (elemNS != string.Empty) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, elemNS); attributes.Append(attr); } } while (r.MoveToNextAttribute()) { if (r.Prefix.Length != 0) { string attNS = _annotationNSManager.LookupNamespace(r.Prefix); if (attNS == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } } } r.MoveToElement(); _parentNode.AppendChild(element); if (!r.IsEmptyElement) { _parentNode = element; } } return element; } private XmlAttribute CreateXmlNsAttribute(string prefix, string value) { XmlAttribute attr; if (prefix.Length == 0) { attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs); } else { attr = _dummyDocument.CreateAttribute(_xmlns, prefix, XmlReservedNs.NsXmlNs); } attr.AppendChild(_dummyDocument.CreateTextNode(value)); _annotationNSManager.AddNamespace(prefix, value); return attr; } private XmlAttribute LoadAttributeNode() { Debug.Assert(_reader.NodeType == XmlNodeType.Attribute); XmlReader r = _reader; XmlAttribute attr = _dummyDocument.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); while (r.ReadAttributeValue()) { switch (r.NodeType) { case XmlNodeType.Text: attr.AppendChild(_dummyDocument.CreateTextNode(r.Value)); continue; case XmlNodeType.EntityReference: attr.AppendChild(LoadEntityReferenceInAttribute()); continue; default: throw XmlLoader.UnexpectedNodeType(r.NodeType); } } return attr; } private XmlEntityReference LoadEntityReferenceInAttribute() { Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference); XmlEntityReference eref = _dummyDocument.CreateEntityReference(_reader.LocalName); if (!_reader.CanResolveEntity) { return eref; } _reader.ResolveEntity(); while (_reader.ReadAttributeValue()) { switch (_reader.NodeType) { case XmlNodeType.Text: eref.AppendChild(_dummyDocument.CreateTextNode(_reader.Value)); continue; case XmlNodeType.EndEntity: if (eref.ChildNodes.Count == 0) { eref.AppendChild(_dummyDocument.CreateTextNode(String.Empty)); } return eref; case XmlNodeType.EntityReference: eref.AppendChild(LoadEntityReferenceInAttribute()); break; default: throw XmlLoader.UnexpectedNodeType(_reader.NodeType); } } return eref; } }; } // namespace System.Xml
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MessageProperties.cs" company="The original author or authors."> // Copyright 2002-2012 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #region Using Directives using System; using System.Collections.Generic; #endregion namespace Spring.Messaging.Amqp.Core { /// <summary> /// Message Properties for an AMQP message. /// </summary> /// <author>Mark Fisher</author> /// <author>Mark Pollack</author> /// <author>Gary Russell</author> /// <author>Joe Fitzgerald (.NET)</author> public class MessageProperties { public static readonly string CONTENT_TYPE_BYTES = @"application/octet-stream"; public static readonly string CONTENT_TYPE_TEXT_PLAIN = @"text/plain"; // TODO: Need to determine correct MIME type for this. We're not serializing java objects. public static readonly string CONTENT_TYPE_SERIALIZED_OBJECT = @"application/x-java-serialized-object"; public static readonly string CONTENT_TYPE_JSON = @"application/json"; public static readonly string CONTENT_TYPE_XML = @"application/xml"; private static readonly string DEFAULT_CONTENT_TYPE = CONTENT_TYPE_BYTES; private static readonly MessageDeliveryMode DEFAULT_DELIVERY_MODE = MessageDeliveryMode.Persistent; private static readonly int DEFAULT_PRIORITY = 0; private readonly IDictionary<string, object> headers = new Dictionary<string, object>(); private DateTime timestamp; private volatile string messageId; private volatile string userId; private volatile string appId; private volatile string clusterId; private volatile string type; private volatile byte[] correlationId; private volatile string replyTo; private volatile string contentType = DEFAULT_CONTENT_TYPE; private volatile string contentEncoding; private long contentLength; private volatile MessageDeliveryMode deliveryMode = DEFAULT_DELIVERY_MODE; private volatile string expiration; private volatile int priority = DEFAULT_PRIORITY; private volatile bool redelivered; private volatile string receivedExchange; private volatile string receivedRoutingKey; private long deliveryTag; private volatile int messageCount; /// <summary>The set header.</summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void SetHeader(string key, object value) { if (this.headers.ContainsKey(key)) { this.headers[key] = value; return; } this.headers.Add(key, value); } /// <summary> /// Gets Headers. /// </summary> public IDictionary<string, object> Headers { get { return this.headers; } } /// <summary> /// Gets or sets Timestamp. /// </summary> public DateTime Timestamp { get { return this.timestamp; } set { this.timestamp = value; } } /// <summary> /// Gets or sets MessageId. /// </summary> public string MessageId { get { return this.messageId; } set { this.messageId = value; } } /// <summary> /// Gets or sets UserId. /// </summary> public string UserId { get { return this.userId; } set { this.userId = value; } } /// <summary> /// Gets or sets AppId. /// </summary> public string AppId { get { return this.appId; } set { this.appId = value; } } /// <summary> /// Gets or sets ClusterId. /// </summary> public string ClusterId { get { return this.clusterId; } set { this.clusterId = value; } } /// <summary> /// Gets or sets Type. /// </summary> public string Type { get { return this.type; } set { this.type = value; } } /// <summary> /// Gets or sets CorrelationId. /// </summary> public byte[] CorrelationId { get { return this.correlationId; } set { this.correlationId = value; } } /// <summary> /// Gets or sets the reply to. /// </summary> /// <value>The reply to.</value> public string ReplyTo { get { return this.replyTo; } set { this.replyTo = value; } } /// <summary> /// Gets or sets reply to address. /// </summary> /// <value>The reply to address.</value> public Address ReplyToAddress { get { return string.IsNullOrEmpty(this.replyTo) ? null : new Address(this.replyTo); } set { this.replyTo = value == null ? string.Empty : value.ToString(); } } /// <summary> /// Gets or sets ContentType. /// </summary> public string ContentType { get { return this.contentType; } set { this.contentType = value; } } /// <summary> /// Gets or sets ContentEncoding. /// </summary> public string ContentEncoding { get { return this.contentEncoding; } set { this.contentEncoding = value; } } /// <summary> /// Gets or sets ContentLength. /// </summary> public long ContentLength { get { return this.contentLength; } set { this.contentLength = value; } } /// <summary> /// Gets or sets DeliveryMode. /// </summary> public MessageDeliveryMode DeliveryMode { get { return this.deliveryMode; } set { this.deliveryMode = value; } } /// <summary> /// Gets or sets Expiration. /// </summary> public string Expiration { get { return this.expiration; } set { this.expiration = value; } } /// <summary> /// Gets or sets Priority. /// </summary> public int Priority { get { return this.priority; } set { this.priority = value; } } /// <summary> /// Gets or sets ReceivedExchange. /// </summary> public string ReceivedExchange { get { return this.receivedExchange; } set { this.receivedExchange = value; } } /// <summary> /// Gets or sets ReceivedRoutingKey. /// </summary> public string ReceivedRoutingKey { get { return this.receivedRoutingKey; } set { this.receivedRoutingKey = value; } } /// <summary> /// Gets or sets a value indicating whether Redelivered. /// </summary> public bool Redelivered { get { return this.redelivered; } set { this.redelivered = value; } } /// <summary> /// Gets or sets DeliveryTag. /// </summary> public long DeliveryTag { get { return this.deliveryTag; } set { this.deliveryTag = value; } } /// <summary> /// Gets or sets MessageCount. /// </summary> public int MessageCount { get { return this.messageCount; } set { this.messageCount = value; } } } }
// // Copyright (c) Microsoft. 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 Xunit; using System.Net; using System.Net.Http; using Microsoft.Azure.Management.Batch; using Microsoft.Azure.Management.Batch.Models; using Batch.Tests.Helpers; namespace Microsoft.Azure.Batch.Tests { public class InMemoryAccountTests { public BatchManagementClient GetBatchManagementClient(RecordedDelegatingHandler handler) { var certCreds = new CertificateCloudCredentials(Guid.NewGuid().ToString(), new System.Security.Cryptography.X509Certificates.X509Certificate2()); handler.IsPassThrough = false; return new BatchManagementClient(certCreds).WithHandler(handler); } [Fact] public void AccountActionsListValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"[ { 'action': 'Microsoft.Batch/ListKeys', 'friendlyName' : 'List Batch Account Keys', 'friendlyTarget' : 'Batch Account', 'friendlyDescription' : 'List Batch account keys including both primary key and secondary key.' }, { 'action': 'Microsoft.Batch/RegenerateKeys', 'friendlyName' : 'Regenerate Batch account key', 'friendlyTarget' : 'Batch Account', 'friendlyDescription' : 'Regenerate the specified Batch account key.' } ]") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetBatchManagementClient(handler); var result = client.Accounts.ListActions(); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); Assert.Equal(result.Actions[0].Action, "Microsoft.Batch/ListKeys"); Assert.Equal(result.Actions[0].FriendlyName, "List Batch Account Keys"); Assert.Equal(result.Actions[0].FriendlyTarget, "Batch Account"); Assert.True(result.Actions[0].FriendlyDescription.StartsWith("List Batch account keys")); Assert.Equal(result.Actions[1].Action, "Microsoft.Batch/RegenerateKeys"); Assert.Equal(result.Actions[1].FriendlyName, "Regenerate Batch account key"); Assert.Equal(result.Actions[1].FriendlyTarget, "Batch Account"); Assert.True(result.Actions[1].FriendlyDescription.StartsWith("Regenerate the specified")); } [Fact] public void AccountCreateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.Create(null, "bar", new BatchAccountCreateParameters())); Assert.Throws<ArgumentNullException>(() => client.Accounts.Create("foo", null, new BatchAccountCreateParameters())); Assert.Throws<ArgumentNullException>(() => client.Accounts.Create("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("invalid+", "account", new BatchAccountCreateParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "invalid%", new BatchAccountCreateParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "/invalid", new BatchAccountCreateParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "s", new BatchAccountCreateParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "account_name_that_is_too_long", new BatchAccountCreateParameters())); } [Fact] public void AccountCreateAsyncValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse }); var client = GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.Accounts.Create("foo", "acctName", new BatchAccountCreateParameters { Location = "South Central US", Tags = tags }); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Put, handler.Requests[0].Method); Assert.NotNull(handler.Requests[0].Headers.GetValues("User-Agent")); // op status is a get Assert.Equal(HttpMethod.Get, handler.Requests[1].Method); Assert.NotNull(handler.Requests[1].Headers.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Resource.Location); Assert.NotEmpty(result.Resource.Properties.AccountEndpoint); Assert.Equal(result.Resource.Properties.ProvisioningState, AccountProvisioningState.Succeeded); Assert.True(result.Resource.Tags.Count == 2); } [Fact] public void AccountCreateSyncValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.Accounts.Create("foo", "acctName", new BatchAccountCreateParameters { Tags = tags }); // Validate headers - User-Agent for certs, Authorization for tokens //Assert.Equal(HttpMethod.Patch, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Resource.Location); Assert.NotEmpty(result.Resource.Properties.AccountEndpoint); Assert.Equal(result.Resource.Properties.ProvisioningState, AccountProvisioningState.Succeeded); Assert.True(result.Resource.Tags.Count == 2); } [Fact] public void AccountUpdateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.Accounts.Update("foo", "acctName", new BatchAccountUpdateParameters { Tags = tags }); // Validate headers - User-Agent for certs, Authorization for tokens //Assert.Equal(HttpMethod.Patch, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Resource.Location); Assert.NotEmpty(result.Resource.Properties.AccountEndpoint); Assert.Equal(result.Resource.Properties.ProvisioningState, AccountProvisioningState.Succeeded); Assert.True(result.Resource.Tags.Count == 2); } [Fact] public void AccountUpdateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.Update(null, null, new BatchAccountUpdateParameters())); Assert.Throws<ArgumentNullException>(() => client.Accounts.Update("foo", null, new BatchAccountUpdateParameters())); Assert.Throws<ArgumentNullException>(() => client.Accounts.Update("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Update("invalid+", "account", new BatchAccountUpdateParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Update("rg", "invalid%", new BatchAccountUpdateParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Update("rg", "/invalid", new BatchAccountUpdateParameters())); } [Fact] public void AccountDeleteValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse }); var client = GetBatchManagementClient(handler); var result = client.Accounts.Delete("resGroup", "acctName"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); Assert.Equal(HttpMethod.Get, handler.Requests[1].Method); Assert.Equal(HttpStatusCode.OK, result.StatusCode); } [Fact] public void AccountDeleteNotFoundValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(@"") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, notFoundResponse }); var client = GetBatchManagementClient(handler); var result = client.Accounts.Delete("resGroup", "acctName"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); Assert.Equal(HttpMethod.Get, handler.Requests[1].Method); Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); } [Fact] public void AccountDeleteNoContentValidateMessage() { var noContentResponse = new HttpResponseMessage(HttpStatusCode.NoContent) { Content = new StringContent(@"") }; noContentResponse.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(noContentResponse); var client = GetBatchManagementClient(handler); var result = client.Accounts.Delete("resGroup", "acctName"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); Assert.Equal(HttpStatusCode.NoContent, result.StatusCode); } [Fact] public void AccountDeleteThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.Delete("foo", null)); Assert.Throws<ArgumentNullException>(() => client.Accounts.Delete(null, "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Delete("invalid+", "account")); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Delete("rg", "invalid%")); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Delete("rg", "/invalid")); } [Fact] public void AccountGetValidateResponse() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetBatchManagementClient(handler); var result = client.Accounts.Get("foo", "acctName"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Resource.Location); Assert.Equal("acctName", result.Resource.Name); Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", result.Resource.Id); Assert.NotEmpty(result.Resource.Properties.AccountEndpoint); Assert.True(result.Resource.Tags.ContainsKey("tag1")); } [Fact] public void AccountGetThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.Get("foo", null)); Assert.Throws<ArgumentNullException>(() => client.Accounts.Get(null, "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Get("invalid+", "account")); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Get("rg", "invalid%")); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Get("rg", "/invalid")); } [Fact] public void AccountListValidateMessage() { var allSubsResponseEmptyNextLink = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : '' }") }; var allSubsResponseNonemptyNextLink = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack' } ") }; var allSubsResponseNonemptyNextLink1 = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack' } ") }; allSubsResponseEmptyNextLink.Headers.Add("x-ms-request-id", "1"); allSubsResponseNonemptyNextLink.Headers.Add("x-ms-request-id", "1"); allSubsResponseNonemptyNextLink1.Headers.Add("x-ms-request-id", "1"); // all accounts under sub and empty next link var handler = new RecordedDelegatingHandler(allSubsResponseEmptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetBatchManagementClient(handler); var result = client.Accounts.List(null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.True(result.Accounts.Count == 2); Assert.Equal("West US", result.Accounts[0].Location); Assert.Equal("acctName", result.Accounts[0].Name); Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", result.Accounts[0].Id); Assert.Equal("/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1", result.Accounts[1].Id); Assert.NotEmpty(result.Accounts[0].Properties.AccountEndpoint); Assert.True(result.Accounts[0].Tags.ContainsKey("tag1")); // all accounts under sub and a non-empty nextLink handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK }; client = GetBatchManagementClient(handler); result = client.Accounts.List(null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // all accounts under sub with a non-empty nextLink response handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink1) { StatusCodeToReturn = HttpStatusCode.OK }; client = GetBatchManagementClient(handler); result = client.Accounts.ListNext(result.NextLink); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); } [Fact] public void AccountListByResourceGroupValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Failed' }, 'tags' : { 'tag1' : 'value for tag1' } } ], 'nextLink' : 'originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack' }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetBatchManagementClient(handler); var result = client.Accounts.List(new AccountListParameters { ResourceGroupName = "foo" }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.True(result.Accounts.Count == 2); Assert.Equal(result.Accounts[0].Location, "West US"); Assert.Equal(result.Accounts[0].Name, "acctName"); Assert.Equal(result.Accounts[0].Id, @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName" ); Assert.Equal(result.Accounts[0].Properties.AccountEndpoint, @"http://acctName.batch.core.windows.net/"); Assert.Equal(result.Accounts[0].Properties.ProvisioningState, AccountProvisioningState.Succeeded); Assert.Equal(result.Accounts[1].Location, "South Central US"); Assert.Equal(result.Accounts[1].Name, "acctName1"); Assert.Equal(result.Accounts[1].Id, @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1"); Assert.Equal(result.Accounts[1].Properties.AccountEndpoint, @"http://acctName1.batch.core.windows.net/"); Assert.Equal(result.Accounts[1].Properties.ProvisioningState, AccountProvisioningState.Failed); Assert.True(result.Accounts[0].Tags.Count == 2); Assert.True(result.Accounts[0].Tags.ContainsKey("tag2")); Assert.True(result.Accounts[1].Tags.Count == 1); Assert.True(result.Accounts[1].Tags.ContainsKey("tag1")); Assert.Equal(result.NextLink, @"originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack"); } [Fact] public void AccountListNextThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.ListNext(null)); } [Fact] public void AccountKeysListValidateMessage() { var primaryKeyString = "primary key string which is alot longer than this"; var secondaryKeyString = "secondary key string which is alot longer than this"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'primary' : 'primary key string which is alot longer than this', 'secondary' : 'secondary key string which is alot longer than this', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetBatchManagementClient(handler); var result = client.Accounts.ListKeys("foo", "acctName"); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.NotEmpty(result.PrimaryKey); Assert.Equal(result.PrimaryKey, primaryKeyString); Assert.NotEmpty(result.SecondaryKey); Assert.Equal(result.SecondaryKey, secondaryKeyString); } [Fact] public void AccountKeysListThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.ListKeys("foo", null)); Assert.Throws<ArgumentNullException>(() => client.Accounts.ListKeys(null, "bar")); } [Fact] public void AccountKeysRegenerateValidateMessage() { var primaryKeyString = "primary key string which is alot longer than this"; var secondaryKeyString = "secondary key string which is alot longer than this"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'primary' : 'primary key string which is alot longer than this', 'secondary' : 'secondary key string which is alot longer than this', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetBatchManagementClient(handler); var result = client.Accounts.RegenerateKey("foo", "acctName", new BatchAccountRegenerateKeyParameters { KeyName = AccountKeyType.Primary }); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.NotEmpty(result.PrimaryKey); Assert.Equal(result.PrimaryKey, primaryKeyString); Assert.NotEmpty(result.SecondaryKey); Assert.Equal(result.SecondaryKey, secondaryKeyString); } [Fact] public void AccountKeysRegenerateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetBatchManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Accounts.RegenerateKey(null, "bar", new BatchAccountRegenerateKeyParameters())); Assert.Throws<ArgumentNullException>(() => client.Accounts.RegenerateKey("foo", null, new BatchAccountRegenerateKeyParameters())); Assert.Throws<ArgumentNullException>(() => client.Accounts.RegenerateKey("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.RegenerateKey("invalid+", "account", new BatchAccountRegenerateKeyParameters())); Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.RegenerateKey("rg", "invalid%", new BatchAccountRegenerateKeyParameters())); } } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.ComponentModel; // ***************************************************************************** // // Copyright 2004, Weifen Luo // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Weifen Luo // and are supplied subject to licence terms. // // WinFormsUI Library Version 1.0 // ***************************************************************************** namespace SoftLogik.Win { namespace UI { namespace Docking { [ToolboxItem(false)]public class AutoHideStripFromBase : AutoHideStripBase { private const int _ImageHeight = 16; private const int _ImageWidth = 16; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 4; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 4; private const int _TextGapRight = 10; private const int _TabGapTop = 3; private const int _TabGapLeft = 2; private const int _TabGapBetween = 10; private static StringFormat _stringFormatTabHorizontal; private static StringFormat _stringFormatTabVertical; private static Matrix _matrixIdentity; private static DockState[] _dockStates; #region Customizable Properties protected virtual StringFormat StringFormatTabHorizontal { get { return _stringFormatTabHorizontal; } } protected virtual StringFormat StringFormatTabVertical { get { return _stringFormatTabVertical; } } protected virtual int ImageHeight { get { return _ImageHeight; } } protected virtual int ImageWidth { get { return _ImageWidth; } } protected virtual int ImageGapTop { get { return _ImageGapTop; } } protected virtual int ImageGapLeft { get { return _ImageGapLeft; } } protected virtual int ImageGapRight { get { return _ImageGapRight; } } protected virtual int ImageGapBottom { get { return _ImageGapBottom; } } protected virtual int TextGapLeft { get { return _TextGapLeft; } } protected virtual int TextGapRight { get { return _TextGapRight; } } protected virtual int TabGapTop { get { return _TabGapTop; } } protected virtual int TabGapLeft { get { return _TabGapLeft; } } protected virtual int TabGapBetween { get { return _TabGapBetween; } } protected virtual void BeginDrawTab() { } protected virtual void EndDrawTab() { } protected virtual Brush BrushTabBackGround { get { return SystemBrushes.Control; } } protected virtual Pen PenTabBorder { get { return SystemPens.GrayText; } } protected virtual Brush BrushTabText { get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); } } #endregion private Matrix MatrixIdentity { get { return _matrixIdentity; } } private DockState[] DockStates { get { return _dockStates; } } static AutoHideStripFromBase() { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap || StringFormatFlags.DirectionVertical; _matrixIdentity = new Matrix(); _dockStates = new DockState[5]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } protected internal AutoHideStripFromBase(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); BackColor = Color.WhiteSmoke; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.Navy, Color.WhiteSmoke, LinearGradientMode.BackwardDiagonal)) { g.FillRectangle(brush, ClientRectangle); } DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout(levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) { return; } Matrix matrixIdentity = g.Transform; if (dockState == dockState.DockLeftAutoHide || dockState == dockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((rectTabStrip.X)+ (rectTabStrip.Height)/ 2, (rectTabStrip.Y)+ (rectTabStrip.Height)/ 2)); g.Transform = matrixRotated; } foreach (AutoHidePane pane in GetPanes(dockState)) { foreach (AutoHideTabFromBase tab in pane.Tabs) { DrawTab(g, tab); } } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = imageWidth; if (imageHeight > this.ImageHeight) { imageWidth = this.ImageWidth * (imageHeight / this.ImageHeight); } using (Graphics g = CreateGraphics()) { int x = TabGapLeft + rectTabStrip.X; foreach (AutoHidePane pane in GetPanes(dockState)) { int maxWidth = 0; foreach (AutoHideTabFromBase tab in pane.Tabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + ((int) (g.MeasureString(tab.Content.DockHandler.TabText, Font).Width))+ 1 + TextGapLeft + TextGapRight; if (width > maxWidth) { maxWidth = width; } } foreach (AutoHideTabFromBase tab in pane.Tabs) { tab.TabX = x; if (tab.Content == pane.DockPane.ActiveContent) { tab.TabWidth = maxWidth; } else { tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight; } x += tab.TabWidth; } x += TabGapBetween; } } } private void DrawTab(Graphics g, AutoHideTabFromBase tab) { Rectangle rectTab = GetTabRectangle(tab); if (rectTab.IsEmpty) { return; } DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; BeginDrawTab(); Brush brushTabBackGround = this.BrushTabBackGround; Pen penTabBorder = this.PenTabBorder; Brush brushTabText = this.BrushTabText; g.SmoothingMode = SmoothingMode.AntiAlias; if (dockState == dockState.DockTopAutoHide || dockState == dockState.DockRightAutoHide) { DrawHelper.DrawTab(g, rectTab, Corners.Bottom, GradientType.Flat, Color.FromArgb(244, 242, 232), Color.FromArgb(244, 242, 232), Color.FromArgb(172, 168, 153), true); } else { DrawHelper.DrawTab(g, rectTab, Corners.Top, GradientType.Flat, Color.FromArgb(244, 242, 232), Color.FromArgb(244, 242, 232), Color.FromArgb(172, 168, 153), true); } // Set no rotate for drawing icon and text Matrix matrixRotate = g.Transform; g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTab; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTab.Height - ImageGapTop - ImageGapBottom; int imageWidth = this.ImageWidth; if (imageHeight > this.ImageHeight) { imageWidth = this.ImageWidth * (imageHeight / this.ImageHeight); } rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); g.DrawIcon(content.DockHandler.Icon, rectImage); // Draw the text if (content == content.DockHandler.Pane.ActiveContent) { Rectangle rectText = rectTab; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = GetTransformedRectangle(dockState, rectText); if (dockState == dockState.DockLeftAutoHide || dockState == dockState.DockRightAutoHide) { g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabVertical); } else { g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal); } } // Set rotate back g.Transform = matrixRotate; EndDrawTab(); } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (! DockHelper.IsDockStateAutoHide(dockState)) { return Rectangle.Empty; } int leftPanes = GetPanes(dockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(dockState.DockRightAutoHide).Count; int topPanes = GetPanes(dockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(dockState.DockBottomAutoHide).Count; int x; int y; int width; int height; height = MeasureHeight(); if (dockState == dockState.DockLeftAutoHide && leftPanes > 0) { x = 0; if (topPanes == 0) { y = 0; } else { y = height; } if (topPanes == 0) { if (bottomPanes == 0) { width = this.Height; } else { width = this.Height - height; } } else { if (bottomPanes == 0) { width = this.Height - height; } else { width = this.Height - height * 2; } } } else if (dockState == dockState.DockRightAutoHide && rightPanes > 0) { x = this.Width - height; if (leftPanes != 0 && x < height) { x = height; } if (topPanes == 0) { y = 0; } else { y = height; } if (topPanes == 0) { if (bottomPanes == 0) { width = this.Height; } else { width = this.Height - height; } } else { if (bottomPanes == 0) { width = this.Height - height; } else { width = this.Height - height * 2; } } } else if (dockState == dockState.DockTopAutoHide && topPanes > 0) { if (leftPanes == 0) { x = 0; } else { x = height; } y = 0; if (leftPanes == 0) { if (rightPanes == 0) { width = this.Width; } else { width = this.Width - height; } } else { if (rightPanes == 0) { width = this.Width - height; } else { width = this.Width - height * 2; } } } else if (dockState == dockState.DockBottomAutoHide && bottomPanes > 0) { if (leftPanes == 0) { x = 0; } else { x = height; } y = this.Height - height; if (topPanes != 0 && y < height) { y = height; } if (leftPanes == 0) { if (rightPanes == 0) { width = this.Width; } else { width = this.Width - height; } } else { if (rightPanes == 0) { width = this.Width - height; } else { width = this.Width - height * 2; } } } else { return Rectangle.Empty; } if (! transformed) { return new Rectangle(x, y, width, height); } else { return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } } private Rectangle GetTabRectangle(AutoHideTabFromBase tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(AutoHideTabFromBase tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) { return Rectangle.Empty; } int x = tab.TabX; int y; if (dockState == dockState.DockTopAutoHide || dockState == dockState.DockRightAutoHide) { y = rectTabStrip.Y; } else { y = rectTabStrip.Y + TabGapTop; } int width = (tab ).TabWidth; int height = rectTabStrip.Height - TabGapTop; if (! transformed) { return new Rectangle(x, y, width, height); } else { return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != dockState.DockLeftAutoHide && dockState != dockState.DockRightAutoHide) { return rect; } PointF[] pts = new PointF[2](); // the center of the rectangle pts[0].X = (rect.X)+ (rect.Width)/ 2; pts[0].Y = (rect.Y)+ (rect.Height)/ 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); Matrix matrix = new Matrix(); matrix.RotateAt(90, new PointF((rectTabStrip.X)+ (rectTabStrip.Height)/ 2, (rectTabStrip.Y)+ (rectTabStrip.Height)/ 2)); matrix.TransformPoints(pts); return new Rectangle(System.Convert.ToInt32(pts[0].X - (rect.Height)/ 2 + 0.5F), System.Convert.ToInt32(pts[0].Y - (rect.Width)/ 2 + 0.5F), rect.Height, rect.Width); } protected override IDockContent GetHitTest(Point ptMouse) { foreach (DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (! rectTabStrip.Contains(ptMouse)) { continue; } foreach (AutoHidePane pane in GetPanes(state)) { foreach (AutoHideTabFromBase tab in pane.Tabs) { Rectangle rectTab = GetTabRectangle(tab, true); rectTab.Intersect(rectTabStrip); if (rectTab.Contains(ptMouse)) { return tab.Content; } } } } return null; } protected override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, Font.Height) + TabGapTop; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } } } } }
namespace AgileObjects.AgileMapper.ObjectPopulation { using System; using System.Collections.Generic; #if NET35 using Microsoft.Scripting.Ast; #else using System.Linq.Expressions; #endif using Caching; using DataSources; using Extensions.Internal; using MapperKeys; using Members; using NetStandardPolyfills; using Validation; #if NET35 using static Microsoft.Scripting.Ast.Expression; #else using static System.Linq.Expressions.Expression; #endif internal class ObjectMappingData<TSource, TTarget> : MappingInstanceData<TSource, TTarget>, IObjectMappingData, IObjectMappingData<TSource, TTarget>, IObjectCreationMappingData<TSource, TTarget, TTarget> { private ICache<IQualifiedMember, Func<TSource, Type>> _runtimeTypeGettersCache; private Dictionary<object, List<object>> _mappedObjectsBySource; private ObjectMapper<TSource, TTarget> _mapper; private ObjectMapperData _mapperData; public ObjectMappingData( TSource source, TTarget target, int? elementIndex, object elementKey, MappingTypes mappingTypes, IMappingContext mappingContext, IObjectMappingData parent, bool createMapper = true) : this( source, target, elementIndex, elementKey, mappingTypes, mappingContext, null, parent, createMapper) { } private ObjectMappingData( TSource source, TTarget target, int? elementIndex, object elementKey, MappingTypes mappingTypes, IMappingContext mappingContext, IObjectMappingData declaredTypeMappingData, IObjectMappingData parent, bool createMapper) : base(source, target, elementIndex, elementKey, parent, mappingContext) { MappingTypes = mappingTypes; MappingContext = mappingContext; DeclaredTypeMappingData = declaredTypeMappingData; if (parent != null) { Parent = parent; return; } if (createMapper) { _mapper = MapperContext.ObjectMapperFactory.GetOrCreateRoot(this); } } public IMappingContext MappingContext { get; } public MapperContext MapperContext => MappingContext.MapperContext; public MappingTypes MappingTypes { get; } public ObjectMapperKeyBase MapperKey { get; set; } public IRootMapperKey EnsureRootMapperKey() { MapperKey = MappingContext.RuleSet.RootMapperKeyFactory.Invoke(this); return (IRootMapperKey)MapperKey; } public IObjectMapper GetOrCreateMapper() { if (_mapper != null) { return _mapper; } _mapper = MapperContext.ObjectMapperFactory.Create(this); MapperKey.MappingData = null; if (_mapper == null) { return null; } if (IsRoot && MapperContext.UserConfigurations.ValidateMappingPlans) { // TODO: Test coverage for validation of standalone child mappers MappingValidator.Validate(_mapper.MapperData); } StaticMapperCache<TSource, TTarget>.AddIfAppropriate(_mapper, this); return _mapper; } public void SetMapper(IObjectMapper mapper) => _mapper = (ObjectMapper<TSource, TTarget>)mapper; public bool MapperDataPopulated => (_mapperData ?? _mapper?.MapperData) != null; IMemberMapperData IDataSourceSetInfo.MapperData => MapperData; public ObjectMapperData MapperData { get => _mapperData ??= _mapper?.MapperData ?? ObjectMapperData.For(this); set => _mapperData = value; } public TTarget CreatedObject { get; set; } #region IObjectMappingData Members public bool IsRoot => Parent == null; public IObjectMappingData Parent { get; } IObjectMappingDataUntyped IObjectMappingData<TSource, TTarget>.Parent => Parent; public bool IsPartOfRepeatedMapping { get; set; } public bool IsPartOfDerivedTypeMapping => DeclaredTypeMappingData != null; public IObjectMappingData DeclaredTypeMappingData { get; } private Dictionary<object, List<object>> MappedObjectsBySource => _mappedObjectsBySource ??= new Dictionary<object, List<object>>(13); IChildMemberMappingData IObjectMappingData.GetChildMappingData(IMemberMapperData childMapperData) => new ChildMemberMappingData<TSource, TTarget>(this, childMapperData); public Type GetSourceMemberRuntimeType(IQualifiedMember childSourceMember) { if (Source == null) { return childSourceMember.Type; } if (childSourceMember.Type.IsSealed()) { return childSourceMember.Type; } var mapperData = MapperData; while (mapperData != null) { if (childSourceMember == mapperData.SourceMember) { return mapperData.SourceMember.Type; } mapperData = mapperData.Parent; } if (_runtimeTypeGettersCache == null) { _runtimeTypeGettersCache = MapperContext.Cache.CreateScoped<IQualifiedMember, Func<TSource, Type>>(); } var getRuntimeTypeFunc = _runtimeTypeGettersCache.GetOrAdd(childSourceMember, sm => { var sourceParameter = typeof(TSource).GetOrCreateParameter("source"); var memberAccess = sm .GetRelativeQualifiedAccess(MapperData) .Replace( MapperData.SourceObject, sourceParameter, ExpressionEvaluation.Equivalator); if (memberAccess.NodeType == ExpressionType.Invoke) { var runtimeTypeLambda = Lambda<Func<TSource, Type>>(Constant(sm.Type), sourceParameter); return runtimeTypeLambda.Compile(); } var getRuntimeTypeCall = Call( ObjectExtensions.GetRuntimeSourceTypeMethod.MakeGenericMethod(sm.Type), memberAccess); var getRuntimeTypeLambda = Lambda<Func<TSource, Type>>(getRuntimeTypeCall, sourceParameter); return getRuntimeTypeLambda.Compile(); }); return getRuntimeTypeFunc.Invoke(Source); } #endregion #region Map Methods object IObjectMappingData.MapStart() => MapStart(); public TTarget MapStart() => _mapper.Map(this); public TDeclaredTarget Map<TDeclaredSource, TDeclaredTarget>( TDeclaredSource sourceValue, TDeclaredTarget targetValue, string targetMemberRegistrationName, int dataSourceIndex) { var childMappingData = GetChildMappingData( sourceValue, targetValue, GetElementIndex(), GetElementKey(), targetMemberRegistrationName, dataSourceIndex); return (TDeclaredTarget)_mapper.MapSubObject(childMappingData); } private IObjectMappingData GetChildMappingData<TDeclaredSource, TDeclaredTarget>( TDeclaredSource sourceValue, TDeclaredTarget targetValue, int? elementIndex, object elementKey, string targetMemberRegistrationName, int dataSourceIndex) { return ObjectMappingDataFactory.ForChild( sourceValue, targetValue, elementIndex, elementKey, targetMemberRegistrationName, dataSourceIndex, this); } public TTargetElement Map<TSourceElement, TTargetElement>( TSourceElement sourceElement, TTargetElement targetElement, int elementIndex, object elementKey) { var elementMappingData = GetElementMappingData(sourceElement, targetElement, elementIndex, elementKey); return (TTargetElement)_mapper.MapSubObject(elementMappingData); } private IObjectMappingData GetElementMappingData<TSourceElement, TTargetElement>( TSourceElement sourceElement, TTargetElement targetElement, int elementIndex, object elementKey) { return ObjectMappingDataFactory.ForElement( sourceElement, targetElement, elementIndex, elementKey, this); } TDeclaredTarget IObjectMappingDataUntyped.MapRepeated<TDeclaredSource, TDeclaredTarget>( TDeclaredSource sourceValue, TDeclaredTarget targetValue, int? elementIndex, object elementKey, string targetMemberRegistrationName, int dataSourceIndex) { if (IsRoot || MapperKey.MappingTypes.RuntimeTypesNeeded) { var childMappingData = GetChildMappingData( sourceValue, targetValue, elementIndex, elementKey, targetMemberRegistrationName, dataSourceIndex); childMappingData.IsPartOfRepeatedMapping = true; return (TDeclaredTarget)_mapper.MapRepeated(childMappingData); } return Parent.MapRepeated( sourceValue, targetValue, elementIndex, elementKey, targetMemberRegistrationName, dataSourceIndex); } TDeclaredTarget IObjectMappingDataUntyped.MapRepeated<TDeclaredSource, TDeclaredTarget>( TDeclaredSource sourceElement, TDeclaredTarget targetElement, int elementIndex, object elementKey) { if (IsRoot || MapperKey.MappingTypes.RuntimeTypesNeeded) { var childMappingData = GetElementMappingData( sourceElement, targetElement, elementIndex, elementKey); childMappingData.IsPartOfRepeatedMapping = true; return (TDeclaredTarget)_mapper.MapRepeated(childMappingData); } return Parent.MapRepeated(sourceElement, targetElement, elementIndex, elementKey); } #endregion public bool TryGet<TKey, TComplex>(TKey key, out TComplex complexType) where TComplex : class { if (!IsRoot) { return Parent.TryGet(key, out complexType); } if (MappedObjectsBySource.TryGetValue(key, out var mappedTargets)) { complexType = (TComplex)mappedTargets.FirstOrDefault(t => t is TComplex); return complexType != null; } complexType = default; return false; } public void Register<TKey, TComplex>(TKey key, TComplex complexType) { if (!IsRoot) { Parent.Register(key, complexType); return; } if (MappedObjectsBySource.TryGetValue(key, out var mappedTargets)) { mappedTargets.Add(complexType); return; } _mappedObjectsBySource[key] = new List<object> { complexType }; } public IObjectMappingData<TNewSource, TTarget> WithSource<TNewSource>(TNewSource newSource) => With(newSource, Target, isForDerivedTypeMapping: false); public IObjectMappingData<TNewSource, TNewTarget> WithSourceType<TNewSource, TNewTarget>(bool isForDerivedTypeMapping) where TNewSource : class { return With(Source as TNewSource, default(TNewTarget), isForDerivedTypeMapping); } public IObjectMappingData<TNewSource, TNewTarget> WithTargetType<TNewSource, TNewTarget>(bool isForDerivedTypeMapping) where TNewTarget : class { return With(default(TNewSource), Target as TNewTarget, isForDerivedTypeMapping); } public IObjectMappingData WithToTargetSource(IQualifiedMember sourceMember) { var newSourceType = GetSourceMemberRuntimeType(sourceMember); var newSourceMappingData = UpdateTypes( newSourceType, MapperData.TargetType, IsPartOfDerivedTypeMapping); newSourceMappingData.MapperKey = MappingContext .RuleSet .RootMapperKeyFactory .Invoke(newSourceMappingData); var newSourceMapperData = newSourceMappingData.MapperData; newSourceMapperData.OriginalMapperData = MapperData; newSourceMapperData.Context.IsForToTargetMapping = true; return newSourceMappingData; } IObjectMappingData IObjectMappingData.WithDerivedTypes(Type derivedSourceType, Type derivedTargetType) => UpdateTypes(derivedSourceType, derivedTargetType, isForDerivedTypeMapping: true); private IObjectMappingData UpdateTypes( Type newSourceType, Type newTargetType, bool isForDerivedTypeMapping) { var typesKey = new SourceAndTargetTypesKey(newSourceType, newTargetType); var typedAsCaller = GlobalContext.Instance.Cache.GetOrAddWithHashCodes(typesKey, k => { var mappingDataParameter = Parameters.Create<IObjectMappingData<TSource, TTarget>>("mappingData"); var isForDerivedTypeParameter = Parameters.Create<bool>("isForDerivedType"); var typesConversionCall = mappingDataParameter.GetAsCall( isForDerivedTypeParameter, k.SourceType, k.TargetType); var typesConversionLambda = Lambda<Func<IObjectMappingData<TSource, TTarget>, bool, IObjectMappingDataUntyped>>( typesConversionCall, mappingDataParameter, isForDerivedTypeParameter); return typesConversionLambda.Compile(); }); return (IObjectMappingData)typedAsCaller.Invoke(this, isForDerivedTypeMapping); } public IObjectMappingData<TNewSource, TNewTarget> As<TNewSource, TNewTarget>(bool isForDerivedTypeMapping) where TNewSource : class where TNewTarget : class { return With(Source as TNewSource, Target as TNewTarget, isForDerivedTypeMapping); } private IObjectMappingData<TNewSource, TNewTarget> With<TNewSource, TNewTarget>( TNewSource typedSource, TNewTarget typedTarget, bool isForDerivedTypeMapping) { if (MapperKey == null) { EnsureRootMapperKey(); } var forceNewKey = isForDerivedTypeMapping && MapperKey.MappingTypes.TargetType.IsInterface(); var mapperKey = MapperKey.WithTypes(typeof(TNewSource), typeof(TNewTarget), forceNewKey); return new ObjectMappingData<TNewSource, TNewTarget>( typedSource, typedTarget, GetElementIndex(), GetElementKey(), mapperKey.MappingTypes, MappingContext, isForDerivedTypeMapping ? this : null, Parent, createMapper: false) { MapperKey = mapperKey }; } } }
// 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.Text; using System.Diagnostics.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Rules for the Hebrew calendar: // - The Hebrew calendar is both a Lunar (months) and Solar (years) // calendar, but allows for a week of seven days. // - Days begin at sunset. // - Leap Years occur in the 3, 6, 8, 11, 14, 17, & 19th years of a // 19-year cycle. Year = leap iff ((7y+1) mod 19 < 7). // - There are 12 months in a common year and 13 months in a leap year. // - In a common year, the 6th month, Adar, has 29 days. In a leap // year, the 6th month, Adar I, has 30 days and the leap month, // Adar II, has 29 days. // - Common years have 353-355 days. Leap years have 383-385 days. // - The Hebrew new year (Rosh HaShanah) begins on the 1st of Tishri, // the 7th month in the list below. // - The new year may not begin on Sunday, Wednesday, or Friday. // - If the new year would fall on a Tuesday and the conjunction of // the following year were at midday or later, the new year is // delayed until Thursday. // - If the new year would fall on a Monday after a leap year, the // new year is delayed until Tuesday. // - The length of the 8th and 9th months vary from year to year, // depending on the overall length of the year. // - The length of a year is determined by the dates of the new // years (Tishri 1) preceding and following the year in question. // - The 2th month is long (30 days) if the year has 355 or 385 days. // - The 3th month is short (29 days) if the year has 353 or 383 days. // - The Hebrew months are: // 1. Tishri (30 days) // 2. Heshvan (29 or 30 days) // 3. Kislev (29 or 30 days) // 4. Teveth (29 days) // 5. Shevat (30 days) // 6. Adar I (30 days) // 7. Adar {II} (29 days, this only exists if that year is a leap year) // 8. Nisan (30 days) // 9. Iyyar (29 days) // 10. Sivan (30 days) // 11. Tammuz (29 days) // 12. Av (30 days) // 13. Elul (29 days) // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1583/01/01 2239/09/29 ** Hebrew 5343/04/07 5999/13/29 */ // Includes CHebrew implemetation;i.e All the code necessary for converting // Gregorian to Hebrew Lunar from 1583 to 2239. [System.Runtime.InteropServices.ComVisible(true)] public class HebrewCalendar : Calendar { public static readonly int HebrewEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; internal const int DatePartDayOfWeek = 4; // // Hebrew Translation Table. // // This table is used to get the following Hebrew calendar information for a // given Gregorian year: // 1. The day of the Hebrew month corresponding to Gregorian January 1st // for a given Gregorian year. // 2. The month of the Hebrew month corresponding to Gregorian January 1st // for a given Gregorian year. // The information is not directly in the table. Instead, the info is decoded // by special values (numbers above 29 and below 1). // 3. The type of the Hebrew year for a given Gregorian year. // /* More notes: This table includes 2 numbers for each year. The offset into the table determines the year. (offset 0 is Gregorian year 1500) 1st number determines the day of the Hebrew month coresponeds to January 1st. 2nd number determines the type of the Hebrew year. (the type determines how many days are there in the year.) normal years : 1 = 353 days 2 = 354 days 3 = 355 days. Leap years : 4 = 383 5 384 6 = 385 days. A 99 means the year is not supported for translation. for convenience the table was defined for 750 year, but only 640 years are supported. (from 1583 to 2239) the years before 1582 (starting of Georgian calander) and after 2239, are filled with 99. Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. That's why, there no nead to specify the lunar month in the table. There are exceptions, these are coded by giving numbers above 29 and below 1. Actual decoding is takenig place whenever fetching information from the table. The function for decoding is in GetLunarMonthDay(). Example: The data for 2000 - 2005 A.D. is: 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004 For year 2000, we know it has a Hebrew year type 6, which means it has 385 days. And 1/1/2000 A.D. is Hebrew year 5760, 23rd day of 4th month. */ // // Jewish Era in use today is dated from the supposed year of the // Creation with its beginning in 3761 B.C. // // The Hebrew year of Gregorian 1st year AD. // 0001/01/01 AD is Hebrew 3760/01/01 private const int HebrewYearOf1AD = 3760; // The first Gregorian year in HebrewTable. private const int FirstGregorianTableYear = 1583; // == Hebrew Year 5343 // The last Gregorian year in HebrewTable. private const int LastGregorianTableYear = 2239; // == Hebrew Year 5999 private const int TABLESIZE = (LastGregorianTableYear - FirstGregorianTableYear); private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343 private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999 private static readonly byte[] HebrewTable = { 7,3,17,3, // 1583-1584 (Hebrew year: 5343 - 5344) 0,4,11,2,21,6,1,3,13,2, // 1585-1589 25,4,5,3,16,2,27,6,9,1, // 1590-1594 20,2,0,6,11,3,23,4,4,2, // 1595-1599 14,3,27,4,8,2,18,3,28,6, // 1600 11,1,22,5,2,3,12,3,25,4, // 1605 6,2,16,3,26,6,8,2,20,1, // 1610 0,6,11,2,24,4,4,3,15,2, // 1615 25,6,8,1,19,2,29,6,9,3, // 1620 22,4,3,2,13,3,25,4,6,3, // 1625 17,2,27,6,7,3,19,2,31,4, // 1630 11,3,23,4,5,2,15,3,25,6, // 1635 6,2,19,1,29,6,10,2,22,4, // 1640 3,3,14,2,24,6,6,1,17,3, // 1645 28,5,8,3,20,1,32,5,12,3, // 1650 22,6,4,1,16,2,26,6,6,3, // 1655 17,2,0,4,10,3,22,4,3,2, // 1660 14,3,24,6,5,2,17,1,28,6, // 1665 9,2,19,3,31,4,13,2,23,6, // 1670 3,3,15,1,27,5,7,3,17,3, // 1675 29,4,11,2,21,6,3,1,14,2, // 1680 25,6,5,3,16,2,28,4,9,3, // 1685 20,2,0,6,12,1,23,6,4,2, // 1690 14,3,26,4,8,2,18,3,0,4, // 1695 10,3,21,5,1,3,13,1,24,5, // 1700 5,3,15,3,27,4,8,2,19,3, // 1705 29,6,10,2,22,4,3,3,14,2, // 1710 26,4,6,3,18,2,28,6,10,1, // 1715 20,6,2,2,12,3,24,4,5,2, // 1720 16,3,28,4,8,3,19,2,0,6, // 1725 12,1,23,5,3,3,14,3,26,4, // 1730 7,2,17,3,28,6,9,2,21,4, // 1735 1,3,13,2,25,4,5,3,16,2, // 1740 27,6,9,1,19,3,0,5,11,3, // 1745 23,4,4,2,14,3,25,6,7,1, // 1750 18,2,28,6,9,3,21,4,2,2, // 1755 12,3,25,4,6,2,16,3,26,6, // 1760 8,2,20,1,0,6,11,2,22,6, // 1765 4,1,15,2,25,6,6,3,18,1, // 1770 29,5,9,3,22,4,2,3,13,2, // 1775 23,6,4,3,15,2,27,4,7,3, // 1780 19,2,31,4,11,3,21,6,3,2, // 1785 15,1,25,6,6,2,17,3,29,4, // 1790 10,2,20,6,3,1,13,3,24,5, // 1795 4,3,16,1,27,5,7,3,17,3, // 1800 0,4,11,2,21,6,1,3,13,2, // 1805 25,4,5,3,16,2,29,4,9,3, // 1810 19,6,30,2,13,1,23,6,4,2, // 1815 14,3,27,4,8,2,18,3,0,4, // 1820 11,3,22,5,2,3,14,1,26,5, // 1825 6,3,16,3,28,4,10,2,20,6, // 1830 30,3,11,2,24,4,4,3,15,2, // 1835 25,6,8,1,19,2,29,6,9,3, // 1840 22,4,3,2,13,3,25,4,7,2, // 1845 17,3,27,6,9,1,21,5,1,3, // 1850 11,3,23,4,5,2,15,3,25,6, // 1855 6,2,19,1,29,6,10,2,22,4, // 1860 3,3,14,2,24,6,6,1,18,2, // 1865 28,6,8,3,20,4,2,2,12,3, // 1870 24,4,4,3,16,2,26,6,6,3, // 1875 17,2,0,4,10,3,22,4,3,2, // 1880 14,3,24,6,5,2,17,1,28,6, // 1885 9,2,21,4,1,3,13,2,23,6, // 1890 5,1,15,3,27,5,7,3,19,1, // 1895 0,5,10,3,22,4,2,3,13,2, // 1900 24,6,4,3,15,2,27,4,8,3, // 1905 20,4,1,2,11,3,22,6,3,2, // 1910 15,1,25,6,7,2,17,3,29,4, // 1915 10,2,21,6,1,3,13,1,24,5, // 1920 5,3,15,3,27,4,8,2,19,6, // 1925 1,1,12,2,22,6,3,3,14,2, // 1930 26,4,6,3,18,2,28,6,10,1, // 1935 20,6,2,2,12,3,24,4,5,2, // 1940 16,3,28,4,9,2,19,6,30,3, // 1945 12,1,23,5,3,3,14,3,26,4, // 1950 7,2,17,3,28,6,9,2,21,4, // 1955 1,3,13,2,25,4,5,3,16,2, // 1960 27,6,9,1,19,6,30,2,11,3, // 1965 23,4,4,2,14,3,27,4,7,3, // 1970 18,2,28,6,11,1,22,5,2,3, // 1975 12,3,25,4,6,2,16,3,26,6, // 1980 8,2,20,4,30,3,11,2,24,4, // 1985 4,3,15,2,25,6,8,1,18,3, // 1990 29,5,9,3,22,4,3,2,13,3, // 1995 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004 20,4,1,2,11,3,23,4,5,2, // 2005 - 2009 15,3,25,6,6,2,19,1,29,6, // 2010 10,2,20,6,3,1,14,2,24,6, // 2015 4,3,17,1,28,5,8,3,20,4, // 2020 1,3,12,2,22,6,2,3,14,2, // 2025 26,4,6,3,17,2,0,4,10,3, // 2030 20,6,1,2,14,1,24,6,5,2, // 2035 15,3,28,4,9,2,19,6,1,1, // 2040 12,3,23,5,3,3,15,1,27,5, // 2045 7,3,17,3,29,4,11,2,21,6, // 2050 1,3,12,2,25,4,5,3,16,2, // 2055 28,4,9,3,19,6,30,2,12,1, // 2060 23,6,4,2,14,3,26,4,8,2, // 2065 18,3,0,4,10,3,22,5,2,3, // 2070 14,1,25,5,6,3,16,3,28,4, // 2075 9,2,20,6,30,3,11,2,23,4, // 2080 4,3,15,2,27,4,7,3,19,2, // 2085 29,6,11,1,21,6,3,2,13,3, // 2090 25,4,6,2,17,3,27,6,9,1, // 2095 20,5,30,3,10,3,22,4,3,2, // 2100 14,3,24,6,5,2,17,1,28,6, // 2105 9,2,21,4,1,3,13,2,23,6, // 2110 5,1,16,2,27,6,7,3,19,4, // 2115 30,2,11,3,23,4,3,3,14,2, // 2120 25,6,5,3,16,2,28,4,9,3, // 2125 21,4,2,2,12,3,23,6,4,2, // 2130 16,1,26,6,8,2,20,4,30,3, // 2135 11,2,22,6,4,1,14,3,25,5, // 2140 6,3,18,1,29,5,9,3,22,4, // 2145 2,3,13,2,23,6,4,3,15,2, // 2150 27,4,7,3,20,4,1,2,11,3, // 2155 21,6,3,2,15,1,25,6,6,2, // 2160 17,3,29,4,10,2,20,6,3,1, // 2165 13,3,24,5,4,3,17,1,28,5, // 2170 8,3,18,6,1,1,12,2,22,6, // 2175 2,3,14,2,26,4,6,3,17,2, // 2180 28,6,10,1,20,6,1,2,12,3, // 2185 24,4,5,2,15,3,28,4,9,2, // 2190 19,6,33,3,12,1,23,5,3,3, // 2195 13,3,25,4,6,2,16,3,26,6, // 2200 8,2,20,4,30,3,11,2,24,4, // 2205 4,3,15,2,25,6,8,1,18,6, // 2210 33,2,9,3,22,4,3,2,13,3, // 2215 25,4,6,3,17,2,27,6,9,1, // 2220 21,5,1,3,11,3,23,4,5,2, // 2225 15,3,25,6,6,2,19,4,33,3, // 2230 10,2,22,4,3,3,14,2,24,6, // 2235 6,1 // 2240 (Hebrew year: 6000) }; const int MaxMonthPlusOne = 14; // // The lunar calendar has 6 different variations of month lengths // within a year. // private static readonly byte[] LunarMonthLen = { 0,00,00,00,00,00,00,00,00,00,00,00,00,0, 0,30,29,29,29,30,29,30,29,30,29,30,29,0, // 3 common year variations 0,30,29,30,29,30,29,30,29,30,29,30,29,0, 0,30,30,30,29,30,29,30,29,30,29,30,29,0, 0,30,29,29,29,30,30,29,30,29,30,29,30,29, // 3 leap year variations 0,30,29,30,29,30,30,29,30,29,30,29,30,29, 0,30,30,30,29,30,30,29,30,29,30,29,30,29 }; //internal static Calendar m_defaultInstance; internal static readonly DateTime calendarMinValue = new DateTime(1583, 1, 1); // Gregorian 2239/9/29 = Hebrew 5999/13/29 (last day in Hebrew year 5999). // We can only format/parse Hebrew numbers up to 999, so we limit the max range to Hebrew year 5999. internal static readonly DateTime calendarMaxValue = new DateTime((new DateTime(2239, 9, 29, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (calendarMaxValue); } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of HebrewCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ /* internal static Calendar GetDefaultInstance() { if (m_defaultInstance == null) { m_defaultInstance = new HebrewCalendar(); } return (m_defaultInstance); } */ // Construct an instance of gregorian calendar. public HebrewCalendar() { } internal override CalendarId ID { get { return (CalendarId.HEBREW); } } /*=================================CheckHebrewYearValue========================== **Action: Check if the Hebrew year value is supported in this class. **Returns: None. **Arguments: y Hebrew year value ** ear Hebrew era value **Exceptions: ArgumentOutOfRange_Range if the year value is not supported. **Note: ** We use a table for the Hebrew calendar calculation, so the year supported is limited. ============================================================================*/ static private void CheckHebrewYearValue(int y, int era, String varName) { CheckEraRange(era); if (y > MaxHebrewYear || y < MinHebrewYear) { throw new ArgumentOutOfRangeException( varName, String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear)); } } /*=================================CheckHebrewMonthValue========================== **Action: Check if the Hebrew month value is valid. **Returns: None. **Arguments: year Hebrew year value ** month Hebrew month value **Exceptions: ArgumentOutOfRange_Range if the month value is not valid. **Note: ** Call CheckHebrewYearValue() before calling this to verify the year value is supported. ============================================================================*/ private void CheckHebrewMonthValue(int year, int month, int era) { int monthsInYear = GetMonthsInYear(year, era); if (month < 1 || month > monthsInYear) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, monthsInYear)); } } /*=================================CheckHebrewDayValue========================== **Action: Check if the Hebrew day value is valid. **Returns: None. **Arguments: year Hebrew year value ** month Hebrew month value ** day Hebrew day value. **Exceptions: ArgumentOutOfRange_Range if the day value is not valid. **Note: ** Call CheckHebrewYearValue()/CheckHebrewMonthValue() before calling this to verify the year/month values are valid. ============================================================================*/ private void CheckHebrewDayValue(int year, int month, int day, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, daysInMonth)); } } static internal void CheckEraRange(int era) { if (era != CurrentEra && era != HebrewEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } } static private void CheckTicksRange(long ticks) { if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) { throw new ArgumentOutOfRangeException( "time", // Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar. String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, calendarMinValue, calendarMaxValue)); } } static internal int GetResult(__DateBuffer result, int part) { switch (part) { case DatePartYear: return (result.year); case DatePartMonth: return (result.month); case DatePartDay: return (result.day); } throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } /*=================================GetLunarMonthDay========================== **Action: Using the Hebrew table (HebrewTable) to get the Hebrew month/day value for Gregorian January 1st ** in a given Gregorian year. ** Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. ** That's why, there no nead to specify the lunar month in the table. There are exceptions, and these ** are coded by giving numbers above 29 and below 1. ** Actual decoding is takenig place in the switch statement below. **Returns: ** The Hebrew year type. The value is from 1 to 6. ** normal years : 1 = 353 days 2 = 354 days 3 = 355 days. ** Leap years : 4 = 383 5 384 6 = 385 days. **Arguments: ** gregorianYear The year value in Gregorian calendar. The value should be between 1500 and 2239. ** lunarDate Object to take the result of the Hebrew year/month/day. **Exceptions: ============================================================================*/ static internal int GetLunarMonthDay(int gregorianYear, __DateBuffer lunarDate) { // // Get the offset into the LunarMonthLen array and the lunar day // for January 1st. // int index = gregorianYear - FirstGregorianTableYear; if (index < 0 || index > TABLESIZE) { throw new ArgumentOutOfRangeException("gregorianYear"); } index *= 2; lunarDate.day = HebrewTable[index]; // Get the type of the year. The value is from 1 to 6 int LunarYearType = HebrewTable[index + 1]; // // Get the Lunar Month. // switch (lunarDate.day) { case (0): // 1/1 is on Shvat 1 lunarDate.month = 5; lunarDate.day = 1; break; case (30): // 1/1 is on Kislev 30 lunarDate.month = 3; break; case (31): // 1/1 is on Shvat 2 lunarDate.month = 5; lunarDate.day = 2; break; case (32): // 1/1 is on Shvat 3 lunarDate.month = 5; lunarDate.day = 3; break; case (33): // 1/1 is on Kislev 29 lunarDate.month = 3; lunarDate.day = 29; break; default: // 1/1 is on Tevet (This is the general case) lunarDate.month = 4; break; } return (LunarYearType); } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { // The Gregorian year, month, day value for ticks. int gregorianYear, gregorianMonth, gregorianDay; int hebrewYearType; // lunar year type long AbsoluteDate; // absolute date - absolute date 1/1/1600 // // Make sure we have a valid Gregorian date that will fit into our // Hebrew conversion limits. // CheckTicksRange(ticks); DateTime time = new DateTime(ticks); // // Save the Gregorian date values. // gregorianYear = time.Year; gregorianMonth = time.Month; gregorianDay = time.Day; __DateBuffer lunarDate = new __DateBuffer(); // lunar month and day for Jan 1 // From the table looking-up value of HebrewTable[index] (stored in lunarDate.day), we get the the // lunar month and lunar day where the Gregorian date 1/1 falls. lunarDate.year = gregorianYear + HebrewYearOf1AD; hebrewYearType = GetLunarMonthDay(gregorianYear, lunarDate); // This is the buffer used to store the result Hebrew date. __DateBuffer result = new __DateBuffer(); // // Store the values for the start of the new year - 1/1. // result.year = lunarDate.year; result.month = lunarDate.month; result.day = lunarDate.day; // // Get the absolute date from 1/1/1600. // AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay); // // If the requested date was 1/1, then we're done. // if ((gregorianMonth == 1) && (gregorianDay == 1)) { return (GetResult(result, part)); } // // Calculate the number of days between 1/1 and the requested date. // long NumDays; // number of days since 1/1 NumDays = AbsoluteDate - GregorianCalendar.GetAbsoluteDate(gregorianYear, 1, 1); // // If the requested date is within the current lunar month, then // we're done. // if ((NumDays + (long)lunarDate.day) <= (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month])) { result.day += (int)NumDays; return (GetResult(result, part)); } // // Adjust for the current partial month. // result.month++; result.day = 1; // // Adjust the Lunar Month and Year (if necessary) based on the number // of days between 1/1 and the requested date. // // Assumes Jan 1 can never translate to the last Lunar month, which // is true. // NumDays -= (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day); Contract.Assert(NumDays >= 1, "NumDays >= 1"); // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month // and day. if (NumDays > 1) { // // See if we're on the correct Lunar month. // while (NumDays > (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month])) { // // Adjust the number of days and move to the next month. // NumDays -= (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month++]); // // See if we need to adjust the Year. // Must handle both 12 and 13 month years. // if ((result.month > 13) || (LunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month] == 0)) { // // Adjust the Year. // result.year++; hebrewYearType = HebrewTable[(gregorianYear + 1 - FirstGregorianTableYear) * 2 + 1]; // // Adjust the Month. // result.month = 1; } } // // Found the right Lunar month. // result.day += (int)(NumDays - 1); } return (GetResult(result, part)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { try { int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int monthsInYear; int i; if (months >= 0) { i = m + months; while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra))) { y++; i -= monthsInYear; } } else { if ((i = m + months) <= 0) { months = -months; months -= m; y--; while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra))) { y--; months -= monthsInYear; } monthsInYear = GetMonthsInYear(y, CurrentEra); i = monthsInYear - months; } } int days = GetDaysInMonth(y, i); if (d > days) { d = days; } return (new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay))); } // We expect ArgumentException and ArgumentOutOfRangeException (which is subclass of ArgumentException) // If exception is thrown in the calls above, we are out of the supported range of this calendar. catch (ArgumentException) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_AddValue)); } } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); y += years; CheckHebrewYearValue(y, Calendar.CurrentEra, "years"); int months = GetMonthsInYear(y, CurrentEra); if (m > months) { m = months; } int days = GetDaysInMonth(y, m); if (d > days) { d = days; } long ticks = ToDateTime(y, m, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { // If we calculate back, the Hebrew day of week for Gregorian 0001/1/1 is Monday (1). // Therfore, the fomula is: return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } static internal int GetHebrewYearType(int year, int era) { CheckHebrewYearValue(year, era, "year"); // The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear. // So we need to convert year (Hebrew year value) to Gregorian Year below. return (HebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { // Get Hebrew year value of the specified time. int year = GetYear(time); DateTime beginOfYearDate; if (year == 5343) { // Gregorian 1583/01/01 corresponds to Hebrew 5343/04/07 (MinSupportedDateTime) // To figure out the Gregorian date associated with Hebrew 5343/01/01, we need to // count the days from 5343/01/01 to 5343/04/07 and subtract that from Gregorian // 1583/01/01. // 1. Tishri (30 days) // 2. Heshvan (30 days since 5343 has 355 days) // 3. Kislev (30 days since 5343 has 355 days) // 96 days to get from 5343/01/01 to 5343/04/07 // Gregorian 1583/01/01 - 96 days = 1582/9/27 // the beginning of Hebrew year 5343 corresponds to Gregorian September 27, 1582. beginOfYearDate = new DateTime(1582, 9, 27); } else { // following line will fail when year is 5343 (first supported year) beginOfYearDate = ToDateTime(year, 1, 1, 0, 0, 0, 0, CurrentEra); } return ((int)((time.Ticks - beginOfYearDate.Ticks) / TicksPerDay) + 1); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { CheckEraRange(era); int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6, "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); int monthDays = LunarMonthLen[hebrewYearType * MaxMonthPlusOne + month]; if (monthDays == 0) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month); } return (monthDays); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { CheckEraRange(era); // normal years : 1 = 353 days 2 = 354 days 3 = 355 days. // Leap years : 4 = 383 5 384 6 = 385 days. // LunarYearType is from 1 to 6 int LunarYearType = GetHebrewYearType(year, era); if (LunarYearType < 4) { // common year: LunarYearType = 1, 2, 3 return (352 + LunarYearType); } return (382 + (LunarYearType - 3)); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (HebrewEra); } public override int[] Eras { get { return (new int[] { HebrewEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { return (IsLeapYear(year, era) ? 13 : 12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (IsLeapMonth(year, month, era)) { // Every day in a leap month is a leap day. CheckHebrewDayValue(year, month, day, era); return (true); } else if (IsLeapYear(year, Calendar.CurrentEra)) { // There is an additional day in the 6th month in the leap year (the extra day is the 30th day in the 6th month), // so we should return true for 6/30 if that's in a leap year. if (month == 6 && day == 30) { return (true); } } CheckHebrewDayValue(year, month, day, era); return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { // Year/era values are checked in IsLeapYear(). if (IsLeapYear(year, era)) { // The 7th month in a leap year is a leap month. return (7); } return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { // Year/era values are checked in IsLeapYear(). bool isLeapYear = IsLeapYear(year, era); CheckHebrewMonthValue(year, month, era); // The 7th month in a leap year is a leap month. if (isLeapYear) { if (month == 7) { return (true); } } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckHebrewYearValue(year, era, "year"); return (((7 * (long)year + 1) % 19) < 7); } // (month1, day1) - (month2, day2) static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2) { if (month1 == month2) { return (day1 - day2); } // Make sure that (month1, day1) < (month2, day2) bool swap = (month1 > month2); if (swap) { // (month1, day1) < (month2, day2). Swap the values. // The result will be a negative number. int tempMonth, tempDay; tempMonth = month1; tempDay = day1; month1 = month2; day1 = day2; month2 = tempMonth; day2 = tempDay; } // Get the number of days from (month1,day1) to (month1, end of month1) int days = LunarMonthLen[lunarYearType * MaxMonthPlusOne + month1] - day1; // Move to next month. month1++; // Add up the days. while (month1 < month2) { days += LunarMonthLen[lunarYearType * MaxMonthPlusOne + month1++]; } days += day2; return (swap ? days : -days); } /*=================================HebrewToGregorian========================== **Action: Convert Hebrew date to Gregorian date. **Returns: **Arguments: **Exceptions: ** The algorithm is like this: ** The hebrew year has an offset to the Gregorian year, so we can guess the Gregorian year for ** the specified Hebrew year. That is, GreogrianYear = HebrewYear - FirstHebrewYearOf1AD. ** ** From the Gregorian year and HebrewTable, we can get the Hebrew month/day value ** of the Gregorian date January 1st. Let's call this month/day value [hebrewDateForJan1] ** ** If the requested Hebrew month/day is less than [hebrewDateForJan1], we know the result ** Gregorian date falls in previous year. So we decrease the Gregorian year value, and ** retrieve the Hebrew month/day value of the Gregorian date january 1st again. ** ** Now, we get the answer of the Gregorian year. ** ** The next step is to get the number of days between the requested Hebrew month/day ** and [hebrewDateForJan1]. When we get that, we can create the DateTime by adding/subtracting ** the ticks value of the number of days. ** ============================================================================*/ static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond) { // Get the rough Gregorian year for the specified hebrewYear. // int gregorianYear = hebrewYear - HebrewYearOf1AD; __DateBuffer hebrewDateOfJan1 = new __DateBuffer(); // year value is unused. int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1); if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day)) { return (new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond)); } int days = GetDayDifference(lunarYearType, hebrewMonth, hebrewDay, hebrewDateOfJan1.month, hebrewDateOfJan1.day); DateTime gregorianNewYear = new DateTime(gregorianYear, 1, 1); return (new DateTime(gregorianNewYear.Ticks + days * TicksPerDay + TimeToTicks(hour, minute, second, millisecond))); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckHebrewYearValue(year, era, "year"); CheckHebrewMonthValue(year, month, era); CheckHebrewDayValue(year, month, day, era); DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond); CheckTicksRange(dt.Ticks); return (dt); } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 5790; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value == 99) { // Do nothing here. Year 99 is allowed so that TwoDitYearMax is disabled. } else { CheckHebrewYearValue(value, HebrewEra, "value"); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return (base.ToFourDigitYear(year)); } if (year > MaxHebrewYear || year < MinHebrewYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear)); } return (year); } internal class __DateBuffer { internal int year; internal int month; internal int day; } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.ComponentModel; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// <para> /// Abstract Cimindication event args, which containing all elements related to /// an Cimindication. /// </para> /// </summary> public abstract class CimIndicationEventArgs : EventArgs { /// <summary> /// <para> /// Returns an Object value for an operation context /// </para> /// </summary> public Object Context { get { return context; } } internal Object context; } /// <summary> /// Cimindication exception event args, which containing occurred exception /// </summary> public class CimIndicationEventExceptionEventArgs : CimIndicationEventArgs { /// <summary> /// <para> /// Returns an exception /// </para> /// </summary> public Exception Exception { get { return exception; } } private Exception exception; /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="result"></param> public CimIndicationEventExceptionEventArgs(Exception theException) { context = null; this.exception = theException; } } /// <summary> /// Cimindication event args, which containing all elements related to /// an Cimindication. /// </summary> public class CimIndicationEventInstanceEventArgs : CimIndicationEventArgs { /// <summary> /// Get ciminstance of the indication object /// </summary> public CimInstance NewEvent { get { return (result == null) ? null : result.Instance; } } /// <summary> /// Get MachineId of the indication object /// </summary> public string MachineId { get { return (result == null) ? null : result.MachineId; } } /// <summary> /// Get BookMark of the indication object /// </summary> public string Bookmark { get { return (result == null) ? null : result.Bookmark; } } /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="result"></param> public CimIndicationEventInstanceEventArgs(CimSubscriptionResult result) { context = null; this.result = result; } /// <summary> /// <para> /// subscription result /// </para> /// </summary> private CimSubscriptionResult result; } /// <summary> /// <para> /// A public class used to start/stop the subscription to specific indication source, /// and listen to the incoming indications, event <see cref="CimIndicationArrived"/> /// will be raised for each cimindication. /// </para> /// </summary> public class CimIndicationWatcher { /// <summary> /// status of <see cref="CimIndicationWatcher"/> object. /// </summary> internal enum Status { Default, Started, Stopped } /// <summary> /// <para> /// CimIndication arrived event /// </para> /// </summary> public event EventHandler<CimIndicationEventArgs> CimIndicationArrived; /// <summary> /// <para> /// Constructor with given computerName, namespace, queryExpression and timeout /// </para> /// </summary> /// <param name="computerName"></param> /// <param name="nameSpace"></param> /// <param name="queryExpression"></param> /// <param name="operationTimeout"></param> public CimIndicationWatcher( string computerName, string theNamespace, string queryDialect, string queryExpression, UInt32 operationTimeout) { ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); computerName = ConstValue.GetComputerName(computerName); theNamespace = ConstValue.GetNamespace(theNamespace); Initialize(computerName, null, theNamespace, queryDialect, queryExpression, operationTimeout); } /// <summary> /// <para> /// Constructor with given cimsession, namespace, queryExpression and timeout /// </para> /// </summary> /// <param name="cimSession"></param> /// <param name="nameSpace"></param> /// <param name="queryExpression"></param> /// <param name="operationTimeout"></param> public CimIndicationWatcher( CimSession cimSession, string theNamespace, string queryDialect, string queryExpression, UInt32 operationTimeout) { ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); ValidationHelper.ValidateNoNullArgument(cimSession, cimSessionParameterName); theNamespace = ConstValue.GetNamespace(theNamespace); Initialize(null, cimSession, theNamespace, queryDialect, queryExpression, operationTimeout); } /// <summary> /// <para> /// Initialize /// </para> /// </summary> private void Initialize( string theComputerName, CimSession theCimSession, string theNameSpace, string theQueryDialect, string theQueryExpression, UInt32 theOpreationTimeout) { enableRaisingEvents = false; status = Status.Default; myLock = new object(); cimRegisterCimIndication = new CimRegisterCimIndication(); cimRegisterCimIndication.OnNewSubscriptionResult += NewSubscriptionResultHandler; this.cimSession = theCimSession; this.nameSpace = theNameSpace; this.queryDialect = ConstValue.GetQueryDialectWithDefault(theQueryDialect); this.queryExpression = theQueryExpression; this.operationTimeout = theOpreationTimeout; this.computerName = theComputerName; } /// <summary> /// <para> /// Handler of new subscription result /// </para> /// </summary> /// <param name="src"></param> /// <param name="args"></param> private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs args) { EventHandler<CimIndicationEventArgs> temp = this.CimIndicationArrived; if (temp != null) { // raise the event CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs; if (resultArgs != null) temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result)); else { CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs; if (exceptionArgs != null) temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); } } } /// <summary> /// <para> /// Will be called by admin\monad\src\eengine\EventManager.cs: /// PSEventManager::ProcessNewSubscriber to start to listen to the Cim Indication. /// </para> /// <para> /// If set EnableRaisingEvents to false, which will be ignored /// </para> /// </summary> #if !CORECLR [BrowsableAttribute(false)] #endif public bool EnableRaisingEvents { get { return enableRaisingEvents; } set { DebugHelper.WriteLogEx(); if (value && !enableRaisingEvents) { enableRaisingEvents = value; Start(); } } } private bool enableRaisingEvents; /// <summary> /// <para> /// Start the subscription /// </para> /// </summary> public void Start() { DebugHelper.WriteLogEx(); lock(myLock) { if (status == Status.Default) { if (this.cimSession == null) { cimRegisterCimIndication.RegisterCimIndication( this.computerName, this.nameSpace, this.queryDialect, this.queryExpression, this.operationTimeout); } else { cimRegisterCimIndication.RegisterCimIndication( this.cimSession, this.nameSpace, this.queryDialect, this.queryExpression, this.operationTimeout); } status = Status.Started; } } } /// <summary> /// <para> /// Unsubscribe the subscription /// </para> /// </summary> public void Stop() { DebugHelper.WriteLogEx("Status = {0}", 0, this.status); lock (this.myLock) { if (status == Status.Started) { if (this.cimRegisterCimIndication != null) { DebugHelper.WriteLog("Dispose CimRegisterCimIndication object", 4); this.cimRegisterCimIndication.Dispose(); } status = Status.Stopped; } } } #region internal method /// <summary> /// Set the cmdlet object to throw ThrowTerminatingError /// in case there is a subscription failure /// </summary> /// <param name="cmdlet"></param> internal void SetCmdlet(Cmdlet cmdlet) { if (this.cimRegisterCimIndication != null) { this.cimRegisterCimIndication.Cmdlet = cmdlet; } } #endregion #region private members /// <summary> /// <para> /// CimRegisterCimIndication object /// </para> /// </summary> private CimRegisterCimIndication cimRegisterCimIndication; /// <summary> /// the status of <see cref="CimIndicationWatcher"/> object /// </summary> private Status status; /// <summary> /// lock started field /// </summary> private object myLock; /// <summary> /// CimSession parameter name /// </summary> private const string cimSessionParameterName = "cimSession"; /// <summary> /// QueryExpression parameter name /// </summary> private const string queryExpressionParameterName = "queryExpression"; #region parameters /// <summary> /// <para> /// parameters used to start the subscription /// </para> /// </summary> private string computerName; private CimSession cimSession; private string nameSpace; private string queryDialect; private string queryExpression; private UInt32 operationTimeout; #endregion #endregion } }//End namespace
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest\GameLogic // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 05:50 #region Using directives using DungeonQuest.Collision; using DungeonQuest.GameLogic; using DungeonQuest.Graphics; using DungeonQuest.Helpers; using DungeonQuest.Properties; using DungeonQuest.Sounds; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Text; using System.Threading; #endregion namespace DungeonQuest.Game { /// <summary> /// Third person camera camera class for Dungeon Quest. /// Always focuses on the head of the player and uses the same direction /// vector, which is only rotate around the z axis. /// </summary> public class ThirdPersonCamera : BaseCamera { #region Variables /// <summary> /// Initial player position. /// </summary> static readonly Vector3 InitialPlayerPosition = new Vector3(0, 0, 0); /// <summary> /// The player is about 2 meters in height and we always look on his head /// (around 1.9m). /// </summary> const float DefaultPlayerHeight = 1.5f;//1.9f; /// <summary> /// Player position /// </summary> Vector3 playerPos = InitialPlayerPosition, wannaHavePlayerPos = InitialPlayerPosition; /// <summary> /// X rotation is fixed, but the player can change +/- 15 degrees. /// The Z rotation is freely chooseable (just rotate around), /// Y (roll) is never changed. /// </summary> const float InitialXRotation = MathHelper.PiOver2 - MathHelper.Pi / 12.0f, MaxXRotationOffset = (float)Math.PI * 25.0f / 180.0f, InitialZRotation = MathHelper.Pi, InitialPlayerRotation = 0;//MathHelper.Pi; /// <summary> /// X and z rotation for the camera behind the player. /// The player itself has its own rotation and moves in that direction. /// The rotation will be calculated from the movement the user /// wants, but is has to be interpolated to look smooth. /// The wanna have variables help us interpolating. /// </summary> float xRotation = InitialXRotation, zRotation = InitialZRotation, playerRotation = InitialPlayerRotation, wannaHaveXRotation = InitialXRotation, wannaHaveZRotation = InitialZRotation, wannaHavePlayerRotation = InitialPlayerRotation; /// <summary> /// The camera distance is always the same. /// </summary> public const float CameraDistance = 3.0f;//2.25f;//2.75f;//1.75f; #endregion #region Reset /// <summary> /// Reset /// </summary> public override void Reset() { playerPos = InitialPlayerPosition; wannaHavePlayerPos = InitialPlayerPosition; xRotation = InitialXRotation; zRotation = InitialZRotation; playerRotation = InitialPlayerRotation; wannaHaveXRotation = InitialXRotation; wannaHaveZRotation = InitialZRotation; wannaHavePlayerRotation = InitialPlayerRotation; playerObject = new AnimatedGameObject( GameManager.AnimatedTypes.Hero, Matrix.Identity); } // Reset() #endregion #region Properties /// <summary> /// Player position /// </summary> /// <returns>Vector 3</returns> public override Vector3 PlayerPos { get { return playerPos; } // get } // PlayerPos /// <summary> /// Player rotation /// </summary> /// <returns>Float</returns> public override float PlayerRotation { get { return playerRotation; } // get } // PlayerRotation /// <summary> /// Player blend states /// </summary> public override float[] PlayerBlendStates { get { return playerObject.blendedStates; } // get } // PlayerBlendStates #endregion #region Constructor /// <summary> /// Keys for moving around. Assigned from settings! /// </summary> static Keys moveLeftKey, moveRightKey, moveUpKey, moveDownKey; public ThirdPersonCamera(BaseGame game) : base(game) { // Assign keys. Warning: This is VERY slow, never use it // inside any render loop (getting Settings, etc.)! //Note: Not true anymore for the new GameSettings class, it is faster! moveLeftKey = GameSettings.Default.MoveLeftKey; moveRightKey = GameSettings.Default.MoveRightKey; moveUpKey = GameSettings.Default.MoveForwardKey; moveDownKey = GameSettings.Default.MoveBackwardKey; } // ThridPersonCamera(game) #endregion #region Initialize /// <summary> /// Initialize /// </summary> public override void Initialize() { base.Initialize(); } // Initialize() #endregion #region Update /// <summary> /// Update /// </summary> /// <param name="gameTime">Game time</param> public override void Update(GameTime gameTime) { base.Update(gameTime); // Player movement! Vector2 playerMove = Vector2.Zero; float playerSpeed = 5.0f + Player.speedIncrease; playerMove.X += Input.GamePad.ThumbSticks.Left.X * BaseGame.MoveFactorPerSecond * playerSpeed; playerMove.Y += Input.GamePad.ThumbSticks.Left.Y * BaseGame.MoveFactorPerSecond * playerSpeed; if (Input.Keyboard.IsKeyDown(moveLeftKey) || Input.Keyboard.IsKeyDown(Keys.Left) || Input.GamePad.DPad.Left == ButtonState.Pressed) playerMove.X -= BaseGame.MoveFactorPerSecond * playerSpeed; if (Input.Keyboard.IsKeyDown(moveRightKey) || Input.Keyboard.IsKeyDown(Keys.Right) || Input.GamePad.DPad.Right == ButtonState.Pressed) playerMove.X += BaseGame.MoveFactorPerSecond * playerSpeed; if (Input.Keyboard.IsKeyDown(moveUpKey) || Input.Keyboard.IsKeyDown(Keys.Up) || Input.GamePad.DPad.Up == ButtonState.Pressed) playerMove.Y += BaseGame.MoveFactorPerSecond * playerSpeed; if (Input.Keyboard.IsKeyDown(moveDownKey) || Input.Keyboard.IsKeyDown(Keys.Down) || Input.GamePad.DPad.Down == ButtonState.Pressed) playerMove.Y -= BaseGame.MoveFactorPerSecond * playerSpeed; // Update wannaHavePlayerPos, which will change the playerPos below, // but use the rotated playerMove for that (else movement is not // relative to the camera) Vector3 playerMovement = Vector3.Transform( //normal:new Vector3(playerMove, 0), new Vector3(playerMove*2, 0), Matrix.CreateRotationZ(zRotation)); // If the movement is big enough, update the rotation! if (playerMovement.Length() > 0.0001f) { wannaHavePlayerRotation = MathHelper.PiOver2 + (float)Math.Atan2(playerMovement.Y, playerMovement.X); Sound.StartSteps(); } // if (playerMovement.Length) else Sound.StopSteps(); if (Player.GameOver || //always: Player.victory == false || Player.GameTime < 0) { if (Player.GameOver && Player.victory == false) playerObject.state = AnimatedGameObject.States.Die; wannaHaveZRotation = zRotation = BaseGame.TotalTime / 4.509f; } // if (Player.GameOver) else if (Input.Keyboard.IsKeyDown(Keys.LeftControl) || Input.GamePadAPressed || Input.MouseLeftButtonPressed) { // Don't change hit mode until we got through with the animation. if (playerObject.state != AnimatedGameObject.States.Hit1 && playerObject.state != AnimatedGameObject.States.Hit2) playerObject.state = RandomHelper.GetRandomInt(2) == 0 ? AnimatedGameObject.States.Hit1 : AnimatedGameObject.States.Hit2; playerMovement = Vector3.Zero; } // else if else if (playerMovement.Length() > BaseGame.MoveFactorPerSecond * 5) playerObject.state = AnimatedGameObject.States.Run; else playerObject.state = AnimatedGameObject.States.Idle; // Update and blend states. playerObject.UpdateState(); //tst: Thread.Sleep(100); // Use collision system now! CaveCollision.UpdatePlayerPosition( ref wannaHavePlayerPos, playerMovement, false, playerObject); // Always hit at frame 11 if (playerObject.state == AnimatedGameObject.States.Hit1 || playerObject.state == AnimatedGameObject.States.Hit2) { // Use 49 for animation length for Hit1 and 29 for Hit2, // see AnimatedColladaModel.cs:218 for details. //int animationLength = // playerObject.state == AnimatedGameObject.States.Hit1 ? 45 : 29; AnimatedGameObject nearestEnemy = null; foreach (AnimatedGameObject model in GameManager.animatedObjects) if ((nearestEnemy == null || (BaseGame.camera.PlayerPos - model.positionMatrix.Translation). Length() < (BaseGame.camera.PlayerPos - nearestEnemy.positionMatrix.Translation). Length()) && // Must not be dead model.state != AnimatedGameObject.States.Die) nearestEnemy = model; if (nearestEnemy != null && (nearestEnemy.positionMatrix.Translation - BaseGame.camera.PlayerPos).Length() < 2.25f) { // Rotate player towards this enemy if not moving right now if (playerMovement.Length() <= 0.0001f) { Vector3 helperVector = nearestEnemy.positionMatrix.Translation - BaseGame.camera.PlayerPos; wannaHavePlayerRotation = MathHelper.PiOver2 + (float)Math.Atan2(helperVector.Y, helperVector.X); } // if (playerMovement.Length) if (playerObject.GetAnimationElapsedTimeFrame(16))//22)) { // Hurt monster if its close. Vector3 effectPos = Vector3.Transform( new Vector3(0.2f, -0.82f, 1.2f) + RandomHelper.GetRandomVector3(-0.3f, 0.3f), Matrix.CreateRotationZ(wannaHavePlayerRotation)); float damage = Player.CurrentWeaponDamage; EffectManager.AddBlood(wannaHavePlayerPos + effectPos, 0.125f); //Sound.Play(Sound.Sounds.HitFlesh); // Hit1 does 33% more damage (animation takes longer)! damage = (playerObject.state == AnimatedGameObject.States.Hit1 ? 1.33f : 1.0f) * damage; // More speed gives also more attack! damage *= 1.0f + Player.speedIncrease / 6.0f; // Increase armor for higher levels damage -= Player.level / 2; if (damage > 0) { nearestEnemy.hitpoints -= damage; Player.score++; // Give a little energy to player if monster died if (nearestEnemy.hitpoints <= 0) { Player.health += (3 + (int)nearestEnemy.type); if (Player.health > 100) Player.health = 100; } // if (nearestEnemy.hitpoints) } // if (damage) if (damage > 0) { // Do not always play a player cry if (RandomHelper.GetRandomInt(3) == 0) Sound.Play( nearestEnemy.type == GameManager.AnimatedTypes.Ogre || nearestEnemy.type == GameManager.AnimatedTypes.BigOgre ? Sound.Sounds.OgreWasHit : Sound.Sounds.GoblinWasHit); } // if (damage) // No damage? Then don't cry // But always play hit sound, this makes the sound make much realer Sound.Play(Player.currentWeapon == Player.WeaponTypes.Club ? Sound.Sounds.HitClub : Sound.Sounds.HitFlesh); } // if (playerObject.GetAnimationElapsedTimeFrame) //else if ((int)(Player.GameTime * 30) % animationLength == 11 || // (int)(Player.GameTime * 30) % animationLength == 12) else if (playerObject.GetAnimationElapsedTimeFrame(11) || playerObject.GetAnimationElapsedTimeFrame(25)) { // Hurt player if he is close. Vector3 effectPos = Vector3.Transform( new Vector3(0.2f, -0.82f, 1.2f) + RandomHelper.GetRandomVector3(-0.3f, 0.3f), Matrix.CreateRotationZ(wannaHavePlayerRotation)); EffectManager.AddBlood(wannaHavePlayerPos + effectPos, 0.1f); } // else if } // if (nearestEnemy) //if ((int)(Player.GameTime * 30) % animationLength == 2 || // 30 is only used for Hit1, Hit2 has only 29 ani steps // (int)(Player.GameTime * 30) % animationLength == 30) if (playerObject.GetAnimationElapsedTimeFrame(1) || playerObject.GetAnimationElapsedTimeFrame(10) || playerObject.GetAnimationElapsedTimeFrame(11)) { Sound.Play(Sound.Sounds.Whosh); } // if (playerObject.GetAnimationElapsedTimeFrame) // At end of animation? //if ((int)(Player.GameTime*30) % animationLength == animationLength-1) if (playerObject.GetAnimationElapsedTimeFrame(0)) { // Set state back to idle, next frame it will be replaced // with a randomly choosen new hit animation! playerObject.state = RandomHelper.GetRandomInt(2) == 0 ? AnimatedGameObject.States.Hit1 : AnimatedGameObject.States.Hit2; } // if (playerObject.GetAnimationElapsedTimeFrame) } // if (playerObject.state) //TextureFont.WriteText(2, 60, "Blended states: " + // StringHelper.WriteArrayData(playerObject.blendedStates)); //obs: wannaHavePlayerPos += playerMovement; /*tst: if (Input.Keyboard.IsKeyDown(Keys.U)) wannaHavePlayerPos.Z += BaseGame.MoveFactorPerSecond * 5.0f; if (Input.Keyboard.IsKeyDown(Keys.V)) wannaHavePlayerPos.Z -= BaseGame.MoveFactorPerSecond * 5.0f; // Update player rotation which just results from the direction // we are moving to. If the player is not moving, there will be no change. /*TODO rotation += BaseGame.MoveFactorPerSecond / 1.75f; cameraPos = Vector3.Transform(initialPos*distance, Matrix.CreateRotationZ(rotation)); */ //TODO: resulting player rotation // Allow rotating with gamepad, mouse and keyboard are not supported yet. wannaHaveXRotation -= Input.GamePad.ThumbSticks.Right.Y * BaseGame.MoveFactorPerSecond * 1.6f; /*obs, cursor keys allow movement now! if (Input.Keyboard.IsKeyDown(Keys.Up)) wannaHaveXRotation -= BaseGame.MoveFactorPerSecond * 1.0f; if (Input.Keyboard.IsKeyDown(Keys.Down)) wannaHaveXRotation += BaseGame.MoveFactorPerSecond * 1.0f; */ if (wannaHaveXRotation < InitialXRotation - MaxXRotationOffset) wannaHaveXRotation = InitialXRotation - MaxXRotationOffset; if (wannaHaveXRotation > InitialXRotation + MaxXRotationOffset) wannaHaveXRotation = InitialXRotation + MaxXRotationOffset; wannaHaveZRotation -= Input.GamePad.ThumbSticks.Right.X * BaseGame.MoveFactorPerSecond * 3.5f; /*obs, cursor keys allow movement now! if (Input.Keyboard.IsKeyDown(Keys.Left)) wannaHaveZRotation += BaseGame.MoveFactorPerSecond * 2.5f; if (Input.Keyboard.IsKeyDown(Keys.Right)) wannaHaveZRotation -= BaseGame.MoveFactorPerSecond * 2.5f; */ // Allow control with mouse instead! // Ignore first 100ms, else we rotate around like crazy! if (Player.GameTime > 0.1f) { wannaHaveXRotation -= Input.MouseYMovement * BaseGame.MoveFactorPerSecond * 0.5f / 3.0f; wannaHaveZRotation -= Input.MouseXMovement * BaseGame.MoveFactorPerSecond * 1.0f / 3.5f; } // if (Player.GameTime) // Do the interpolation (25% each frame) // Do not allow any movement anymore if game is over if (Player.GameOver == false && Player.GameTime >= 0) { xRotation = xRotation * 0.75f + wannaHaveXRotation * 0.25f; //TODO: InterpolateRotation(xRotation, wannaHaveXRotation, 0.75f); zRotation = //Problematic because 0-360, just assign. wannaHaveZRotation; //TODO: zRotation * 0.75f + wannaHaveZRotation * 0.25f; // Quick fix! if (playerRotation - wannaHavePlayerRotation > 3.1415f) wannaHavePlayerRotation += MathHelper.Pi * 2.0f; else if (playerRotation - wannaHavePlayerRotation < -3.1415f) wannaHavePlayerRotation -= MathHelper.Pi * 2.0f; playerRotation = playerRotation * 0.925f + wannaHavePlayerRotation * 0.075f; playerPos = playerPos * 0.75f + wannaHavePlayerPos * 0.25f; } // if (Player.GameOver) // Look at the player pos (at his head) and build the view matrix // from all the rotation values we got. Vector3 lookTarget = playerPos + new Vector3(0, 0, DefaultPlayerHeight); BaseGame.ViewMatrix = Matrix.CreateLookAt( lookTarget + Vector3.Transform( new Vector3(0, 0, CameraDistance), Matrix.CreateRotationX(xRotation) * Matrix.CreateRotationZ(zRotation)), lookTarget, new Vector3(0, 0, 1)); } // Update(gameTime) #endregion } // class ThirdPersonCamera } // namespace DungeonQuest.Game
// // Backtrace.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Mono.Debugging.Client; using Mono.Debugging.Backend; namespace Mono.Debugging.Evaluation { public abstract class BaseBacktrace: RemoteFrameObject, IBacktrace { readonly Dictionary<int, FrameInfo> frameInfo = new Dictionary<int, FrameInfo> (); protected BaseBacktrace (ObjectValueAdaptor adaptor) { Adaptor = adaptor; } public abstract StackFrame[] GetStackFrames (int firstIndex, int lastIndex); public ObjectValueAdaptor Adaptor { get; set; } protected abstract EvaluationContext GetEvaluationContext (int frameIndex, EvaluationOptions options); public abstract int FrameCount { get; } public virtual ObjectValue[] GetLocalVariables (int frameIndex, EvaluationOptions options) { var frame = GetFrameInfo (frameIndex, options, false); var list = new List<ObjectValue> (); if (frame == null) { var val = Adaptor.CreateObjectValueAsync ("Local Variables", ObjectValueFlags.EvaluatingGroup, delegate { frame = GetFrameInfo (frameIndex, options, true); foreach (var local in frame.LocalVariables) list.Add (local.CreateObjectValue (false, options)); return ObjectValue.CreateArray (null, new ObjectPath ("Local Variables"), "", list.Count, ObjectValueFlags.EvaluatingGroup, list.ToArray ()); }); return new [] { val }; } foreach (ValueReference local in frame.LocalVariables) list.Add (local.CreateObjectValue (true, options)); return list.ToArray (); } public virtual ObjectValue[] GetParameters (int frameIndex, EvaluationOptions options) { var frame = GetFrameInfo (frameIndex, options, false); var values = new List<ObjectValue> (); if (frame == null) { var value = Adaptor.CreateObjectValueAsync ("Parameters", ObjectValueFlags.EvaluatingGroup, delegate { frame = GetFrameInfo (frameIndex, options, true); foreach (var param in frame.Parameters) values.Add (param.CreateObjectValue (false, options)); return ObjectValue.CreateArray (null, new ObjectPath ("Parameters"), "", values.Count, ObjectValueFlags.EvaluatingGroup, values.ToArray ()); }); return new [] { value }; } foreach (var param in frame.Parameters) values.Add (param.CreateObjectValue (true, options)); return values.ToArray (); } public virtual ObjectValue GetThisReference (int frameIndex, EvaluationOptions options) { var frame = GetFrameInfo (frameIndex, options, false); if (frame == null) { return Adaptor.CreateObjectValueAsync ("this", ObjectValueFlags.EvaluatingGroup, delegate { frame = GetFrameInfo (frameIndex, options, true); ObjectValue[] values; if (frame.This != null) values = new [] { frame.This.CreateObjectValue (false, options) }; else values = new ObjectValue [0]; return ObjectValue.CreateArray (null, new ObjectPath ("this"), "", values.Length, ObjectValueFlags.EvaluatingGroup, values); }); } return frame.This != null ? frame.This.CreateObjectValue (true, options) : null; } public virtual ExceptionInfo GetException (int frameIndex, EvaluationOptions options) { var frame = GetFrameInfo (frameIndex, options, false); ObjectValue value; if (frame == null) { value = Adaptor.CreateObjectValueAsync (options.CurrentExceptionTag, ObjectValueFlags.EvaluatingGroup, delegate { frame = GetFrameInfo (frameIndex, options, true); ObjectValue[] values; if (frame.Exception != null) values = new [] { frame.Exception.CreateObjectValue (false, options) }; else values = new ObjectValue [0]; return ObjectValue.CreateArray (null, new ObjectPath (options.CurrentExceptionTag), "", values.Length, ObjectValueFlags.EvaluatingGroup, values); }); } else if (frame.Exception != null) { value = frame.Exception.CreateObjectValue (true, options); } else { return null; } return new ExceptionInfo (value); } public virtual ObjectValue GetExceptionInstance (int frameIndex, EvaluationOptions options) { var frame = GetFrameInfo (frameIndex, options, false); if (frame == null) { return Adaptor.CreateObjectValueAsync (options.CurrentExceptionTag, ObjectValueFlags.EvaluatingGroup, delegate { frame = GetFrameInfo (frameIndex, options, true); ObjectValue[] values; if (frame.Exception != null) values = new [] { frame.Exception.Exception.CreateObjectValue (false, options) }; else values = new ObjectValue [0]; return ObjectValue.CreateArray (null, new ObjectPath (options.CurrentExceptionTag), "", values.Length, ObjectValueFlags.EvaluatingGroup, values); }); } return frame.Exception != null ? frame.Exception.Exception.CreateObjectValue (true, options) : null; } public virtual ObjectValue[] GetAllLocals (int frameIndex, EvaluationOptions options) { var locals = new List<ObjectValue> (); var excObj = GetExceptionInstance (frameIndex, options); if (excObj != null) locals.Insert (0, excObj); locals.AddRange (GetLocalVariables (frameIndex, options)); locals.AddRange (GetParameters (frameIndex, options)); locals.Sort ((v1, v2) => StringComparer.InvariantCulture.Compare (v1.Name, v2.Name)); var thisObj = GetThisReference (frameIndex, options); if (thisObj != null) locals.Insert (0, thisObj); return locals.ToArray (); } public virtual ObjectValue[] GetExpressionValues (int frameIndex, string[] expressions, EvaluationOptions options) { if (Adaptor.IsEvaluating) { var values = new List<ObjectValue> (); foreach (string exp in expressions) { string tmpExp = exp; var value = Adaptor.CreateObjectValueAsync (tmpExp, ObjectValueFlags.Field, delegate { EvaluationContext cctx = GetEvaluationContext (frameIndex, options); return Adaptor.GetExpressionValue (cctx, tmpExp); }); values.Add (value); } return values.ToArray (); } var ctx = GetEvaluationContext (frameIndex, options); return ctx.Adapter.GetExpressionValuesAsync (ctx, expressions); } public virtual CompletionData GetExpressionCompletionData (int frameIndex, string exp) { var ctx = GetEvaluationContext (frameIndex, EvaluationOptions.DefaultOptions); return ctx.Adapter.GetExpressionCompletionData (ctx, exp); } public virtual AssemblyLine[] Disassemble (int frameIndex, int firstLine, int count) { throw new NotImplementedException (); } public virtual ValidationResult ValidateExpression (int frameIndex, string expression, EvaluationOptions options) { var ctx = GetEvaluationContext (frameIndex, options); return Adaptor.ValidateExpression (ctx, expression); } FrameInfo GetFrameInfo (int frameIndex, EvaluationOptions options, bool ignoreEvalStatus) { FrameInfo finfo; if (frameInfo.TryGetValue (frameIndex, out finfo)) return finfo; if (!ignoreEvalStatus && Adaptor.IsEvaluating) return null; var ctx = GetEvaluationContext (frameIndex, options); if (ctx == null) return null; finfo = new FrameInfo (); finfo.Context = ctx; //Don't try to optimize lines below with lazy loading, you won't gain anything(in communication with runtime) finfo.LocalVariables.AddRange (ctx.Evaluator.GetLocalVariables (ctx)); finfo.Parameters.AddRange (ctx.Evaluator.GetParameters (ctx)); finfo.This = ctx.Evaluator.GetThisReference (ctx); var exp = ctx.Evaluator.GetCurrentException (ctx); if (exp != null) finfo.Exception = new ExceptionInfoSource (ctx, exp); frameInfo[frameIndex] = finfo; return finfo; } } class FrameInfo { public EvaluationContext Context; public List<ValueReference> LocalVariables = new List<ValueReference> (); public List<ValueReference> Parameters = new List<ValueReference> (); public ValueReference This; public ExceptionInfoSource Exception; } }
// 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.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal static class CSharpStructureHelpers { public const string Ellipsis = "..."; public const string MultiLineCommentSuffix = "*/"; public const int MaxXmlDocCommentBannerLength = 120; private static int GetCollapsibleStart(SyntaxToken firstToken) { // If the *next* token has any leading comments, we use the end of the last one. // If not, we check *this* token to see if it has any trailing comments and use the last one; // otherwise, we use the end of this token. var start = firstToken.Span.End; var nextToken = firstToken.GetNextToken(); if (nextToken.Kind() != SyntaxKind.None && nextToken.HasLeadingTrivia) { var lastLeadingCommentTrivia = nextToken.LeadingTrivia.GetLastComment(); if (lastLeadingCommentTrivia != null) { start = lastLeadingCommentTrivia.Value.Span.End; } } if (firstToken.HasTrailingTrivia) { var lastTrailingCommentOrWhitespaceTrivia = firstToken.TrailingTrivia.GetLastCommentOrWhitespace(); if (lastTrailingCommentOrWhitespaceTrivia != null) { start = lastTrailingCommentOrWhitespaceTrivia.Value.Span.End; } } return start; } private static int GetCollapsibleEnd(SyntaxToken lastToken) { // If the token has any trailing comments, we use the end of the token; // otherwise, we skip to the start of the first new line trivia. var end = lastToken.Span.End; if (lastToken.HasTrailingTrivia && !lastToken.TrailingTrivia.Any(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia)) { var firstNewLineTrivia = lastToken.TrailingTrivia.GetFirstNewLine(); if (firstNewLineTrivia != null) { end = firstNewLineTrivia.Value.SpanStart; } } return end; } public static SyntaxToken GetLastInlineMethodBlockToken(SyntaxNode node) { var lastToken = node.GetLastToken(includeZeroWidth: true); if (lastToken.Kind() == SyntaxKind.None) { return default(SyntaxToken); } // If the next token is a semicolon, and we aren't in the initializer of a for-loop, use that token as the end. SyntaxToken nextToken = lastToken.GetNextToken(includeSkipped: true); if (nextToken.Kind() != SyntaxKind.None && nextToken.Kind() == SyntaxKind.SemicolonToken) { var forStatement = nextToken.GetAncestor<ForStatementSyntax>(); if (forStatement != null && forStatement.FirstSemicolonToken == nextToken) { return default(SyntaxToken); } lastToken = nextToken; } return lastToken; } private static string CreateCommentBannerTextWithPrefix(string text, string prefix) { Contract.ThrowIfNull(text); Contract.ThrowIfNull(prefix); int prefixLength = prefix.Length; return prefix + " " + text.Substring(prefixLength).Trim() + " " + Ellipsis; } private static string GetCommentBannerText(SyntaxTrivia comment) { Contract.ThrowIfFalse(comment.IsSingleLineComment() || comment.IsMultiLineComment()); if (comment.IsSingleLineComment()) { return CreateCommentBannerTextWithPrefix(comment.ToString(), "//"); } else if (comment.IsMultiLineComment()) { int lineBreakStart = comment.ToString().IndexOfAny(new char[] { '\r', '\n' }); var text = comment.ToString(); if (lineBreakStart >= 0) { text = text.Substring(0, lineBreakStart); } else { text = text.EndsWith(MultiLineCommentSuffix) ? text.Substring(0, text.Length - MultiLineCommentSuffix.Length) : text; } return CreateCommentBannerTextWithPrefix(text, "/*"); } else { return string.Empty; } } private static BlockSpan CreateCommentBlockSpan( SyntaxTrivia startComment, SyntaxTrivia endComment) { var span = TextSpan.FromBounds(startComment.SpanStart, endComment.Span.End); return new BlockSpan( isCollapsible: true, textSpan: span, hintSpan: span, bannerText: GetCommentBannerText(startComment), autoCollapse: true, type: BlockTypes.Nonstructural); } // For testing purposes internal static ImmutableArray<BlockSpan> CreateCommentBlockSpan( SyntaxTriviaList triviaList) { var result = ArrayBuilder<BlockSpan>.GetInstance(); CollectCommentBlockSpans(triviaList, result); return result.ToImmutableAndFree(); } public static void CollectCommentBlockSpans( SyntaxTriviaList triviaList, ArrayBuilder<BlockSpan> spans) { if (triviaList.Count > 0) { SyntaxTrivia? startComment = null; SyntaxTrivia? endComment = null; Action completeSingleLineCommentGroup = () => { if (startComment != null) { var singleLineCommentGroupRegion = CreateCommentBlockSpan(startComment.Value, endComment.Value); spans.Add(singleLineCommentGroupRegion); startComment = null; endComment = null; } }; // Iterate through trivia and collect the following: // 1. Groups of contiguous single-line comments that are only separated by whitespace // 2. Multi-line comments foreach (var trivia in triviaList) { if (trivia.IsSingleLineComment()) { startComment = startComment ?? trivia; endComment = trivia; } else if (trivia.IsMultiLineComment()) { completeSingleLineCommentGroup(); var multilineCommentRegion = CreateCommentBlockSpan(trivia, trivia); spans.Add(multilineCommentRegion); } else if (!trivia.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia, SyntaxKind.EndOfFileToken)) { completeSingleLineCommentGroup(); } } completeSingleLineCommentGroup(); } } public static void CollectCommentBlockSpans( SyntaxNode node, ArrayBuilder<BlockSpan> spans) { if (node == null) { throw new ArgumentNullException(nameof(node)); } var triviaList = node.GetLeadingTrivia(); CollectCommentBlockSpans(triviaList, spans); } private static BlockSpan CreateBlockSpan( TextSpan textSpan, string bannerText, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( textSpan, textSpan, bannerText, autoCollapse, type, isCollapsible); } private static BlockSpan CreateBlockSpan( TextSpan textSpan, TextSpan hintSpan, string bannerText, bool autoCollapse, string type, bool isCollapsible) { return new BlockSpan( textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse, type: type, isCollapsible: isCollapsible); } public static BlockSpan CreateBlockSpan( SyntaxNode node, string bannerText, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( node.Span, bannerText, autoCollapse, type, isCollapsible); } public static BlockSpan CreateBlockSpan( SyntaxNode node, SyntaxToken syntaxToken, string bannerText, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( node, syntaxToken, node.GetLastToken(), bannerText, autoCollapse, type, isCollapsible); } public static BlockSpan CreateBlockSpan( SyntaxNode node, SyntaxToken startToken, int endPos, string bannerText, bool autoCollapse, string type, bool isCollapsible) { // If the SyntaxToken is actually missing, don't attempt to create an outlining region. if (startToken.IsMissing) { return null; } // Since we creating a span for everything after syntaxToken to ensure // that it collapses properly. However, the hint span begins at the start // of the next token so indentation in the tooltip is accurate. var span = TextSpan.FromBounds(GetCollapsibleStart(startToken), endPos); var hintSpan = TextSpan.FromBounds(node.SpanStart, endPos); return CreateBlockSpan( span, hintSpan, bannerText, autoCollapse, type, isCollapsible); } public static BlockSpan CreateBlockSpan( SyntaxNode node, SyntaxToken startToken, SyntaxToken endToken, string bannerText, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( node, startToken, GetCollapsibleEnd(endToken), bannerText, autoCollapse, type, isCollapsible); } public static BlockSpan CreateBlockSpan( SyntaxNode node, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( node, bannerText: Ellipsis, autoCollapse: autoCollapse, type: type, isCollapsible: isCollapsible); } // Adds everything after 'syntaxToken' up to and including the end // of node as a region. The snippet to display is just "..." public static BlockSpan CreateBlockSpan( SyntaxNode node, SyntaxToken syntaxToken, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( node, syntaxToken, bannerText: Ellipsis, autoCollapse: autoCollapse, type: type, isCollapsible: isCollapsible); } // Adds everything after 'syntaxToken' up to and including the end // of node as a region. The snippet to display is just "..." public static BlockSpan CreateBlockSpan( SyntaxNode node, SyntaxToken startToken, SyntaxToken endToken, bool autoCollapse, string type, bool isCollapsible) { return CreateBlockSpan( node, startToken, endToken, bannerText: Ellipsis, autoCollapse: autoCollapse, type: type, isCollapsible: isCollapsible); } // Adds the span surrounding the syntax list as a region. The // snippet shown is the text from the first line of the first // node in the list. public static BlockSpan CreateBlockSpan( IEnumerable<SyntaxNode> syntaxList, bool autoCollapse, string type, bool isCollapsible) { if (syntaxList.IsEmpty()) { return null; } var end = GetCollapsibleEnd(syntaxList.Last().GetLastToken()); var spanStart = syntaxList.First().GetFirstToken().FullSpan.End; var spanEnd = end >= spanStart ? end : spanStart; var hintSpanStart = syntaxList.First().SpanStart; var hintSpanEnd = end >= hintSpanStart ? end : hintSpanStart; return CreateBlockSpan( textSpan: TextSpan.FromBounds(spanStart, spanEnd), hintSpan: TextSpan.FromBounds(hintSpanStart, hintSpanEnd), bannerText: Ellipsis, autoCollapse: autoCollapse, type: type, isCollapsible: isCollapsible); } } }
// Visual Studio Shared Project // 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 ON AN *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, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.WebSockets; namespace Microsoft.VisualStudioTools { public abstract class WebSocketProxyBase : IHttpHandler { private static long _lastId; private static Task _currentSession; // represents the current active debugging session, and completes when it is over private static volatile StringWriter _log; private readonly long _id; public WebSocketProxyBase() { _id = Interlocked.Increment(ref _lastId); } public abstract int DebuggerPort { get; } public abstract bool AllowConcurrentConnections { get; } public abstract void ProcessHelpPageRequest(HttpContext context); public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { if (context.IsWebSocketRequest) { context.AcceptWebSocketRequest(WebSocketRequestHandler); } else { context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Encoding.UTF8; switch (context.Request.QueryString["debug"]) { case "startlog": _log = new StringWriter(); context.Response.Write("Logging is now enabled. <a href='?debug=viewlog'>View</a>. <a href='?debug=stoplog'>Disable</a>."); return; case "stoplog": _log = null; context.Response.Write("Logging is now disabled. <a href='?debug=startlog'>Enable</a>."); return; case "clearlog": { var log = _log; if (log != null) { log.GetStringBuilder().Clear(); } context.Response.Write("Log is cleared. <a href='?debug=viewlog'>View</a>."); return; } case "viewlog": { var log = _log; if (log == null) { context.Response.Write("Logging is disabled. <a href='?debug=startlog'>Enable</a>."); } else { context.Response.Write("Logging is enabled. <a href='?debug=clearlog'>Clear</a>. <a href='?debug=stoplog'>Disable</a>. <p><pre>"); context.Response.Write(HttpUtility.HtmlDecode(log.ToString())); context.Response.Write("</pre>"); } context.Response.End(); return; } } ProcessHelpPageRequest(context); } } private async Task WebSocketRequestHandler(AspNetWebSocketContext context) { Log("Accepted web socket request from {0}.", context.UserHostAddress); TaskCompletionSource<bool> tcs = null; if (!AllowConcurrentConnections) { tcs = new TaskCompletionSource<bool>(); while (true) { var currentSession = Interlocked.CompareExchange(ref _currentSession, tcs.Task, null); if (currentSession == null) { break; } Log("Another session is active, waiting for completion."); await currentSession; Log("The other session completed, proceeding."); } } try { var webSocket = context.WebSocket; using (var tcpClient = new TcpClient("localhost", DebuggerPort)) { try { var stream = tcpClient.GetStream(); var cts = new CancellationTokenSource(); // Start the workers that copy data from one socket to the other in both directions, and wait until either // completes. The workers are fully async, and so their loops are transparently interleaved when running. // Usually end of session is caused by VS dropping its connection on detach, and so it will be // CopyFromWebSocketToStream that returns first; but it can be the other one if debuggee process crashes. Log("Starting copy workers."); var copyFromStreamToWebSocketTask = CopyFromStreamToWebSocketWorker(stream, webSocket, cts.Token); var copyFromWebSocketToStreamTask = CopyFromWebSocketToStreamWorker(webSocket, stream, cts.Token); Task completedTask = null; try { completedTask = await Task.WhenAny(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask); } catch (IOException ex) { Log(ex); } catch (WebSocketException ex) { Log(ex); } // Now that one worker is done, try to gracefully terminate the other one by issuing a cancellation request. // it is normally blocked on a read, and this will cancel it if possible, and throw OperationCanceledException. Log("One of the workers completed, shutting down the remaining one."); cts.Cancel(); try { await Task.WhenAny(Task.WhenAll(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask), Task.Delay(1000)); } catch (OperationCanceledException ex) { Log(ex); } // Try to gracefully close the websocket if it's still open - this is not necessary, but nice to have. Log("Both workers shut down, trying to close websocket."); try { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None); } catch (WebSocketException ex) { Log(ex); } } finally { // Gracefully close the TCP socket. This is crucial to avoid "Remote debugger already attached" problems. Log("Shutting down TCP socket."); try { tcpClient.Client.Shutdown(SocketShutdown.Both); tcpClient.Client.Disconnect(false); } catch (SocketException ex) { Log(ex); } Log("All done!"); } } } finally { if (tcs != null) { Volatile.Write(ref _currentSession, null); tcs.SetResult(true); } } } private async Task CopyFromStreamToWebSocketWorker(Stream stream, WebSocket webSocket, CancellationToken ct) { var buffer = new byte[0x10000]; while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("TCP -> WS: waiting for packet."); int count = await stream.ReadAsync(buffer, 0, buffer.Length, ct); Log("TCP -> WS: received packet:\n{0}", Encoding.UTF8.GetString(buffer, 0, count)); if (count == 0) { Log("TCP -> WS: zero-length TCP packet received, connection closed."); break; } await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, count), WebSocketMessageType.Binary, true, ct); Log("TCP -> WS: packet relayed."); } } private async Task CopyFromWebSocketToStreamWorker(WebSocket webSocket, Stream stream, CancellationToken ct) { var buffer = new ArraySegment<byte>(new byte[0x10000]); while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("WS -> TCP: waiting for packet."); var recv = await webSocket.ReceiveAsync(buffer, ct); Log("WS -> TCP: received packet:\n{0}", Encoding.UTF8.GetString(buffer.Array, 0, recv.Count)); await stream.WriteAsync(buffer.Array, 0, recv.Count, ct); Log("WS -> TCP: packet relayed."); } } private void Log(object o) { var log = _log; if (log != null) { log.WriteLine(_id + " :: " + o); } } private void Log(string format, object arg1) { var log = _log; if (log != null) { log.WriteLine(_id + " :: " + format, arg1); } } } }
// <copyright file="SparseMatrixTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double { /// <summary> /// Sparse matrix tests. /// </summary> public class SparseMatrixTests : MatrixTests { /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<double> CreateMatrix(int rows, int columns) { return Matrix<double>.Build.Sparse(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<double> CreateMatrix(double[,] data) { return Matrix<double>.Build.SparseOfArray(data); } /// <summary> /// Can create a matrix form array. /// </summary> [Test] public void CanCreateMatrixFrom1DArray() { var testData = new Dictionary<string, Matrix<double>> { {"Singular3x3", Matrix<double>.Build.SparseOfColumnMajor(3, 3, new double[] {1, 1, 1, 1, 1, 1, 2, 2, 2})}, {"Square3x3", Matrix<double>.Build.SparseOfColumnMajor(3, 3, new[] {-1.1, 0.0, -4.4, -2.2, 1.1, 5.5, -3.3, 2.2, 6.6})}, {"Square4x4", Matrix<double>.Build.SparseOfColumnMajor(4, 4, new[] {-1.1, 0.0, 1.0, -4.4, -2.2, 1.1, 2.1, 5.5, -3.3, 2.2, 6.2, 6.6, -4.4, 3.3, 4.3, -7.7})}, {"Tall3x2", Matrix<double>.Build.SparseOfColumnMajor(3, 2, new[] {-1.1, 0.0, -4.4, -2.2, 1.1, 5.5})}, {"Wide2x3", Matrix<double>.Build.SparseOfColumnMajor(2, 3, new[] {-1.1, 0.0, -2.2, 1.1, -3.3, 2.2})} }; foreach (var name in testData.Keys) { Assert.AreEqual(TestMatrices[name], testData[name]); } } /// <summary> /// Matrix from array is a copy. /// </summary> [Test] public void MatrixFrom1DArrayIsCopy() { // Sparse Matrix copies values from double[], but no remember reference. var data = new double[] {1, 1, 1, 1, 1, 1, 2, 2, 2}; var matrix = Matrix<double>.Build.SparseOfColumnMajor(3, 3, data); matrix[0, 0] = 10.0; Assert.AreNotEqual(10.0, data[0]); } /// <summary> /// Matrix from two-dimensional array is a copy. /// </summary> [Test] public void MatrixFrom2DArrayIsCopy() { var matrix = Matrix<double>.Build.SparseOfArray(TestData2D["Singular3x3"]); matrix[0, 0] = 10.0; Assert.AreEqual(1.0, TestData2D["Singular3x3"][0, 0]); } /// <summary> /// Can create a matrix from two-dimensional array. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Square3x3")] [TestCase("Square4x4")] [TestCase("Tall3x2")] [TestCase("Wide2x3")] public void CanCreateMatrixFrom2DArray(string name) { var matrix = Matrix<double>.Build.SparseOfArray(TestData2D[name]); for (var i = 0; i < TestData2D[name].GetLength(0); i++) { for (var j = 0; j < TestData2D[name].GetLength(1); j++) { Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]); } } } /// <summary> /// Can create an identity matrix. /// </summary> [Test] public void CanCreateIdentity() { var matrix = Matrix<double>.Build.SparseIdentity(5); Assert.That(matrix, Is.TypeOf<SparseMatrix>()); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, matrix[i, j]); } } } /// <summary> /// Identity with wrong order throws <c>ArgumentOutOfRangeException</c>. /// </summary> /// <param name="order">The size of the square matrix</param> [TestCase(0)] [TestCase(-1)] public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order) { Assert.That(() => Matrix<double>.Build.SparseIdentity(order), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeSparseMatrix() { var matrix = new SparseMatrix(500, 1000); var nonzero = 0; var rnd = new System.Random(0); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { var value = rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10); if (value != 0) { nonzero++; } matrix[i, j] = value; } } Assert.AreEqual(matrix.NonZerosCount, nonzero); } /// <summary> /// Test whether order matters when adding sparse matrices. /// </summary> [Test] public void CanAddSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.IsTrue(sum1.Equals(m2)); Assert.IsTrue(sum1.Equals(sum2)); Matrix<double> sparseResult = new SparseMatrix(1, 3); sparseResult.Add(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); sparseResult.Add(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); m1.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); sparseResult.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(2*sum1)); Matrix<double> denseResult = Matrix<double>.Build.Dense(1, 3); denseResult.Add(m2, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); denseResult = Matrix<double>.Build.DenseOfArray(new double[,] { { 0, 1, 1 } }); denseResult.Add(m1, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); var m3 = Matrix<double>.Build.DenseOfArray(new double[,] { { 0, 1, 1 } }); var sum3 = m1 + m3; var sum4 = m3 + m1; Assert.IsTrue(sum3.Equals(m3)); Assert.IsTrue(sum3.Equals(sum4)); } /// <summary> /// Test whether order matters when subtracting sparse matrices. /// </summary> [Test] public void CanSubtractSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); var diff1 = m1 - m2; var diff2 = m2 - m1; Assert.IsTrue(diff1.Equals(m2.Negate())); Assert.IsTrue(diff1.Equals(diff2.Negate())); Matrix<double> sparseResult = new SparseMatrix(1, 3); sparseResult.Subtract(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); sparseResult.Subtract(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(diff2)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); m1.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); sparseResult.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(0*diff1)); Matrix<double> denseResult = Matrix<double>.Build.Dense(1, 3); denseResult.Subtract(m2, denseResult); Assert.IsTrue(denseResult.Equals(diff1)); denseResult = Matrix<double>.Build.DenseOfArray(new double[,] { { 0, 1, 1 } }); denseResult.Subtract(m1, denseResult); Assert.IsTrue(denseResult.Equals(diff2)); var m3 = Matrix<double>.Build.DenseOfArray(new double[,] { { 0, 1, 1 } }); var diff3 = m1 - m3; var diff4 = m3 - m1; Assert.IsTrue(diff3.Equals(m3.Negate())); Assert.IsTrue(diff3.Equals(diff4.Negate())); } /// <summary> /// Test whether we can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeMatrix() { const int Order = 1000000; var matrix = Matrix<double>.Build.Sparse(Order, Order); Assert.AreEqual(Order, matrix.RowCount); Assert.AreEqual(Order, matrix.ColumnCount); Assert.DoesNotThrow(() => matrix[0, 0] = 1); } } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.Config.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Config.Api.Tests { public class CustomFieldSetupTests { public static CustomFieldSetupController Fixture() { CustomFieldSetupController controller = new CustomFieldSetupController(new CustomFieldSetupRepository()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Config.Entities.CustomFieldSetup customFieldSetup = Fixture().Get(0); Assert.NotNull(customFieldSetup); } [Fact] [Conditional("Debug")] public void First() { Frapid.Config.Entities.CustomFieldSetup customFieldSetup = Fixture().GetFirst(); Assert.NotNull(customFieldSetup); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Config.Entities.CustomFieldSetup customFieldSetup = Fixture().GetPrevious(0); Assert.NotNull(customFieldSetup); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Config.Entities.CustomFieldSetup customFieldSetup = Fixture().GetNext(0); Assert.NotNull(customFieldSetup); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Config.Entities.CustomFieldSetup customFieldSetup = Fixture().GetLast(); Assert.NotNull(customFieldSetup); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Config.Entities.CustomFieldSetup> customFieldSetups = Fixture().Get(new int[] { }); Assert.NotNull(customFieldSetups); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }