context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Threading; namespace Netduino.IP { internal class ArpResolver : IDisposable { // fixed buffer for ARP request/reply frames const int ARP_FRAME_BUFFER_LENGTH = 28; byte[] _arpFrameBuffer = new byte[ARP_FRAME_BUFFER_LENGTH]; object _arpFrameBufferLock = new object(); UInt32 _currentArpRequestProtocolAddress = 0x00000000; UInt64 _currentArpRequestPhysicalAddress = 0x000000000000; object _simultaneousArpRequestLock = new object(); // this lock is used to make sure we only have one simultaneous outgoing ARP request at a time; we could modify this to allow multiple parallel requests in the future AutoResetEvent _currentArpRequestAnsweredEvent = new AutoResetEvent(false); byte[][] _bufferArray = new byte[1][]; int[] _indexArray = new int[1]; int[] _countArray = new int[1]; const UInt16 HARDWARE_TYPE_ETHERNET = 0x0001; const UInt16 DATA_TYPE_ARP = 0x0806; const UInt16 PROTOCOL_TYPE_IPV4 = 0x0800; const byte HARDWARE_ADDRESS_SIZE = 6; const byte PROTOCOL_ADDRESS_SIZE = 4; const UInt32 MAX_ARP_TRANSLATE_ATTEMPTS = 3; /* the maximum number of times we will attempt to translate an IP Address into a Physical Address, per packet */ const UInt16 DEFAULT_ARP_CACHE_TIMEOUT_IN_SECONDS = 1200; /* the default timeout for ARP cache items */ enum ArpOperation : ushort { ARP_OPERATION_REQUEST = 0x01, ARP_OPERATION_REPLY = 0x02, } const UInt64 ETHERNET_BROADCAST_ADDRESS = 0x00FFFFFFFFFFFF; UInt32 _ipv4ProtocolAddress = 0x00000000; // NOTE: in a future version of NETMF (with nullable type support), we would ideally change this to a struct--and use nullable struct types instead of classes. class ArpCacheEntry { public ArpCacheEntry(UInt64 physicalAddress, Int64 timeoutTicks, Int64 lastUsedTicks = 0) { this.PhysicalAddress = physicalAddress; this.TimeoutTicks = timeoutTicks; this.LastUsedTicks = lastUsedTicks; } public UInt64 PhysicalAddress; public Int64 TimeoutTicks; /* LastUsedTicks is set whenever the entry is used to send a packet; * it is set to zero (unused) when this entry is a reply of an incoming ARP request; * when the ARP Cache is full, we clean out the oldest ARP entry based on the value of LastUsedTicks */ public Int64 LastUsedTicks; } const byte ARP_CACHE_MAXIMUM_ENTRIES = 254; /* we will store a maximum of 254 entires in our ARP cache */ /* TODO: we should consider making this a configurable option...and default it to 4-8 */ System.Collections.Hashtable _arpCache; object _arpCacheLock = new object(); struct ArpGenericData { public ArpGenericData(UInt64 destinationEthernetAddress, ArpOperation arpOperation, UInt64 targetPhysicalAddress, UInt32 targetProtocolAddress) { this.DestinationEthernetAddress = destinationEthernetAddress; this.ArpOperaton = arpOperation; this.TargetPhysicalAddress = targetPhysicalAddress; this.TargetProtocolAddress = targetProtocolAddress; } public UInt64 DestinationEthernetAddress; public ArpOperation ArpOperaton; public UInt32 TargetProtocolAddress; public UInt64 TargetPhysicalAddress; } System.Threading.Thread _sendArpGenericInBackgroundThread; AutoResetEvent _sendArpGenericInBackgroundEvent = new AutoResetEvent(false); System.Collections.Queue _sendArpGenericInBackgroundQueue; System.Threading.Timer _cleanupArpCacheTimer; EthernetInterface _ethernetInterface; bool _isDisposed = false; public ArpResolver(EthernetInterface ethernetInterface) { // save a reference to our ethernet interface; we will use this to send ARP fraems _ethernetInterface = ethernetInterface; // create our ARP cache _arpCache = new System.Collections.Hashtable(); /* write fixed ARP frame parameters (which do not change) to our ARP frame buffer */ /* Hardware Type: 0x0001 (Ethernet) */ _arpFrameBuffer[0] = (byte)((HARDWARE_TYPE_ETHERNET >> 8) & 0xFF); _arpFrameBuffer[1] = (byte)(HARDWARE_TYPE_ETHERNET & 0xFF); /* Protocol Type: 0x0800 (IPv4) */ _arpFrameBuffer[2] = (byte)((PROTOCOL_TYPE_IPV4 >> 8) & 0xFF); _arpFrameBuffer[3] = (byte)(PROTOCOL_TYPE_IPV4 & 0xFF); /* Hardware Address Size: 6 bytes */ _arpFrameBuffer[4] = HARDWARE_ADDRESS_SIZE; /* Protocol Address Size: 4 bytes */ _arpFrameBuffer[5] = PROTOCOL_ADDRESS_SIZE; /* fixed values for index and count (passed to EthernetInterface.Send(...) with _arpFrameBuffer */ _indexArray[0] = 0; _countArray[0] = ARP_FRAME_BUFFER_LENGTH; // start our "send ARP replies" thread _sendArpGenericInBackgroundQueue = new System.Collections.Queue(); _sendArpGenericInBackgroundThread = new Thread(SendArpGenericThread); _sendArpGenericInBackgroundThread.Start(); // enable our "cleanup ARP cache" timer (fired every 60 seconds) _cleanupArpCacheTimer = new Timer(CleanupArpCache, null, 60000, 60000); // wire up the incoming ARP frame handler _ethernetInterface.ARPFrameReceived += _ethernetInterface_ARPFrameReceived; } public void Dispose() { if (_isDisposed) return; _isDisposed = true; // shut down our ARP response thread if (_sendArpGenericInBackgroundEvent != null) { _sendArpGenericInBackgroundEvent.Set(); _sendArpGenericInBackgroundEvent = null; } // timeout any current ARP requests if (_currentArpRequestAnsweredEvent != null) { _currentArpRequestAnsweredEvent.Set(); _currentArpRequestAnsweredEvent = null; } if (_arpCache != null) _arpCache.Clear(); _cleanupArpCacheTimer.Dispose(); _ethernetInterface = null; _arpFrameBuffer = null; _arpFrameBufferLock = null; _bufferArray = null; _indexArray = null; _countArray = null; } internal void SetIpv4Address(UInt32 ipv4ProtocolAddress) { _ipv4ProtocolAddress = ipv4ProtocolAddress; } void _ethernetInterface_ARPFrameReceived(object sender, byte[] buffer, int index, int count) { // verify that our ARP frame is long enough if (count < ARP_FRAME_BUFFER_LENGTH) return; // discard packet /* parse our ARP frame */ // first validate our frame's fixed header UInt16 hardwareType = (UInt16)((buffer[index] << 8) + buffer[index + 1]); if (hardwareType != HARDWARE_TYPE_ETHERNET) return; // only Ethernet hardware is supported; discard frame UInt16 protocolType = (UInt16)((buffer[index + 2] << 8) + buffer[index + 3]); if (protocolType != PROTOCOL_TYPE_IPV4) return; // only IPv4 protocol is supported; discard frame byte hardwareAddressSize = buffer[index + 4]; if (hardwareAddressSize != HARDWARE_ADDRESS_SIZE) return; // invalid hardware address size byte protocolAddressSize = buffer[index + 5]; if (protocolAddressSize != PROTOCOL_ADDRESS_SIZE) return; // invalid protocol address size ArpOperation operation = (ArpOperation)((buffer[index + 6] << 8) + buffer[index + 7]); // NOTE: we will validate the operation a bit later after we compare the incoming targetProtocolAddress. // retrieve the sender and target addresses UInt64 senderPhysicalAddress = (UInt64)(((UInt64)buffer[index + 8] << 40) + ((UInt64)buffer[index + 9] << 32) + ((UInt64)buffer[index + 10] << 24) + ((UInt64)buffer[index + 11] << 16) + ((UInt64)buffer[index + 12] << 8) + (UInt64)buffer[index + 13]); UInt32 senderProtocolAddress = (UInt32)(((UInt32)buffer[index + 14] << 24) + ((UInt32)buffer[index + 15] << 16) + ((UInt32)buffer[index + 16] << 8) + (UInt32)buffer[index + 17]); //UInt64 targetHardwareAddress = (UInt64)(((UInt64)buffer[index + 18] << 40) + ((UInt64)buffer[index + 19] << 32) + ((UInt64)buffer[index + 20] << 24) + ((UInt64)buffer[index + 21] << 16) + ((UInt64)buffer[index + 22] << 8) + (UInt64)buffer[index + 23]); UInt32 targetProtocolAddress = (UInt32)(((UInt32)buffer[index + 24] << 24) + ((UInt32)buffer[index + 25] << 16) + ((UInt32)buffer[index + 26] << 8) + (UInt32)buffer[index + 27]); // if the sender IP is already listed in our ARP cache then update the entry lock (_arpCacheLock) { ArpCacheEntry arpEntry = (ArpCacheEntry)_arpCache[senderProtocolAddress]; if (arpEntry != null) { arpEntry.PhysicalAddress = senderPhysicalAddress; Int64 nowTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks; arpEntry.TimeoutTicks = nowTicks + (TimeSpan.TicksPerSecond * DEFAULT_ARP_CACHE_TIMEOUT_IN_SECONDS); // NOTE: we do not update the LastUsedTicks property since this is not the result of a request for a non-existent cache entry } else { // do nothing. some implementation of ARP would create a cache entry for any incoming ARP packets...but we only cache a limited number of entries which we requested. } } if (operation == ArpOperation.ARP_OPERATION_REQUEST) { // if the request is asking for our IP protocol address, then send an ARP reply if (targetProtocolAddress == _ipv4ProtocolAddress) { // we do not want to block our RX thread, so queue a response on a worker thread SendArpGenericInBackground(senderPhysicalAddress, ArpOperation.ARP_OPERATION_REPLY, senderPhysicalAddress, senderProtocolAddress); } } else if (operation == ArpOperation.ARP_OPERATION_REPLY) { if (senderProtocolAddress == _currentArpRequestProtocolAddress) { _currentArpRequestPhysicalAddress = senderPhysicalAddress; _currentArpRequestAnsweredEvent.Set(); } } else { // invalid operation; discard frame } } /* this function translates a target IP address into a destination physical address * NOTE: if the address could not be translated, the function returns zero. */ internal UInt64 TranslateIPAddressToPhysicalAddress(UInt32 ipAddress, Int64 timeoutInMachineTicks) { // if the ipAdderss is the broadcast address, return a broadcast MAC address if (ipAddress == 0xFFFFFFFF) return ETHERNET_BROADCAST_ADDRESS; ArpCacheEntry arpEntry = null; // retrieve our existing ARP entry, if it exists lock (_arpCacheLock) { arpEntry = (ArpCacheEntry)_arpCache[ipAddress]; // if we retrieved an entry, make sure it has not timed out. if (arpEntry != null) { Int64 nowTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks; if (arpEntry.TimeoutTicks < nowTicks) { // if the entry has timed out, dispose of it; we will re-query the target _arpCache.Remove(ipAddress); arpEntry = null; } } } // if we were caching a valid ARP entry, return its PhysicalAddress now. if (arpEntry != null) return arpEntry.PhysicalAddress; // if we did not obtain a valid ARP entry, query for one now. lock (_simultaneousArpRequestLock) /* lock our current ARP request...we can only have one request at a time. */ { Int32 waitTimeout; for (int iAttempt = 0; iAttempt < MAX_ARP_TRANSLATE_ATTEMPTS; iAttempt++) { // set the IP Address of our current ARP request _currentArpRequestProtocolAddress = ipAddress; _currentArpRequestPhysicalAddress = 0; // this will be set to a non-zero value if we get a response _currentArpRequestAnsweredEvent.Reset(); // send the ARP request SendArpRequest(ipAddress, timeoutInMachineTicks); // wait on a reply (for up to our timeout time or 1 second...whichever is less) waitTimeout = System.Math.Min((Int32)((timeoutInMachineTicks != Int64.MaxValue) ? Math.Max((timeoutInMachineTicks - Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks) / System.TimeSpan.TicksPerMillisecond, 0) : 1000), 1000); _currentArpRequestAnsweredEvent.WaitOne(waitTimeout, false); // if we received an ARP reply, add it to our cache table try { if (_currentArpRequestPhysicalAddress != 0) { lock (_arpCacheLock) { // first make sure that our cache table is not full; if it is full then remove the oldest entry (based on LastUsedTime) if (_arpCache.Count >= ARP_CACHE_MAXIMUM_ENTRIES) { Int64 oldestLastUsedTicks = Int64.MaxValue; UInt32 oldestKey = 0; foreach (UInt32 key in _arpCache.Keys) { if (((ArpCacheEntry)_arpCache[key]).LastUsedTicks < oldestLastUsedTicks) { oldestKey = key; oldestLastUsedTicks = ((ArpCacheEntry)_arpCache[key]).LastUsedTicks; } } _arpCache.Remove(oldestKey); } // then add our new cache entry and return the ARP reply's address. Int64 nowTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks; arpEntry = new ArpCacheEntry(_currentArpRequestPhysicalAddress, nowTicks + (TimeSpan.TicksPerSecond * DEFAULT_ARP_CACHE_TIMEOUT_IN_SECONDS), nowTicks); _arpCache.Add(_currentArpRequestProtocolAddress, arpEntry); } return _currentArpRequestPhysicalAddress; } // if we're out of (user-specified) time without a reply, return zero (no address). if (Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks > timeoutInMachineTicks) return 0; } finally { _currentArpRequestProtocolAddress = 0; // no ARP request is in process now. } } } // if we could not get the address of the target, return zero. return 0; } void SendArpGenericThread() { while (true) { _sendArpGenericInBackgroundEvent.WaitOne(); // if we have been disposed, shut down our thread now. if (_isDisposed) return; while ((_sendArpGenericInBackgroundQueue != null) && (_sendArpGenericInBackgroundQueue.Count > 0)) { try { ArpGenericData arpGenericData = (ArpGenericData)_sendArpGenericInBackgroundQueue.Dequeue(); SendArpGeneric(arpGenericData.DestinationEthernetAddress, arpGenericData.ArpOperaton, arpGenericData.TargetPhysicalAddress, arpGenericData.TargetProtocolAddress, Int64.MaxValue); } catch (InvalidOperationException) { // reply queue was empty } // if we have been disposed, shut down our thread now. if (_isDisposed) return; } } } ///* TODO: verify that this content is correct for an ARP announcement */ //public void SendArpAnnouncement() //{ // SendArpGeneric(ETHERNET_BROADCAST_ADDRESS, ArpOperation.ARP_OPERATION_REQUEST, _ethernetInterface.PhysicalAddress, _ipv4ProtocolAddress, 0x000000000000, _ipv4ProtocolAddress, Int64.MaxValue); //} public void SendArpGratuitousInBackground() { SendArpGenericInBackground(ETHERNET_BROADCAST_ADDRESS, ArpOperation.ARP_OPERATION_REQUEST, 0x000000000000, _ipv4ProtocolAddress); } public void SendArpGratuitous() { SendArpGeneric(ETHERNET_BROADCAST_ADDRESS, ArpOperation.ARP_OPERATION_REQUEST, 0x000000000000, _ipv4ProtocolAddress, Int64.MaxValue); } ///* TODO: verify that this content is correct for an ARP probe */ //public void SendArpProbe(UInt32 targetProtocolAddress) //{ // /* TODO: should the two "0" entries be our NIC's IP address and the broadcast MAC respectively? */ // SendArpGeneric(ETHERNET_BROADCAST_ADDRESS, _ethernetInterface.PhysicalAddress, ArpOperation.ARP_OPERATION_REQUEST, _ethernetInterface.PhysicalAddress, 0x00000000, 0x000000000000, targetProtocolAddress, Int64.MaxValue); //} public void SendArpRequest(UInt32 targetProtocolAddress, Int64 timeoutInMachineTicks) { SendArpGeneric(ETHERNET_BROADCAST_ADDRESS, ArpOperation.ARP_OPERATION_REQUEST, 0x000000000000, targetProtocolAddress, timeoutInMachineTicks); } void SendArpReply(UInt64 targetPhysicalAddress, UInt32 targetProtocolAddress) { SendArpGeneric(targetPhysicalAddress, ArpOperation.ARP_OPERATION_REPLY, targetPhysicalAddress, targetProtocolAddress, Int64.MaxValue); } void SendArpGenericInBackground(UInt64 destinationEthernetAddress, ArpOperation arpOperation, UInt64 targetPhysicalAddress, UInt32 targetProtocolAddress) { ArpGenericData arpGenericData = new ArpGenericData(destinationEthernetAddress, arpOperation, targetPhysicalAddress, targetProtocolAddress); _sendArpGenericInBackgroundQueue.Enqueue(arpGenericData); _sendArpGenericInBackgroundEvent.Set(); } void SendArpGeneric(UInt64 destinationEthernetAddress, ArpOperation arpOperation, UInt64 targetPhysicalAddress, UInt32 targetProtocolAddress, Int64 timeoutInMachineTicks) { if (_isDisposed) return; lock (_arpFrameBufferLock) { UInt64 physicalAddress = _ethernetInterface.PhysicalAddressAsUInt64; // configure ARP packet /* Op: request (1) or reply (2) */ _arpFrameBuffer[6] = (byte)(((UInt16)arpOperation >> 8) & 0xFF); _arpFrameBuffer[7] = (byte)((UInt16)arpOperation & 0xFF); /* Sender Harwdare Address */ _arpFrameBuffer[8] = (byte)((physicalAddress >> 40) & 0xFF); _arpFrameBuffer[9] = (byte)((physicalAddress >> 32) & 0xFF); _arpFrameBuffer[10] = (byte)((physicalAddress >> 24) & 0xFF); _arpFrameBuffer[11] = (byte)((physicalAddress >> 16) & 0xFF); _arpFrameBuffer[12] = (byte)((physicalAddress >> 8) & 0xFF); _arpFrameBuffer[13] = (byte)(physicalAddress & 0xFF); /* Sender Protocol Address */ _arpFrameBuffer[14] = (byte)((_ipv4ProtocolAddress >> 24) & 0xFF); _arpFrameBuffer[15] = (byte)((_ipv4ProtocolAddress >> 16) & 0xFF); _arpFrameBuffer[16] = (byte)((_ipv4ProtocolAddress >> 8) & 0xFF); _arpFrameBuffer[17] = (byte)(_ipv4ProtocolAddress & 0xFF); /* Target Harwdare Address (if known) */ _arpFrameBuffer[18] = (byte)((targetPhysicalAddress >> 40) & 0xFF); _arpFrameBuffer[19] = (byte)((targetPhysicalAddress >> 32) & 0xFF); _arpFrameBuffer[20] = (byte)((targetPhysicalAddress >> 24) & 0xFF); _arpFrameBuffer[21] = (byte)((targetPhysicalAddress >> 16) & 0xFF); _arpFrameBuffer[22] = (byte)((targetPhysicalAddress >> 8) & 0xFF); _arpFrameBuffer[23] = (byte)(targetPhysicalAddress & 0xFF); /* Target Protocol Address */ _arpFrameBuffer[24] = (byte)((targetProtocolAddress >> 24) & 0xFF); _arpFrameBuffer[25] = (byte)((targetProtocolAddress >> 16) & 0xFF); _arpFrameBuffer[26] = (byte)((targetProtocolAddress >> 8) & 0xFF); _arpFrameBuffer[27] = (byte)(targetProtocolAddress & 0xFF); _bufferArray[0] = _arpFrameBuffer; _ethernetInterface.Send(destinationEthernetAddress, DATA_TYPE_ARP /* dataType: ARP */, _ipv4ProtocolAddress, targetProtocolAddress, 1 /* one buffer in bufferArray */, _bufferArray, _indexArray, _countArray, timeoutInMachineTicks); } } // this function is called ocassionally to clean up timed-out entries in the ARP cache void CleanupArpCache(object state) { Int64 nowTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks; bool keyWasRemoved = true; // NOTE: this loop isn't very efficient since it starts over after every key removal: we may consider more efficient removal processes in the future. while (keyWasRemoved == true) { keyWasRemoved = false; // default to "no keys removed" lock (_arpCacheLock) { foreach (UInt32 key in _arpCache.Keys) { if (((ArpCacheEntry)_arpCache[key]).TimeoutTicks < nowTicks) { _arpCache.Remove(key); keyWasRemoved = true; break; // exit the loop so we can parse the set of keys again; since we just removed a key the collection is not in a valid enumerable state. } } } } } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.ModelBinding; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using SearchCrawlerHelper.Sample.Models; using SearchCrawlerHelper.Sample.Providers; using SearchCrawlerHelper.Sample.Results; using System.Linq; using SearchCrawlerHelper.Sample.Filters; namespace SearchCrawlerHelper.Sample.Controllers { [Authorize] [RoutePrefix("api/Account")] public class AccountController : ApiController { private const string LocalLoginProvider = "Local"; private const string DefaultUserRole = "user"; private ApplicationUserManager _userManager; public AccountController() : this(Startup.OAuthOptions.AccessTokenFormat) { } public AccountController(ISecureDataFormat<AuthenticationTicket> accessTokenFormat) { // AccessTokenFormat = accessTokenFormat; } public ApplicationUserManager UserManager { get { return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; } // GET api/Account/UserInfo [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("UserInfo")] public UserInfoViewModel GetUserInfo() { ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); var roleClaimValues = ((ClaimsIdentity)User.Identity).FindAll(ClaimTypes.Role).Select(c => c.Value); var roles = string.Join(",", roleClaimValues); return new UserInfoViewModel { UserName = User.Identity.GetUserName(), Email = ((ClaimsIdentity)User.Identity).FindFirstValue(ClaimTypes.Email), HasRegistered = externalLogin == null, LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null, UserRoles = roles }; } // POST api/Account/Logout [Route("Logout")] public IHttpActionResult Logout() { Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); return Ok(); } // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true [Route("ManageInfo")] public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false) { IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return null; } List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>(); foreach (IdentityUserLogin linkedAccount in user.Logins) { logins.Add(new UserLoginInfoViewModel { LoginProvider = linkedAccount.LoginProvider, ProviderKey = linkedAccount.ProviderKey }); } if (user.PasswordHash != null) { logins.Add(new UserLoginInfoViewModel { LoginProvider = LocalLoginProvider, ProviderKey = user.UserName, }); } return new ManageInfoViewModel { LocalLoginProvider = LocalLoginProvider, Email = user.Email, UserName = user.UserName, Logins = logins, ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) }; } // POST api/Account/ChangePassword [Route("ChangePassword")] public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/SetPassword [Route("SetPassword")] public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/AddExternalLogin [Route("AddExternalLogin")] public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); if (ticket == null || ticket.Identity == null || (ticket.Properties != null && ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) { return BadRequest("External login failure."); } ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); if (externalData == null) { return BadRequest("The external login is already associated with an account."); } IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/RemoveLogin [Route("RemoveLogin")] public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result; if (model.LoginProvider == LocalLoginProvider) { result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId()); } else { result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(model.LoginProvider, model.ProviderKey)); } if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // GET api/Account/ExternalLogin [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] [AllowAnonymous] [Route("ExternalLogin", Name = "ExternalLogin")] public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return Redirect(Url.Content("~/externalauth") + "#error=" + Uri.EscapeDataString(error)); } if (!User.Identity.IsAuthenticated) { return new ChallengeResult(provider, this); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return InternalServerError(); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return new ChallengeResult(provider, this); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(oAuthIdentity); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable<Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return Ok(); } // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true [AllowAnonymous] [Route("ExternalLogins")] public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false) { //returnUrl = @""; IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes(); List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>(); string state; if (generateState) { const int strengthInBits = 256; state = RandomOAuthStateGenerator.Generate(strengthInBits); } else { state = null; } foreach (AuthenticationDescription description in descriptions) { ExternalLoginViewModel login = new ExternalLoginViewModel { Name = description.Caption, Url = Url.Route("ExternalLogin", new { provider = description.AuthenticationType, response_type = "token", client_id = Startup.PublicClientId, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, state = state }), State = state }; logins.Add(login); } return logins; } // GET api/Account/ExternalLogins?returnUrl=%2F&provider=name&generateState=true [AllowAnonymous] [Route("ExternalLogins")] public IHttpActionResult GetExternalLogins(string returnUrl,string provider, bool generateState = false) { var description = Authentication.GetExternalAuthenticationTypes() .FirstOrDefault(ad => ad.AuthenticationType == provider); if (description == null) { return NotFound(); } string state; if (generateState) { const int strengthInBits = 256; state = RandomOAuthStateGenerator.Generate(strengthInBits); } else { state = null; } ExternalLoginViewModel login = new ExternalLoginViewModel { Name = description.Caption, Url = Url.Route("ExternalLogin", new { provider = description.AuthenticationType, response_type = "token", client_id = Startup.PublicClientId, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, state = state }), State = state }; return Ok(login); } // POST api/Account/Register [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddToRoleAsync(user.Id, DefaultUserRole); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } [AllowAnonymous] [HttpPost] [Route("checkEmailAvailable")] public async Task<IHttpActionResult> CheckEmailAvailable([FromBody] emailQueryBindingModel query) { var user = await UserManager.FindByEmailAsync(query.Email); if (user == null) { return Ok("email available"); } else { return BadRequest("email already in use"); } } [AllowAnonymous] [HttpPost] [Route("checkUsernameAvailable")] public async Task<IHttpActionResult> CheckUsernameAvailable([FromBody] usernameQueryBindingModel query) { var user = await UserManager.FindByNameAsync(query.Username); if (user == null) { return Ok("username available"); } else { return BadRequest("username already in use"); } } // POST api/Account/RegisterExternal [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("RegisterExternal")] public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var info = await Authentication.GetExternalLoginInfoAsync(); if (info == null) { return InternalServerError(); } var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email != null ? model.Email : "" }; IdentityResult result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddToRoleAsync(user.Id, DefaultUserRole); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } protected override void Dispose(bool disposing) { if (disposing) { UserManager.Dispose(); } base.Dispose(disposing); } #region Helpers private IAuthenticationManager Authentication { get { return Request.GetOwinContext().Authentication; } } private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; } private class ExternalLoginData { public string LoginProvider { get; set; } public string ProviderKey { get; set; } public string UserName { get; set; } public string Email { get; set; } public IList<Claim> GetClaims() { IList<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider)); if (UserName != null) { claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider)); } if (Email != null) { claims.Add(new Claim(ClaimTypes.Email, Email, null, LoginProvider)); } return claims; } public static ExternalLoginData FromIdentity(ClaimsIdentity identity) { if (identity == null) { return null; } Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value)) { return null; } if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) { return null; } return new ExternalLoginData { LoginProvider = providerKeyClaim.Issuer, ProviderKey = providerKeyClaim.Value, UserName = identity.FindFirstValue(ClaimTypes.Name), Email = identity.FindFirstValue(ClaimTypes.Email) }; } } private static class RandomOAuthStateGenerator { private static RandomNumberGenerator _random = new RNGCryptoServiceProvider(); public static string Generate(int strengthInBits) { const int bitsPerByte = 8; if (strengthInBits % bitsPerByte != 0) { throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits"); } int strengthInBytes = strengthInBits / bitsPerByte; byte[] data = new byte[strengthInBytes]; _random.GetBytes(data); return HttpServerUtility.UrlTokenEncode(data); } } #endregion } }
// FileSystemScanner.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. using System; namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> public class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> public class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> public class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base (name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> public class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a directory. /// </summary> public delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> public class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public ProcessDirectoryHandler ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if ( result ){ ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if ( handler!= null ) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { ProcessDirectoryHandler handler = ProcessDirectory; if ( handler != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } void ScanDir(string directory, bool recurse) { try { string[] names = System.IO.Directory.GetFiles(directory); bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if ( !fileFilter_.IsMatch(names[fileIndex]) ) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if ( alive_ && hasMatch ) { foreach (string fileName in names) { try { if ( fileName != null ) { OnProcessFile(fileName); if ( !alive_ ) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if ( alive_ && recurse ) { try { string[] names = System.IO.Directory.GetDirectories(directory); foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if ( !alive_ ) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> bool alive_; #endregion } }
using System; using System.Collections; using System.IO; using Raksha.Asn1.X509; namespace Raksha.Asn1.Tsp { public class TstInfo : Asn1Encodable { private readonly DerInteger version; private readonly DerObjectIdentifier tsaPolicyId; private readonly MessageImprint messageImprint; private readonly DerInteger serialNumber; private readonly DerGeneralizedTime genTime; private readonly Accuracy accuracy; private readonly DerBoolean ordering; private readonly DerInteger nonce; private readonly GeneralName tsa; private readonly X509Extensions extensions; public static TstInfo GetInstance( object o) { if (o == null || o is TstInfo) { return (TstInfo) o; } if (o is Asn1Sequence) { return new TstInfo((Asn1Sequence) o); } if (o is Asn1OctetString) { try { byte[] octets = ((Asn1OctetString)o).GetOctets(); return GetInstance(Asn1Object.FromByteArray(octets)); } catch (IOException) { throw new ArgumentException( "Bad object format in 'TstInfo' factory."); } } throw new ArgumentException( "Unknown object in 'TstInfo' factory: " + o.GetType().FullName); } private TstInfo( Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); // version e.MoveNext(); version = DerInteger.GetInstance(e.Current); // tsaPolicy e.MoveNext(); tsaPolicyId = DerObjectIdentifier.GetInstance(e.Current); // messageImprint e.MoveNext(); messageImprint = MessageImprint.GetInstance(e.Current); // serialNumber e.MoveNext(); serialNumber = DerInteger.GetInstance(e.Current); // genTime e.MoveNext(); genTime = DerGeneralizedTime.GetInstance(e.Current); // default for ordering ordering = DerBoolean.False; while (e.MoveNext()) { Asn1Object o = (Asn1Object) e.Current; if (o is Asn1TaggedObject) { DerTaggedObject tagged = (DerTaggedObject) o; switch (tagged.TagNo) { case 0: tsa = GeneralName.GetInstance(tagged, true); break; case 1: extensions = X509Extensions.GetInstance(tagged, false); break; default: throw new ArgumentException("Unknown tag value " + tagged.TagNo); } } if (o is DerSequence) { accuracy = Accuracy.GetInstance(o); } if (o is DerBoolean) { ordering = DerBoolean.GetInstance(o); } if (o is DerInteger) { nonce = DerInteger.GetInstance(o); } } } public TstInfo( DerObjectIdentifier tsaPolicyId, MessageImprint messageImprint, DerInteger serialNumber, DerGeneralizedTime genTime, Accuracy accuracy, DerBoolean ordering, DerInteger nonce, GeneralName tsa, X509Extensions extensions) { this.version = new DerInteger(1); this.tsaPolicyId = tsaPolicyId; this.messageImprint = messageImprint; this.serialNumber = serialNumber; this.genTime = genTime; this.accuracy = accuracy; this.ordering = ordering; this.nonce = nonce; this.tsa = tsa; this.extensions = extensions; } public MessageImprint MessageImprint { get { return messageImprint; } } public DerObjectIdentifier Policy { get { return tsaPolicyId; } } public DerInteger SerialNumber { get { return serialNumber; } } public Accuracy Accuracy { get { return accuracy; } } public DerGeneralizedTime GenTime { get { return genTime; } } public DerBoolean Ordering { get { return ordering; } } public DerInteger Nonce { get { return nonce; } } public GeneralName Tsa { get { return tsa; } } public X509Extensions Extensions { get { return extensions; } } /** * <pre> * * TstInfo ::= SEQUENCE { * version INTEGER { v1(1) }, * policy TSAPolicyId, * messageImprint MessageImprint, * -- MUST have the same value as the similar field in * -- TimeStampReq * serialNumber INTEGER, * -- Time-Stamping users MUST be ready to accommodate integers * -- up to 160 bits. * genTime GeneralizedTime, * accuracy Accuracy OPTIONAL, * ordering BOOLEAN DEFAULT FALSE, * nonce INTEGER OPTIONAL, * -- MUST be present if the similar field was present * -- in TimeStampReq. In that case it MUST have the same value. * tsa [0] GeneralName OPTIONAL, * extensions [1] IMPLICIT Extensions OPTIONAL } * * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector( version, tsaPolicyId, messageImprint, serialNumber, genTime); if (accuracy != null) { v.Add(accuracy); } if (ordering != null && ordering.IsTrue) { v.Add(ordering); } if (nonce != null) { v.Add(nonce); } if (tsa != null) { v.Add(new DerTaggedObject(true, 0, tsa)); } if (extensions != null) { v.Add(new DerTaggedObject(false, 1, extensions)); } return new DerSequence(v); } } }
using System; using System.Collections.Generic; using System.Linq; using Music.Plugin.Abstractions; using CoreGraphics; #if __IOSUNIFIED__ using MediaPlayer; using Foundation; #else using MonoTouch.MediaPlayer; using MonoTouch.Foundation; #endif namespace Music.Plugin { /// <summary> /// Implementation for Music /// </summary> public class MusicImplementation : IMusic { bool _fireEvents; List<MPMediaItem> _mediaMusic; readonly List<MusicTrack> _playlist = new List<MusicTrack> (); public event EventHandler<PlaybackStateEventArgs> PlaybackStateChanged; public event EventHandler<PlaybackStateEventArgs> PlaybackItemChanged; public List<MusicTrack> Playlist { get { return _playlist; } } public bool IsPlaying { get { var item = MPMusicPlayerController.ApplicationMusicPlayer.NowPlayingItem; var rate = MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackRate; var state = MPMusicPlayerController.ApplicationMusicPlayer.PlaybackState; return item != null && state == MPMusicPlaybackState.Playing && Math.Round (rate) >= 1f; } } public bool IsStopped { get { var item = MPMusicPlayerController.ApplicationMusicPlayer.NowPlayingItem; var rate = MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackRate; var state = MPMusicPlayerController.ApplicationMusicPlayer.PlaybackState; return item == null || state == MPMusicPlaybackState.Stopped || Math.Round (rate).Equals (0); } } public bool IsPaused { get { var rate = MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackRate; var state = MPMusicPlayerController.ApplicationMusicPlayer.PlaybackState; return state == MPMusicPlaybackState.Paused && Math.Round (rate).Equals (0); } } public MusicTrack PlayingTrack { get { MusicTrack track = null; var item = MPMusicPlayerController.ApplicationMusicPlayer.NowPlayingItem; if (item != null) { track = item.ToTrack (); } return track; } set { var item = _mediaMusic.FirstOrDefault (m => m.PersistentID.Equals (value.Id)); if (item != null) { MPMusicPlayerController.ApplicationMusicPlayer.NowPlayingItem = item; } } } public double PlaybackPosition { get { double position = 0d; var item = MPMusicPlayerController.ApplicationMusicPlayer.NowPlayingItem; if (item != null) { position = MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackTime; } return position; } set { MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackTime = value; } } public float PlaybackSpeed { get { return MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackRate; } set { MPMusicPlayerController.ApplicationMusicPlayer.CurrentPlaybackRate = value; } } public PlayerState PlaybackState { get { return MPMusicPlayerController.ApplicationMusicPlayer.PlaybackState.ToPlayerState (); } } public bool FireEvents { get { return _fireEvents; } set { _fireEvents = value; if (_fireEvents) { MPMusicPlayerController.ApplicationMusicPlayer.BeginGeneratingPlaybackNotifications (); } else { MPMusicPlayerController.ApplicationMusicPlayer.EndGeneratingPlaybackNotifications (); } } } public void Initialize (object context) { NSNotificationCenter.DefaultCenter.AddObserver (MPMusicPlayerController.NowPlayingItemDidChangeNotification, delegate (NSNotification n) { if (PlaybackItemChanged != null && _fireEvents) { PlaybackItemChanged (this, new PlaybackStateEventArgs ()); } }); NSNotificationCenter.DefaultCenter.AddObserver (MPMusicPlayerController.PlaybackStateDidChangeNotification, delegate (NSNotification n) { if (PlaybackStateChanged != null && _fireEvents) { PlaybackStateChanged (this, new PlaybackStateEventArgs ()); } }); FireEvents = true; } public void Play () { if (_playlist.Count > 0) { MPMusicPlayerController.ApplicationMusicPlayer.Play (); } } public void Pause () { if (_playlist.Count > 0) { MPMusicPlayerController.ApplicationMusicPlayer.Pause (); } } public void Stop () { if (_playlist.Count > 0) { MPMusicPlayerController.ApplicationMusicPlayer.Stop (); } } public void SkipToNext () { var track = PlayingTrack; if (track != null && _playlist.Count > 0) { var index = _playlist.FindIndex (i => i.Id.Equals (track.Id)); if (index < _playlist.Count - 1) { MPMusicPlayerController.ApplicationMusicPlayer.SkipToNextItem (); } } } public void SkipToPrevious () { var track = PlayingTrack; if (track != null && _playlist.Count > 0) { var index = _playlist.FindIndex (i => i.Id.Equals (track.Id)); if (index > 0) { MPMusicPlayerController.ApplicationMusicPlayer.SkipToPreviousItem (); } } } public void QueuePlaylist(List<MusicTrack> playlist) { _playlist.Clear (); _playlist.AddRange (playlist); var mediaItemList = new List<MPMediaItem> (); playlist.ToList ().ForEach (delegate (MusicTrack i) { var m = GetAllSongs().FirstOrDefault (s => s.PersistentID.Equals (i.Id)); if (m != null) { mediaItemList.Add (m); } }); MPMusicPlayerController.ApplicationMusicPlayer.SetQueue (new MPMediaItemCollection (mediaItemList.ToArray ())); } public List<MusicTrack> GetPlatformMusicLibrary() { return GetAllSongs().Where(s => s != null).Select(s => s.ToTrack()).ToList(); } public void Reset () { Stop (); _playlist.Clear (); MPMusicPlayerController.ApplicationMusicPlayer.NowPlayingItem = null; } public byte[] GetTrackImage(ulong id) { var imageBytes = new byte[0]; var item = _mediaMusic.FirstOrDefault(x => x.PersistentID.Equals(id)); if (item != null) { if (item.Artwork != null) { var thumb = item.Artwork.ImageWithSize (new CGSize (60, 60)); if (thumb != null) { return thumb.AsPNG ().ToArray (); } } } return imageBytes; } IEnumerable<MPMediaItem> GetAllSongs() { if (_mediaMusic == null) { MPMediaItem[] items; #if __IOSUNIFIED__ items = MPMediaQuery.SongsQuery.Items; #else items = MPMediaQuery.songsQuery.Items; #endif if (items != null && items.Length > 0) { _mediaMusic = items.ToList (); } else { _mediaMusic = new List<MPMediaItem> (); } } return _mediaMusic; } } }
// 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.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest() { _log = TestLogging.GetInstance(); } [Fact] public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. // We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up. Assert.InRange(nic.Speed, -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/1332")] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_AccessInstanceProperties_NoExceptions_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); // Disabled for https://github.com/dotnet/runtime/issues/1332 //if (nic.Name.StartsWith("en") || nic.Name == "lo0") //{ //// Ethernet, WIFI and loopback should have known status. //Assert.True((nic.OperationalStatus == OperationalStatus.Up) || (nic.OperationalStatus == OperationalStatus.Down)); //} } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); return; // Only check IPv4 loopback } } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 and https://github.com/Microsoft/WSL/issues/3561 [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_GetIPInterfaceStatistics_Success_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 and https://github.com/Microsoft/WSL/issues/3561 public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } [Theory] [PlatformSpecific(~(TestPlatforms.OSX|TestPlatforms.FreeBSD))] [InlineData(false)] [InlineData(true)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
using System.Collections.Generic; using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.TestHelper; using Xunit; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.TemplateConfigTests { public class SplitConfigurationTests : TestBase { [Fact(DisplayName = nameof(SplitConfigCantReferenceFileOutsideBasePath))] public void SplitConfigCantReferenceFileOutsideBasePath() { string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings); TestTemplateSetup setup = SetupSplitConfigWithAFileOutsideMountPoint(EngineEnvironmentSettings, sourcePath); IGenerator generator = new RunnableProjectGenerator(); IFileSystemInfo templateConfigFileInfo = setup.InfoForSourceFile(TemplateConfigTestHelpers.DefaultConfigRelativePath); bool result = generator.TryGetTemplateFromConfigInfo(templateConfigFileInfo, out ITemplate template, null, null); Assert.False(result, "Template config should not be readable - additional file is outside the base path."); Assert.Null(template); } // The file outside the proper location is not created - it can't be by this mechanism. // It doesn't need to exist, the reader will fail in trying to read it. private static TestTemplateSetup SetupSplitConfigWithAFileOutsideMountPoint(IEngineEnvironmentSettings environment, string basePath) { IDictionary<string, string> templateSourceFiles = new Dictionary<string, string>(); templateSourceFiles.Add(".template.config/template.json", TemplateJsonWithAdditionalFileOutsideBasePath); TestTemplateSetup setup = new TestTemplateSetup(environment, basePath, templateSourceFiles); setup.WriteSource(); return setup; } [Fact(DisplayName = nameof(SplitConfigReadFailsIfAReferencedFileIsMissing))] public void SplitConfigReadFailsIfAReferencedFileIsMissing() { string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings); TestTemplateSetup setup = SetupSplitConfigWithAMissingReferencedFile(EngineEnvironmentSettings, sourcePath); IGenerator generator = new RunnableProjectGenerator(); IFileSystemInfo templateConfigFileInfo = setup.InfoForSourceFile(TemplateConfigTestHelpers.DefaultConfigRelativePath); bool result = generator.TryGetTemplateFromConfigInfo(templateConfigFileInfo, out ITemplate template, null, null); Assert.False(result, "Template config should not be readable - missing additional file."); Assert.Null(template); } // Uses the same template.json as the test that successfully reads a split config. // But doesn't create the additional file private static TestTemplateSetup SetupSplitConfigWithAMissingReferencedFile(IEngineEnvironmentSettings environment, string basePath) { IDictionary<string, string> templateSourceFiles = new Dictionary<string, string>(); templateSourceFiles.Add(".template.config/template.json", TemplateJsonWithProperAdditionalConfigFilesString); TestTemplateSetup setup = new TestTemplateSetup(environment, basePath, templateSourceFiles); setup.WriteSource(); return setup; } [Fact(DisplayName = nameof(SplitConfigTest))] public void SplitConfigTest() { string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings); TestTemplateSetup setup = SetupSplitConfigTestTemplate(EngineEnvironmentSettings, sourcePath); IGenerator generator = new RunnableProjectGenerator(); IFileSystemInfo templateConfigFileInfo = setup.InfoForSourceFile("templateSource/.template.config/template.json"); generator.TryGetTemplateFromConfigInfo(templateConfigFileInfo, out ITemplate template, null, null); IDictionary<string, ITemplateParameter> parameters = template.Parameters.ToDictionary(p => p.Name, p => p); Assert.Equal(6, parameters.Count); // 5 in the configs + 1 for 'name' (implicit) Assert.True(parameters.ContainsKey("type")); Assert.True(parameters.ContainsKey("language")); Assert.True(parameters.ContainsKey("RuntimeFrameworkVersion")); Assert.True(parameters.ContainsKey("Framework")); Assert.True(parameters.ContainsKey("MyThing")); } private static TestTemplateSetup SetupSplitConfigTestTemplate(IEngineEnvironmentSettings environment, string basePath) { IDictionary<string, string> templateSourceFiles = new Dictionary<string, string>(); templateSourceFiles.Add("templateSource/.template.config/template.json", TemplateJsonWithProperAdditionalConfigFilesString); templateSourceFiles.Add("templateSource/.template.config/symbols.template.json", SymbolsTemplateJsonString); TestTemplateSetup setup = new TestTemplateSetup(environment, basePath, templateSourceFiles); setup.WriteSource(); return setup; } private static string TemplateJsonWithProperAdditionalConfigFilesString { get { string templateJsonString = @" { ""author"": ""Microsoft"", ""classifications"": [""Common"", ""Console""], ""name"": ""Test Split Config Console Application"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""Testing.Split.Config.Console"", ""identity"": ""Testing.Framework.Versioned.Console.CSharp"", ""shortName"": ""splitconfigtest"", ""sourceName"": ""Company.ConsoleApplication1"", ""preferNameDirectory"": true, ""additionalConfigFiles"": [ ""symbols.template.json"" ], ""symbols"": { ""type"": { ""type"": ""parameter"", ""datatype"": ""choice"", ""choices"": [ { ""choice"": ""project"" } ] }, ""language"": { ""type"": ""parameter"", ""datatype"": ""choice"", ""choices"": [ { ""choice"": ""C#"" } ] } } } "; return templateJsonString; } } private static string SymbolsTemplateJsonString { get { string symbolsTemplateJsonString = @" { ""symbols"": { ""RuntimeFrameworkVersion"": { ""type"": ""parameter"", ""replaces"": ""2.0.0-beta-xyz"" }, ""Framework"": { ""type"": ""parameter"", ""datatype"": ""choice"", ""choices"": [ { ""choice"": ""1.0"", ""description"": ""Target netcoreapp1.0"" }, { ""choice"": ""1.1"", ""description"": ""Target netcoreapp1.1"" }, { ""choice"": ""2.0"", ""description"": ""Target netcoreapp2.0 build specified by RuntimeFrameworkVersion"" } ], ""defaultValue"": ""1.0"" }, ""MyThing"": { ""type"": ""parameter"", ""datatype"": ""choice"", ""choices"": [ { ""choice"": ""foo"" }, { ""choice"": ""bar"" }, { ""choice"": ""baz"" } ], ""defaultValue"": ""foo"" } } } "; return symbolsTemplateJsonString; } } private static string TemplateJsonWithAdditionalFileOutsideBasePath { get { string templateJsonString = @" { ""additionalConfigFiles"": [ ""../../improper.template.json"" ] } "; return templateJsonString; } } } }
namespace Factotum { partial class InspectedComponentView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InspectedComponentView)); this.btnEdit = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.cboHasMin = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtComponentID = new System.Windows.Forms.TextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.cboStatusComplete = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.cboPrepComplete = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.txtReportID = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.cboUtFieldCplt = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.cboReviewer = new System.Windows.Forms.ComboBox(); this.cboSubmitted = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cboFinal = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.btnPrint = new System.Windows.Forms.Button(); this.btnPreview = new System.Windows.Forms.Button(); this.btnValidate = new System.Windows.Forms.Button(); this.btnStatusRept = new System.Windows.Forms.Button(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.validateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.componentReportPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.printComponentReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dgvReportList = new Factotum.DataGridViewStd(); this.panel1.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvReportList)).BeginInit(); this.SuspendLayout(); // // btnEdit // this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnEdit.Location = new System.Drawing.Point(11, 298); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(64, 22); this.btnEdit.TabIndex = 2; this.btnEdit.Text = "Edit"; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(9, 135); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(115, 13); this.label1.TabIndex = 5; this.label1.Text = "Component Report List"; // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAdd.Location = new System.Drawing.Point(81, 298); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(64, 22); this.btnAdd.TabIndex = 3; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnDelete.Location = new System.Drawing.Point(151, 298); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(64, 22); this.btnDelete.TabIndex = 4; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // cboHasMin // this.cboHasMin.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboHasMin.FormattingEnabled = true; this.cboHasMin.Items.AddRange(new object[] { "All", "Yes", "No"}); this.cboHasMin.Location = new System.Drawing.Point(434, 41); this.cboHasMin.Name = "cboHasMin"; this.cboHasMin.Size = new System.Drawing.Size(85, 21); this.cboHasMin.TabIndex = 13; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(382, 45); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(46, 13); this.label2.TabIndex = 12; this.label2.Text = "Has Min"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 45); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(75, 13); this.label3.TabIndex = 2; this.label3.Text = "Component ID"; // // txtComponentID // this.txtComponentID.Location = new System.Drawing.Point(93, 42); this.txtComponentID.Name = "txtComponentID"; this.txtComponentID.Size = new System.Drawing.Size(85, 20); this.txtComponentID.TabIndex = 3; // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.cboStatusComplete); this.panel1.Controls.Add(this.label11); this.panel1.Controls.Add(this.cboPrepComplete); this.panel1.Controls.Add(this.label9); this.panel1.Controls.Add(this.txtReportID); this.panel1.Controls.Add(this.label4); this.panel1.Controls.Add(this.cboUtFieldCplt); this.panel1.Controls.Add(this.label10); this.panel1.Controls.Add(this.label8); this.panel1.Controls.Add(this.cboReviewer); this.panel1.Controls.Add(this.cboSubmitted); this.panel1.Controls.Add(this.label7); this.panel1.Controls.Add(this.cboFinal); this.panel1.Controls.Add(this.label6); this.panel1.Controls.Add(this.txtComponentID); this.panel1.Controls.Add(this.cboHasMin); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.label3); this.panel1.ForeColor = System.Drawing.SystemColors.ControlText; this.panel1.Location = new System.Drawing.Point(15, 18); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(532, 101); this.panel1.TabIndex = 1; // // cboStatusComplete // this.cboStatusComplete.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboStatusComplete.FormattingEnabled = true; this.cboStatusComplete.Items.AddRange(new object[] { "All", "Yes", "No"}); this.cboStatusComplete.Location = new System.Drawing.Point(272, 68); this.cboStatusComplete.Name = "cboStatusComplete"; this.cboStatusComplete.Size = new System.Drawing.Size(85, 21); this.cboStatusComplete.TabIndex = 17; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(205, 71); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(61, 13); this.label11.TabIndex = 16; this.label11.Text = "Status Cplt."; // // cboPrepComplete // this.cboPrepComplete.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboPrepComplete.FormattingEnabled = true; this.cboPrepComplete.Items.AddRange(new object[] { "All", "Yes", "No"}); this.cboPrepComplete.Location = new System.Drawing.Point(272, 14); this.cboPrepComplete.Name = "cboPrepComplete"; this.cboPrepComplete.Size = new System.Drawing.Size(85, 21); this.cboPrepComplete.TabIndex = 5; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(212, 19); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(53, 13); this.label9.TabIndex = 4; this.label9.Text = "Prep Cplt."; // // txtReportID // this.txtReportID.Location = new System.Drawing.Point(93, 16); this.txtReportID.Name = "txtReportID"; this.txtReportID.Size = new System.Drawing.Size(85, 20); this.txtReportID.TabIndex = 1; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(12, 19); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(53, 13); this.label4.TabIndex = 0; this.label4.Text = "Report ID"; // // cboUtFieldCplt // this.cboUtFieldCplt.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboUtFieldCplt.FormattingEnabled = true; this.cboUtFieldCplt.Items.AddRange(new object[] { "All", "Yes", "No"}); this.cboUtFieldCplt.Location = new System.Drawing.Point(272, 41); this.cboUtFieldCplt.Name = "cboUtFieldCplt"; this.cboUtFieldCplt.Size = new System.Drawing.Size(85, 21); this.cboUtFieldCplt.TabIndex = 7; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(195, 44); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(71, 13); this.label10.TabIndex = 6; this.label10.Text = "UT Field Cplt."; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(376, 71); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(52, 13); this.label8.TabIndex = 14; this.label8.Text = "Reviewer"; // // cboReviewer // this.cboReviewer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboReviewer.FormattingEnabled = true; this.cboReviewer.Items.AddRange(new object[] { "Active", "Inactive"}); this.cboReviewer.Location = new System.Drawing.Point(434, 68); this.cboReviewer.Name = "cboReviewer"; this.cboReviewer.Size = new System.Drawing.Size(85, 21); this.cboReviewer.TabIndex = 15; // // cboSubmitted // this.cboSubmitted.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSubmitted.FormattingEnabled = true; this.cboSubmitted.Items.AddRange(new object[] { "All", "Yes", "No"}); this.cboSubmitted.Location = new System.Drawing.Point(93, 68); this.cboSubmitted.Name = "cboSubmitted"; this.cboSubmitted.Size = new System.Drawing.Size(85, 21); this.cboSubmitted.TabIndex = 9; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(11, 71); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(54, 13); this.label7.TabIndex = 8; this.label7.Text = "Submitted"; // // cboFinal // this.cboFinal.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboFinal.FormattingEnabled = true; this.cboFinal.Items.AddRange(new object[] { "All", "Yes", "No"}); this.cboFinal.Location = new System.Drawing.Point(434, 14); this.cboFinal.Name = "cboFinal"; this.cboFinal.Size = new System.Drawing.Size(85, 21); this.cboFinal.TabIndex = 11; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(399, 17); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(29, 13); this.label6.TabIndex = 10; this.label6.Text = "Final"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.SystemColors.ControlText; this.label5.Location = new System.Drawing.Point(22, 9); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 0; this.label5.Text = "List Filters"; // // btnPrint // this.btnPrint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnPrint.Location = new System.Drawing.Point(488, 298); this.btnPrint.Name = "btnPrint"; this.btnPrint.Size = new System.Drawing.Size(64, 22); this.btnPrint.TabIndex = 7; this.btnPrint.Text = "Print"; this.btnPrint.UseVisualStyleBackColor = true; this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click); // // btnPreview // this.btnPreview.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnPreview.Location = new System.Drawing.Point(418, 298); this.btnPreview.Name = "btnPreview"; this.btnPreview.Size = new System.Drawing.Size(64, 22); this.btnPreview.TabIndex = 8; this.btnPreview.Text = "Preview"; this.btnPreview.UseVisualStyleBackColor = true; this.btnPreview.Click += new System.EventHandler(this.btnPreview_Click); // // btnValidate // this.btnValidate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnValidate.Location = new System.Drawing.Point(348, 298); this.btnValidate.Name = "btnValidate"; this.btnValidate.Size = new System.Drawing.Size(64, 22); this.btnValidate.TabIndex = 9; this.btnValidate.Text = "Validate"; this.btnValidate.UseVisualStyleBackColor = true; this.btnValidate.Click += new System.EventHandler(this.btnValidate_Click); // // btnStatusRept // this.btnStatusRept.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnStatusRept.Location = new System.Drawing.Point(278, 298); this.btnStatusRept.Name = "btnStatusRept"; this.btnStatusRept.Size = new System.Drawing.Size(64, 22); this.btnStatusRept.TabIndex = 10; this.btnStatusRept.Text = "Status"; this.btnStatusRept.UseVisualStyleBackColor = true; this.btnStatusRept.Click += new System.EventHandler(this.btnStatusRept_Click); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.validateToolStripMenuItem, this.editReportToolStripMenuItem, this.componentReportPreviewToolStripMenuItem, this.printComponentReportToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(218, 114); // // validateToolStripMenuItem // this.validateToolStripMenuItem.Name = "validateToolStripMenuItem"; this.validateToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.validateToolStripMenuItem.Text = "Validate"; this.validateToolStripMenuItem.Click += new System.EventHandler(this.validateToolStripMenuItem_Click); // // editReportToolStripMenuItem // this.editReportToolStripMenuItem.Name = "editReportToolStripMenuItem"; this.editReportToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.editReportToolStripMenuItem.Text = "Edit"; this.editReportToolStripMenuItem.Click += new System.EventHandler(this.editReportToolStripMenuItem_Click); // // componentReportPreviewToolStripMenuItem // this.componentReportPreviewToolStripMenuItem.Name = "componentReportPreviewToolStripMenuItem"; this.componentReportPreviewToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.componentReportPreviewToolStripMenuItem.Text = "Preview Component Report"; this.componentReportPreviewToolStripMenuItem.Click += new System.EventHandler(this.componentReportPreviewToolStripMenuItem_Click); // // printComponentReportToolStripMenuItem // this.printComponentReportToolStripMenuItem.Name = "printComponentReportToolStripMenuItem"; this.printComponentReportToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.printComponentReportToolStripMenuItem.Text = "Print Component Report"; this.printComponentReportToolStripMenuItem.Click += new System.EventHandler(this.printComponentReportToolStripMenuItem_Click); // // dgvReportList // this.dgvReportList.AllowUserToAddRows = false; this.dgvReportList.AllowUserToDeleteRows = false; this.dgvReportList.AllowUserToOrderColumns = true; this.dgvReportList.AllowUserToResizeRows = false; this.dgvReportList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dgvReportList.Location = new System.Drawing.Point(12, 151); this.dgvReportList.MultiSelect = false; this.dgvReportList.Name = "dgvReportList"; this.dgvReportList.ReadOnly = true; this.dgvReportList.RowHeadersVisible = false; this.dgvReportList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvReportList.Size = new System.Drawing.Size(535, 141); this.dgvReportList.StandardTab = true; this.dgvReportList.TabIndex = 6; this.dgvReportList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dgvReportList_KeyDown); this.dgvReportList.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dgvReportList_CellMouseClick); this.dgvReportList.DoubleClick += new System.EventHandler(this.btnEdit_Click); // // InspectedComponentView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(194)))), ((int)(((byte)(170)))), ((int)(((byte)(156))))); this.ClientSize = new System.Drawing.Size(559, 332); this.Controls.Add(this.btnStatusRept); this.Controls.Add(this.btnValidate); this.Controls.Add(this.btnPreview); this.Controls.Add(this.btnPrint); this.Controls.Add(this.label5); this.Controls.Add(this.panel1); this.Controls.Add(this.dgvReportList); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnAdd); this.Controls.Add(this.label1); this.Controls.Add(this.btnEdit); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(567, 302); this.Name = "InspectedComponentView"; this.Text = "View Component Reports"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.InspectedComponentView_FormClosed); this.SizeChanged += new System.EventHandler(this.InspectedComponentView_SizeChanged); this.Load += new System.EventHandler(this.InspectedComponentView_Load); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.contextMenuStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgvReportList)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.ComboBox cboHasMin; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtComponentID; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cboSubmitted; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cboFinal; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox cboReviewer; private System.Windows.Forms.ComboBox cboUtFieldCplt; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox txtReportID; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cboPrepComplete; private System.Windows.Forms.Label label9; private System.Windows.Forms.Button btnPrint; private System.Windows.Forms.Button btnPreview; private DataGridViewStd dgvReportList; private System.Windows.Forms.ComboBox cboStatusComplete; private System.Windows.Forms.Label label11; private System.Windows.Forms.Button btnValidate; private System.Windows.Forms.Button btnStatusRept; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem validateToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editReportToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem componentReportPreviewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem printComponentReportToolStripMenuItem; } }
namespace FakeItEasy.Tests.Core { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FakeItEasy.Core; using FluentAssertions; using Xunit; using static FakeItEasy.Tests.TestHelpers.ExpressionHelper; public class MethodInfoManagerTests { public interface IInterface { void Foo(); } public interface IHaveAGenericMethod { [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Required for testing.")] void GenericMethod<T>(); } [Fact] public void Matches_returns_false_when_methods_are_not_the_same() { var first = GetMethodInfo<Base>(x => x.DoSomething()); var second = GetMethodInfo<Base>(x => x.ToString()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(Base), first, second).Should().BeFalse(); } [Fact] public void Will_invoke_same_method_on_target_when_both_methods_are_same() { var first = GetMethodInfo<Base>(x => x.DoSomething()); var second = GetMethodInfo<Base>(x => x.DoSomething()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(Base), first, second).Should().BeTrue(); } [Fact] public void Will_invoke_same_method_on_target_when_first_is_method_on_derived_type() { var first = GetMethodInfo<Derived>(x => x.DoSomething()); var second = GetMethodInfo<Base>(x => x.DoSomething()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(Derived), first, second).Should().BeTrue(); } [Fact] public void Will_invoke_same_method_on_target_when_first_is_method_on_base_type() { var first = GetMethodInfo<Base>(x => x.DoSomething()); var second = GetMethodInfo<Derived>(x => x.DoSomething()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(Base), first, second).Should().BeTrue(); } [Fact] public void Will_not_invoke_same_method_on_target_when_calls_are_to_same_method_but_with_different_generic_arguments() { var first = GetMethodInfo<IHaveAGenericMethod>(x => x.GenericMethod<string>()); var second = GetMethodInfo<IHaveAGenericMethod>(x => x.GenericMethod<int>()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(HaveAGenericMethod), first, second).Should().BeFalse(); } [Fact] public void Will_invoke_same_method_on_target_when_first_points_to_interface_method_and_second_to_implementing_method() { var first = GetMethodInfo<IInterface>(x => x.Foo()); var second = GetMethodInfo<Concrete>(x => x.Foo()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(Concrete), first, second).Should().BeTrue(); } [Fact] public void Will_invoke_same_method_on_target_when_one_points_to_interface_method_with_generic_argument_and_second_to_implementing_method() { var first = GetMethodInfo<IHaveAGenericMethod>(x => x.GenericMethod<int>()); var second = GetMethodInfo<HaveAGenericMethod>(x => x.GenericMethod<int>()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(HaveAGenericMethod), first, second).Should().BeTrue(); } [Fact] public void Will_not_invoke_same_method_on_target_when_one_points_to_interface_method_with_generic_argument_and_second_to_implementing_method_but_with_different_type_argument() { var first = GetMethodInfo<IHaveAGenericMethod>(x => x.GenericMethod<int>()); var second = GetMethodInfo<HaveAGenericMethod>(x => x.GenericMethod<string>()); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(HaveAGenericMethod), first, second).Should().BeFalse(); } [Fact] public void Will_not_invoke_same_method_on_target_when_calls_are_to_same_method_but_to_different_overloads() { var first = GetMethodInfo<Base>(x => x.DoSomething()); var second = GetMethodInfo<Base>(x => x.DoSomething("a")); var manager = this.CreateManager(); manager.WillInvokeSameMethodOnTarget(typeof(Base), first, second).Should().BeFalse(); } [Fact] public void Should_return_true_when_method_is_explicit_implementation_of_interface_method() { // Arrange var explicitImplementation = typeof(ConcreteWithExplicitImplementation).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic).Single(x => x.Name == "FakeItEasy.Tests.Core.MethodInfoManagerTests.IInterface.Foo"); var interfaceMethod = GetMethodInfo<IInterface>(x => x.Foo()); var manager = this.CreateManager(); // Act // Assert manager.WillInvokeSameMethodOnTarget(typeof(ConcreteWithExplicitImplementation), explicitImplementation, interfaceMethod).Should().BeTrue(); } [Fact] public void Should_return_false_when_same_method_is_invoked_on_generic_type_with_different_type_arguments() { // Arrange var first = GetMethodInfo<GenericType<int>>(x => x.Foo()); var second = GetMethodInfo<GenericType<string>>(x => x.Foo()); var manager = this.CreateManager(); // Act // Assert manager.WillInvokeSameMethodOnTarget(typeof(GenericType<int>), first, second).Should().BeFalse(); } [Fact] public void Should_return_method_from_derived_type_when_getting_non_virtual_method_on_base_type() { // Arrange var method = GetMethodInfo<Derived>(x => x.DoSomething("foo")); var manager = this.CreateManager(); // Act, Assert manager.GetMethodOnTypeThatWillBeInvokedByMethodInfo(typeof(Derived), method) .Should().NotBeNull().And.Subject .Name.Should().Be(nameof(Derived.DoSomething)); } private MethodInfoManager CreateManager() { return new MethodInfoManager(); } public class ConcreteWithExplicitImplementation : IInterface { public void Foo() { } void IInterface.Foo() { throw new NotImplementedException(); } } public class Concrete : IInterface { public void Foo() { throw new NotImplementedException(); } } public class HaveAGenericMethod : IHaveAGenericMethod { public void GenericMethod<T>() { throw new NotImplementedException(); } } public class Base : IEquatable<Base> { public virtual void DoSomething() { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "text", Justification = "Required for testing.")] public void DoSomething(string text) { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "other", Justification = "Required for testing.")] public bool Equals(Base other) => true; public override bool Equals(object? other) => true; public override int GetHashCode() => 0; } public class Derived : Base { public override void DoSomething() { } } public class GenericType<T> { public void Foo() { } } } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia.VisualTree; namespace Avalonia.Input.Navigation { /// <summary> /// The implementation for default tab navigation. /// </summary> internal static class TabNavigation { public static IInputElement? GetNextTab(IInputElement e, bool goDownOnly) { return GetNextTab(e, GetGroupParent(e), goDownOnly); } public static IInputElement? GetNextTab(IInputElement? e, IInputElement container, bool goDownOnly) { var tabbingType = GetKeyNavigationMode(container); if (e == null) { if (IsTabStop(container)) return container; // Using ActiveElement if set var activeElement = GetActiveElement(container); if (activeElement != null) return GetNextTab(null, activeElement, true); } else { if (tabbingType == KeyboardNavigationMode.Once || tabbingType == KeyboardNavigationMode.None) { if (container != e) { if (goDownOnly) return null; var parentContainer = GetGroupParent(container); return GetNextTab(container, parentContainer, goDownOnly); } } } // All groups IInputElement? loopStartElement = null; var nextTabElement = e; var currentTabbingType = tabbingType; // Search down inside the container while ((nextTabElement = GetNextTabInGroup(nextTabElement, container, currentTabbingType)) != null) { // Avoid the endless loop here for Cycle groups if (loopStartElement == nextTabElement) break; if (loopStartElement == null) loopStartElement = nextTabElement; var firstTabElementInside = GetNextTab(null, nextTabElement, true); if (firstTabElementInside != null) return firstTabElementInside; // If we want to continue searching inside the Once groups, we should change the navigation mode if (currentTabbingType == KeyboardNavigationMode.Once) currentTabbingType = KeyboardNavigationMode.Contained; } // If there is no next element in the group (nextTabElement == null) // Search up in the tree if allowed // consider: Use original tabbingType instead of currentTabbingType if (!goDownOnly && currentTabbingType != KeyboardNavigationMode.Contained && GetParent(container) != null) { return GetNextTab(container, GetGroupParent(container), false); } return null; } public static IInputElement? GetNextTabOutside(ICustomKeyboardNavigation e) { if (e is IInputElement container) { var last = GetLastInTree(container); if (last is object) return GetNextTab(last, false); } return null; } public static IInputElement? GetPrevTab(IInputElement? e, IInputElement? container, bool goDownOnly) { if (e is null && container is null) throw new InvalidOperationException("Either 'e' or 'container' must be non-null."); if (container is null) container = GetGroupParent(e!); KeyboardNavigationMode tabbingType = GetKeyNavigationMode(container); if (e == null) { // Using ActiveElement if set var activeElement = GetActiveElement(container); if (activeElement != null) return GetPrevTab(null, activeElement, true); else { // If we Shift+Tab on a container with KeyboardNavigationMode=Once, and ActiveElement is null // then we want to go to the first item (not last) within the container if (tabbingType == KeyboardNavigationMode.Once) { var firstTabElement = GetNextTabInGroup(null, container, tabbingType); if (firstTabElement == null) { if (IsTabStop(container)) return container; if (goDownOnly) return null; return GetPrevTab(container, null, false); } else { return GetPrevTab(null, firstTabElement, true); } } } } else { if (tabbingType == KeyboardNavigationMode.Once || tabbingType == KeyboardNavigationMode.None) { if (goDownOnly || container == e) return null; // FocusedElement should not be e otherwise we will delegate focus to the same element if (IsTabStop(container)) return container; return GetPrevTab(container, null, false); } } // All groups (except Once) - continue IInputElement? loopStartElement = null; IInputElement? nextTabElement = e; // Look for element with the same TabIndex before the current element while ((nextTabElement = GetPrevTabInGroup(nextTabElement, container, tabbingType)) != null) { if (nextTabElement == container && tabbingType == KeyboardNavigationMode.Local) break; // At this point nextTabElement is TabStop or TabGroup // In case it is a TabStop only return the element if (IsTabStop(nextTabElement) && !IsGroup(nextTabElement)) return nextTabElement; // Avoid the endless loop here if (loopStartElement == nextTabElement) break; if (loopStartElement == null) loopStartElement = nextTabElement; // At this point nextTabElement is TabGroup var lastTabElementInside = GetPrevTab(null, nextTabElement, true); if (lastTabElementInside != null) return lastTabElementInside; } if (tabbingType == KeyboardNavigationMode.Contained) return null; if (e != container && IsTabStop(container)) return container; // If end of the subtree is reached or there no other elements above if (!goDownOnly && GetParent(container) != null) { return GetPrevTab(container, null, false); } return null; } public static IInputElement? GetPrevTabOutside(ICustomKeyboardNavigation e) { if (e is IInputElement container) { var first = GetFirstChild(container); if (first is object) return GetPrevTab(first, null, false); } return null; } private static IInputElement? FocusedElement(IInputElement e) { var iie = e; // Focus delegation is enabled only if keyboard focus is outside the container if (iie != null && !iie.IsKeyboardFocusWithin) { var focusedElement = (FocusManager.Instance as FocusManager)?.GetFocusedElement(e); if (focusedElement != null) { if (!IsFocusScope(e)) { // Verify if focusedElement is a visual descendant of e if (focusedElement is IVisual visualFocusedElement && visualFocusedElement != e && e.IsVisualAncestorOf(visualFocusedElement)) { return focusedElement; } } } } return null; } private static IInputElement? GetFirstChild(IInputElement e) { // If the element has a FocusedElement it should be its first child if (FocusedElement(e) is IInputElement focusedElement) return focusedElement; // Return the first visible element. var uiElement = e as InputElement; if (uiElement is null || IsVisibleAndEnabled(uiElement)) { if (e is IVisual elementAsVisual) { var children = elementAsVisual.VisualChildren; var count = children.Count; for (int i = 0; i < count; i++) { if (children[i] is InputElement ie) { if (IsVisibleAndEnabled(ie)) return ie; else { var firstChild = GetFirstChild(ie); if (firstChild != null) return firstChild; } } } } } return null; } private static IInputElement? GetLastChild(IInputElement e) { // If the element has a FocusedElement it should be its last child if (FocusedElement(e) is IInputElement focusedElement) return focusedElement; // Return the last visible element. var uiElement = e as InputElement; if (uiElement == null || IsVisibleAndEnabled(uiElement)) { var elementAsVisual = e as IVisual; if (elementAsVisual != null) { var children = elementAsVisual.VisualChildren; var count = children.Count; for (int i = count - 1; i >= 0; i--) { if (children[i] is InputElement ie) { if (IsVisibleAndEnabled(ie)) return ie; else { var lastChild = GetLastChild(ie); if (lastChild != null) return lastChild; } } } } } return null; } private static IInputElement? GetFirstTabInGroup(IInputElement container) { IInputElement? firstTabElement = null; int minIndexFirstTab = int.MinValue; var currElement = container; while ((currElement = GetNextInTree(currElement, container)) != null) { if (IsTabStopOrGroup(currElement)) { int currPriority = KeyboardNavigation.GetTabIndex(currElement); if (currPriority < minIndexFirstTab || firstTabElement == null) { minIndexFirstTab = currPriority; firstTabElement = currElement; } } } return firstTabElement; } private static IInputElement? GetLastInTree(IInputElement container) { IInputElement? result; IInputElement? c = container; do { result = c; c = GetLastChild(c); } while (c != null && !IsGroup(c)); if (c != null) return c; return result; } private static IInputElement? GetLastTabInGroup(IInputElement container) { IInputElement? lastTabElement = null; int maxIndexFirstTab = int.MaxValue; var currElement = GetLastInTree(container); while (currElement != null && currElement != container) { if (IsTabStopOrGroup(currElement)) { int currPriority = KeyboardNavigation.GetTabIndex(currElement); if (currPriority > maxIndexFirstTab || lastTabElement == null) { maxIndexFirstTab = currPriority; lastTabElement = currElement; } } currElement = GetPreviousInTree(currElement, container); } return lastTabElement; } private static IInputElement? GetNextInTree(IInputElement e, IInputElement container) { IInputElement? result = null; if (e == container || !IsGroup(e)) result = GetFirstChild(e); if (result != null || e == container) return result; IInputElement? parent = e; do { var sibling = GetNextSibling(parent); if (sibling != null) return sibling; parent = GetParent(parent); } while (parent != null && parent != container); return null; } private static IInputElement? GetNextSibling(IInputElement e) { if (GetParent(e) is IVisual parentAsVisual && e is IVisual elementAsVisual) { var children = parentAsVisual.VisualChildren; var count = children.Count; var i = 0; //go till itself for (; i < count; i++) { var vchild = children[i]; if (vchild == elementAsVisual) break; } i++; //search ahead for (; i < count; i++) { var visual = children[i]; if (visual is IInputElement ie) return ie; } } return null; } private static IInputElement? GetNextTabInGroup(IInputElement? e, IInputElement container, KeyboardNavigationMode tabbingType) { // None groups: Tab navigation is not supported if (tabbingType == KeyboardNavigationMode.None) return null; // e == null or e == container -> return the first TabStopOrGroup if (e == null || e == container) { return GetFirstTabInGroup(container); } if (tabbingType == KeyboardNavigationMode.Once) return null; var nextTabElement = GetNextTabWithSameIndex(e, container); if (nextTabElement != null) return nextTabElement; return GetNextTabWithNextIndex(e, container, tabbingType); } private static IInputElement? GetNextTabWithSameIndex(IInputElement e, IInputElement container) { var elementTabPriority = KeyboardNavigation.GetTabIndex(e); var currElement = e; while ((currElement = GetNextInTree(currElement, container)) != null) { if (IsTabStopOrGroup(currElement) && KeyboardNavigation.GetTabIndex(currElement) == elementTabPriority) { return currElement; } } return null; } private static IInputElement? GetNextTabWithNextIndex(IInputElement e, IInputElement container, KeyboardNavigationMode tabbingType) { // Find the next min index in the tree // min (index>currentTabIndex) IInputElement? nextTabElement = null; IInputElement? firstTabElement = null; int minIndexFirstTab = int.MinValue; int minIndex = int.MinValue; int elementTabPriority = KeyboardNavigation.GetTabIndex(e); IInputElement? currElement = container; while ((currElement = GetNextInTree(currElement, container)) != null) { if (IsTabStopOrGroup(currElement)) { int currPriority = KeyboardNavigation.GetTabIndex(currElement); if (currPriority > elementTabPriority) { if (currPriority < minIndex || nextTabElement == null) { minIndex = currPriority; nextTabElement = currElement; } } if (currPriority < minIndexFirstTab || firstTabElement == null) { minIndexFirstTab = currPriority; firstTabElement = currElement; } } } // Cycle groups: if not found - return first element if (tabbingType == KeyboardNavigationMode.Cycle && nextTabElement == null) nextTabElement = firstTabElement; return nextTabElement; } private static IInputElement? GetPrevTabInGroup(IInputElement? e, IInputElement container, KeyboardNavigationMode tabbingType) { // None groups: Tab navigation is not supported if (tabbingType == KeyboardNavigationMode.None) return null; // Search the last index inside the group if (e == null) { return GetLastTabInGroup(container); } if (tabbingType == KeyboardNavigationMode.Once) return null; if (e == container) return null; var nextTabElement = GetPrevTabWithSameIndex(e, container); if (nextTabElement != null) return nextTabElement; return GetPrevTabWithPrevIndex(e, container, tabbingType); } private static IInputElement? GetPrevTabWithSameIndex(IInputElement e, IInputElement container) { int elementTabPriority = KeyboardNavigation.GetTabIndex(e); var currElement = GetPreviousInTree(e, container); while (currElement != null) { if (IsTabStopOrGroup(currElement) && KeyboardNavigation.GetTabIndex(currElement) == elementTabPriority && currElement != container) { return currElement; } currElement = GetPreviousInTree(currElement, container); } return null; } private static IInputElement? GetPrevTabWithPrevIndex(IInputElement e, IInputElement container, KeyboardNavigationMode tabbingType) { // Find the next max index in the tree // max (index<currentTabIndex) IInputElement? lastTabElement = null; IInputElement? nextTabElement = null; int elementTabPriority = KeyboardNavigation.GetTabIndex(e); int maxIndexFirstTab = Int32.MaxValue; int maxIndex = Int32.MaxValue; var currElement = GetLastInTree(container); while (currElement != null) { if (IsTabStopOrGroup(currElement) && currElement != container) { int currPriority = KeyboardNavigation.GetTabIndex(currElement); if (currPriority < elementTabPriority) { if (currPriority > maxIndex || nextTabElement == null) { maxIndex = currPriority; nextTabElement = currElement; } } if (currPriority > maxIndexFirstTab || lastTabElement == null) { maxIndexFirstTab = currPriority; lastTabElement = currElement; } } currElement = GetPreviousInTree(currElement, container); } // Cycle groups: if not found - return first element if (tabbingType == KeyboardNavigationMode.Cycle && nextTabElement == null) nextTabElement = lastTabElement; return nextTabElement; } private static IInputElement? GetPreviousInTree(IInputElement e, IInputElement container) { if (e == container) return null; var result = GetPreviousSibling(e); if (result != null) { if (IsGroup(result)) return result; else return GetLastInTree(result); } else return GetParent(e); } private static IInputElement? GetPreviousSibling(IInputElement e) { if (GetParent(e) is IVisual parentAsVisual && e is IVisual elementAsVisual) { var children = parentAsVisual.VisualChildren; var count = children.Count; IInputElement? prev = null; for (int i = 0; i < count; i++) { var vchild = children[i]; if (vchild == elementAsVisual) break; if (vchild is IInputElement ie && IsVisibleAndEnabled(ie)) prev = ie; } return prev; } return null; } private static IInputElement? GetActiveElement(IInputElement e) { return ((IAvaloniaObject)e).GetValue(KeyboardNavigation.TabOnceActiveElementProperty); } private static IInputElement GetGroupParent(IInputElement e) => GetGroupParent(e, false); private static IInputElement GetGroupParent(IInputElement element, bool includeCurrent) { var result = element; // Keep the last non null element var e = element; // If we don't want to include the current element, // start at the parent of the element. If the element // is the root, then just return it as the group parent. if (!includeCurrent) { result = e; e = GetParent(e); if (e == null) return result; } while (e != null) { if (IsGroup(e)) return e; result = e; e = GetParent(e); } return result; } private static IInputElement? GetParent(IInputElement e) { // For Visual - go up the visual parent chain until we find Visual. if (e is IVisual v) return v.FindAncestorOfType<IInputElement>(); // This will need to be implemented when we have non-visual input elements. throw new NotSupportedException(); } private static KeyboardNavigationMode GetKeyNavigationMode(IInputElement e) { return ((IAvaloniaObject)e).GetValue(KeyboardNavigation.TabNavigationProperty); } private static bool IsFocusScope(IInputElement e) => FocusManager.GetIsFocusScope(e) || GetParent(e) == null; private static bool IsGroup(IInputElement e) => GetKeyNavigationMode(e) != KeyboardNavigationMode.Continue; private static bool IsTabStop(IInputElement e) { if (e is InputElement ie) return ie.Focusable && KeyboardNavigation.GetIsTabStop(ie) && ie.IsVisible && ie.IsEnabled; return false; } private static bool IsTabStopOrGroup(IInputElement e) => IsTabStop(e) || IsGroup(e); private static bool IsVisibleAndEnabled(IInputElement e) => e.IsVisible && e.IsEnabled; } }
using UnityEngine; using System; using System.Linq; using RoaringFangs.Adapters.FluffyUnderware.Curvy; using RoaringFangs.Utility; using RoaringFangs.Editor; #if FLUFFYUNDERWARE_CURVY #else using RoaringFangs.Adapters.FluffyUnderware.Curvy; #endif using RoaringFangs.Attributes; namespace RoaringFangs.Visuals { [ExecuteInEditMode] public class CurvySplineMeshDeformer : MonoBehaviour, ISerializationCallbackReceiver { #region Properties [SerializeField, AutoProperty] private Renderer _Renderer; public Renderer Renderer { get { return _Renderer; } set { if (value == null) _Renderer = GetComponent<Renderer>(); else _Renderer = value; } } [SerializeField, AutoProperty] private Material[] _Materials; [SerializeField, HideInInspector] private SynchronizedMaterial[] _SyncedMaterials; public Material[] Materials { get { return _Materials; } set { _Materials = value; _SyncedMaterials = value .Select(m => m != null ? new SynchronizedMaterial(m, new Material(m)) : new SynchronizedMaterial()) .ToArray(); SyncMaterials(); RefreshProperties(); } } // TODO: abstract this into a static helper function private void SyncMaterials() { foreach(var m in _SyncedMaterials) m.SyncProperties(); Renderer.sharedMaterials = _SyncedMaterials .Select(m => m.Destination) .ToArray(); } private void RefreshProperties() { // These should be good enough StretchFactor = StretchFactor; SegmentScale = SegmentScale; SegmentLength = SegmentLength; Color = Color; } [SerializeField, AutoProperty] private Color _Color; public Color Color { get { return _Color; } set { _Color = value; foreach (var material in Renderer.sharedMaterials.Where(m => m != null)) material.color = value; } } [SerializeField, AutoProperty] private Vector2 _StretchFactor; public Vector2 StretchFactor { get { return _StretchFactor; } set { var valid_materials = Renderer.sharedMaterials.Where(m => m != null); foreach (var material in valid_materials) { material.SetFloat("_StretchX", value.x); material.SetFloat("_StretchY", value.y * _SegmentLength); } _StretchFactor = value; //StraightenEnds = _StraightenEnds; } } [SerializeField, AutoProperty] private Transform[] _Weights; public Transform[] Weights { get { return _Weights; } set { _Weights = value; _WeightsDirty = true; } } [SerializeField, AutoProperty("TargetPathSpline")] private MonoBehaviour _TargetPathSplineBehavior; public ICurvySpline TargetPathSpline { get { return (ICurvySpline)_TargetPathSplineBehavior; } set { _TargetPathSplineBehavior = (MonoBehaviour)value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private float _SegmentPathPosition = 0f; public float SegmentPathPosition { get { return _SegmentPathPosition; } set { _SegmentPathPosition = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private float _SegmentLength = 1f; public float SegmentLength { get { return _SegmentLength; } set { var valid_materials = Renderer.sharedMaterials.Where(m => m != null); foreach (var material in valid_materials) { material.SetFloat("_StretchY", _StretchFactor.y * value); } _SegmentLength = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private float _SegmentAngle = 0f; public float SegmentAngle { get { return _SegmentAngle; } set { _SegmentAngle = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private Vector3 _SegmentForwardVector = Vector3.forward; public Vector3 SegmentForwardVector { get { return _SegmentForwardVector; } set { _SegmentForwardVector = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private Vector3 _SegmentScale = Vector3.one; public Vector3 SegmentScale { get { return _SegmentScale; } set { _SegmentScale = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private Vector3 _SegmentNormalShift = Vector3.zero; public Vector3 SegmentNormalShift { get { return _SegmentNormalShift; } set { _SegmentNormalShift = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private bool _SegmentUseFixedAngle = false; public bool SegmentUseFixedAngle { get { return _SegmentUseFixedAngle; } set { _SegmentUseFixedAngle = value; _WeightsDirty = true; } } [SerializeField, AutoProperty] private bool _SegmentFlipWeightDirection = false; public bool SegmentFlipWeightDirection { get { return _SegmentFlipWeightDirection; } set { _SegmentFlipWeightDirection = value; _WeightsDirty = true; } } [Tooltip("Experimental feature to evenly space weights along the length of the spline.")] [SerializeField, AutoProperty] private bool _UseUniformSpacing = false; public bool UseUniformSpacing { get { return _UseUniformSpacing; } set { _UseUniformSpacing = value; _WeightsDirty = true; } } [SerializeField, MinMax(0f, 1f), AutoProperty] private Vector2 _StraightenEnds = new Vector2(0f, 1f); public Vector2 StraightenEnds { get { return _StraightenEnds; } set { _StraightenEnds = value; _StraightenEnds.x = Mathf.Min(value.x, value.y); _WeightsDirty = true; } } [SerializeField] private Positioning _Positioning; public Positioning Positioning { get { return _Positioning; } set { _Positioning = value; _WeightsDirty = true; } } private bool _WeightsDirty = true; private bool _MaterialsDirty = true; #endregion Properties private void Start() { // Necessary if(TargetPathSpline != null) TargetPathSpline.Refresh(); // Round-trip update and instantiate runtime materials Materials = Materials; } private int _SplinePointsChecksum; private void Update() { if (TargetPathSpline != null) { int spline_points_checksum = CurvyControlPointsHash(TargetPathSpline); if (TargetPathSpline.Dirty || _SplinePointsChecksum != spline_points_checksum || _WeightsDirty) { UpdateMeshWeights(true, true, _WeightsDirty); _SplinePointsChecksum = spline_points_checksum; } } SyncMaterials(); RefreshProperties(); } private static int CurvySplineSegmentHash(ICurvySplineSegment s) { return s.transform.localToWorldMatrix.GetHashCode(); } private static int CurvyControlPointsHash(ICurvySpline spline) { if (spline.ControlPoints.Count == 0) return 0; var hash_codes = spline.ControlPoints .Where(p => p != null) .Select((Func<ICurvySplineSegment, int>)CurvySplineSegmentHash) .ToArray(); int xor_hash = hash_codes.Aggregate((a, b) => a ^ b); return xor_hash; } public void UpdateMeshWeights() { UpdateMeshWeights(true, true, true); } public void UpdateMeshWeights(bool affect_position, bool affect_rotation, bool affect_scale) { if (TargetPathSpline != null && Weights != null) { float weights_length_m1 = (float)Weights.Length - 1f; Vector3 point, tangent; Quaternion rotation, rotation_initial; for (int i = 0; i < Weights.Length; i++) { float t; float x = (float)i / weights_length_m1; float x_min = StraightenEnds.x; float x_max = StraightenEnds.y; if (x < x_min || x > x_max) { if (x < x_min) t = SegmentPathPosition + SegmentLength * x_min; else t = SegmentPathPosition + SegmentLength * x_max; if (UseUniformSpacing) t = TargetPathSpline.DistanceToTF(TargetPathSpline.Length * t); tangent = TargetPathSpline.GetTangentFast(t); point = TargetPathSpline.InterpolateFast(t); if (x < x_min) point += (x - x_min) * SegmentLength * TargetPathSpline.Length * tangent; else point += (x - x_max) * SegmentLength * TargetPathSpline.Length * tangent; } else { t = SegmentPathPosition + SegmentLength * x; if (UseUniformSpacing) t = TargetPathSpline.DistanceToTF(TargetPathSpline.Length * t); tangent = TargetPathSpline.GetTangentFast(t); point = TargetPathSpline.InterpolateFast(t); } rotation_initial = Quaternion.AngleAxis(SegmentAngle, SegmentForwardVector); if (SegmentFlipWeightDirection) { Quaternion flip = Quaternion.FromToRotation(SegmentForwardVector, -SegmentForwardVector); rotation_initial = rotation_initial * flip; } if (SegmentUseFixedAngle) { rotation = rotation_initial; } else { rotation = TargetPathSpline.GetOrientationFast(t) * rotation_initial; } point += rotation * SegmentNormalShift; Transform weight = Weights[i]; if (Positioning == Positioning.WorldSpace) { if (affect_position) weight.position = point; if (affect_rotation) weight.rotation = rotation; } else if (Positioning == Positioning.LocalSpace) { if (affect_position) weight.localPosition = point; if (affect_rotation) weight.localRotation = rotation; } if (affect_scale) weight.localScale = SegmentScale; } _WeightsDirty = false; } } public void OnBeforeSerialize() { /* // Additional validation logic for materials b/c they keep unsetting on the meshes if (Renderer.sharedMaterials == null || !Renderer.sharedMaterials.Any() || Renderer.sharedMaterials.All(m => m == null)) ReferenceMaterials = ReferenceMaterials; */ EditorUtilities.OnBeforeSerializeAutoProperties(this); } public void OnAfterDeserialize() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.Tests { public partial class StringTests { [Theory] [InlineData(0, 0)] [InlineData(3, 1)] public static void Ctor_CharSpan_EmptyString(int length, int offset) { Assert.Same(string.Empty, new string(new ReadOnlySpan<char>(new char[length], offset, 0))); } [Fact] public static unsafe void Ctor_CharSpan_Empty() { Assert.Same(string.Empty, new string((ReadOnlySpan<char>)null)); Assert.Same(string.Empty, new string(ReadOnlySpan<char>.Empty)); } [Theory] [InlineData(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0' }, 0, 8, "abcdefgh")] [InlineData(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0', 'i', 'j', 'k' }, 0, 12, "abcdefgh\0ijk")] [InlineData(new char[] { 'a', 'b', 'c' }, 0, 0, "")] [InlineData(new char[] { 'a', 'b', 'c' }, 0, 1, "a")] [InlineData(new char[] { 'a', 'b', 'c' }, 2, 1, "c")] [InlineData(new char[] { '\u8001', '\u8002', '\ufffd', '\u1234', '\ud800', '\udfff' }, 0, 6, "\u8001\u8002\ufffd\u1234\ud800\udfff")] public static void Ctor_CharSpan(char[] valueArray, int startIndex, int length, string expected) { var span = new ReadOnlySpan<char>(valueArray, startIndex, length); Assert.Equal(expected, new string(span)); } [Fact] public static void Create_InvalidArguments_Throw() { AssertExtensions.Throws<ArgumentNullException>("action", () => string.Create(-1, 0, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => string.Create(-1, 0, (span, state) => { })); } [Fact] public static void Create_Length0_ReturnsEmptyString() { bool actionInvoked = false; Assert.Same(string.Empty, string.Create(0, 0, (span, state) => actionInvoked = true)); Assert.False(actionInvoked); } [Fact] public static void Create_NullState_Allowed() { string result = string.Create(1, (object)null, (span, state) => { span[0] = 'a'; Assert.Null(state); }); Assert.Equal("a", result); } [Fact] public static void Create_ClearsMemory() { const int Length = 10; string result = string.Create(Length, (object)null, (span, state) => { for (int i = 0; i < span.Length; i++) { Assert.Equal('\0', span[i]); } }); Assert.Equal(new string('\0', Length), result); } [Theory] [InlineData("a")] [InlineData("this is a test")] [InlineData("\0\u8001\u8002\ufffd\u1234\ud800\udfff")] public static void Create_ReturnsExpectedString(string expected) { char[] input = expected.ToCharArray(); string result = string.Create(input.Length, input, (span, state) => { Assert.Same(input, state); for (int i = 0; i < state.Length; i++) { span[i] = state[i]; } }); Assert.Equal(expected, result); } [Theory] [InlineData("Hello", 'H', true)] [InlineData("Hello", 'Z', false)] [InlineData("Hello", 'e', true)] [InlineData("Hello", 'E', false)] [InlineData("", 'H', false)] public static void Contains(string s, char value, bool expected) { Assert.Equal(expected, s.Contains(value)); ReadOnlySpan<char> span = s.AsSpan(); Assert.Equal(expected, span.Contains(value)); } [Theory] // CurrentCulture [InlineData("Hello", 'H', StringComparison.CurrentCulture, true)] [InlineData("Hello", 'Z', StringComparison.CurrentCulture, false)] [InlineData("Hello", 'e', StringComparison.CurrentCulture, true)] [InlineData("Hello", 'E', StringComparison.CurrentCulture, false)] [InlineData("", 'H', StringComparison.CurrentCulture, false)] // CurrentCultureIgnoreCase [InlineData("Hello", 'H', StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", 'Z', StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("Hello", 'e', StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", 'E', StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("", 'H', StringComparison.CurrentCultureIgnoreCase, false)] // InvariantCulture [InlineData("Hello", 'H', StringComparison.InvariantCulture, true)] [InlineData("Hello", 'Z', StringComparison.InvariantCulture, false)] [InlineData("Hello", 'e', StringComparison.InvariantCulture, true)] [InlineData("Hello", 'E', StringComparison.InvariantCulture, false)] [InlineData("", 'H', StringComparison.InvariantCulture, false)] // InvariantCultureIgnoreCase [InlineData("Hello", 'H', StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", 'Z', StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("Hello", 'e', StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", 'E', StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("", 'H', StringComparison.InvariantCultureIgnoreCase, false)] // Ordinal [InlineData("Hello", 'H', StringComparison.Ordinal, true)] [InlineData("Hello", 'Z', StringComparison.Ordinal, false)] [InlineData("Hello", 'e', StringComparison.Ordinal, true)] [InlineData("Hello", 'E', StringComparison.Ordinal, false)] [InlineData("", 'H', StringComparison.Ordinal, false)] // OrdinalIgnoreCase [InlineData("Hello", 'H', StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", 'Z', StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", 'e', StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", 'E', StringComparison.OrdinalIgnoreCase, true)] [InlineData("", 'H', StringComparison.OrdinalIgnoreCase, false)] public static void Contains(string s, char value, StringComparison comparisionType, bool expected) { Assert.Equal(expected, s.Contains(value, comparisionType)); } [Theory] // CurrentCulture [InlineData("Hello", "ello", StringComparison.CurrentCulture, true)] [InlineData("Hello", "ELL", StringComparison.CurrentCulture, false)] [InlineData("Hello", "ElLo", StringComparison.CurrentCulture, false)] [InlineData("Hello", "Larger Hello", StringComparison.CurrentCulture, false)] [InlineData("Hello", "Goodbye", StringComparison.CurrentCulture, false)] [InlineData("", "", StringComparison.CurrentCulture, true)] [InlineData("", "hello", StringComparison.CurrentCulture, false)] [InlineData("Hello", "", StringComparison.CurrentCulture, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.CurrentCulture, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.CurrentCulture, false)] // CurrentCultureIgnoreCase [InlineData("Hello", "ello", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "ELL", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "ElLo", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "Larger Hello", StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("Hello", "Goodbye", StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("", "", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("", "hello", StringComparison.CurrentCultureIgnoreCase, false)] [InlineData("Hello", "", StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.CurrentCultureIgnoreCase, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.CurrentCultureIgnoreCase, true)] // InvariantCulture [InlineData("Hello", "ello", StringComparison.InvariantCulture, true)] [InlineData("Hello", "ELL", StringComparison.InvariantCulture, false)] [InlineData("Hello", "ElLo", StringComparison.InvariantCulture, false)] [InlineData("Hello", "Larger Hello", StringComparison.InvariantCulture, false)] [InlineData("Hello", "Goodbye", StringComparison.InvariantCulture, false)] [InlineData("", "", StringComparison.InvariantCulture, true)] [InlineData("", "hello", StringComparison.InvariantCulture, false)] [InlineData("Hello", "", StringComparison.InvariantCulture, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.InvariantCulture, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.InvariantCulture, false)] // InvariantCultureIgnoreCase [InlineData("Hello", "ello", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "ELL", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "ElLo", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "Larger Hello", StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("Hello", "Goodbye", StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("", "", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("", "hello", StringComparison.InvariantCultureIgnoreCase, false)] [InlineData("Hello", "", StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.InvariantCultureIgnoreCase, true)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.InvariantCultureIgnoreCase, true)] // Ordinal [InlineData("Hello", "ello", StringComparison.Ordinal, true)] [InlineData("Hello", "ELL", StringComparison.Ordinal, false)] [InlineData("Hello", "ElLo", StringComparison.Ordinal, false)] [InlineData("Hello", "Larger Hello", StringComparison.Ordinal, false)] [InlineData("Hello", "Goodbye", StringComparison.Ordinal, false)] [InlineData("", "", StringComparison.Ordinal, true)] [InlineData("", "hello", StringComparison.Ordinal, false)] [InlineData("Hello", "", StringComparison.Ordinal, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.Ordinal, false)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.Ordinal, false)] // OrdinalIgnoreCase [InlineData("Hello", "ello", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "ELL", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "ElLo", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "Larger Hello", StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", "Goodbye", StringComparison.OrdinalIgnoreCase, false)] [InlineData("", "", StringComparison.OrdinalIgnoreCase, true)] [InlineData("", "hello", StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", "", StringComparison.OrdinalIgnoreCase, true)] [InlineData("Hello", "ell" + SoftHyphen, StringComparison.OrdinalIgnoreCase, false)] [InlineData("Hello", "Ell" + SoftHyphen, StringComparison.OrdinalIgnoreCase, false)] public static void Contains(string s, string value, StringComparison comparisonType, bool expected) { Assert.Equal(expected, s.Contains(value, comparisonType)); Assert.Equal(expected, s.AsSpan().Contains(value, comparisonType)); } [Fact] public static void Contains_StringComparison_TurkishI() { string str = "\u0069\u0130"; RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); Assert.True(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); Assert.True(source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, str).Dispose(); RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.False(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); Assert.False(source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, str).Dispose(); } [Fact] public static void Contains_Match_Char() { Assert.False("".Contains('a')); Assert.False("".AsSpan().Contains('a')); // Use a long-enough string to incur vectorization code const int max = 250; for (var length = 1; length < max; length++) { char[] ca = new char[length]; for (int i = 0; i < length; i++) { ca[i] = (char)(i + 1); } var span = new Span<char>(ca); var ros = new ReadOnlySpan<char>(ca); var str = new string(ca); for (var targetIndex = 0; targetIndex < length; targetIndex++) { char target = ca[targetIndex]; // Span bool found = span.Contains(target); Assert.True(found); // ReadOnlySpan found = ros.Contains(target); Assert.True(found); // String found = str.Contains(target); Assert.True(found); } } } [Fact] public static void Contains_ZeroLength_Char() { // Span var span = new Span<char>(Array.Empty<char>()); bool found = span.Contains((char)0); Assert.False(found); span = Span<char>.Empty; found = span.Contains((char)0); Assert.False(found); // ReadOnlySpan var ros = new ReadOnlySpan<char>(Array.Empty<char>()); found = ros.Contains((char)0); Assert.False(found); ros = ReadOnlySpan<char>.Empty; found = ros.Contains((char)0); Assert.False(found); // String found = string.Empty.Contains((char)0); Assert.False(found); } [Fact] public static void Contains_MultipleMatches_Char() { for (int length = 2; length < 32; length++) { var ca = new char[length]; for (int i = 0; i < length; i++) { ca[i] = (char)(i + 1); } ca[length - 1] = (char)200; ca[length - 2] = (char)200; // Span var span = new Span<char>(ca); bool found = span.Contains((char)200); Assert.True(found); // ReadOnlySpan var ros = new ReadOnlySpan<char>(ca); found = ros.Contains((char)200); Assert.True(found); // String var str = new string(ca); found = str.Contains((char)200); Assert.True(found); } } [Fact] public static void Contains_EnsureNoChecksGoOutOfRange_Char() { for (int length = 0; length < 100; length++) { var ca = new char[length + 2]; ca[0] = '9'; ca[length + 1] = '9'; // Span var span = new Span<char>(ca, 1, length); bool found = span.Contains('9'); Assert.False(found); // ReadOnlySpan var ros = new ReadOnlySpan<char>(ca, 1, length); found = ros.Contains('9'); Assert.False(found); // String var str = new string(ca, 1, length); found = str.Contains('9'); Assert.False(found); } } [Theory] [InlineData(StringComparison.CurrentCulture)] [InlineData(StringComparison.CurrentCultureIgnoreCase)] [InlineData(StringComparison.InvariantCulture)] [InlineData(StringComparison.InvariantCultureIgnoreCase)] [InlineData(StringComparison.Ordinal)] [InlineData(StringComparison.OrdinalIgnoreCase)] public static void Contains_NullValue_ThrowsArgumentNullException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentNullException>("value", () => "foo".Contains(null, comparisonType)); } [Theory] [InlineData(StringComparison.CurrentCulture - 1)] [InlineData(StringComparison.OrdinalIgnoreCase + 1)] public static void Contains_InvalidComparisonType_ThrowsArgumentOutOfRangeException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentException>("comparisonType", () => "ab".Contains("a", comparisonType)); } [Theory] [InlineData("Hello", 'o', true)] [InlineData("Hello", 'O', false)] [InlineData("o", 'o', true)] [InlineData("o", 'O', false)] [InlineData("Hello", 'e', false)] [InlineData("Hello", '\0', false)] [InlineData("", '\0', false)] [InlineData("\0", '\0', true)] [InlineData("", 'a', false)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'z', true)] public static void EndsWith(string s, char value, bool expected) { Assert.Equal(expected, s.EndsWith(value)); } [Theory] [InlineData("Hello", 'H', true)] [InlineData("Hello", 'h', false)] [InlineData("H", 'H', true)] [InlineData("H", 'h', false)] [InlineData("Hello", 'e', false)] [InlineData("Hello", '\0', false)] [InlineData("", '\0', false)] [InlineData("\0", '\0', true)] [InlineData("", 'a', false)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'a', true)] public static void StartsWith(string s, char value, bool expected) { Assert.Equal(expected, s.StartsWith(value)); } public static IEnumerable<object[]> Join_Char_StringArray_TestData() { yield return new object[] { '|', new string[0], 0, 0, "" }; yield return new object[] { '|', new string[] { "a" }, 0, 1, "a" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 3, "a|b|c" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 2, "a|b" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 1, "b" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 2, "b|c" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 3, 0, "" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 0, "" }; yield return new object[] { '|', new string[] { "", "", "" }, 0, 3, "||" }; yield return new object[] { '|', new string[] { null, null, null }, 0, 3, "||" }; } [Theory] [MemberData(nameof(Join_Char_StringArray_TestData))] public static void Join_Char_StringArray(char separator, string[] values, int startIndex, int count, string expected) { if (startIndex == 0 && count == values.Length) { Assert.Equal(expected, string.Join(separator, values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<string>)values)); Assert.Equal(expected, string.Join(separator, (object[])values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values)); } Assert.Equal(expected, string.Join(separator, values, startIndex, count)); Assert.Equal(expected, string.Join(separator.ToString(), values, startIndex, count)); } public static IEnumerable<object[]> Join_Char_ObjectArray_TestData() { yield return new object[] { '|', new object[0], "" }; yield return new object[] { '|', new object[] { 1 }, "1" }; yield return new object[] { '|', new object[] { 1, 2, 3 }, "1|2|3" }; yield return new object[] { '|', new object[] { new ObjectWithNullToString(), 2, new ObjectWithNullToString() }, "|2|" }; yield return new object[] { '|', new object[] { "1", null, "3" }, "1||3" }; yield return new object[] { '|', new object[] { "", "", "" }, "||" }; yield return new object[] { '|', new object[] { "", null, "" }, "||" }; yield return new object[] { '|', new object[] { null, null, null }, "||" }; } [Theory] [MemberData(nameof(Join_Char_ObjectArray_TestData))] public static void Join_Char_ObjectArray(char separator, object[] values, string expected) { Assert.Equal(expected, string.Join(separator, values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values)); } [Fact] public static void Join_Char_NullValues_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null)); AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (IEnumerable<object>)null)); } [Fact] public static void Join_Char_NegativeStartIndex_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, -1, 0)); } [Fact] public static void Join_Char_NegativeCount_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => string.Join('|', new string[] { "Foo" }, 0, -1)); } [Theory] [InlineData(2, 1)] [InlineData(2, 0)] [InlineData(1, 2)] [InlineData(1, 1)] [InlineData(0, 2)] [InlineData(-1, 0)] public static void Join_Char_InvalidStartIndexCount_ThrowsArgumentOutOfRangeException(int startIndex, int count) { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, startIndex, count)); } public static IEnumerable<object[]> Replace_StringComparison_TestData() { yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCulture, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCulture, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.CurrentCulture, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCulture, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.CurrentCulture, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.CurrentCulture, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCulture, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.CurrentCultureIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCultureIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.CurrentCultureIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.CurrentCultureIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.Ordinal, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.Ordinal, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.Ordinal, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.Ordinal, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.Ordinal, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.Ordinal, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.Ordinal, "abc" }; yield return new object[] { "abc", "abc", "def", StringComparison.OrdinalIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.OrdinalIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.OrdinalIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.OrdinalIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.OrdinalIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.OrdinalIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.OrdinalIgnoreCase, "abc" }; yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCulture, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.InvariantCulture, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCulture, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.InvariantCulture, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.InvariantCulture, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCulture, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCultureIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.InvariantCultureIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCultureIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.InvariantCultureIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.InvariantCultureIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCultureIgnoreCase, "def" }; string turkishSource = "\u0069\u0130"; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.Ordinal, "a\u0130" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.OrdinalIgnoreCase, "a\u0130" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.Ordinal, "\u0069a" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.OrdinalIgnoreCase, "\u0069a" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCulture, "a\u0130" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCultureIgnoreCase, "a\u0130" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCulture, "\u0069a" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCultureIgnoreCase, "\u0069a" }; } [Theory] [MemberData(nameof(Replace_StringComparison_TestData))] public void Replace_StringComparison_ReturnsExpected(string original, string oldValue, string newValue, StringComparison comparisonType, string expected) { Assert.Equal(expected, original.Replace(oldValue, newValue, comparisonType)); } [Fact] public void Replace_StringComparison_TurkishI() { string src = "\u0069\u0130"; RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture)); Assert.Equal("aa", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture)); Assert.Equal("aa", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, src).Dispose(); RemoteInvoke((source) => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }, src).Dispose(); } public static IEnumerable<object[]> Replace_StringComparisonCulture_TestData() { yield return new object[] { "abc", "abc", "def", false, null, "def" }; yield return new object[] { "abc", "ABC", "def", false, null, "abc" }; yield return new object[] { "abc", "abc", "def", false, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", false, CultureInfo.InvariantCulture, "abc" }; yield return new object[] { "abc", "abc", "def", true, null, "def" }; yield return new object[] { "abc", "ABC", "def", true, null, "def" }; yield return new object[] { "abc", "abc", "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, null, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, null, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", false, new CultureInfo("tr-TR"), "a\u0130" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", true, new CultureInfo("tr-TR"), "aa" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", false, CultureInfo.InvariantCulture, "a\u0130" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", true, CultureInfo.InvariantCulture, "a\u0130" }; } [Theory] [MemberData(nameof(Replace_StringComparisonCulture_TestData))] public void Replace_StringComparisonCulture_ReturnsExpected(string original, string oldValue, string newValue, bool ignoreCase, CultureInfo culture, string expected) { Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, culture)); if (culture == null) { Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, CultureInfo.CurrentCulture)); } } [Fact] public void Replace_StringComparison_NullOldValue_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", StringComparison.CurrentCulture)); AssertExtensions.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", true, CultureInfo.CurrentCulture)); } [Fact] public void Replace_StringComparison_EmptyOldValue_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", StringComparison.CurrentCulture)); AssertExtensions.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", true, CultureInfo.CurrentCulture)); } [Theory] [InlineData(StringComparison.CurrentCulture - 1)] [InlineData(StringComparison.OrdinalIgnoreCase + 1)] public void Replace_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentException>("comparisonType", () => "abc".Replace("abc", "def", comparisonType)); } private static readonly StringComparison[] StringComparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison)); public static IEnumerable<object[]> GetHashCode_StringComparison_Data => StringComparisons.Select(value => new object[] { value }); [Theory] [MemberData(nameof(GetHashCode_StringComparison_Data))] public static void GetHashCode_StringComparison(StringComparison comparisonType) { Assert.Equal(StringComparer.FromComparison(comparisonType).GetHashCode("abc"), "abc".GetHashCode(comparisonType)); } public static IEnumerable<object[]> GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data => new[] { new object[] { StringComparisons.Min() - 1 }, new object[] { StringComparisons.Max() + 1 }, }; [Theory] [MemberData(nameof(GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data))] public static void GetHashCode_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType) { AssertExtensions.Throws<ArgumentException>("comparisonType", () => "abc".GetHashCode(comparisonType)); } [Theory] [InlineData("")] [InlineData("a")] [InlineData("\0")] [InlineData("abc")] public static unsafe void ImplicitCast_ResultingSpanMatches(string s) { ReadOnlySpan<char> span = s; Assert.Equal(s.Length, span.Length); fixed (char* stringPtr = s) fixed (char* spanPtr = &MemoryMarshal.GetReference(span)) { Assert.Equal((IntPtr)stringPtr, (IntPtr)spanPtr); } } [Fact] public static void ImplicitCast_NullString_ReturnsDefaultSpan() { ReadOnlySpan<char> span = (string)null; Assert.True(span == default); } [Theory] [InlineData("Hello", 'l', StringComparison.Ordinal, 2)] [InlineData("Hello", 'x', StringComparison.Ordinal, -1)] [InlineData("Hello", 'h', StringComparison.Ordinal, -1)] [InlineData("Hello", 'o', StringComparison.Ordinal, 4)] [InlineData("Hello", 'h', StringComparison.OrdinalIgnoreCase, 0)] [InlineData("HelLo", 'L', StringComparison.OrdinalIgnoreCase, 2)] [InlineData("HelLo", 'L', StringComparison.Ordinal, 3)] [InlineData("HelLo", '\0', StringComparison.Ordinal, -1)] [InlineData("!@#$%", '%', StringComparison.Ordinal, 4)] [InlineData("!@#$", '!', StringComparison.Ordinal, 0)] [InlineData("!@#$", '@', StringComparison.Ordinal, 1)] [InlineData("!@#$%", '%', StringComparison.OrdinalIgnoreCase, 4)] [InlineData("!@#$", '!', StringComparison.OrdinalIgnoreCase, 0)] [InlineData("!@#$", '@', StringComparison.OrdinalIgnoreCase, 1)] [InlineData("_____________\u807f", '\u007f', StringComparison.Ordinal, -1)] [InlineData("_____________\u807f__", '\u007f', StringComparison.Ordinal, -1)] [InlineData("_____________\u807f\u007f_", '\u007f', StringComparison.Ordinal, 14)] [InlineData("__\u807f_______________", '\u007f', StringComparison.Ordinal, -1)] [InlineData("__\u807f___\u007f___________", '\u007f', StringComparison.Ordinal, 6)] [InlineData("_____________\u807f", '\u007f', StringComparison.OrdinalIgnoreCase, -1)] [InlineData("_____________\u807f__", '\u007f', StringComparison.OrdinalIgnoreCase, -1)] [InlineData("_____________\u807f\u007f_", '\u007f', StringComparison.OrdinalIgnoreCase, 14)] [InlineData("__\u807f_______________", '\u007f', StringComparison.OrdinalIgnoreCase, -1)] [InlineData("__\u807f___\u007f___________", '\u007f', StringComparison.OrdinalIgnoreCase, 6)] public static void IndexOf_SingleLetter(string s, char target, StringComparison stringComparison, int expected) { Assert.Equal(expected, s.IndexOf(target, stringComparison)); var charArray = new char[1]; charArray[0] = target; Assert.Equal(expected, s.AsSpan().IndexOf(charArray, stringComparison)); } [Fact] public static void IndexOf_TurkishI_TurkishCulture_Char() { RemoteInvoke(() => { CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); string s = "Turkish I \u0131s TROUBL\u0130NG!"; char value = '\u0130'; Assert.Equal(19, s.IndexOf(value)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); ReadOnlySpan<char> span = s.AsSpan(); Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture)); Assert.Equal(4, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.Ordinal)); Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase)); value = '\u0131'; Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture)); Assert.Equal(8, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.Ordinal)); Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_TurkishI_InvariantCulture_Char() { RemoteInvoke(() => { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; string s = "Turkish I \u0131s TROUBL\u0130NG!"; char value = '\u0130'; Assert.Equal(19, s.IndexOf(value)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); value = '\u0131'; Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_TurkishI_EnglishUSCulture_Char() { RemoteInvoke(() => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); string s = "Turkish I \u0131s TROUBL\u0130NG!"; char value = '\u0130'; Assert.Equal(19, s.IndexOf(value)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); value = '\u0131'; Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_EquivalentDiacritics_EnglishUSCulture_Char() { RemoteInvoke(() => { string s = "Exhibit a\u0300\u00C0"; char value = '\u00C0'; CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.Equal(10, s.IndexOf(value)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_EquivalentDiacritics_InvariantCulture_Char() { RemoteInvoke(() => { string s = "Exhibit a\u0300\u00C0"; char value = '\u00C0'; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal(10, s.IndexOf(value)); Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_CyrillicE_EnglishUSCulture_Char() { RemoteInvoke(() => { string s = "Foo\u0400Bar"; char value = '\u0400'; CultureInfo.CurrentCulture = new CultureInfo("en-US"); Assert.Equal(3, s.IndexOf(value)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal)); Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_CyrillicE_InvariantCulture_Char() { RemoteInvoke(() => { string s = "Foo\u0400Bar"; char value = '\u0400'; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal(3, s.IndexOf(value)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture)); Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase)); return SuccessExitCode; }).Dispose(); } [Fact] public static void IndexOf_Invalid_Char() { // Invalid comparison type AssertExtensions.Throws<ArgumentException>("comparisonType", () => "foo".IndexOf('o', StringComparison.CurrentCulture - 1)); AssertExtensions.Throws<ArgumentException>("comparisonType", () => "foo".IndexOf('o', StringComparison.OrdinalIgnoreCase + 1)); } } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web.Mvc; using System.Web.Routing; using Orchard.ContentManagement; using Orchard.Core.Settings.Models; using Orchard.DisplayManagement; using Orchard.Localization; using Orchard.Mvc; using Orchard.Security; using Orchard.UI.Notify; using Orchard.Users.Events; using Orchard.Users.Models; using Orchard.Users.Services; using Orchard.Users.ViewModels; using Orchard.Mvc.Extensions; using System; using Orchard.Settings; using Orchard.UI.Navigation; using Orchard.Utility.Extensions; namespace Orchard.Users.Controllers { [ValidateInput(false)] public class AdminController : Controller, IUpdateModel { private readonly IMembershipService _membershipService; private readonly IUserService _userService; private readonly IUserEventHandler _userEventHandlers; private readonly ISiteService _siteService; public AdminController( IOrchardServices services, IMembershipService membershipService, IUserService userService, IShapeFactory shapeFactory, IUserEventHandler userEventHandlers, ISiteService siteService) { Services = services; _membershipService = membershipService; _userService = userService; _userEventHandlers = userEventHandlers; _siteService = siteService; T = NullLocalizer.Instance; Shape = shapeFactory; } dynamic Shape { get; set; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Index(UserIndexOptions options, PagerParameters pagerParameters) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to list users"))) return new HttpUnauthorizedResult(); var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); // default options if (options == null) options = new UserIndexOptions(); var users = Services.ContentManager .Query<UserPart, UserPartRecord>(); switch (options.Filter) { case UsersFilter.Approved: users = users.Where(u => u.RegistrationStatus == UserStatus.Approved); break; case UsersFilter.Pending: users = users.Where(u => u.RegistrationStatus == UserStatus.Pending); break; case UsersFilter.EmailPending: users = users.Where(u => u.EmailStatus == UserStatus.Pending); break; } if(!string.IsNullOrWhiteSpace(options.Search)) { users = users.Where(u => u.UserName.Contains(options.Search) || u.Email.Contains(options.Search)); } var pagerShape = Shape.Pager(pager).TotalItemCount(users.Count()); switch (options.Order) { case UsersOrder.Name: users = users.OrderBy(u => u.UserName); break; case UsersOrder.Email: users = users.OrderBy(u => u.Email); break; case UsersOrder.CreatedUtc: users = users.OrderBy(u => u.CreatedUtc); break; case UsersOrder.LastLoginUtc: users = users.OrderBy(u => u.LastLoginUtc); break; } var results = users .Slice(pager.GetStartIndex(), pager.PageSize) .ToList(); var model = new UsersIndexViewModel { Users = results .Select(x => new UserEntry { User = x.Record }) .ToList(), Options = options, Pager = pagerShape }; // maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.Order", options.Order); pagerShape.RouteData(routeData); return View(model); } [HttpPost] [FormValueRequired("submit.BulkEdit")] public ActionResult Index(FormCollection input) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var viewModel = new UsersIndexViewModel {Users = new List<UserEntry>(), Options = new UserIndexOptions()}; UpdateModel(viewModel); var checkedEntries = viewModel.Users.Where(c => c.IsChecked); switch (viewModel.Options.BulkAction) { case UsersBulkAction.None: break; case UsersBulkAction.Approve: foreach (var entry in checkedEntries) { Approve(entry.User.Id); } break; case UsersBulkAction.Disable: foreach (var entry in checkedEntries) { Moderate(entry.User.Id); } break; case UsersBulkAction.ChallengeEmail: foreach (var entry in checkedEntries) { SendChallengeEmail(entry.User.Id); } break; case UsersBulkAction.Delete: foreach (var entry in checkedEntries) { Delete(entry.User.Id); } break; } return RedirectToAction("Index", ControllerContext.RouteData.Values); } public ActionResult Create() { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.New<IUser>("User"); var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: new UserCreateViewModel(), Prefix: null); editor.Metadata.Position = "2"; var model = Services.ContentManager.BuildEditor(user); model.Content.Add(editor); return View(model); } [HttpPost, ActionName("Create")] public ActionResult CreatePOST(UserCreateViewModel createModel) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); if (!string.IsNullOrEmpty(createModel.UserName)) { if (!_userService.VerifyUserUnicity(createModel.UserName, createModel.Email)) { AddModelError("NotUniqueUserName", T("User with that username and/or email already exists.")); } } if (!Regex.IsMatch(createModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase)) { // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx ModelState.AddModelError("Email", T("You must specify a valid email address.")); } if (createModel.Password != createModel.ConfirmPassword) { AddModelError("ConfirmPassword", T("Password confirmation must match")); } var user = Services.ContentManager.New<IUser>("User"); if (ModelState.IsValid) { user = _membershipService.CreateUser(new CreateUserParams( createModel.UserName, createModel.Password, createModel.Email, null, null, true)); } var model = Services.ContentManager.UpdateEditor(user, this); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: createModel, Prefix: null); editor.Metadata.Position = "2"; model.Content.Add(editor); return View(model); } Services.Notifier.Information(T("User created")); return RedirectToAction("Index"); } public ActionResult Edit(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.Get<UserPart>(id); if (user == null) return HttpNotFound(); var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: new UserEditViewModel {User = user}, Prefix: null); editor.Metadata.Position = "2"; var model = Services.ContentManager.BuildEditor(user); model.Content.Add(editor); return View(model); } [HttpPost, ActionName("Edit")] public ActionResult EditPOST(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.Get<UserPart>(id, VersionOptions.DraftRequired); if (user == null) return HttpNotFound(); string previousName = user.UserName; var model = Services.ContentManager.UpdateEditor(user, this); var editModel = new UserEditViewModel { User = user }; if (TryUpdateModel(editModel)) { if (!_userService.VerifyUserUnicity(id, editModel.UserName, editModel.Email)) { AddModelError("NotUniqueUserName", T("User with that username and/or email already exists.")); } else if (!Regex.IsMatch(editModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase)) { // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx ModelState.AddModelError("Email", T("You must specify a valid email address.")); } else { // also update the Super user if this is the renamed account if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, previousName, StringComparison.Ordinal)) { _siteService.GetSiteSettings().As<SiteSettingsPart>().SuperUser = editModel.UserName; } user.NormalizedUserName = editModel.UserName.ToLowerInvariant(); } } if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: editModel, Prefix: null); editor.Metadata.Position = "2"; model.Content.Add(editor); return View(model); } Services.ContentManager.Publish(user.ContentItem); Services.Notifier.Information(T("User information updated")); return RedirectToAction("Index"); } [HttpPost] public ActionResult Delete(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.Get<IUser>(id); if (user == null) return HttpNotFound(); if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, user.UserName, StringComparison.Ordinal)) { Services.Notifier.Error(T("The Super user can't be removed. Please disable this account or specify another Super user account.")); } else if (string.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal)) { Services.Notifier.Error(T("You can't remove your own account. Please log in with another account.")); } else { Services.ContentManager.Remove(user.ContentItem); Services.Notifier.Information(T("User {0} deleted", user.UserName)); } return RedirectToAction("Index"); } [HttpPost] public ActionResult SendChallengeEmail(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.Get<IUser>(id); if (user == null) return HttpNotFound(); var siteUrl = Services.WorkContext.CurrentSite.BaseUrl; if (string.IsNullOrWhiteSpace(siteUrl)) { siteUrl = HttpContext.Request.ToRootUrlString(); } _userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl)); Services.Notifier.Information(T("Challenge email sent to {0}", user.UserName)); return RedirectToAction("Index"); } [HttpPost] public ActionResult Approve(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.Get<IUser>(id); if (user == null) return HttpNotFound(); user.As<UserPart>().RegistrationStatus = UserStatus.Approved; Services.Notifier.Information(T("User {0} approved", user.UserName)); _userEventHandlers.Approved(user); return RedirectToAction("Index"); } [HttpPost] public ActionResult Moderate(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users"))) return new HttpUnauthorizedResult(); var user = Services.ContentManager.Get<IUser>(id); if (user == null) return HttpNotFound(); if (string.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal)) { Services.Notifier.Error(T("You can't disable your own account. Please log in with another account")); } else { user.As<UserPart>().RegistrationStatus = UserStatus.Pending; Services.Notifier.Information(T("User {0} disabled", user.UserName)); } return RedirectToAction("Index"); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } public void AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Xml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; using Google.Apis.Auth.OAuth2; using Google.Apis.Blogger.v3; using Google.Apis.Util.Store; using Google.Apis.Services; using Google.Apis.Auth.OAuth2.Flows; using OpenLiveWriter.BlogClient.Providers; using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Util; using System.Globalization; using System.Diagnostics; using Google.Apis.Blogger.v3.Data; using System.Net.Http.Headers; using OpenLiveWriter.Controls; using System.Windows.Forms; namespace OpenLiveWriter.BlogClient.Clients { [BlogClient("GoogleBloggerv3", "GoogleBloggerv3")] public class GoogleBloggerv3Client : BlogClientBase, IBlogClient { // These URLs map to OAuth2 permission scopes for Google Blogger. public static string PicasaServiceScope = "https://picasaweb.google.com/data"; public static string BloggerServiceScope = BloggerService.Scope.Blogger; public static char LabelDelimiter = ','; public static Task<UserCredential> GetOAuth2AuthorizationAsync(string blogId, CancellationToken taskCancellationToken) { // This async task will either find cached credentials in the IDataStore provided, or it will pop open a // browser window and prompt the user for permissions and then write those permissions to the IDataStore. return GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(ClientSecretsStream).Secrets, new List<string>() { BloggerServiceScope, PicasaServiceScope }, blogId, taskCancellationToken, GetCredentialsDataStoreForBlog(blogId)); } private static Stream ClientSecretsStream { get { // The secrets file is automatically generated at build time by OpenLiveWriter.BlogClient.csproj. It // contains just a client ID and client secret, which are pulled from the user's environment variables. return ResourceHelper.LoadAssemblyResourceStream("Clients.GoogleBloggerv3Secrets.json"); } } private static IDataStore GetCredentialsDataStoreForBlog(string blogId) { // The Google APIs will automatically store the OAuth2 tokens in the given path. var folderPath = Path.Combine(ApplicationEnvironment.ApplicationDataDirectory, "GoogleBloggerv3"); return new FileDataStore(folderPath, true); } private static BlogPost ConvertToBlogPost(Page page) { return new BlogPost() { Title = page.Title, Id = page.Id, Permalink = page.Url, Contents = page.Content, DatePublished = page.Published.Value, //Keywords = string.Join(LabelDelimiter, page.Labels) }; } private static BlogPost ConvertToBlogPost(Post post) { return new BlogPost() { Title = post.Title, Id = post.Id, Permalink = post.Url, Contents = post.Content, DatePublished = post.Published.Value, Keywords = string.Join(new string(LabelDelimiter,1), post.Labels ?? new List<string>()) }; } private static Page ConvertToGoogleBloggerPage(BlogPost page) { return new Page() { Content = page.Contents, // TODO:OLW - DatePublishedOverride didn't work quite right. Either the date published override was off by several hours, // needs to be normalized to UTC or the Blogger website thinks I'm in the wrong time zone. Published = page.HasDatePublishedOverride ? page?.DatePublishedOverride : null, Title = page.Title, }; } private static Post ConvertToGoogleBloggerPost(BlogPost post) { return new Post() { Content = post.Contents, Labels = post.Keywords?.Split(new char[] { LabelDelimiter }, StringSplitOptions.RemoveEmptyEntries).Select(k => k.Trim()).ToList(), // TODO:OLW - DatePublishedOverride didn't work quite right. Either the date published override was off by several hours, // needs to be normalized to UTC or the Blogger website thinks I'm in the wrong time zone. Published = post.HasDatePublishedOverride ? post?.DatePublishedOverride : null, Title = post.Title, }; } private static PageInfo ConvertToPageInfo(Page page) { // Google Blogger doesn't support parent/child pages, so we pass string.Empty. return new PageInfo(page.Id, page.Title, page.Published.GetValueOrDefault(DateTime.Now), string.Empty); } private const int MaxRetries = 5; private const string ENTRY_CONTENT_TYPE = "application/atom+xml;type=entry"; private const string XHTML_NS = "http://www.w3.org/1999/xhtml"; private const string FEATURES_NS = "http://purl.org/atompub/features/1.0"; private const string MEDIA_NS = "http://search.yahoo.com/mrss/"; private const string LIVE_NS = "http://api.live.com/schemas"; private static readonly Namespace atomNS = new Namespace(AtomProtocolVersion.V10DraftBlogger.NamespaceUri, "atom"); private static readonly Namespace pubNS = new Namespace(AtomProtocolVersion.V10DraftBlogger.PubNamespaceUri, "app"); private IBlogClientOptions _clientOptions; private XmlNamespaceManager _nsMgr; public GoogleBloggerv3Client(Uri postApiUrl, IBlogCredentialsAccessor credentials) : base(credentials) { // configure client options BlogClientOptions clientOptions = new BlogClientOptions(); clientOptions.SupportsCategories = false; clientOptions.SupportsMultipleCategories = false; clientOptions.SupportsNewCategories = false; clientOptions.SupportsCustomDate = true; clientOptions.SupportsExcerpt = false; clientOptions.SupportsSlug = false; clientOptions.SupportsFileUpload = true; clientOptions.SupportsKeywords = true; clientOptions.SupportsGetKeywords = true; clientOptions.SupportsPages = true; clientOptions.SupportsExtendedEntries = true; _clientOptions = clientOptions; _nsMgr = new XmlNamespaceManager(new NameTable()); _nsMgr.AddNamespace(atomNS.Prefix, atomNS.Uri); _nsMgr.AddNamespace(pubNS.Prefix, pubNS.Uri); _nsMgr.AddNamespace(AtomClient.xhtmlNS.Prefix, AtomClient.xhtmlNS.Uri); _nsMgr.AddNamespace(AtomClient.featuresNS.Prefix, AtomClient.featuresNS.Uri); _nsMgr.AddNamespace(AtomClient.mediaNS.Prefix, AtomClient.mediaNS.Uri); _nsMgr.AddNamespace(AtomClient.liveNS.Prefix, AtomClient.liveNS.Uri); } public IBlogClientOptions Options { get { return _clientOptions; } } public bool IsSecure { get { return true; } } private BloggerService GetService() { TransientCredentials transientCredentials = Login(); return new BloggerService(new BaseClientService.Initializer() { HttpClientInitializer = (UserCredential)transientCredentials.Token, ApplicationName = string.Format(CultureInfo.InvariantCulture, "{0} {1}", ApplicationEnvironment.ProductName, ApplicationEnvironment.ProductVersion), }); } private bool IsValidToken(TokenResponse token) { // If the token is expired but we have a non-null RefreshToken, we can assume the token will be // automatically refreshed when we query Google Blogger and is therefore valid. return token != null && (!token.IsExpired(SystemClock.Default) || token.RefreshToken != null); } protected override TransientCredentials Login() { var transientCredentials = Credentials.TransientCredentials as TransientCredentials ?? new TransientCredentials(Credentials.Username, Credentials.Password, null); VerifyAndRefreshCredentials(transientCredentials); Credentials.TransientCredentials = transientCredentials; return transientCredentials; } protected override void VerifyCredentials(TransientCredentials tc) { VerifyAndRefreshCredentials(tc); } private void VerifyAndRefreshCredentials(TransientCredentials tc) { var userCredential = tc.Token as UserCredential; var token = userCredential?.Token; if (IsValidToken(token)) { // We already have a valid OAuth token. return; } if (userCredential == null) { // Attempt to load a cached OAuth token. var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecretsStream = ClientSecretsStream, DataStore = GetCredentialsDataStoreForBlog(tc.Username), Scopes = new List<string>() { BloggerServiceScope, PicasaServiceScope }, }); var loadTokenTask = flow.LoadTokenAsync(tc.Username, CancellationToken.None); loadTokenTask.Wait(); if (loadTokenTask.IsCompleted) { // We were able re-create the user credentials from the cache. userCredential = new UserCredential(flow, tc.Username, loadTokenTask.Result); token = loadTokenTask.Result; } } if (!IsValidToken(token)) { // The token is invalid, so we need to login again. This likely includes popping out a new browser window. if (BlogClientUIContext.SilentModeForCurrentThread) { // If we're in silent mode where prompting isn't allowed, throw the verification exception throw new BlogClientAuthenticationException(String.Empty, String.Empty); } // Start an OAuth flow to renew the credentials. var authorizationTask = GetOAuth2AuthorizationAsync(tc.Username, CancellationToken.None); authorizationTask.Wait(); if (authorizationTask.IsCompleted) { userCredential = authorizationTask.Result; token = userCredential?.Token; } } if (!IsValidToken(token)) { // The token is still invalid after all of our attempts to refresh it. The user did not complete the // authorization flow, so we interpret that as a cancellation. throw new BlogClientOperationCancelledException(); } // Stash the valid user credentials. tc.Token = userCredential; } private void RefreshAccessToken(TransientCredentials transientCredentials) { // Using the BloggerService automatically refreshes the access token, but we call the Picasa endpoint // directly and therefore need to force refresh the access token on occasion. var userCredential = transientCredentials.Token as UserCredential; userCredential?.RefreshTokenAsync(CancellationToken.None).Wait(); } private HttpRequestFilter CreateAuthorizationFilter() { var transientCredentials = Login(); var userCredential = (UserCredential)transientCredentials.Token; var accessToken = userCredential.Token.AccessToken; return (HttpWebRequest request) => { // OAuth uses a Bearer token in the HTTP Authorization header. request.Headers.Add( HttpRequestHeader.Authorization, string.Format(CultureInfo.InvariantCulture, "Bearer {0}", accessToken)); }; } public void OverrideOptions(IBlogClientOptions newClientOptions) { _clientOptions = newClientOptions; } public BlogInfo[] GetUsersBlogs() { var blogList = GetService().Blogs.ListByUser("self").Execute(); return blogList.Items.Select(b => new BlogInfo(b.Id, b.Name, b.Url)).ToArray(); } public BlogPostCategory[] GetCategories(string blogId) { // Google Blogger does not support categories return new BlogPostCategory[] { }; } public BlogPostKeyword[] GetKeywords(string blogId) { // Google Blogger does not support get labels return new BlogPostKeyword[] { }; } public BlogPost[] GetRecentPosts(string blogId, int maxPosts, bool includeCategories, DateTime? now) { var recentPostsRequest = GetService().Posts.List(blogId); if (now.HasValue) { recentPostsRequest.EndDate = now.Value; } recentPostsRequest.FetchImages = false; recentPostsRequest.MaxResults = maxPosts; recentPostsRequest.OrderBy = PostsResource.ListRequest.OrderByEnum.Published; recentPostsRequest.Status = PostsResource.ListRequest.StatusEnum.Live; var recentPosts = recentPostsRequest.Execute(); return recentPosts.Items.Select(p => ConvertToBlogPost(p)).ToArray(); } public string NewPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, out string etag, out XmlDocument remotePost) { // The remote post is only meant to be used for blogs that use the Atom protocol. remotePost = null; if (!publish && !Options.SupportsPostAsDraft) { Trace.Fail("Post to draft not supported on this provider"); throw new BlogClientPostAsDraftUnsupportedException(); } var bloggerPost = ConvertToGoogleBloggerPost(post); var newPostRequest = GetService().Posts.Insert(bloggerPost, blogId); newPostRequest.IsDraft = !publish; var newPost = newPostRequest.Execute(); etag = newPost.ETag; return newPost.Id; } public bool EditPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, out string etag, out XmlDocument remotePost) { // The remote post is only meant to be used for blogs that use the Atom protocol. remotePost = null; if (!publish && !Options.SupportsPostAsDraft) { Trace.Fail("Post to draft not supported on this provider"); throw new BlogClientPostAsDraftUnsupportedException(); } var bloggerPost = ConvertToGoogleBloggerPost(post); var updatePostRequest = GetService().Posts.Update(bloggerPost, blogId, post.Id); updatePostRequest.Publish = publish; var updatedPost = updatePostRequest.Execute(); etag = updatedPost.ETag; return true; } public BlogPost GetPost(string blogId, string postId) { var getPostRequest = GetService().Posts.Get(blogId, postId); return ConvertToBlogPost(getPostRequest.Execute()); } public void DeletePost(string blogId, string postId, bool publish) { var deletePostRequest = GetService().Posts.Delete(blogId, postId); deletePostRequest.Execute(); } public BlogPost GetPage(string blogId, string pageId) { var getPageRequest = GetService().Pages.Get(blogId, pageId); return ConvertToBlogPost(getPageRequest.Execute()); } public PageInfo[] GetPageList(string blogId) { var getPagesRequest = GetService().Pages.List(blogId); var pageList = getPagesRequest.Execute(); return pageList.Items.Select(p => ConvertToPageInfo(p)).ToArray(); } public BlogPost[] GetPages(string blogId, int maxPages) { var getPagesRequest = GetService().Pages.List(blogId); getPagesRequest.MaxResults = maxPages; var pageList = getPagesRequest.Execute(); return pageList.Items.Select(p => ConvertToBlogPost(p)).ToArray(); } public string NewPage(string blogId, BlogPost page, bool publish, out string etag, out XmlDocument remotePost) { // The remote post is only meant to be used for blogs that use the Atom protocol. remotePost = null; if (!publish && !Options.SupportsPostAsDraft) { Trace.Fail("Post to draft not supported on this provider"); throw new BlogClientPostAsDraftUnsupportedException(); } var bloggerPage = ConvertToGoogleBloggerPage(page); var newPageRequest = GetService().Pages.Insert(bloggerPage, blogId); newPageRequest.IsDraft = !publish; var newPage = newPageRequest.Execute(); etag = newPage.ETag; return newPage.Id; } public bool EditPage(string blogId, BlogPost page, bool publish, out string etag, out XmlDocument remotePost) { // The remote post is only meant to be used for blogs that use the Atom protocol. remotePost = null; if (!publish && !Options.SupportsPostAsDraft) { Trace.Fail("Post to draft not supported on this provider"); throw new BlogClientPostAsDraftUnsupportedException(); } var bloggerPage = ConvertToGoogleBloggerPage(page); var updatePostRequest = GetService().Pages.Update(bloggerPage, blogId, page.Id); updatePostRequest.Publish = publish; var updatedPage = updatePostRequest.Execute(); etag = updatedPage.ETag; return true; } public void DeletePage(string blogId, string pageId) { var deletePostRequest = GetService().Pages.Delete(blogId, pageId); deletePostRequest.Execute(); } public AuthorInfo[] GetAuthors(string blogId) { throw new NotImplementedException(); } public bool? DoesFileNeedUpload(IFileUploadContext uploadContext) { return null; } public string DoBeforePublishUploadWork(IFileUploadContext uploadContext) { string albumName = ApplicationEnvironment.ProductName; string path = uploadContext.GetContentsLocalFilePath(); if (Options.FileUploadNameFormat != null && Options.FileUploadNameFormat.Length > 0) { string formattedFileName = uploadContext.FormatFileName(uploadContext.PreferredFileName); string[] chunks = StringHelper.Reverse(formattedFileName).Split(new char[] { '/' }, 2); if (chunks.Length == 2) albumName = StringHelper.Reverse(chunks[1]); } string EDIT_MEDIA_LINK = "EditMediaLink"; string srcUrl; string editUri = uploadContext.Settings.GetString(EDIT_MEDIA_LINK, null); if (editUri == null || editUri.Length == 0) { PostNewImage(albumName, path, out srcUrl, out editUri); } else { try { UpdateImage(editUri, path, out srcUrl, out editUri); } catch (Exception e) { Trace.Fail(e.ToString()); if (e is WebException) HttpRequestHelper.LogException((WebException)e); bool success = false; srcUrl = null; // compiler complains without this line try { // couldn't update existing image? try posting a new one PostNewImage(albumName, path, out srcUrl, out editUri); success = true; } catch { } if (!success) throw; // rethrow the exception from the update, not the post } } uploadContext.Settings.SetString(EDIT_MEDIA_LINK, editUri); PicasaRefererBlockingWorkaround(uploadContext.BlogId, uploadContext.Role, ref srcUrl); return srcUrl; } /// <summary> /// "It looks like the problem with the inline image is due to referrer checking. /// The thumbnail image being used is protected for display only on certain domains. /// These domains include *.blogspot.com and *.google.com. This user is using a /// feature in Blogger which allows him to display his blog directly on his own /// domain, which will not pass the referrer checking. /// /// "The maximum size of a thumbnail image that can be displayed on non-*.blogspot.com /// domains is 800px. (blogs don't actually appear at *.google.com). However, if you /// request a 800px thumbnail, and the image is less than 800px for the maximum /// dimension, then the original image will be returned without the referrer /// restrictions. That sounds like it will work for you, so feel free to give it a /// shot and let me know if you have any further questions or problems." /// -- Anonymous Google Employee /// </summary> private void PicasaRefererBlockingWorkaround(string blogId, FileUploadRole role, ref string srcUrl) { if (role == FileUploadRole.LinkedImage && Options.UsePicasaS1600h) { try { int lastSlash = srcUrl.LastIndexOf('/'); string srcUrl2 = srcUrl.Substring(0, lastSlash) + "/s1600-h" + srcUrl.Substring(lastSlash); HttpWebRequest req = HttpRequestHelper.CreateHttpWebRequest(srcUrl2, true); req.Method = "HEAD"; req.GetResponse().Close(); srcUrl = srcUrl2; return; } catch (WebException we) { Debug.Fail("Picasa s1600-h hack failed: " + we.ToString()); } } try { srcUrl += ((srcUrl.IndexOf('?') >= 0) ? "&" : "?") + "imgmax=800"; } catch (Exception ex) { Trace.Fail("Unexpected error while doing Picasa upload: " + ex.ToString()); } } public void DoAfterPublishUploadWork(IFileUploadContext uploadContext) { // Nothing to do. } public string AddCategory(string blogId, BlogPostCategory category) { throw new BlogClientMethodUnsupportedException("AddCategory"); } public BlogPostCategory[] SuggestCategories(string blogId, string partialCategoryName) { throw new BlogClientMethodUnsupportedException("SuggestCategories"); } public HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter) { return BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, CreateAuthorizationFilter()); } public BlogInfo[] GetImageEndpoints() { throw new NotImplementedException(); } #region Picasa image uploading - stolen from BloggerAtomClient public string GetBlogImagesAlbum(string albumName) { const string FEED_REL = "http://schemas.google.com/g/2005#feed"; const string GPHOTO_NS_URI = "http://schemas.google.com/photos/2007"; Uri picasaUri = new Uri("https://picasaweb.google.com/data/feed/api/user/default"); try { Uri reqUri = picasaUri; XmlDocument albumListDoc = AtomClient.xmlRestRequestHelper.Get(ref reqUri, CreateAuthorizationFilter(), "kind", "album"); foreach (XmlElement entryEl in albumListDoc.SelectNodes(@"/atom:feed/atom:entry", _nsMgr)) { XmlElement titleNode = entryEl.SelectSingleNode(@"atom:title", _nsMgr) as XmlElement; if (titleNode != null) { string titleText = AtomProtocolVersion.V10DraftBlogger.TextNodeToPlaintext(titleNode); if (titleText == albumName) { XmlNamespaceManager nsMgr2 = new XmlNamespaceManager(new NameTable()); nsMgr2.AddNamespace("gphoto", "http://schemas.google.com/photos/2007"); XmlNode numPhotosRemainingNode = entryEl.SelectSingleNode("gphoto:numphotosremaining/text()", nsMgr2); if (numPhotosRemainingNode != null) { int numPhotosRemaining; if (int.TryParse(numPhotosRemainingNode.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out numPhotosRemaining)) { if (numPhotosRemaining < 1) continue; } } string selfHref = AtomEntry.GetLink(entryEl, _nsMgr, FEED_REL, "application/atom+xml", null, reqUri); if (selfHref.Length > 1) return selfHref; } } } } catch (WebException we) { HttpWebResponse httpWebResponse = we.Response as HttpWebResponse; if (httpWebResponse != null) { HttpRequestHelper.DumpResponse(httpWebResponse); if (httpWebResponse.StatusCode == HttpStatusCode.NotFound) { throw new BlogClientOperationCancelledException(); } } throw; } XmlDocument newDoc = new XmlDocument(); XmlElement newEntryEl = newDoc.CreateElement("atom", "entry", AtomProtocolVersion.V10DraftBlogger.NamespaceUri); newDoc.AppendChild(newEntryEl); XmlElement newTitleEl = newDoc.CreateElement("atom", "title", AtomProtocolVersion.V10DraftBlogger.NamespaceUri); newTitleEl.SetAttribute("type", "text"); newTitleEl.InnerText = albumName; newEntryEl.AppendChild(newTitleEl); XmlElement newSummaryEl = newDoc.CreateElement("atom", "summary", AtomProtocolVersion.V10DraftBlogger.NamespaceUri); newSummaryEl.SetAttribute("type", "text"); newSummaryEl.InnerText = Res.Get(StringId.BloggerImageAlbumDescription); newEntryEl.AppendChild(newSummaryEl); XmlElement newAccessEl = newDoc.CreateElement("gphoto", "access", GPHOTO_NS_URI); newAccessEl.InnerText = "private"; newEntryEl.AppendChild(newAccessEl); XmlElement newCategoryEl = newDoc.CreateElement("atom", "category", AtomProtocolVersion.V10DraftBlogger.NamespaceUri); newCategoryEl.SetAttribute("scheme", "http://schemas.google.com/g/2005#kind"); newCategoryEl.SetAttribute("term", "http://schemas.google.com/photos/2007#album"); newEntryEl.AppendChild(newCategoryEl); Uri postUri = picasaUri; XmlDocument newAlbumResult = AtomClient.xmlRestRequestHelper.Post(ref postUri, CreateAuthorizationFilter(), "application/atom+xml", newDoc, null); XmlElement newAlbumResultEntryEl = newAlbumResult.SelectSingleNode("/atom:entry", _nsMgr) as XmlElement; Debug.Assert(newAlbumResultEntryEl != null); return AtomEntry.GetLink(newAlbumResultEntryEl, _nsMgr, FEED_REL, "application/atom+xml", null, postUri); } private void ShowPicasaSignupPrompt(object sender, EventArgs e) { if (DisplayMessage.Show(MessageId.PicasawebSignup) == DialogResult.Yes) { ShellHelper.LaunchUrl("http://picasaweb.google.com"); } } private void PostNewImage(string albumName, string filename, out string srcUrl, out string editUri) { for (int retry = 0; retry < MaxRetries; retry++) { var transientCredentials = Login(); try { string albumUrl = GetBlogImagesAlbum(albumName); HttpWebResponse response = RedirectHelper.GetResponse(albumUrl, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, filename, "POST").Create)); using (Stream s = response.GetResponseStream()) { ParseMediaEntry(s, out srcUrl, out editUri); return; } } catch (WebException we) { if (retry < MaxRetries - 1 && we.Response as HttpWebResponse != null && ((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Forbidden) { // HTTP 403 Forbidden means our OAuth access token is not valid. RefreshAccessToken(transientCredentials); } else { throw; } } } Trace.Fail("Should never get here"); throw new ApplicationException("Should never get here"); } private void UpdateImage(string editUri, string filename, out string srcUrl, out string newEditUri) { for (int retry = 0; retry < MaxRetries; retry++) { var transientCredentials = Login(); HttpWebResponse response; bool conflict = false; try { response = RedirectHelper.GetResponse(editUri, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, filename, "PUT").Create)); } catch (WebException we) { if (retry < MaxRetries - 1 && we.Response as HttpWebResponse != null) { if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Conflict) { response = (HttpWebResponse)we.Response; conflict = true; } else if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Forbidden) { // HTTP 403 Forbidden means our OAuth access token is not valid. RefreshAccessToken(transientCredentials); continue; } } throw; } using (Stream s = response.GetResponseStream()) { ParseMediaEntry(s, out srcUrl, out newEditUri); } if (!conflict) { return; // success! } editUri = newEditUri; } Trace.Fail("Should never get here"); throw new ApplicationException("Should never get here"); } private void ParseMediaEntry(Stream s, out string srcUrl, out string editUri) { srcUrl = null; // First try <content src> XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(s); XmlElement contentEl = xmlDoc.SelectSingleNode("/atom:entry/atom:content", _nsMgr) as XmlElement; if (contentEl != null) srcUrl = XmlHelper.GetUrl(contentEl, "@src", _nsMgr, null); // Then try media RSS if (srcUrl == null || srcUrl.Length == 0) { contentEl = xmlDoc.SelectSingleNode("/atom:entry/media:group/media:content[@medium='image']", _nsMgr) as XmlElement; if (contentEl == null) throw new ArgumentException("Picasa photo entry was missing content element"); srcUrl = XmlHelper.GetUrl(contentEl, "@url", _nsMgr, null); } editUri = AtomEntry.GetLink(xmlDoc.SelectSingleNode("/atom:entry", _nsMgr) as XmlElement, _nsMgr, "edit-media", null, null, null); } private class UploadFileRequestFactory { private readonly GoogleBloggerv3Client _parent; private readonly string _filename; private readonly string _method; public UploadFileRequestFactory(GoogleBloggerv3Client parent, string filename, string method) { _parent = parent; _filename = filename; _method = method; } public HttpWebRequest Create(string uri) { // TODO: choose rational timeout values HttpWebRequest request = HttpRequestHelper.CreateHttpWebRequest(uri, false); _parent.CreateAuthorizationFilter().Invoke(request); request.ContentType = MimeHelper.GetContentType(Path.GetExtension(_filename)); try { request.Headers.Add("Slug", Path.GetFileNameWithoutExtension(_filename)); } catch (ArgumentException) { request.Headers.Add("Slug", "Image"); } request.Method = _method; using (Stream s = request.GetRequestStream()) { using (Stream inS = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { StreamHelper.Transfer(inS, s); } } return request; } } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: reporting/rpc/management_reporting_svc.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Reporting.RPC { /// <summary>Holder for reflection information generated from reporting/rpc/management_reporting_svc.proto</summary> public static partial class ManagementReportingSvcReflection { #region Descriptor /// <summary>File descriptor for reporting/rpc/management_reporting_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ManagementReportingSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CixyZXBvcnRpbmcvcnBjL21hbmFnZW1lbnRfcmVwb3J0aW5nX3N2Yy5wcm90", "bxIZaG9sbXMudHlwZXMucmVwb3J0aW5nLnJwYxo4cmVwb3J0aW5nL2lucHV0", "X3BhcmFtcy9tYW5hZ2VtZW50X3JlcG9ydF9tYW5pZmVzdHMucHJvdG8aLHJl", "cG9ydGluZy9vdXRwdXRzL2h0bWxfcmVwb3J0X3Jlc3BvbnNlLnByb3RvGjJ0", "ZW5hbmN5X2NvbmZpZy9pbmRpY2F0b3JzL3Byb3BlcnR5X2luZGljYXRvci5w", "cm90byKUBAonTWFuYWdtZW50UmVwb3J0aW5nU3ZjQmF0Y2hSZXBvcnRSZXF1", "ZXN0EkwKCnByb3BlcnRpZXMYASADKAsyOC5ob2xtcy50eXBlcy50ZW5hbmN5", "X2NvbmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5kaWNhdG9yEmYKFWN1cnJl", "bnRfdGltZV9tYW5pZmVzdBgCIAEoCzJHLmhvbG1zLnR5cGVzLnJlcG9ydGlu", "Zy5pbnB1dF9wYXJhbXMuTWFuYWdlbWVudEN1cnJlbnRUaW1lUmVwb3J0TWFu", "aWZlc3QSbQoZY2xvY2tfdGltZV9yYW5nZV9tYW5pZmVzdBgDIAEoCzJKLmhv", "bG1zLnR5cGVzLnJlcG9ydGluZy5pbnB1dF9wYXJhbXMuTWFuYWdlbWVudENs", "b2NrVGltZVJhbmdlUmVwb3J0TWFuaWZlc3QSaAoWb3BzZGF0ZV9yYW5nZV9t", "YW5pZmVzdBgEIAEoCzJILmhvbG1zLnR5cGVzLnJlcG9ydGluZy5pbnB1dF9w", "YXJhbXMuTWFuYWdlbWVudE9wc2RhdGVSYW5nZVJlcG9ydE1hbmlmZXN0EloK", "FHNpbmdsZV9kYXRlX21hbmlmZXN0GAUgASgLMjwuaG9sbXMudHlwZXMucmVw", "b3J0aW5nLmlucHV0X3BhcmFtcy5TaW5nbGVEYXRlUmVwb3J0TWFuaWZlc3Qi", "sQEKOE1hbmFnZW1lbnRSZXBvcnRpbmdTdmNIb3VzZWtlZXBlck1hbmFnZW1l", "bnRSZXBvcnRSZXF1ZXN0EhwKFG9ubHlfYXR0ZW50aW9uX3Jvb21zGAEgASgI", "ElcKDm5vdGVfc2VsZWN0aW9uGAIgASgOMj8uaG9sbXMudHlwZXMucmVwb3J0", "aW5nLnJwYy5NYW5hZ2VtZW50UmVwb3J0aW5nU3ZjTm90ZXNTZWxlY3Rpb24q", "ewokTWFuYWdlbWVudFJlcG9ydGluZ1N2Y05vdGVzU2VsZWN0aW9uEg0KCWFs", "bF9ub3RlcxAAEhsKF29ubHlfaG91c2VrZWVwaW5nX25vdGVzEAESGQoVb25s", "eV9mcm9udF9kZXNrX25vdGVzEAISDAoIbm9fbm90ZXMQAzLeAgoWTWFuYWdl", "bWVudFJlcG9ydGluZ1N2YxKRAQoYR2V0TWFuYWdlbWVudFJlcG9ydEJhdGNo", "EkIuaG9sbXMudHlwZXMucmVwb3J0aW5nLnJwYy5NYW5hZ21lbnRSZXBvcnRp", "bmdTdmNCYXRjaFJlcG9ydFJlcXVlc3QaMS5ob2xtcy50eXBlcy5yZXBvcnRp", "bmcub3V0cHV0cy5IdG1sUmVwb3J0UmVzcG9uc2USrwEKJUdldEN1cnJlbnRI", "b3VzZWtlZXBlck1hbmFnZW1lbnRSZXBvcnQSUy5ob2xtcy50eXBlcy5yZXBv", "cnRpbmcucnBjLk1hbmFnZW1lbnRSZXBvcnRpbmdTdmNIb3VzZWtlZXBlck1h", "bmFnZW1lbnRSZXBvcnRSZXF1ZXN0GjEuaG9sbXMudHlwZXMucmVwb3J0aW5n", "Lm91dHB1dHMuSHRtbFJlcG9ydFJlc3BvbnNlQhyqAhlIT0xNUy5UeXBlcy5S", "ZXBvcnRpbmcuUlBDYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Reporting.ReportParams.ManagementReportManifestsReflection.Descriptor, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponseReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcNotesSelection), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Reporting.RPC.ManagmentReportingSvcBatchReportRequest), global::HOLMS.Types.Reporting.RPC.ManagmentReportingSvcBatchReportRequest.Parser, new[]{ "Properties", "CurrentTimeManifest", "ClockTimeRangeManifest", "OpsdateRangeManifest", "SingleDateManifest" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcHousekeeperManagementReportRequest), global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcHousekeeperManagementReportRequest.Parser, new[]{ "OnlyAttentionRooms", "NoteSelection" }, null, null, null) })); } #endregion } #region Enums public enum ManagementReportingSvcNotesSelection { [pbr::OriginalName("all_notes")] AllNotes = 0, [pbr::OriginalName("only_housekeeping_notes")] OnlyHousekeepingNotes = 1, [pbr::OriginalName("only_front_desk_notes")] OnlyFrontDeskNotes = 2, [pbr::OriginalName("no_notes")] NoNotes = 3, } #endregion #region Messages public sealed partial class ManagmentReportingSvcBatchReportRequest : pb::IMessage<ManagmentReportingSvcBatchReportRequest> { private static readonly pb::MessageParser<ManagmentReportingSvcBatchReportRequest> _parser = new pb::MessageParser<ManagmentReportingSvcBatchReportRequest>(() => new ManagmentReportingSvcBatchReportRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ManagmentReportingSvcBatchReportRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ManagmentReportingSvcBatchReportRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ManagmentReportingSvcBatchReportRequest(ManagmentReportingSvcBatchReportRequest other) : this() { properties_ = other.properties_.Clone(); CurrentTimeManifest = other.currentTimeManifest_ != null ? other.CurrentTimeManifest.Clone() : null; ClockTimeRangeManifest = other.clockTimeRangeManifest_ != null ? other.ClockTimeRangeManifest.Clone() : null; OpsdateRangeManifest = other.opsdateRangeManifest_ != null ? other.OpsdateRangeManifest.Clone() : null; SingleDateManifest = other.singleDateManifest_ != null ? other.SingleDateManifest.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ManagmentReportingSvcBatchReportRequest Clone() { return new ManagmentReportingSvcBatchReportRequest(this); } /// <summary>Field number for the "properties" field.</summary> public const int PropertiesFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> _repeated_properties_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> properties_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> Properties { get { return properties_; } } /// <summary>Field number for the "current_time_manifest" field.</summary> public const int CurrentTimeManifestFieldNumber = 2; private global::HOLMS.Types.Reporting.ReportParams.ManagementCurrentTimeReportManifest currentTimeManifest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.ReportParams.ManagementCurrentTimeReportManifest CurrentTimeManifest { get { return currentTimeManifest_; } set { currentTimeManifest_ = value; } } /// <summary>Field number for the "clock_time_range_manifest" field.</summary> public const int ClockTimeRangeManifestFieldNumber = 3; private global::HOLMS.Types.Reporting.ReportParams.ManagementClockTimeRangeReportManifest clockTimeRangeManifest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.ReportParams.ManagementClockTimeRangeReportManifest ClockTimeRangeManifest { get { return clockTimeRangeManifest_; } set { clockTimeRangeManifest_ = value; } } /// <summary>Field number for the "opsdate_range_manifest" field.</summary> public const int OpsdateRangeManifestFieldNumber = 4; private global::HOLMS.Types.Reporting.ReportParams.ManagementOpsdateRangeReportManifest opsdateRangeManifest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.ReportParams.ManagementOpsdateRangeReportManifest OpsdateRangeManifest { get { return opsdateRangeManifest_; } set { opsdateRangeManifest_ = value; } } /// <summary>Field number for the "single_date_manifest" field.</summary> public const int SingleDateManifestFieldNumber = 5; private global::HOLMS.Types.Reporting.ReportParams.SingleDateReportManifest singleDateManifest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.ReportParams.SingleDateReportManifest SingleDateManifest { get { return singleDateManifest_; } set { singleDateManifest_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ManagmentReportingSvcBatchReportRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ManagmentReportingSvcBatchReportRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!properties_.Equals(other.properties_)) return false; if (!object.Equals(CurrentTimeManifest, other.CurrentTimeManifest)) return false; if (!object.Equals(ClockTimeRangeManifest, other.ClockTimeRangeManifest)) return false; if (!object.Equals(OpsdateRangeManifest, other.OpsdateRangeManifest)) return false; if (!object.Equals(SingleDateManifest, other.SingleDateManifest)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= properties_.GetHashCode(); if (currentTimeManifest_ != null) hash ^= CurrentTimeManifest.GetHashCode(); if (clockTimeRangeManifest_ != null) hash ^= ClockTimeRangeManifest.GetHashCode(); if (opsdateRangeManifest_ != null) hash ^= OpsdateRangeManifest.GetHashCode(); if (singleDateManifest_ != null) hash ^= SingleDateManifest.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { properties_.WriteTo(output, _repeated_properties_codec); if (currentTimeManifest_ != null) { output.WriteRawTag(18); output.WriteMessage(CurrentTimeManifest); } if (clockTimeRangeManifest_ != null) { output.WriteRawTag(26); output.WriteMessage(ClockTimeRangeManifest); } if (opsdateRangeManifest_ != null) { output.WriteRawTag(34); output.WriteMessage(OpsdateRangeManifest); } if (singleDateManifest_ != null) { output.WriteRawTag(42); output.WriteMessage(SingleDateManifest); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += properties_.CalculateSize(_repeated_properties_codec); if (currentTimeManifest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CurrentTimeManifest); } if (clockTimeRangeManifest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ClockTimeRangeManifest); } if (opsdateRangeManifest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OpsdateRangeManifest); } if (singleDateManifest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SingleDateManifest); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ManagmentReportingSvcBatchReportRequest other) { if (other == null) { return; } properties_.Add(other.properties_); if (other.currentTimeManifest_ != null) { if (currentTimeManifest_ == null) { currentTimeManifest_ = new global::HOLMS.Types.Reporting.ReportParams.ManagementCurrentTimeReportManifest(); } CurrentTimeManifest.MergeFrom(other.CurrentTimeManifest); } if (other.clockTimeRangeManifest_ != null) { if (clockTimeRangeManifest_ == null) { clockTimeRangeManifest_ = new global::HOLMS.Types.Reporting.ReportParams.ManagementClockTimeRangeReportManifest(); } ClockTimeRangeManifest.MergeFrom(other.ClockTimeRangeManifest); } if (other.opsdateRangeManifest_ != null) { if (opsdateRangeManifest_ == null) { opsdateRangeManifest_ = new global::HOLMS.Types.Reporting.ReportParams.ManagementOpsdateRangeReportManifest(); } OpsdateRangeManifest.MergeFrom(other.OpsdateRangeManifest); } if (other.singleDateManifest_ != null) { if (singleDateManifest_ == null) { singleDateManifest_ = new global::HOLMS.Types.Reporting.ReportParams.SingleDateReportManifest(); } SingleDateManifest.MergeFrom(other.SingleDateManifest); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { properties_.AddEntriesFrom(input, _repeated_properties_codec); break; } case 18: { if (currentTimeManifest_ == null) { currentTimeManifest_ = new global::HOLMS.Types.Reporting.ReportParams.ManagementCurrentTimeReportManifest(); } input.ReadMessage(currentTimeManifest_); break; } case 26: { if (clockTimeRangeManifest_ == null) { clockTimeRangeManifest_ = new global::HOLMS.Types.Reporting.ReportParams.ManagementClockTimeRangeReportManifest(); } input.ReadMessage(clockTimeRangeManifest_); break; } case 34: { if (opsdateRangeManifest_ == null) { opsdateRangeManifest_ = new global::HOLMS.Types.Reporting.ReportParams.ManagementOpsdateRangeReportManifest(); } input.ReadMessage(opsdateRangeManifest_); break; } case 42: { if (singleDateManifest_ == null) { singleDateManifest_ = new global::HOLMS.Types.Reporting.ReportParams.SingleDateReportManifest(); } input.ReadMessage(singleDateManifest_); break; } } } } } public sealed partial class ManagementReportingSvcHousekeeperManagementReportRequest : pb::IMessage<ManagementReportingSvcHousekeeperManagementReportRequest> { private static readonly pb::MessageParser<ManagementReportingSvcHousekeeperManagementReportRequest> _parser = new pb::MessageParser<ManagementReportingSvcHousekeeperManagementReportRequest>(() => new ManagementReportingSvcHousekeeperManagementReportRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ManagementReportingSvcHousekeeperManagementReportRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ManagementReportingSvcHousekeeperManagementReportRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ManagementReportingSvcHousekeeperManagementReportRequest(ManagementReportingSvcHousekeeperManagementReportRequest other) : this() { onlyAttentionRooms_ = other.onlyAttentionRooms_; noteSelection_ = other.noteSelection_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ManagementReportingSvcHousekeeperManagementReportRequest Clone() { return new ManagementReportingSvcHousekeeperManagementReportRequest(this); } /// <summary>Field number for the "only_attention_rooms" field.</summary> public const int OnlyAttentionRoomsFieldNumber = 1; private bool onlyAttentionRooms_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool OnlyAttentionRooms { get { return onlyAttentionRooms_; } set { onlyAttentionRooms_ = value; } } /// <summary>Field number for the "note_selection" field.</summary> public const int NoteSelectionFieldNumber = 2; private global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcNotesSelection noteSelection_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcNotesSelection NoteSelection { get { return noteSelection_; } set { noteSelection_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ManagementReportingSvcHousekeeperManagementReportRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ManagementReportingSvcHousekeeperManagementReportRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OnlyAttentionRooms != other.OnlyAttentionRooms) return false; if (NoteSelection != other.NoteSelection) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (OnlyAttentionRooms != false) hash ^= OnlyAttentionRooms.GetHashCode(); if (NoteSelection != 0) hash ^= NoteSelection.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (OnlyAttentionRooms != false) { output.WriteRawTag(8); output.WriteBool(OnlyAttentionRooms); } if (NoteSelection != 0) { output.WriteRawTag(16); output.WriteEnum((int) NoteSelection); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (OnlyAttentionRooms != false) { size += 1 + 1; } if (NoteSelection != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NoteSelection); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ManagementReportingSvcHousekeeperManagementReportRequest other) { if (other == null) { return; } if (other.OnlyAttentionRooms != false) { OnlyAttentionRooms = other.OnlyAttentionRooms; } if (other.NoteSelection != 0) { NoteSelection = other.NoteSelection; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { OnlyAttentionRooms = input.ReadBool(); break; } case 16: { noteSelection_ = (global::HOLMS.Types.Reporting.RPC.ManagementReportingSvcNotesSelection) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; public class UInt32IConvertibleToType { public static int Main() { UInt32IConvertibleToType ui32icttype = new UInt32IConvertibleToType(); TestLibrary.TestFramework.BeginTestCase("UInt32IConvertibleToType"); if (ui32icttype.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:UInt32 MinValue to Type of string"); try { UInt32 uintA = UInt32.MinValue; IConvertible iConvert = (IConvertible)(uintA); string strA = (string)iConvert.ToType(typeof(string), null); if (strA != uintA.ToString()) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:UInt32 MinValue to Type of bool"); try { UInt32 uintA = UInt32.MinValue; IConvertible iConvert = (IConvertible)(uintA); bool boolA = (bool)iConvert.ToType(typeof(bool), null); if (boolA) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:UInt32 MaxValue to Type of bool"); try { UInt32 uintA = UInt32.MaxValue; IConvertible iConvert = (IConvertible)(uintA); bool boolA = (bool)iConvert.ToType(typeof(bool), null); if (!boolA) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:UInt32 MaxValue to Type of Int64,double and decimal"); try { UInt32 uintA = UInt32.MaxValue; IConvertible iConvert = (IConvertible)(uintA); Int64 int64A = (Int64)iConvert.ToType(typeof(Int64), null); Double doubleA = (Double)iConvert.ToType(typeof(Double), null); Decimal decimalA = (Decimal)iConvert.ToType(typeof(Decimal), null); Single singleA = (Single)iConvert.ToType(typeof(Single), null); if (int64A != uintA || doubleA!= uintA || decimalA != uintA || singleA != uintA) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5:UInt32 between MinValue to Int32.Max to Type of Int32"); try { UInt32 uintA = (UInt32)this.GetInt32(0, Int32.MaxValue); IConvertible iConvert = (IConvertible)(uintA); Int32 int32A = (Int32)iConvert.ToType(typeof(Int32), null); if (int32A != uintA) { TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6:UInt32 between MinValue to Int16.Max to Type of Int16"); try { UInt32 uintA = (UInt32)this.GetInt32(0, Int16.MaxValue + 1); IConvertible iConvert = (IConvertible)(uintA); Int16 int16A = (Int16)iConvert.ToType(typeof(Int16), null); if (int16A != uintA) { TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7:UInt32 between MinValue and SByte.Max to Type of SByte"); try { UInt32 uintA = (UInt32)this.GetInt32(0, SByte.MaxValue + 1); IConvertible iConvert = (IConvertible)(uintA); SByte sbyteA = (SByte)iConvert.ToType(typeof(SByte), null); if (sbyteA != uintA) { TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8:UInt32 between MinValue and Byte.Max to Type of Byte"); try { UInt32 uintA = (UInt32)this.GetInt32(0, Byte.MaxValue + 1); IConvertible iConvert = (IConvertible)(uintA); Byte byteA = (Byte)iConvert.ToType(typeof(Byte), null); if (byteA != uintA) { TestLibrary.TestFramework.LogError("015", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:UInt32 between Int32.MaxValue and UInt32.MaxValue to Type of Int32"); try { UInt32 uintA = (UInt32)(this.GetInt32(0, Int32.MaxValue) + Int32.MaxValue); IConvertible iConvert = (IConvertible)(uintA); Int32 int32A = (Int32)iConvert.ToType(typeof(Int32), null); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2:UInt32 between Int16.Max and UInt32.MaxValue Type of Int16"); try { UInt32 uintA = (UInt32)(Int16.MaxValue + this.GetInt32(1, Int32.MaxValue)); IConvertible iConvert = (IConvertible)(uintA); Int16 int16A = (Int16)iConvert.ToType(typeof(Int16), null); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3:UInt32 between SByte.Max and UInt32.MaxValue to Type of SByte"); try { UInt32 uintA = (UInt32)(SByte.MaxValue + this.GetInt32(1, Int32.MaxValue)); IConvertible iConvert = (IConvertible)(uintA); SByte sbyteA = (SByte)iConvert.ToType(typeof(SByte), null); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N003", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4:UInt32 between Byte.Max and UInt32.MaxValue to Type of Byte"); try { UInt32 uintA = (UInt32)(Byte.MaxValue + this.GetInt32(1,Int32.MaxValue)); IConvertible iConvert = (IConvertible)(uintA); Byte byteA = (Byte)iConvert.ToType(typeof(Byte), null); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region ForTestObject private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using System; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Client; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { public interface ICredentialProvider { Boolean RequireInteractive { get; } CredentialData CredentialData { get; set; } VssCredentials GetVssCredentials(IHostContext context); void EnsureCredential(IHostContext context, CommandSettings command, string serverUrl); } public abstract class CredentialProvider : ICredentialProvider { public CredentialProvider(string scheme) { CredentialData = new CredentialData(); CredentialData.Scheme = scheme; } public virtual Boolean RequireInteractive => false; public CredentialData CredentialData { get; set; } public abstract VssCredentials GetVssCredentials(IHostContext context); public abstract void EnsureCredential(IHostContext context, CommandSettings command, string serverUrl); } public sealed class AadDeviceCodeAccessToken : CredentialProvider { private string _azureDevOpsClientId = "97877f11-0fc6-4aee-b1ff-febb0519dd00"; public override Boolean RequireInteractive => true; public AadDeviceCodeAccessToken() : base(Constants.Configuration.AAD) { } public override VssCredentials GetVssCredentials(IHostContext context) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(AadDeviceCodeAccessToken)); trace.Info(nameof(GetVssCredentials)); ArgUtil.NotNull(CredentialData, nameof(CredentialData)); CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out string serverUrl); ArgUtil.NotNullOrEmpty(serverUrl, nameof(serverUrl)); var tenantAuthorityUrl = GetTenantAuthorityUrl(context, serverUrl); if (tenantAuthorityUrl == null) { throw new NotSupportedException($"This Azure DevOps organization '{serverUrl}' is not backed by Azure Active Directory."); } LoggerCallbackHandler.LogCallback = ((LogLevel level, string message, bool containsPii) => { switch (level) { case LogLevel.Information: trace.Info(message); break; case LogLevel.Error: trace.Error(message); break; case LogLevel.Warning: trace.Warning(message); break; default: trace.Verbose(message); break; } }); LoggerCallbackHandler.UseDefaultLogging = false; AuthenticationContext ctx = new AuthenticationContext(tenantAuthorityUrl.AbsoluteUri); var queryParameters = $"redirect_uri={Uri.EscapeDataString(new Uri(serverUrl).GetLeftPart(UriPartial.Authority))}"; if (PlatformUtil.RunningOnMacOS) { throw new Exception("AAD isn't supported for MacOS"); } DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync("https://management.core.windows.net/", _azureDevOpsClientId, queryParameters).GetAwaiter().GetResult(); var term = context.GetService<ITerminal>(); term.WriteLine($"Please finish AAD device code flow in browser ({codeResult.VerificationUrl}), user code: {codeResult.UserCode}"); if (string.Equals(CredentialData.Data[Constants.Agent.CommandLine.Flags.LaunchBrowser], bool.TrueString, StringComparison.OrdinalIgnoreCase)) { try { if (PlatformUtil.RunningOnWindows) { Process.Start(new ProcessStartInfo() { FileName = codeResult.VerificationUrl, UseShellExecute = true }); } else if (PlatformUtil.RunningOnLinux) { Process.Start(new ProcessStartInfo() { FileName = "xdg-open", Arguments = codeResult.VerificationUrl }); } else { throw new NotImplementedException("Unexpected platform"); } } catch (Exception ex) { // not able to open browser, ex: xdg-open/open is not installed. trace.Error(ex); term.WriteLine($"Fail to open browser. {codeResult.Message}"); } } AuthenticationResult authResult = ctx.AcquireTokenByDeviceCodeAsync(codeResult).GetAwaiter().GetResult(); ArgUtil.NotNull(authResult, nameof(authResult)); trace.Info($"receive AAD auth result with {authResult.AccessTokenType} token"); var aadCred = new VssAadCredential(new VssAadToken(authResult)); VssCredentials creds = new VssCredentials(null, aadCred, CredentialPromptType.DoNotPrompt); trace.Info("cred created"); return creds; } public override void EnsureCredential(IHostContext context, CommandSettings command, string serverUrl) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(AadDeviceCodeAccessToken)); trace.Info(nameof(EnsureCredential)); ArgUtil.NotNull(command, nameof(command)); CredentialData.Data[Constants.Agent.CommandLine.Args.Url] = serverUrl; CredentialData.Data[Constants.Agent.CommandLine.Flags.LaunchBrowser] = command.GetAutoLaunchBrowser().ToString(); } private Uri GetTenantAuthorityUrl(IHostContext context, string serverUrl) { using (var handler = context.CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress"); client.DefaultRequestHeaders.UserAgent.Clear(); client.DefaultRequestHeaders.UserAgent.AddRange(VssClientHttpRequestSettings.Default.UserAgent); using (var requestMessage = new HttpRequestMessage(HttpMethod.Head, $"{serverUrl.Trim('/')}/_apis/connectiondata")) { var response = client.SendAsync(requestMessage).GetAwaiter().GetResult(); // Get the tenant from the Login URL, MSA backed accounts will not return `Bearer` www-authenticate header. var bearerResult = response.Headers.WwwAuthenticate.Where(p => p.Scheme.Equals("Bearer", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (bearerResult != null && bearerResult.Parameter.StartsWith("authorization_uri=", StringComparison.OrdinalIgnoreCase)) { var authorizationUri = bearerResult.Parameter.Substring("authorization_uri=".Length); if (Uri.TryCreate(authorizationUri, UriKind.Absolute, out Uri aadTenantUrl)) { return aadTenantUrl; } } return null; } } } } public sealed class PersonalAccessToken : CredentialProvider { public PersonalAccessToken() : base(Constants.Configuration.PAT) { } public override VssCredentials GetVssCredentials(IHostContext context) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(PersonalAccessToken)); trace.Info(nameof(GetVssCredentials)); ArgUtil.NotNull(CredentialData, nameof(CredentialData)); string token; if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Token, out token)) { token = null; } ArgUtil.NotNullOrEmpty(token, nameof(token)); trace.Info("token retrieved: {0} chars", token.Length); // PAT uses a basic credential VssBasicCredential basicCred = new VssBasicCredential("VstsAgent", token); VssCredentials creds = new VssCredentials(null, basicCred, CredentialPromptType.DoNotPrompt); trace.Info("cred created"); return creds; } public override void EnsureCredential(IHostContext context, CommandSettings command, string serverUrl) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(PersonalAccessToken)); trace.Info(nameof(EnsureCredential)); ArgUtil.NotNull(command, nameof(command)); CredentialData.Data[Constants.Agent.CommandLine.Args.Token] = command.GetToken(); } } public sealed class ServiceIdentityCredential : CredentialProvider { public ServiceIdentityCredential() : base(Constants.Configuration.ServiceIdentity) { } public override VssCredentials GetVssCredentials(IHostContext context) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(ServiceIdentityCredential)); trace.Info(nameof(GetVssCredentials)); ArgUtil.NotNull(CredentialData, nameof(CredentialData)); string token; if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Token, out token)) { token = null; } string username; if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.UserName, out username)) { username = null; } ArgUtil.NotNullOrEmpty(token, nameof(token)); ArgUtil.NotNullOrEmpty(username, nameof(username)); trace.Info("token retrieved: {0} chars", token.Length); // ServiceIdentity uses a service identity credential VssServiceIdentityToken identityToken = new VssServiceIdentityToken(token); VssServiceIdentityCredential serviceIdentityCred = new VssServiceIdentityCredential(username, "", identityToken); VssCredentials creds = new VssCredentials(null, serviceIdentityCred, CredentialPromptType.DoNotPrompt); trace.Info("cred created"); return creds; } public override void EnsureCredential(IHostContext context, CommandSettings command, string serverUrl) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(ServiceIdentityCredential)); trace.Info(nameof(EnsureCredential)); ArgUtil.NotNull(command, nameof(command)); CredentialData.Data[Constants.Agent.CommandLine.Args.Token] = command.GetToken(); CredentialData.Data[Constants.Agent.CommandLine.Args.UserName] = command.GetUserName(); } } public sealed class AlternateCredential : CredentialProvider { public AlternateCredential() : base(Constants.Configuration.Alternate) { } public override VssCredentials GetVssCredentials(IHostContext context) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(AlternateCredential)); trace.Info(nameof(GetVssCredentials)); string username; if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.UserName, out username)) { username = null; } string password; if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Password, out password)) { password = null; } ArgUtil.NotNull(username, nameof(username)); ArgUtil.NotNull(password, nameof(password)); trace.Info("username retrieved: {0} chars", username.Length); trace.Info("password retrieved: {0} chars", password.Length); VssBasicCredential loginCred = new VssBasicCredential(username, password); VssCredentials creds = new VssCredentials(null, loginCred, CredentialPromptType.DoNotPrompt); trace.Info("cred created"); return creds; } public override void EnsureCredential(IHostContext context, CommandSettings command, string serverUrl) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(AlternateCredential)); trace.Info(nameof(EnsureCredential)); ArgUtil.NotNull(command, nameof(command)); CredentialData.Data[Constants.Agent.CommandLine.Args.UserName] = command.GetUserName(); CredentialData.Data[Constants.Agent.CommandLine.Args.Password] = command.GetPassword(); } } }
// // doc.cs: Support for XML documentation comment. // // Authors: // Atsushi Enomoto <[email protected]> // Marek Safar ([email protected]> // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2004 Novell, Inc. // Copyright 2011 Xamarin Inc // // using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using System.Linq; namespace Mono.CSharp { // // Implements XML documentation generation. // class DocumentationBuilder { // // Used to create element which helps well-formedness checking. // readonly XmlDocument XmlDocumentation; readonly ModuleContainer module; readonly ModuleContainer doc_module; // // The output for XML documentation. // XmlWriter XmlCommentOutput; static readonly string line_head = Environment.NewLine + " "; // // Stores XmlDocuments that are included in XML documentation. // Keys are included filenames, values are XmlDocuments. // Dictionary<string, XmlDocument> StoredDocuments = new Dictionary<string, XmlDocument> (); ParserSession session; public DocumentationBuilder (ModuleContainer module) { doc_module = new ModuleContainer (module.Compiler); doc_module.DocumentationBuilder = this; this.module = module; XmlDocumentation = new XmlDocument (); XmlDocumentation.PreserveWhitespace = false; } Report Report { get { return module.Compiler.Report; } } public MemberName ParsedName { get; set; } public List<DocumentationParameter> ParsedParameters { get; set; } public TypeExpression ParsedBuiltinType { get; set; } public Operator.OpType? ParsedOperator { get; set; } XmlNode GetDocCommentNode (MemberCore mc, string name) { // FIXME: It could be even optimizable as not // to use XmlDocument. But anyways the nodes // are not kept in memory. XmlDocument doc = XmlDocumentation; try { XmlElement el = doc.CreateElement ("member"); el.SetAttribute ("name", name); string normalized = mc.DocComment; el.InnerXml = normalized; string [] split = normalized.Split ('\n'); el.InnerXml = line_head + String.Join (line_head, split); return el; } catch (Exception ex) { Report.Warning (1570, 1, mc.Location, "XML documentation comment on `{0}' is not well-formed XML markup ({1})", mc.GetSignatureForError (), ex.Message); return doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name)); } } // // Generates xml doc comments (if any), and if required, // handle warning report. // internal void GenerateDocumentationForMember (MemberCore mc) { string name = mc.DocCommentHeader + mc.GetSignatureForDocumentation (); XmlNode n = GetDocCommentNode (mc, name); XmlElement el = n as XmlElement; if (el != null) { var pm = mc as IParametersMember; if (pm != null) { CheckParametersComments (mc, pm, el); } // FIXME: it could be done with XmlReader XmlNodeList nl = n.SelectNodes (".//include"); if (nl.Count > 0) { // It could result in current node removal, so prepare another list to iterate. var al = new List<XmlNode> (nl.Count); foreach (XmlNode inc in nl) al.Add (inc); foreach (XmlElement inc in al) if (!HandleInclude (mc, inc)) inc.ParentNode.RemoveChild (inc); } // FIXME: it could be done with XmlReader foreach (XmlElement see in n.SelectNodes (".//see")) HandleSee (mc, see); foreach (XmlElement seealso in n.SelectNodes (".//seealso")) HandleSeeAlso (mc, seealso); foreach (XmlElement see in n.SelectNodes (".//exception")) HandleException (mc, see); foreach (XmlElement node in n.SelectNodes (".//typeparam")) HandleTypeParam (mc, node); foreach (XmlElement node in n.SelectNodes (".//typeparamref")) HandleTypeParamRef (mc, node); } n.WriteTo (XmlCommentOutput); } // // Processes "include" element. Check included file and // embed the document content inside this documentation node. // bool HandleInclude (MemberCore mc, XmlElement el) { bool keep_include_node = false; string file = el.GetAttribute ("file"); string path = el.GetAttribute ("path"); if (file == "") { Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `file' attribute"); el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el); keep_include_node = true; } else if (path.Length == 0) { Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `path' attribute"); el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el); keep_include_node = true; } else { XmlDocument doc; Exception exception = null; var full_path = Path.Combine (Path.GetDirectoryName (mc.Location.NameFullPath), file); if (!StoredDocuments.TryGetValue (full_path, out doc)) { try { doc = new XmlDocument (); doc.Load (full_path); StoredDocuments.Add (full_path, doc); } catch (Exception e) { exception = e; el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file `{0}': cannot be included ", file)), el); } } if (doc != null) { try { XmlNodeList nl = doc.SelectNodes (path); if (nl.Count == 0) { el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el); keep_include_node = true; } foreach (XmlNode n in nl) el.ParentNode.InsertBefore (el.OwnerDocument.ImportNode (n, true), el); } catch (Exception ex) { exception = ex; el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Failed to insert some or all of included XML "), el); } } if (exception != null) { Report.Warning (1589, 1, mc.Location, "Unable to include XML fragment `{0}' of file `{1}'. {2}", path, file, exception.Message); } } return keep_include_node; } // // Handles <see> elements. // void HandleSee (MemberCore mc, XmlElement see) { HandleXrefCommon (mc, see); } // // Handles <seealso> elements. // void HandleSeeAlso (MemberCore mc, XmlElement seealso) { HandleXrefCommon (mc, seealso); } // // Handles <exception> elements. // void HandleException (MemberCore mc, XmlElement seealso) { HandleXrefCommon (mc, seealso); } // // Handles <typeparam /> node // static void HandleTypeParam (MemberCore mc, XmlElement node) { if (!node.HasAttribute ("name")) return; string tp_name = node.GetAttribute ("name"); if (mc.CurrentTypeParameters != null) { if (mc.CurrentTypeParameters.Find (tp_name) != null) return; } // TODO: CS1710, CS1712 mc.Compiler.Report.Warning (1711, 2, mc.Location, "XML comment on `{0}' has a typeparam name `{1}' but there is no type parameter by that name", mc.GetSignatureForError (), tp_name); } // // Handles <typeparamref /> node // static void HandleTypeParamRef (MemberCore mc, XmlElement node) { if (!node.HasAttribute ("name")) return; string tp_name = node.GetAttribute ("name"); var member = mc; do { if (member.CurrentTypeParameters != null) { if (member.CurrentTypeParameters.Find (tp_name) != null) return; } member = member.Parent; } while (member != null); mc.Compiler.Report.Warning (1735, 2, mc.Location, "XML comment on `{0}' has a typeparamref name `{1}' that could not be resolved", mc.GetSignatureForError (), tp_name); } FullNamedExpression ResolveMemberName (IMemberContext context, MemberName mn) { if (mn.Left == null) return context.LookupNamespaceOrType (mn.Name, mn.Arity, LookupMode.Probing, Location.Null); var left = ResolveMemberName (context, mn.Left); var ns = left as NamespaceExpression; if (ns != null) return ns.LookupTypeOrNamespace (context, mn.Name, mn.Arity, LookupMode.Probing, Location.Null); TypeExpr texpr = left as TypeExpr; if (texpr != null) { var found = MemberCache.FindNestedType (texpr.Type, mn.Name, mn.Arity, false); if (found != null) return new TypeExpression (found, Location.Null); return null; } return left; } // // Processes "see" or "seealso" elements from cref attribute. // void HandleXrefCommon (MemberCore mc, XmlElement xref) { string cref = xref.GetAttribute ("cref"); // when, XmlReader, "if (cref == null)" if (!xref.HasAttribute ("cref")) return; // Nothing to be resolved the reference is marked explicitly if (cref.Length > 2 && cref [1] == ':') return; // Additional symbols for < and > are allowed for easier XML typing cref = cref.Replace ('{', '<').Replace ('}', '>'); var encoding = module.Compiler.Settings.Encoding; var s = new MemoryStream (encoding.GetBytes (cref)); var source_file = new CompilationSourceFile (doc_module, mc.Location.SourceFile); var report = new Report (doc_module.Compiler, new NullReportPrinter ()); if (session == null) session = new ParserSession { UseJayGlobalArrays = true }; SeekableStreamReader seekable = new SeekableStreamReader (s, encoding, session.StreamReaderBuffer); var parser = new CSharpParser (seekable, source_file, report, session); ParsedParameters = null; ParsedName = null; ParsedBuiltinType = null; ParsedOperator = null; parser.Lexer.putback_char = Tokenizer.DocumentationXref; parser.Lexer.parsing_generic_declaration_doc = true; parser.parse (); if (report.Errors > 0) { Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'", mc.GetSignatureForError (), cref); xref.SetAttribute ("cref", "!:" + cref); return; } MemberSpec member; string prefix = null; FullNamedExpression fne = null; // // Try built-in type first because we are using ParsedName as identifier of // member names on built-in types // if (ParsedBuiltinType != null && (ParsedParameters == null || ParsedName != null)) { member = ParsedBuiltinType.Type; } else { member = null; } if (ParsedName != null || ParsedOperator.HasValue) { TypeSpec type = null; string member_name = null; if (member == null) { if (ParsedOperator.HasValue) { type = mc.CurrentType; } else if (ParsedName.Left != null) { fne = ResolveMemberName (mc, ParsedName.Left); if (fne != null) { var ns = fne as NamespaceExpression; if (ns != null) { fne = ns.LookupTypeOrNamespace (mc, ParsedName.Name, ParsedName.Arity, LookupMode.Probing, Location.Null); if (fne != null) { member = fne.Type; } } else { type = fne.Type; } } } else { fne = ResolveMemberName (mc, ParsedName); if (fne == null) { type = mc.CurrentType; } else if (ParsedParameters == null) { member = fne.Type; } else if (fne.Type.MemberDefinition == mc.CurrentType.MemberDefinition) { member_name = Constructor.ConstructorName; type = fne.Type; } } } else { type = (TypeSpec) member; member = null; } if (ParsedParameters != null) { var old_printer = mc.Module.Compiler.Report.SetPrinter (new NullReportPrinter ()); try { var context = new DocumentationMemberContext (mc, ParsedName ?? MemberName.Null); foreach (var pp in ParsedParameters) { pp.Resolve (context); } } finally { mc.Module.Compiler.Report.SetPrinter (old_printer); } } if (type != null) { if (member_name == null) member_name = ParsedOperator.HasValue ? Operator.GetMetadataName (ParsedOperator.Value) : ParsedName.Name; int parsed_param_count; if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit) { parsed_param_count = ParsedParameters.Count - 1; } else if (ParsedParameters != null) { parsed_param_count = ParsedParameters.Count; } else { parsed_param_count = 0; } int parameters_match = -1; do { var members = MemberCache.FindMembers (type, member_name, true); if (members != null) { foreach (var m in members) { if (ParsedName != null && m.Arity != ParsedName.Arity) continue; if (ParsedParameters != null) { IParametersMember pm = m as IParametersMember; if (pm == null) continue; if (m.Kind == MemberKind.Operator && !ParsedOperator.HasValue) continue; var pm_params = pm.Parameters; int i; for (i = 0; i < parsed_param_count; ++i) { var pparam = ParsedParameters[i]; if (i >= pm_params.Count || pparam == null || pparam.TypeSpec == null || !TypeSpecComparer.Override.IsEqual (pparam.TypeSpec, pm_params.Types[i]) || (pparam.Modifier & Parameter.Modifier.RefOutMask) != (pm_params.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask)) { if (i > parameters_match) { parameters_match = i; } i = -1; break; } } if (i < 0) continue; if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit) { if (pm.MemberType != ParsedParameters[parsed_param_count].TypeSpec) { parameters_match = parsed_param_count + 1; continue; } } else { if (parsed_param_count != pm_params.Count) continue; } } if (member != null) { Report.Warning (419, 3, mc.Location, "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched", cref, member.GetSignatureForError (), m.GetSignatureForError ()); break; } member = m; } } // Continue with parent type for nested types if (member == null) { type = type.DeclaringType; } else { type = null; } } while (type != null); if (member == null && parameters_match >= 0) { for (int i = parameters_match; i < parsed_param_count; ++i) { Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'", (i + 1).ToString (), cref); } if (parameters_match == parsed_param_count + 1) { Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref); } } } } if (member == null) { Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved", mc.GetSignatureForError (), cref); cref = "!:" + cref; } else if (member == InternalType.Namespace) { cref = "N:" + fne.GetSignatureForError (); } else { prefix = GetMemberDocHead (member); cref = prefix + member.GetSignatureForDocumentation (); } xref.SetAttribute ("cref", cref); } // // Get a prefix from member type for XML documentation (used // to formalize cref target name). // static string GetMemberDocHead (MemberSpec type) { if (type is FieldSpec) return "F:"; if (type is MethodSpec) return "M:"; if (type is EventSpec) return "E:"; if (type is PropertySpec) return "P:"; if (type is TypeSpec) return "T:"; throw new NotImplementedException (type.GetType ().ToString ()); } // // Raised (and passed an XmlElement that contains the comment) // when GenerateDocComment is writing documentation expectedly. // // FIXME: with a few effort, it could be done with XmlReader, // that means removal of DOM use. // void CheckParametersComments (MemberCore member, IParametersMember paramMember, XmlElement el) { HashSet<string> found_tags = null; foreach (XmlElement pelem in el.SelectNodes ("param")) { string xname = pelem.GetAttribute ("name"); if (xname.Length == 0) continue; // really? but MS looks doing so if (found_tags == null) { found_tags = new HashSet<string> (); } if (xname != "" && paramMember.Parameters.GetParameterIndexByName (xname) < 0) { Report.Warning (1572, 2, member.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name", member.GetSignatureForError (), xname); continue; } if (found_tags.Contains (xname)) { Report.Warning (1571, 2, member.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'", member.GetSignatureForError (), xname); continue; } found_tags.Add (xname); } if (found_tags != null) { foreach (Parameter p in paramMember.Parameters.FixedParameters) { if (!found_tags.Contains (p.Name) && !(p is ArglistParameter)) Report.Warning (1573, 4, member.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'", p.Name, member.GetSignatureForError ()); } } } // // Outputs XML documentation comment from tokenized comments. // public bool OutputDocComment (string asmfilename, string xmlFileName) { XmlTextWriter w = null; try { w = new XmlTextWriter (xmlFileName, null); w.Indentation = 4; w.Formatting = Formatting.Indented; w.WriteStartDocument (); w.WriteStartElement ("doc"); w.WriteStartElement ("assembly"); w.WriteStartElement ("name"); w.WriteString (Path.GetFileNameWithoutExtension (asmfilename)); w.WriteEndElement (); // name w.WriteEndElement (); // assembly w.WriteStartElement ("members"); XmlCommentOutput = w; module.GenerateDocComment (this); w.WriteFullEndElement (); // members w.WriteEndElement (); w.WriteWhitespace (Environment.NewLine); w.WriteEndDocument (); return true; } catch (Exception ex) { Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", xmlFileName, ex.Message); return false; } finally { if (w != null) w.Close (); } } } // // Type lookup of documentation references uses context of type where // the reference is used but type parameters from cref value // sealed class DocumentationMemberContext : IMemberContext { readonly MemberCore host; MemberName contextName; public DocumentationMemberContext (MemberCore host, MemberName contextName) { this.host = host; this.contextName = contextName; } public TypeSpec CurrentType { get { return host.CurrentType; } } public TypeParameters CurrentTypeParameters { get { return contextName.TypeParameters; } } public MemberCore CurrentMemberDefinition { get { return host.CurrentMemberDefinition; } } public bool IsObsolete { get { return false; } } public bool IsUnsafe { get { return host.IsStatic; } } public bool IsStatic { get { return host.IsStatic; } } public ModuleContainer Module { get { return host.Module; } } public string GetSignatureForError () { return host.GetSignatureForError (); } public ExtensionMethodCandidates LookupExtensionMethod (string name, int arity) { return null; } public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc) { if (arity == 0) { var tp = CurrentTypeParameters; if (tp != null) { for (int i = 0; i < tp.Count; ++i) { var t = tp[i]; if (t.Name == name) { t.Type.DeclaredPosition = i; return new TypeParameterExpr (t, loc); } } } } return host.Parent.LookupNamespaceOrType (name, arity, mode, loc); } public FullNamedExpression LookupNamespaceAlias (string name) { throw new NotImplementedException (); } } class DocumentationParameter { public readonly Parameter.Modifier Modifier; public FullNamedExpression Type; TypeSpec type; public DocumentationParameter (Parameter.Modifier modifier, FullNamedExpression type) : this (type) { this.Modifier = modifier; } public DocumentationParameter (FullNamedExpression type) { this.Type = type; } public TypeSpec TypeSpec { get { return type; } } public void Resolve (IMemberContext context) { type = Type.ResolveAsType (context); } } }
using System; using System.Collections.Generic; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance; using it.unifi.dsi.stlab.networkreasoner.gas.system.dimensional_objects; using it.unifi.dsi.stlab.math.algebra; using it.unifi.dsi.stlab.networkreasoner.gas.system.formulae; using it.unifi.dsi.stlab.networkreasoner.model.gas; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.computational_objects.edges; namespace it.unifi.dsi.stlab.networkreasoner.gas.system { public class FluidDynamicSystemStateTransitionNewtonRaphsonSolve : FluidDynamicSystemStateTransition { public List<UntilConditionAbstract> UntilConditions{ get; set; } //public Func<Vector<NodeForNetwonRaphsonSystem>, Vector<NodeForNetwonRaphsonSystem>> FromDimensionalToAdimensionalTranslator{ get; set; } public GasFormulaVisitor FormulaVisitor{ get; set; } #region FluidDynamicSystemStateTransition implementation public FluidDynamicSystemStateAbstract forBareSystemState ( FluidDynamicSystemStateBare fluidDynamicSystemStateBare) { throw new Exception ("A system in the bare state cannot be solved, initialize it before and try again"); } public virtual FluidDynamicSystemStateAbstract forUnsolvedSystemState ( FluidDynamicSystemStateUnsolved fluidDynamicSystemStateUnsolved) { var mathematicallySolvedState = new FluidDynamicSystemStateMathematicallySolved (); var startTimeStamp = DateTime.UtcNow; OneStepMutationResults previousOneStepMutationResults = null; OneStepMutationResults currentOneStepMutationResults = new OneStepMutationResults { IterationNumber = 0, Unknowns = fluidDynamicSystemStateUnsolved.InitialUnknownVector, Fvector = fluidDynamicSystemStateUnsolved.InitialFvector, Qvector = fluidDynamicSystemStateUnsolved.InitialQvector }; MutateComputationDriver mutateComputationDriver = new MutateComputationDriverDoOneMoreMutation (); while (mutateComputationDriver.canDoOneMoreStep ()) { UntilConditions.ForEach (condition => { if (this.decideIfComputationShouldBeStopped (condition, previousOneStepMutationResults, currentOneStepMutationResults)) { mutateComputationDriver = new MutateComputationDriverStopMutate (); } } ); mutateComputationDriver.doOneMoreStep ( step: () => { previousOneStepMutationResults = currentOneStepMutationResults; previousOneStepMutationResults.IterationNumber += 1; currentOneStepMutationResults = this.mutate ( previousOneStepMutationResults, fluidDynamicSystemStateUnsolved); } ); } currentOneStepMutationResults.VelocityVector = computeVelocityVector ( currentOneStepMutationResults.Unknowns, currentOneStepMutationResults.Qvector, fluidDynamicSystemStateUnsolved.Nodes, fluidDynamicSystemStateUnsolved.Edges); currentOneStepMutationResults.ComputationEndTimestamp = DateTime.UtcNow; currentOneStepMutationResults.ComputationStartTimestamp = startTimeStamp; mathematicallySolvedState.MutationResult = currentOneStepMutationResults; mathematicallySolvedState.SolvedBy = this; return mathematicallySolvedState; } public FluidDynamicSystemStateAbstract forMathematicallySolvedState ( FluidDynamicSystemStateMathematicallySolved fluidDynamicSystemStateMathematicallySolved) { // simply return the given state since if it is already mathematically solved we've no work to do here return fluidDynamicSystemStateMathematicallySolved; } public FluidDynamicSystemStateAbstract forNegativeLoadsCorrectedState ( FluidDynamicSystemStateNegativeLoadsCorrected fluidDynamicSystemStateNegativeLoadsCorrected) { // simply return the given state since if it is already checked for negative pressures, someone mathematically solved it already. return fluidDynamicSystemStateNegativeLoadsCorrected; } #endregion protected virtual bool decideIfComputationShouldBeStopped ( UntilConditionAbstract condition, OneStepMutationResults previousOneStepMutationResults, OneStepMutationResults currentOneStepMutationResults) { bool until = condition.canContinue ( previousOneStepMutationResults, currentOneStepMutationResults); bool computationShouldBeStopped = until == false; return computationShouldBeStopped; } protected virtual OneStepMutationResults mutate ( OneStepMutationResults previousStepMutationResults, FluidDynamicSystemStateUnsolved fluidDynamicSystemStateUnsolved) { var mutateStartTimestamp = DateTime.UtcNow; var unknownVectorAtPreviousStep = computeUnknownVectorAtPreviousStep ( previousStepMutationResults); var adimensionalUnknownVectorAtPreviousStep = makeAdimensionalUnknowns ( unknownVectorAtPreviousStep); var FvectorAtPreviousStep = computeFvectorAtPreviousStep ( previousStepMutationResults); var KvectorAtCurrentStep = computeKvector ( adimensionalUnknownVectorAtPreviousStep.WrappedObject, FvectorAtPreviousStep, fluidDynamicSystemStateUnsolved.Edges); var AmatrixAtCurrentStep = computeAmatrix ( KvectorAtCurrentStep, fluidDynamicSystemStateUnsolved.Edges); var JacobianMatrixAtCurrentStep = computeJacobianMatrix ( KvectorAtCurrentStep, fluidDynamicSystemStateUnsolved.Edges); fixMatricesIfSupplyGadgetsPresent ( AmatrixAtCurrentStep, JacobianMatrixAtCurrentStep, fluidDynamicSystemStateUnsolved.Nodes); var coefficientsVectorAtCurrentStep = computeCoefficientsVectorAtCurrentStep ( fluidDynamicSystemStateUnsolved.Nodes, previousStepMutationResults.Qvector); DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> unknownVectorAtCurrentStep = computeUnknowns ( AmatrixAtCurrentStep, adimensionalUnknownVectorAtPreviousStep.WrappedObject, coefficientsVectorAtCurrentStep, JacobianMatrixAtCurrentStep, fluidDynamicSystemStateUnsolved.NodesEnumeration); fixNegativeUnknowns (unknownVectorAtCurrentStep.WrappedObject); // the following steps don't work for inverted pressure among nodes in pressure regulation relation. // fixLesserUnknownsForAntecedentsInPressureRegulations ( // unknownVectorAtCurrentStep.WrappedObject, // computationalNode => fluidDynamicSystemStateUnsolved.OriginalNodesByComputationNodes [computationalNode]); // // fixNegativeUnknowns (unknownVectorAtCurrentStep.WrappedObject); var QvectorAtCurrentStep = computeQvector ( unknownVectorAtCurrentStep.WrappedObject, KvectorAtCurrentStep, fluidDynamicSystemStateUnsolved.Edges); var FvectorAtCurrentStep = computeFvector ( FvectorAtPreviousStep, QvectorAtCurrentStep, fluidDynamicSystemStateUnsolved.Edges); var result = computeOneStepMutationResult (AmatrixAtCurrentStep, unknownVectorAtCurrentStep, coefficientsVectorAtCurrentStep, QvectorAtCurrentStep, JacobianMatrixAtCurrentStep, FvectorAtCurrentStep, previousStepMutationResults.IterationNumber, mutateStartTimestamp, fluidDynamicSystemStateUnsolved); return result; } #region ``compute'' methods protected virtual DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> makeAdimensionalUnknowns ( DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> unknownVectorAtPreviousStep) { // we perform the adimensional translation just to ensure that we're // working with adimensional objects, since the translator raise an exception // if it is called. return unknownVectorAtPreviousStep.translateTo ( new AdimensionalPressures ()); } protected virtual DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> computeUnknownVectorAtPreviousStep (OneStepMutationResults previousStepMutationResults) { return previousStepMutationResults.Unknowns; } protected virtual Vector<EdgeForNetwonRaphsonSystem> computeFvectorAtPreviousStep ( OneStepMutationResults previousStepMutationResults) { return previousStepMutationResults.Fvector; } protected virtual void fixMatricesIfSupplyGadgetsPresent ( Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> AmatrixAtCurrentStep, Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> JacobianMatrixAtCurrentStep, List<NodeForNetwonRaphsonSystem> nodes) { nodes.ForEach (aNode => { aNode.fixMatrixIfYouHaveSupplyGadget (AmatrixAtCurrentStep); aNode.fixMatrixIfYouHaveSupplyGadget (JacobianMatrixAtCurrentStep); } ); } protected virtual Vector<NodeForNetwonRaphsonSystem> computeCoefficientsVectorAtCurrentStep ( List<NodeForNetwonRaphsonSystem> nodes, Vector<EdgeForNetwonRaphsonSystem> Qvector) { var coefficientsVectorAtCurrentStep = new Vector<NodeForNetwonRaphsonSystem> (); nodes.ForEach (aNode => aNode.putYourCoefficientInto ( coefficientsVectorAtCurrentStep, FormulaVisitor, Qvector) ); return coefficientsVectorAtCurrentStep; } protected virtual void fixNegativeUnknowns ( Vector<NodeForNetwonRaphsonSystem> unknownVectorAtCurrentStep) { // we set a seed in order to reproduce quite similar results. Random random = new Random (42); unknownVectorAtCurrentStep.updateEach ( (aNode, currentValue) => currentValue <= 0d ? random.NextDouble () / 10d : currentValue ); } protected virtual void fixLesserUnknownsForAntecedentsInPressureRegulations ( Vector<NodeForNetwonRaphsonSystem> unknownVectorAtCurrentStep, Func<NodeForNetwonRaphsonSystem, GasNodeAbstract> originalNodeMapper) { unknownVectorAtCurrentStep.updateEach ( (aNode, currentValue) => aNode.fixPressureIfAntecedentInPressureReductionRelation (currentValue, this.FormulaVisitor) ); unknownVectorAtCurrentStep.updateEach ( (aNode, currentValue) => aNode.fixPressureIfInPressureReductionRelation (unknownVectorAtCurrentStep, currentValue, originalNodeMapper, this.FormulaVisitor) ); } public OneStepMutationResults computeOneStepMutationResult ( Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> AmatrixAtCurrentStep, DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> unknownVectorAtCurrentStep, Vector<NodeForNetwonRaphsonSystem> coefficientsVectorAtCurrentStep, Vector<EdgeForNetwonRaphsonSystem> QvectorAtCurrentStep, Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> JacobianMatrixAtCurrentStep, Vector<EdgeForNetwonRaphsonSystem> FvectorAtCurrentStep, int iterationNumber, DateTime stepStartTimestamp, FluidDynamicSystemStateUnsolved fluidDynamicSystemStateUnsolved) { var result = new OneStepMutationResults (); result.Amatrix = AmatrixAtCurrentStep; result.Unknowns = unknownVectorAtCurrentStep; result.Coefficients = coefficientsVectorAtCurrentStep; result.Qvector = QvectorAtCurrentStep; result.Jacobian = JacobianMatrixAtCurrentStep; result.Fvector = FvectorAtCurrentStep; result.IterationNumber = iterationNumber; result.StartingUnsolvedState = fluidDynamicSystemStateUnsolved; result.UsedFormulae = FormulaVisitor; result.ComputationStartTimestamp = stepStartTimestamp; result.ComputationEndTimestamp = DateTime.UtcNow; return result; } protected virtual Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> computeAmatrix (Vector<EdgeForNetwonRaphsonSystem> kvectorAtCurrentStep, List<EdgeForNetwonRaphsonSystem> edges) { Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> Amatrix = new Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> (); edges.ForEach (anEdge => anEdge.fillAmatrixUsing ( Amatrix, kvectorAtCurrentStep, FormulaVisitor) ); return Amatrix; } protected virtual Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> computeJacobianMatrix (Vector<EdgeForNetwonRaphsonSystem> kvectorAtCurrentStep, List<EdgeForNetwonRaphsonSystem> edges) { Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> JacobianMatrix = new Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> (); edges.ForEach (anEdge => anEdge.fillJacobianMatrixUsing ( JacobianMatrix, kvectorAtCurrentStep, FormulaVisitor) ); return JacobianMatrix; } protected virtual Vector<EdgeForNetwonRaphsonSystem> computeKvector ( Vector<NodeForNetwonRaphsonSystem> unknownVector, Vector<EdgeForNetwonRaphsonSystem> Fvector, List<EdgeForNetwonRaphsonSystem> edges) { var Kvector = new Vector<EdgeForNetwonRaphsonSystem> (); edges.ForEach (anEdge => anEdge.putKvalueIntoUsing ( Kvector, Fvector, unknownVector, FormulaVisitor) ); return Kvector; } protected virtual DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> computeUnknowns ( Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> AmatrixAtCurrentStep, Vector<NodeForNetwonRaphsonSystem> unknownVectorAtPreviousStep, Vector<NodeForNetwonRaphsonSystem> coefficientsVectorAtCurrentStep, Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> jacobianMatrixAtCurrentStep, Dictionary<NodeForNetwonRaphsonSystem, int> nodesEnumeration) { Vector<NodeForNetwonRaphsonSystem> matrixArightProductUnknownAtPreviousStep = AmatrixAtCurrentStep.rightProduct (unknownVectorAtPreviousStep); Vector<NodeForNetwonRaphsonSystem> coefficientVectorForJacobianSystemFactorization = matrixArightProductUnknownAtPreviousStep.minus (coefficientsVectorAtCurrentStep); Vector<NodeForNetwonRaphsonSystem> unknownVectorFromJacobianSystemAtCurrentStep = jacobianMatrixAtCurrentStep.SolveWithGivenEnumerations ( nodesEnumeration, nodesEnumeration, coefficientVectorForJacobianSystemFactorization); unknownVectorFromJacobianSystemAtCurrentStep.updateEach ( (node, currentValue) => currentValue * .55); Vector<NodeForNetwonRaphsonSystem> unknownVectorAtCurrentStep = unknownVectorAtPreviousStep.minus (unknownVectorFromJacobianSystemAtCurrentStep); return new DimensionalObjectWrapperWithAdimensionalValues<Vector<NodeForNetwonRaphsonSystem>> { WrappedObject = unknownVectorAtCurrentStep }; } protected virtual Vector<EdgeForNetwonRaphsonSystem> computeQvector ( Vector<NodeForNetwonRaphsonSystem> unknownVector, Vector<EdgeForNetwonRaphsonSystem> Kvector, List<EdgeForNetwonRaphsonSystem> edges) { Vector<EdgeForNetwonRaphsonSystem> Qvector = new Vector<EdgeForNetwonRaphsonSystem> (); edges.ForEach (anEdge => anEdge.putQvalueIntoUsing ( Qvector, Kvector, unknownVector, FormulaVisitor) ); // TODO: this is quite inefficient, we should maintain // a list of edges with pressure regulator gadget in order // to perform the following behavior only on that subset. edges.ForEach (anEdge => { new IfEdgeHasRegulatorGadget { Do = () => Qvector.atPut (anEdge, anEdge.EndNode.invertedAlgebraicFlowSum (Qvector)) }.performOn (anEdge.RegulatorState); }); return Qvector; } protected virtual Vector<EdgeForNetwonRaphsonSystem> computeFvector ( Vector<EdgeForNetwonRaphsonSystem> Fvector, Vector<EdgeForNetwonRaphsonSystem> Qvector, List<EdgeForNetwonRaphsonSystem> edges) { Vector<EdgeForNetwonRaphsonSystem> newFvector = new Vector<EdgeForNetwonRaphsonSystem> (); edges.ForEach (anEdge => anEdge.putNewFvalueIntoUsing ( newFvector, Qvector, Fvector, FormulaVisitor) ); return newFvector; } protected virtual Vector<EdgeForNetwonRaphsonSystem> computeVelocityVector ( DimensionalObjectWrapper<Vector<NodeForNetwonRaphsonSystem>> pressuresWrapper, Vector<EdgeForNetwonRaphsonSystem> Qvector, List<NodeForNetwonRaphsonSystem> nodes, List<EdgeForNetwonRaphsonSystem> edges) { Vector<EdgeForNetwonRaphsonSystem> velocityVector = new Vector<EdgeForNetwonRaphsonSystem> (); var absolutePressures = pressuresWrapper.translateTo (new AbsolutePressures { Nodes = nodes, Formulae = FormulaVisitor } ).WrappedObject; edges.ForEach (anEdge => anEdge.putVelocityValueIntoUsing ( velocityVector, absolutePressures, Qvector, FormulaVisitor) ); return velocityVector; } public FluidDynamicSystemStateTransition clone () { throw new System.NotImplementedException (); } #endregion } }
//tabs=4 // -------------------------------------------------------------------------------- // TODO fill in this information for your driver, then remove this line! // // ASCOM Telescope driver for NexStar // // Description: Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam // nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam // erat, sed diam voluptua. At vero eos et accusam et justo duo // dolores et ea rebum. Stet clita kasd gubergren, no sea takimata // sanctus est Lorem ipsum dolor sit amet. // // Implements: ASCOM Telescope interface version: <To be completed by driver developer> // Author: (XXX) Your N. Here <[email protected]> // // Edit Log: // // Date Who Vers Description // ----------- --- ----- ------------------------------------------------------- // dd-mmm-yyyy XXX 6.0.0 Initial edit, created from ASCOM driver template // -------------------------------------------------------------------------------- // // This is used to define code in the template that is specific to one class implementation // unused code canbe deleted and this definition removed. #define Telescope using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using ASCOM; using ASCOM.Utilities; using ASCOM.DeviceInterface; using System.Globalization; using System.Collections; namespace ASCOM.NexStar { // // Your driver's DeviceID is ASCOM.NexStar.Telescope // // The Guid attribute sets the CLSID for ASCOM.NexStar.Telescope // The ClassInterface/None addribute prevents an empty interface called // _NexStar from being created and used as the [default] interface // // TODO right click on ITelescopeV3 and select "Implement Interface" to // generate the property amd method definitions for the driver. // // TODO Replace the not implemented exceptions with code to implement the function or // throw the appropriate ASCOM exception. // /// <summary> /// ASCOM Telescope Driver for NexStar. /// </summary> [Guid("9e18e713-1a5c-4200-a7d3-1aafabce0ce4")] [ClassInterface(ClassInterfaceType.None)] public class Telescope : ITelescopeV3 { /// <summary> /// ASCOM DeviceID (COM ProgID) for this driver. /// The DeviceID is used by ASCOM applications to load the driver at runtime. /// </summary> //private static string driverID = "ASCOM.NexStar.Telescope"; // TODO Change the descriptive string for your driver then remove this line /// <summary> /// Driver description that displays in the ASCOM Chooser. /// </summary> //private static string driverDescription = "NexStar Telescope Driver"; #if Telescope // // Driver private data (rate collections) for the telescope driver only. // This can be removed for other driver types // //private readonly AxisRates[] _axisRates; #endif /// <summary> /// Initializes a new instance of the <see cref="NexStar"/> class. /// Must be public for COM registration. /// </summary> public Telescope() { #if Telescope // the rates constructors are only needed for the telescope class // This can be removed for other driver types //_axisRates = new AxisRates[3]; //_axisRates[0] = new AxisRates(TelescopeAxes.axisPrimary); //_axisRates[1] = new AxisRates(TelescopeAxes.axisSecondary); //_axisRates[2] = new AxisRates(TelescopeAxes.axisTertiary); #endif //TODO: Implement your additional construction here } #region ASCOM Registration // // Register or unregister driver for ASCOM. This is harmless if already // registered or unregistered. // /// <summary> /// Register or unregister the driver with the ASCOM Platform. /// This is harmless if the driver is already registered/unregistered. /// </summary> /// <param name="bRegister">If <c>true</c>, registers the driver, otherwise unregisters it.</param> private static void RegUnregASCOM(bool bRegister) { using (var P = new ASCOM.Utilities.Profile()) { P.DeviceType = "Telescope"; if (bRegister) { P.Register(Common.DriverId, Common.DriverDescription); } else { P.Unregister(Common.DriverId); } } } /// <summary> /// This function registers the driver with the ASCOM Chooser and /// is called automatically whenever this class is registered for COM Interop. /// </summary> /// <param name="t">Type of the class being registered, not used.</param> /// <remarks> /// This method typically runs in two distinct situations: /// <list type="numbered"> /// <item> /// In Visual Studio, when the project is successfully built. /// For this to work correctly, the option <c>Register for COM Interop</c> /// must be enabled in the project settings. /// </item> /// <item>During setup, when the installer registers the assembly for COM Interop.</item> /// </list> /// This technique should mean that it is never necessary to manually register a driver with ASCOM. /// </remarks> [ComRegisterFunction] public static void RegisterASCOM(Type t) { RegUnregASCOM(true); } /// <summary> /// This function unregisters the driver from the ASCOM Chooser and /// is called automatically whenever this class is unregistered from COM Interop. /// </summary> /// <param name="t">Type of the class being registered, not used.</param> /// <remarks> /// This method typically runs in two distinct situations: /// <list type="numbered"> /// <item> /// In Visual Studio, when the project is cleaned or prior to rebuilding. /// For this to work correctly, the option <c>Register for COM Interop</c> /// must be enabled in the project settings. /// </item> /// <item>During uninstall, when the installer unregisters the assembly from COM Interop.</item> /// </list> /// This technique should mean that it is never necessary to manually unregister a driver from ASCOM. /// </remarks> [ComUnregisterFunction] public static void UnregisterASCOM(Type t) { RegUnregASCOM(false); } #endregion // // PUBLIC COM INTERFACE ITelescopeV3 IMPLEMENTATION // /// <summary> /// Displays the Setup Dialog form. /// If the user clicks the OK button to dismiss the form, then /// the new settings are saved, otherwise the old values are reloaded. /// THIS IS THE ONLY PLACE WHERE SHOWING USER INTERFACE IS ALLOWED! /// </summary> public void SetupDialog() { // consider only showing the setup dialog if not connected // or call a different dialog if connected if (IsConnected) System.Windows.Forms.MessageBox.Show("Already connected, just press OK"); using (SetupDialogForm F = new SetupDialogForm()) { var result = F.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { Properties.Settings.Default.Save(); return; } Properties.Settings.Default.Reload(); } } #region common properties and methods. All set to no action public System.Collections.ArrayList SupportedActions { get { return new ArrayList(); } } public string Action(string actionName, string actionParameters) { throw new ASCOM.MethodNotImplementedException("Action"); } public void CommandBlind(string command, bool raw) { CheckConnected("CommandBlind"); // Call CommandString and return as soon as it finishes this.CommandString(command, raw); // or throw new ASCOM.MethodNotImplementedException("CommandBlind"); } public bool CommandBool(string command, bool raw) { CheckConnected("CommandBool"); string ret = CommandString(command, raw); // TODO decode the return string and return true or false // or throw new ASCOM.MethodNotImplementedException("CommandBool"); } public string CommandString(string command, bool raw) { CheckConnected("CommandString"); // it's a good idea to put all the low level communication with the device here, // then all communication calls this function // you need something to ensure that only one command is in progress at a time throw new ASCOM.MethodNotImplementedException("CommandString"); } #endregion #region public properties and methods public void Dispose() { if (Scope.isConnected) { Common.ScopeConnect(false); } } public bool Connected /* Done AR */ { get { return IsConnected; } set { if (value == IsConnected) return; if (value) { Common.ScopeConnect(value); } else { Common.ScopeConnect(value); } return; } } public string Description /* done AR */ { get { return Common.DriverDescription; } } public string DriverInfo /* done AR */ { get { return Common.DriverDescription; } } public string DriverVersion { get { Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; return String.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor); } } public short InterfaceVersion { // set by the driver wizard get { return 3; } } #endregion #region private properties and methods // here are some useful properties and methods that can be used as required // to help with /// <summary> /// Returns true if there is a valid connection to the driver hardware /// </summary> private bool IsConnected { get { return Scope.isConnected; } } /// <summary> /// Use this function to throw an exception if we aren't connected to the hardware /// </summary> /// <param name="message"></param> private void CheckConnected(string message) { if (!IsConnected) { throw new ASCOM.NotConnectedException(message); } } #endregion public void AbortSlew() /* done AR */ { Common.AbortSlew(); } public AlignmentModes AlignmentMode /* done AR */ { get { return Scope.AlignmentMode; } } public double Altitude /* done AR */ { get { return Common.GetAltitude(); } } public double ApertureArea /* done AR */ { get { return Scope.ApertureArea; } } public double ApertureDiameter /* done AR */ { get { return Scope.ApertureDiameter; } } public bool AtHome /* done AR */ { get { return false; } } public bool AtPark /* done AR */ { get { return Common.AtPark(); } } public IAxisRates AxisRates(TelescopeAxes Axis) /* done AR */ { switch (Axis) { case TelescopeAxes.axisPrimary: return Scope.AxisRates[0]; case TelescopeAxes.axisSecondary: return Scope.AxisRates[1]; case TelescopeAxes.axisTertiary: return Scope.AxisRates[2]; default: return null; } } public double Azimuth /* done AR */ { get { return Common.GetAzimuth(); } } public bool CanFindHome /* done AR */ { get { return false; } } public bool CanMoveAxis(TelescopeAxes Axis) /* done AR */ { switch (Axis) { case TelescopeAxes.axisPrimary: return Scope.AxisRates[0].Count > 0; case TelescopeAxes.axisSecondary: return Scope.AxisRates[1].Count > 0; case TelescopeAxes.axisTertiary: return Scope.AxisRates[2].Count > 0; default: return false; } } public bool CanPark /* TODO: implement */ { get { return false; } } public bool CanPulseGuide /* done AR */ { get { return Common.CanPulseGuide(); } } public bool CanSetDeclinationRate /* done AR */ { get { return Common.CanPulseGuide(); } } public bool CanSetGuideRates /* done AR */ { get { return Common.CanPulseGuide(); } } public bool CanSetPark /* done AR */ { get { return Common.CanSetTracking(); } } public bool CanSetPierSide /* done AR */ { get { return Common.CanSetPierSide(); } } public bool CanSetRightAscensionRate /* done AR */ { get { return Common.CanPulseGuide(); } } public bool CanSetTracking /* done AR */ { get { return Common.CanSetTracking(); } } public bool CanSlew /* done AR */ { get { return true; } } public bool CanSlewAltAz /* done AR */ { get { return Common.CanSlewAltAz(); } } public bool CanSlewAltAzAsync /* done AR */ { get { return Common.CanSlewAltAz(); } } public bool CanSlewAsync /* done AR */ { get { return Common.CanSlewAsync(); } } public bool CanSync /* done AR */ { get { return Common.CanSync(); } } public bool CanSyncAltAz /* done AR */ { get { return false; } } public bool CanUnpark /* TODO: implement */ { get { return false; } } public double Declination /* done AR */ { get { return Common.GetDeclination(); } } public double DeclinationRate /* TODO: check/debug */ { get { return Scope.RateDec; } set { Common.SetDeclinationRate(value); } } public PierSide DestinationSideOfPier(double RightAscension, double Declination) /* TODO: implement */ { if (Scope.AlignmentMode == AlignmentModes.algGermanPolar) { /* TODO: code here */ return PierSide.pierUnknown; } throw new ASCOM.NotImplementedException(Common.DriverId + ": DestinationSideOfPier() failed"); } public bool DoesRefraction /* done AR */ { get { return false; } set { } } public EquatorialCoordinateType EquatorialSystem /* done AR */ { get { return Common.GetEquatorialSystem(); } } public void FindHome() { throw new ASCOM.NotImplementedException(); } public double FocalLength /* done AR */ { get { return Scope.FocalLength; } } public double GuideRateDeclination /* TODO: check/debug */ { get { double Rate; Common.GetGuidRate(Common.eDeviceId.ALT, out Rate); Scope.GuideRateDec = Rate; return Rate; } set { Scope.GuideRateDec = value; Common.SetGuideRate(Common.eDeviceId.ALT, value); } } public double GuideRateRightAscension /* TODO: check/debug */ { get { double Rate; Common.GetGuidRate(Common.eDeviceId.AZM, out Rate); Scope.GuideRateRa = Rate; return Rate; } set { Scope.GuideRateRa = value; Common.SetGuideRate(Common.eDeviceId.AZM, value); } } public bool IsPulseGuiding /* done AR */ { get { return Common.isPulseGuiding(); } } public void MoveAxis(TelescopeAxes Axis, double Rate) /* TODO: check/debug */ { Common.MoveAxis(Axis, Rate); } public string Name /* done AR */ { get { return Scope.Name; } } public void Park() /* TODO: implement */ { throw new ASCOM.MethodNotImplementedException(); } public void PulseGuide(GuideDirections Direction, int Duration) /* done AR */ { Common.PulseGuide(Direction, Duration); } public double RightAscension /* done AR */ { get { return Common.GetRightAscention(); } } public double RightAscensionRate /* TODO: check/debug */ { get { return Scope.RateRa; } set { Common.SetRightAscensionRate(value); } } public void SetPark() /* TODO: implement */ { throw new ASCOM.MethodNotImplementedException(Common.DriverId + ": SetPark() failed"); } public PierSide SideOfPier /* TODO: implement */ { get { return Common.GetSideOfPier(); } set { Common.SetSideOfPier(value); } } public double SiderealTime /* done AR */ { get { return Common.GetLst(); } } public double SiteElevation /* done AR */ { get { return Scope.Elevation; } set { Common.SetElevation(value); } } public double SiteLatitude /* done AR */ { get { return Scope.Latitude; } set { Common.SetLatitude(value); } } public double SiteLongitude /* done AR */ { get { return Scope.Longitude; } set { Common.SetLongitude(value); } } public short SlewSettleTime /* done AR */ { get { return Scope.SettleTime; } set { Common.SetSlewSettleTime(value); } } public void SlewToAltAz(double Azimuth, double Altitude) /* done AR */ { Common.SlewToAzmAlt(Azimuth, Altitude); while (Scope.isSlewing) { Thread.Sleep(500); Application.DoEvents(); } } public void SlewToAltAzAsync(double Azimuth, double Altitude) /* done AR */ { Common.SlewToAzmAlt(Azimuth, Altitude); } public void SlewToCoordinates(double RightAscension, double Declination) /* done AR */ { Common.SetTargetDeclination(Declination); Common.SetTargetRightAscension(RightAscension); if (Scope.TargetRaSet && Scope.TargetDecSet) { Common.SlewToRaDec(Scope.TargetRa, Scope.TargetDec); Scope.TargetDecSet = false; Scope.TargetRaSet = false; while (Scope.isSlewing) { Thread.Sleep(500); Application.DoEvents(); } } } public void SlewToCoordinatesAsync(double RightAscension, double Declination) /* done AR */ { Common.SetTargetDeclination(Declination); Common.SetTargetRightAscension(RightAscension); if (Scope.TargetRaSet && Scope.TargetDecSet) { Common.SlewToRaDec(Scope.TargetRa, Scope.TargetDec); Scope.TargetDecSet = false; Scope.TargetRaSet = false; } } public void SlewToTarget() /* done AR */ { if (Scope.TargetRaSet && Scope.TargetDecSet) { Common.SlewToRaDec(Scope.TargetRa, Scope.TargetDec); Scope.TargetDecSet = false; Scope.TargetRaSet = false; while (Scope.isSlewing) { Thread.Sleep(500); Application.DoEvents(); } } } public void SlewToTargetAsync() /* done AR */ { if (Scope.TargetRaSet && Scope.TargetDecSet) { Common.SlewToRaDec(Scope.TargetRa, Scope.TargetDec); Scope.TargetDecSet = false; Scope.TargetRaSet = false; } } public bool Slewing /* done AR */ { get { return Scope.isSlewing; } } public void SyncToAltAz(double Azimuth, double Altitude) /* done AR */ /* no scope does SyncAltAz */ { throw new ASCOM.MethodNotImplementedException(Common.DriverId + "SyncToAltAz() failed"); } public void SyncToCoordinates(double RightAscension, double Declination) /* done AR */ { Common.Sync(RightAscension, Declination); } public void SyncToTarget() /* done AR */ { if (Scope.TargetRaSet && Scope.TargetDecSet) { Common.Sync(Scope.TargetRa, Scope.TargetDec); Scope.TargetDecSet = false; Scope.TargetRaSet = false; } } public double TargetDeclination /* done AR */ { get { return Common.GetTargetDeclination(); } set { Common.SetTargetDeclination(value); } } public double TargetRightAscension /* done AR */ { get { return Common.GetTargetRightAscension(); } set { Common.SetTargetRightAscension(value); } } public bool Tracking /* done AR */ { get { return Scope.isTracking; } set { Common.SetTracking(value); } } public DriveRates TrackingRate /* TODO: check/debug */ { get { return Scope.TrackingRate; } set { Common.SetTrackingRate(value); } } public ITrackingRates TrackingRates /* done AR */ { get { return Scope.TrackingRates; } } public DateTime UTCDate /* done AR */ { get { return Common.GetUtcDate(); } set { Common.SetUtcDate(value); } } public void Unpark() /* TODO: implement */ { throw new ASCOM.MethodNotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ZhAsoiafWiki.Plus.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright 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. using System; using System.Collections.Generic; using System.Linq; using UnityEngine; // Two versions of the PurchaseController class exist in this file, depending on whether USE_IAP is defined // The non-USE_IAP version is stub that sets placeholder prices and simply approves purchases. #if !USE_IAP public class PurchaseController : MonoBehaviour { private void Start() { // Placeholder prices const float currentPrice = 0.01f; const string priceString = "$0.01"; var uiPriceChangeController = FindObjectOfType<UIPriceChangeController>(); if (uiPriceChangeController != null) { foreach (var coin in CoinList.List) { coin.Price = currentPrice; uiPriceChangeController.UpdatePriceTextItem(coin.ProductId, priceString); } foreach (var car in CarList.List) { if (car.IsRealMoneyPurchase) { car.Price = currentPrice; uiPriceChangeController.UpdatePriceTextItem(car.ProductId, priceString); } } foreach (var subscription in SubscriptionList.List) { subscription.Price = currentPrice; uiPriceChangeController.UpdatePriceTextItem(subscription.ProductId, priceString); } } } public static void BuyProductId(string productId) { // Unlock the appropriate content. GameDataController.UnlockInGameContent(productId); } public static void PurchaseASubscription(SubscriptionList.Subscription oldSubscription, SubscriptionList.Subscription newSubscription) { BuyProductId(newSubscription.ProductId); } public static void RestorePurchase() { } } #else using UnityEngine.Purchasing; using UnityEngine.Purchasing.Security; /// <summary> /// Controller for the dollar item purchase flow in the game. /// It uses Unity IAP and the Google Play Billing Library plugin /// to do purchasing, order verification, and order restore. /// </summary> public class PurchaseController : MonoBehaviour, IStoreListener { private static IStoreController _storeController; // The Unity Purchasing system. private static IExtensionProvider _storeExtensionProvider; // The store-specific Purchasing subsystems. private static IGooglePlayStoreExtensions _playStoreExtensions; private static GameManager _gameManager; private static UIPriceChangeController _uiPriceChangeController; private static bool IsInitialized() { // Only say we are initialized if both the Purchasing references are set. return _storeController != null && _storeExtensionProvider != null; } private void Start() { _gameManager = FindObjectOfType<GameManager>(); _uiPriceChangeController = FindObjectOfType<UIPriceChangeController>(); // Check if Unity IAP isn't initialized yet if (_storeController == null) { // Initialize the IAP system InitializePurchasing(); } } private void InitializePurchasing() { // If we have already connected to Purchasing ... if (IsInitialized()) { // ... we are done here. return; } // Create a builder, passing in the Google Play store module var builder = (ConfigurationBuilder.Instance(StandardPurchasingModule.Instance())); var googlePlayConfiguration = builder.Configure<IGooglePlayConfiguration>(); googlePlayConfiguration?.SetObfuscatedAccountId(TrivialKartClientUtil.GetObfuscatedAccountId()); googlePlayConfiguration?.SetDeferredPurchaseListener( delegate(Product product) { ProcessDeferredPurchase(product.definition.id); }); // Add consumable products (coins) associated with their product types to sell / restore by way of its identifier, // associating the general identifier with its store-specific identifiers. foreach (var coin in CoinList.List) { builder.AddProduct(coin.ProductId, ProductType.Consumable); } // Continue adding the non-consumable products (car) with their product types. foreach (var car in CarList.List.Where(car => car.IsRealMoneyPurchase && car.Price > 0)) { builder.AddProduct(car.ProductId, ProductType.NonConsumable); } // Adding subscription products with their product types. foreach (var subscription in SubscriptionList.List.Where(subscription => subscription.Type != SubscriptionType.NoSubscription)) { builder.AddProduct(subscription.ProductId, ProductType.Subscription); } // Launch Unity IAP initialization, which is asynchronous, passing our class instance and the // configuration builder. Results are processed by OnInitialized or OnInitializeFailed. Debug.Log("PurchaseController: Calling UnityPurchasing.Initialize"); UnityPurchasing.Initialize(this, builder); } public static void BuyProductId(string productId) { // If Purchasing has been initialized ... if (IsInitialized()) { // ... look up the Product reference with the general product identifier and the Purchasing // system's products collection. var product = _storeController.products.WithID(productId); // If the look up found a product for this device's store and that product is ready to be sold ... if (product != null && product.availableToPurchase) { // Bring up the 'Purchasing' modal message _gameManager.SetPurchasingMessageActive(true); Debug.Log(string.Format("PurchaseController: Purchasing product asynchronously: '{0}'", product.definition.id)); // ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed // asynchronously. _storeController.InitiatePurchase(product); } // Otherwise ... else { // ... report the product look-up failure situation Debug.Log( "PurchaseController: BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase"); } } // Otherwise ... else { // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or // retrying initialization. Debug.Log("PurchaseController: BuyProductID FAIL. Not initialized."); } } public static void PurchaseASubscription(SubscriptionList.Subscription oldSubscription, SubscriptionList.Subscription newSubscription) { // If the player is subscribe to a new subscription from no subscription, // go through the purchase IAP follow. if (oldSubscription.Type == SubscriptionType.NoSubscription) { BuyProductId(newSubscription.ProductId); } // If the player wants to update or downgrade the subscription, // use the upgrade and downgrade flow. else { _playStoreExtensions.UpgradeDowngradeSubscription(oldSubscription.ProductId, newSubscription.ProductId); } } public void OnInitialized(IStoreController controller, IExtensionProvider extensions) { // Purchasing has succeeded initializing. Collect our Purchasing references. Debug.Log("PurchaseController: OnInitialized success"); // Overall Purchasing system, configured with products for this application. _storeController = controller; // Store specific subsystem, for accessing device-specific store features. _storeExtensionProvider = extensions; // Retrieve the current item prices from the store UpdateItemPrices(); // Set play store extensions. _playStoreExtensions = _storeExtensionProvider.GetExtension<IGooglePlayStoreExtensions>(); CheckSubscriptionsAvailabilityBasedOnReceipt(controller); } public void OnInitializeFailed(InitializationFailureReason error) { // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user. Debug.Log("PurchaseController: OnInitializeFailed InitializationFailureReason:" + error); } private void UpdateItemPrices() { Debug.Log("PurchaseController: UpdateItemPrices"); // This is a very basic loop through all the items, updating the // default price information with the current localized price // supplied by the store. foreach (var product in _storeController.products.all) { float currentPrice = Convert.ToSingle(product.metadata.localizedPrice); string productId = product.definition.storeSpecificId; string localizedPriceString = product.metadata.localizedPriceString; bool foundItem = false; foreach (var coin in CoinList.List.Where(coin => string.Equals(productId, coin.ProductId, StringComparison.Ordinal))) { Debug.Log($"Updated price for Product: '{productId}', New Price: {currentPrice}"); coin.Price = currentPrice; foundItem = true; break; } if (!foundItem) { foreach (var car in CarList.List.Where(car => string.Equals(productId, car.ProductId, StringComparison.Ordinal))) { Debug.Log($"Updated price for Product: '{productId}', New Price: {currentPrice}"); car.Price = currentPrice; foundItem = true; break; } } if (!foundItem) { foreach (var subscription in SubscriptionList.List.Where(subscription => string.Equals(productId, subscription.ProductId, StringComparison.Ordinal))) { Debug.Log($"Updated price for Product: '{productId}', New Price: {currentPrice}"); subscription.Price = currentPrice; foundItem = true; break; } } // If we found the item, update the UI text element that actually displays // the price information for the current item if (foundItem) { _uiPriceChangeController.UpdatePriceTextItem(productId, localizedPriceString); } } } private static void CheckSubscriptionsAvailabilityBasedOnReceipt(IStoreController controller) { var silverSubscriptionProduct = controller.products.WithID(SubscriptionList.SilverSubscription.ProductId); var goldenSubscriptionProduct = controller.products.WithID(SubscriptionList.GoldenSubscription.ProductId); if (!(silverSubscriptionProduct.hasReceipt && ClientSideReceiptValidation(silverSubscriptionProduct.receipt)) && !(goldenSubscriptionProduct.hasReceipt && ClientSideReceiptValidation(goldenSubscriptionProduct.receipt))) { GameDataController.GetGameData().UpdateSubscription(SubscriptionList.NoSubscription); Debug.Log("PurchaseController: No subscription receipt found. Unsubscribe all subscriptions"); } } private static void ProcessDeferredPurchase(string productId) { // Check if a consumable (coins) has been deferred purchased by this user. foreach (var coin in CoinList.List.Where(coin => string.Equals(productId, coin.ProductId, StringComparison.Ordinal))) { CoinStorePageController.SetDeferredPurchaseReminderStatus(coin, true); return; } // Check if a non-consumable (car) has been deferred purchased by this user. foreach (var car in CarList.List.Where(car => string.Equals(productId, car.ProductId, StringComparison.Ordinal))) { CarStorePageController.SetDeferredPurchaseReminderStatus(car, true); return; } Debug.LogError("PurchaseController: Product ID doesn't match any of exist one-time products that can be deferred purchase."); } public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) { Debug.Log($"PurchaseController: ProcessPurchase: PASS. Product: '{args.purchasedProduct.definition.id}'"); if (args.purchasedProduct.hasReceipt) { Debug.Log($"PurchaseController: ProcessPurchase: Receipt: '{args.purchasedProduct.receipt}'"); } else { Debug.Log("PurchaseController: ProcessPurchase: No receipt"); } #if USE_SERVER Debug.Log("Calling VerifyAndSaveUserPurchase"); NetworkRequestController.VerifyAndSaveUserPurchase(args.purchasedProduct); // Make sure the 'Purchasing' modal message is dismissed _gameManager.SetPurchasingMessageActive(false); return PurchaseProcessingResult.Pending; #else if (ClientSideReceiptValidation(args.purchasedProduct.receipt)) { // Unlock the appropriate content. GameDataController.UnlockInGameContent(args.purchasedProduct.definition.id); } // Make sure the 'Purchasing' modal message is dismissed _gameManager.SetPurchasingMessageActive(false); // Return a flag indicating whether this product has completely been received, or if the application needs // to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still // saving purchased products to the cloud, and when that save is delayed. return PurchaseProcessingResult.Complete; #endif } public static void ConfirmPendingPurchase(Product product, bool purchaseVerifiedSuccess) { if (purchaseVerifiedSuccess) { GameDataController.UnlockInGameContent(product.definition.id); } _storeController.ConfirmPendingPurchase(product); } private static bool ClientSideReceiptValidation(string unityIapReceipt) { bool validPurchase = true; #if UNITY_ANDROID // Prepare the validator with the secrets we prepared in the Editor // obfuscation window. var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier); try { // Validate the signature of the receipt with unity cross platform validator var result = validator.Validate(unityIapReceipt); // Validate the obfuscated account id of the receipt. ObfuscatedAccountIdValidation(unityIapReceipt); // For informational purposes, we list the receipt(s). Debug.Log("Receipt is valid. Contents:"); foreach (IPurchaseReceipt productReceipt in result) { Debug.Log(productReceipt.productID); Debug.Log(productReceipt.purchaseDate); Debug.Log(productReceipt.transactionID); } } catch (IAPSecurityException) { Debug.Log("PurchaseController: Invalid receipt, not unlocking content"); validPurchase = false; } #endif return validPurchase; } // Check if the obfuscated account id on the receipt is same as the one on the device. private static void ObfuscatedAccountIdValidation(string unityIapReceipt) { Dictionary<string, object> unityIapReceiptDictionary = (Dictionary<string, object>) MiniJson.JsonDecode(unityIapReceipt); string payload = (string) unityIapReceiptDictionary["Payload"]; Dictionary<string, object> payLoadDictionary = (Dictionary<string, object>) MiniJson.JsonDecode(payload); string receipt = (string) payLoadDictionary["json"]; Dictionary<string, object> receiptDictionary = (Dictionary<string, object>) MiniJson.JsonDecode(receipt); if (!receiptDictionary.ContainsKey("obfuscatedAccountId") || !receiptDictionary["obfuscatedAccountId"].Equals(TrivialKartClientUtil.GetObfuscatedAccountId())) { Debug.Log("PurchaseController: Obfuscated account id is invalid"); throw new IAPSecurityException(); } } public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) { // Make sure the 'Purchasing' modal message is dismissed _gameManager.SetPurchasingMessageActive(false); // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing // this reason with the user to guide their troubleshooting actions. Debug.Log( $"PurchaseController: OnPurchaseFailed: FAIL. Product: '{product.definition.storeSpecificId}', PurchaseFailureReason: {failureReason}"); // If the purchase failed with a duplicate transaction response, and the item is not shown in client side, // do a restore purchase to fetch the product. // This situation can occur when the user loses internet connectivity after sending the purchase. if (failureReason == PurchaseFailureReason.DuplicateTransaction) { _playStoreExtensions.RestoreTransactions(null); } } public static void ConfirmSubscriptionPriceChange(string productId) { _playStoreExtensions.ConfirmSubscriptionPriceChange(productId, delegate(bool priceChangeSuccess) { if (priceChangeSuccess) { // Here you can choose to make an update or record that the user accpected the new price Debug.Log("PurchaseController: The user accepted the price change"); } else { Debug.Log("PurchaseController: The user did not accept the price change"); } } ); } // Restore purchase when the user login to a new device. public static void RestorePurchase() { _playStoreExtensions.RestoreTransactions( delegate(bool restoreSuccess) { var garageController = FindObjectOfType<GarageController>(); if (restoreSuccess) { Debug.Log("PurchaseController: Successfully restored purchase!"); garageController.OnRestorePurchaseSuccess(); } else { Debug.Log("PurchaseController: Failed to restore purchase"); garageController.OnRestorePurchaseFail(); } }); } } #endif // !NO_IAP
namespace Fixtures.Azure.SwaggerBatPaging { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Newtonsoft.Json; using Microsoft.Azure; using Models; internal partial class PagingOperations : IServiceOperations<AutoRestPagingTestService>, IPagingOperations { /// <summary> /// Initializes a new instance of the PagingOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PagingOperations(AutoRestPagingTestService client) { this.Client = client; } /// <summary> /// Gets a reference to the AutoRestPagingTestService /// </summary> public AutoRestPagingTestService Client { get; private set; } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetSinglePagesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetSinglePages", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/single"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePages", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/multiple"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesRetryFirst", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/multiple/retryfirst"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesRetrySecond", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/multiple/retrysecond"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetSinglePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetSinglePagesFailure", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/single/failure"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesFailure", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/multiple/failure"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesFailureUriWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesFailureUri", tracingParameters); } // Construct URL string url = this.Client.BaseUri.AbsoluteUri + "//paging/multiple/failureuri"; List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetSinglePagesNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetSinglePagesNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesRetryFirstNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesRetrySecondNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetSinglePagesFailureNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesFailureNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task<AzureOperationResponse<ProductResult>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetMultiplePagesFailureUriNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // trim all duplicate forward slashes in the url url = Regex.Replace(url, "([^:]/)/+", "$1"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { httpRequest.Headers.Add(header.Key, header.Value); } } // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ProductResult>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ProductResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tasks.Tests { public static class CancellationTokenTests { [Fact] public static void CancellationTokenRegister_Exceptions() { CancellationToken token = new CancellationToken(); Assert.Throws<ArgumentNullException>(() => token.Register(null)); Assert.Throws<ArgumentNullException>(() => token.Register(null, false)); Assert.Throws<ArgumentNullException>(() => token.Register(null, null)); } [Fact] public static void CancellationTokenEquality() { //simple empty token comparisons Assert.Equal(new CancellationToken(), new CancellationToken()); //inflated empty token comparisons CancellationToken inflated_empty_CT1 = new CancellationToken(); bool temp1 = inflated_empty_CT1.CanBeCanceled; // inflate the CT CancellationToken inflated_empty_CT2 = new CancellationToken(); bool temp2 = inflated_empty_CT2.CanBeCanceled; // inflate the CT Assert.Equal(inflated_empty_CT1, new CancellationToken()); Assert.Equal(new CancellationToken(), inflated_empty_CT1); Assert.Equal(inflated_empty_CT1, inflated_empty_CT2); // inflated pre-set token comparisons CancellationToken inflated_defaultSet_CT1 = new CancellationToken(true); bool temp3 = inflated_defaultSet_CT1.CanBeCanceled; // inflate the CT CancellationToken inflated_defaultSet_CT2 = new CancellationToken(true); bool temp4 = inflated_defaultSet_CT2.CanBeCanceled; // inflate the CT Assert.Equal(inflated_defaultSet_CT1, new CancellationToken(true)); Assert.Equal(inflated_defaultSet_CT1, inflated_defaultSet_CT2); // Things that are not equal Assert.NotEqual(inflated_empty_CT1, inflated_defaultSet_CT2); Assert.NotEqual(inflated_empty_CT1, new CancellationToken(true)); Assert.NotEqual(new CancellationToken(true), inflated_empty_CT1); } [Fact] public static void CancellationToken_GetHashCode() { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; int hash1 = cts.GetHashCode(); int hash2 = cts.Token.GetHashCode(); int hash3 = ct.GetHashCode(); Assert.Equal(hash1, hash2); Assert.Equal(hash2, hash3); CancellationToken defaultUnsetToken1 = new CancellationToken(); CancellationToken defaultUnsetToken2 = new CancellationToken(); int hashDefaultUnset1 = defaultUnsetToken1.GetHashCode(); int hashDefaultUnset2 = defaultUnsetToken2.GetHashCode(); Assert.Equal(hashDefaultUnset1, hashDefaultUnset2); CancellationToken defaultSetToken1 = new CancellationToken(true); CancellationToken defaultSetToken2 = new CancellationToken(true); int hashDefaultSet1 = defaultSetToken1.GetHashCode(); int hashDefaultSet2 = defaultSetToken2.GetHashCode(); Assert.Equal(hashDefaultSet1, hashDefaultSet2); Assert.NotEqual(hash1, hashDefaultUnset1); Assert.NotEqual(hash1, hashDefaultSet1); Assert.NotEqual(hashDefaultUnset1, hashDefaultSet1); } [Fact] public static void CancellationToken_EqualityAndDispose() { //hashcode. Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); cts.Token.GetHashCode(); }); //x.Equals(y) Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); cts.Token.Equals(new CancellationToken()); }); //x.Equals(y) Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); new CancellationToken().Equals(cts.Token); }); //x==y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = cts.Token == new CancellationToken(); }); //x==y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = new CancellationToken() == cts.Token; }); //x!=y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = cts.Token != new CancellationToken(); }); //x!=y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = new CancellationToken() != cts.Token; }); } [Fact] public static void TokenSourceDispose() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationTokenRegistration preDisposeRegistration = token.Register(() => { }); //WaitHandle and Dispose WaitHandle wh = token.WaitHandle; //ok Assert.NotNull(wh); tokenSource.Dispose(); // Regression test: allow ctr.Dispose() to succeed when the backing cts has already been disposed. try { preDisposeRegistration.Dispose(); } catch { Assert.True(false, string.Format("TokenSourceDispose: > ctr.Dispose() failed when referring to a disposed CTS")); } bool cr = tokenSource.IsCancellationRequested; //this is ok after dispose. tokenSource.Dispose(); //Repeat calls to Dispose should be ok. } /// <summary> /// Test passive signalling. /// /// Gets a token, then polls on its ThrowIfCancellationRequested property. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenPassiveListening() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Assert.False(token.IsCancellationRequested, "CancellationTokenPassiveListening: Cancellation should not have occurred yet."); tokenSource.Cancel(); Assert.True(token.IsCancellationRequested, "CancellationTokenPassiveListening: Cancellation should now have occurred."); } /// <summary> /// Test active signalling. /// /// Gets a token, registers a notification callback and ensure it is called. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenActiveListening() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; bool signalReceived = false; token.Register(() => signalReceived = true); Assert.False(signalReceived, "CancellationTokenActiveListening: Cancellation should not have occurred yet."); tokenSource.Cancel(); Assert.True(signalReceived, "CancellationTokenActiveListening: Cancellation should now have occurred and caused a signal."); } private static event EventHandler AddAndRemoveDelegates_TestEvent; [Fact] public static void AddAndRemoveDelegates() { //Test various properties of callbacks: // 1. the same handler can be added multiple times // 2. removing a handler only removes one instance of a repeat // 3. after some add and removes, everything appears to be correct // 4. The behaviour matches the behaviour of a regular Event(Multicast-delegate). CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; List<string> output = new List<string>(); Action action1 = () => output.Add("action1"); Action action2 = () => output.Add("action2"); CancellationTokenRegistration reg1 = token.Register(action1); CancellationTokenRegistration reg2 = token.Register(action2); CancellationTokenRegistration reg3 = token.Register(action2); CancellationTokenRegistration reg4 = token.Register(action1); reg2.Dispose(); reg3.Dispose(); reg4.Dispose(); tokenSource.Cancel(); Assert.Equal(1, output.Count); Assert.Equal("action1", output[0]); // and prove this is what normal events do... output.Clear(); EventHandler handler1 = (sender, obj) => output.Add("handler1"); EventHandler handler2 = (sender, obj) => output.Add("handler2"); AddAndRemoveDelegates_TestEvent += handler1; AddAndRemoveDelegates_TestEvent += handler2; AddAndRemoveDelegates_TestEvent += handler2; AddAndRemoveDelegates_TestEvent += handler1; AddAndRemoveDelegates_TestEvent -= handler2; AddAndRemoveDelegates_TestEvent -= handler2; AddAndRemoveDelegates_TestEvent -= handler1; AddAndRemoveDelegates_TestEvent(null, EventArgs.Empty); Assert.Equal(1, output.Count); Assert.Equal("handler1", output[0]); } /// <summary> /// Test late enlistment. /// /// If a handler is added to a 'canceled' cancellation token, the handler is called immediately. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenLateEnlistment() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; bool signalReceived = false; tokenSource.Cancel(); //Signal //Late enlist.. should fire the delegate synchronously token.Register(() => signalReceived = true); Assert.True(signalReceived, "CancellationTokenLateEnlistment: The signal should have been received even after late enlistment."); } /// <summary> /// Test the wait handle exposed by the cancellation token /// /// The signal occurs on a separate thread, and should happen after the wait begins. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenWaitHandle_SignalAfterWait() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task.Run( () => { tokenSource.Cancel(); //Signal }); token.WaitHandle.WaitOne(); Assert.True(token.IsCancellationRequested, "CancellationTokenWaitHandle_SignalAfterWait: the token should have been canceled."); } /// <summary> /// Test the wait handle exposed by the cancellation token /// /// The signal occurs on a separate thread, and should happen after the wait begins. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenWaitHandle_SignalBeforeWait() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; tokenSource.Cancel(); token.WaitHandle.WaitOne(); // the wait handle should already be set. Assert.True(token.IsCancellationRequested, "CancellationTokenWaitHandle_SignalBeforeWait: the token should have been canceled."); } /// <summary> /// Test that WaitAny can be used with a CancellationToken.WaitHandle /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenWaitHandle_WaitAny() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationToken tokenNoSource = new CancellationToken(); tokenSource.Cancel(); WaitHandle.WaitAny(new[] { token.WaitHandle, tokenNoSource.WaitHandle }); //make sure the dummy tokens has a valid WaitHanle Assert.True(token.IsCancellationRequested, "CancellationTokenWaitHandle_WaitAny: The token should have been canceled."); } [Fact] public static void CreateLinkedTokenSource_Simple_TwoToken() { CancellationTokenSource signal1 = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); //Neither token is signalled. CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token); Assert.False(combined.IsCancellationRequested, "CreateLinkedToken_Simple_TwoToken: The combined token should start unsignalled"); signal1.Cancel(); Assert.True(combined.IsCancellationRequested, "CreateLinkedToken_Simple_TwoToken: The combined token should now be signalled"); } [Fact] public static void CreateLinkedTokenSource_Simple_MultiToken() { CancellationTokenSource signal1 = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); CancellationTokenSource signal3 = new CancellationTokenSource(); //Neither token is signalled. CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(new[] { signal1.Token, signal2.Token, signal3.Token }); Assert.False(combined.IsCancellationRequested, "CreateLinkedToken_Simple_MultiToken: The combined token should start unsignalled"); signal1.Cancel(); Assert.True(combined.IsCancellationRequested, "CreateLinkedToken_Simple_MultiToken: The combined token should now be signalled"); } [Fact] public static void CreateLinkedToken_SourceTokenAlreadySignalled() { //creating a combined token, when a source token is already signalled. CancellationTokenSource signal1 = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); signal1.Cancel(); //early signal. CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token); Assert.True(combined.IsCancellationRequested, "CreateLinkedToken_SourceTokenAlreadySignalled: The combined token should immediately be in the signalled state."); } [Fact] public static void CreateLinkedToken_MultistepComposition_SourceTokenAlreadySignalled() { //two-step composition CancellationTokenSource signal1 = new CancellationTokenSource(); signal1.Cancel(); //early signal. CancellationTokenSource signal2 = new CancellationTokenSource(); CancellationTokenSource combined1 = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token); CancellationTokenSource signal3 = new CancellationTokenSource(); CancellationTokenSource combined2 = CancellationTokenSource.CreateLinkedTokenSource(signal3.Token, combined1.Token); Assert.True(combined2.IsCancellationRequested, "CreateLinkedToken_MultistepComposition_SourceTokenAlreadySignalled: The 2-step combined token should immediately be in the signalled state."); } [Fact] public static void CallbacksOrderIsLifo() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; List<string> callbackOutput = new List<string>(); token.Register(() => callbackOutput.Add("Callback1")); token.Register(() => callbackOutput.Add("Callback2")); tokenSource.Cancel(); Assert.Equal("Callback2", callbackOutput[0]); Assert.Equal("Callback1", callbackOutput[1]); } [Fact] public static void Enlist_EarlyAndLate() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationTokenSource earlyEnlistedTokenSource = new CancellationTokenSource(); token.Register(() => earlyEnlistedTokenSource.Cancel()); tokenSource.Cancel(); Assert.Equal(true, earlyEnlistedTokenSource.IsCancellationRequested); CancellationTokenSource lateEnlistedTokenSource = new CancellationTokenSource(); token.Register(() => lateEnlistedTokenSource.Cancel()); Assert.Equal(true, lateEnlistedTokenSource.IsCancellationRequested); } /// <summary> /// This test from donnya. Thanks Donny. /// </summary> /// <returns></returns> [Fact] public static void WaitAll() { Debug.WriteLine("WaitAll: Testing CancellationTokenTests.WaitAll, If Join does not work, then a deadlock will occur."); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); ManualResetEvent mre = new ManualResetEvent(false); ManualResetEvent mre2 = new ManualResetEvent(false); Task t = new Task(() => { WaitHandle.WaitAll(new WaitHandle[] { tokenSource.Token.WaitHandle, signal2.Token.WaitHandle, mre }); mre2.Set(); }); t.Start(); tokenSource.Cancel(); signal2.Cancel(); mre.Set(); mre2.WaitOne(); t.Wait(); //true if the Join succeeds.. otherwise a deadlock will occur. } [Fact] public static void BehaviourAfterCancelSignalled() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; token.Register(() => { }); tokenSource.Cancel(); } [Fact] public static void Cancel_ThrowOnFirstException() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Main test body ArgumentException caughtException = null; token.Register(() => { throw new InvalidOperationException(); }); token.Register(() => { throw new ArgumentException(); }); // !!NOTE: Due to LIFO ordering, this delegate should be the only one to run. Task.Run(() => { try { tokenSource.Cancel(true); } catch (ArgumentException ex) { caughtException = ex; } catch (Exception ex) { Assert.True(false, string.Format("Cancel_ThrowOnFirstException: The wrong exception type was thrown. ex=" + ex)); } mre_CancelHasBeenEnacted.Set(); }); mre_CancelHasBeenEnacted.WaitOne(); Assert.NotNull(caughtException); } [Fact] public static void Cancel_DontThrowOnFirstException() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Main test body AggregateException caughtException = null; token.Register(() => { throw new ArgumentException(); }); token.Register(() => { throw new InvalidOperationException(); }); Task.Run( () => { try { tokenSource.Cancel(false); } catch (AggregateException ex) { caughtException = ex; } mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.NotNull(caughtException); Assert.Equal(2, caughtException.InnerExceptions.Count); Assert.True(caughtException.InnerExceptions[0] is InvalidOperationException, "Cancel_ThrowOnFirstException: Due to LIFO call order, the first inner exception should be an InvalidOperationException."); Assert.True(caughtException.InnerExceptions[1] is ArgumentException, "Cancel_ThrowOnFirstException: Due to LIFO call order, the second inner exception should be an ArgumentException."); } [Fact] public static void CancellationRegistration_RepeatDispose() { Exception caughtException = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; CancellationTokenRegistration registration = ct.Register(() => { }); try { registration.Dispose(); registration.Dispose(); } catch (Exception ex) { caughtException = ex; } Assert.Null(caughtException); } [Fact] public static void CancellationTokenRegistration_EqualityAndHashCode() { CancellationTokenSource outerCTS = new CancellationTokenSource(); { // different registrations on 'different' default tokens CancellationToken ct1 = new CancellationToken(); CancellationToken ct2 = new CancellationToken(); CancellationTokenRegistration ctr1 = ct1.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = ct2.Register(() => outerCTS.Cancel()); Assert.True(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: [1]The two registrations should compare equal, as they are both dummies."); Assert.True(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [2]The two registrations should compare equal, as they are both dummies."); Assert.False(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [3]The two registrations should compare equal, as they are both dummies."); Assert.True(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: [4]The two registrations should have the same hashcode, as they are both dummies."); } { // different registrations on the same already cancelled token CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); CancellationToken ct = cts.Token; CancellationTokenRegistration ctr1 = ct.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = ct.Register(() => outerCTS.Cancel()); Assert.True(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: [1]The two registrations should compare equal, as they are both dummies due to CTS being already canceled."); Assert.True(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [2]The two registrations should compare equal, as they are both dummies due to CTS being already canceled."); Assert.False(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [3]The two registrations should compare equal, as they are both dummies due to CTS being already canceled."); Assert.True(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: [4]The two registrations should have the same hashcode, as they are both dummies due to CTS being already canceled."); } { // different registrations on one real token CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationTokenRegistration ctr1 = cts1.Token.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = cts1.Token.Register(() => outerCTS.Cancel()); Assert.False(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.True(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not have the same hashcode."); CancellationTokenRegistration ctr1copy = ctr1; Assert.True(ctr1 == ctr1copy, "The two registrations should be equal."); } { // registrations on different real tokens. // different registrations on one token CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationTokenSource cts2 = new CancellationTokenSource(); CancellationTokenRegistration ctr1 = cts1.Token.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = cts2.Token.Register(() => outerCTS.Cancel()); Assert.False(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.True(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not have the same hashcode."); CancellationTokenRegistration ctr1copy = ctr1; Assert.True(ctr1.Equals(ctr1copy), "The two registrations should be equal."); } } [Fact] public static void CancellationTokenLinking_ODEinTarget() { CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationTokenSource cts2 = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, new CancellationToken()); Exception caughtException = null; cts2.Token.Register(() => { throw new ObjectDisposedException("myException"); }); try { cts1.Cancel(true); } catch (Exception ex) { caughtException = ex; } Assert.True( caughtException is AggregateException && caughtException.InnerException is ObjectDisposedException && caughtException.InnerException.Message.Contains("myException"), "CancellationTokenLinking_ODEinTarget: The users ODE should be caught. Actual:" + caughtException); } [Fact] public static void ThrowIfCancellationRequested() { OperationCanceledException caughtEx = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; ct.ThrowIfCancellationRequested(); // no exception should occur cts.Cancel(); try { ct.ThrowIfCancellationRequested(); } catch (OperationCanceledException oce) { caughtEx = oce; } Assert.NotNull(caughtEx); Assert.Equal(ct, caughtEx.CancellationToken); } /// <summary> /// ensure that calling ctr.Dipose() from within a cancellation callback will not deadlock. /// </summary> /// <returns></returns> [Fact] public static void DeregisterFromWithinACallbackIsSafe_BasicTest() { Debug.WriteLine("CancellationTokenTests.Bug720327_DeregisterFromWithinACallbackIsSafe_BasicTest()"); Debug.WriteLine(" - this method should complete immediately. Delay to complete indicates a deadlock failure."); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; CancellationTokenRegistration ctr1 = ct.Register(() => { }); ct.Register(() => { ctr1.Dispose(); }); cts.Cancel(); Debug.WriteLine(" - Completed OK."); } // regression test // Disposing a linkedCTS would previously throw if a source CTS had been // disposed already. (it is an error for a user to get in this situation, but we decided to allow it to work). [Fact] public static void ODEWhenDisposingLinkedCTS() { try { // User passes a cancellation token (CT) to component A. CancellationTokenSource userTokenSource = new CancellationTokenSource(); CancellationToken userToken = userTokenSource.Token; // Component A implements "timeout", by creating its own cancellation token source (CTS) and invoking cts.Cancel() when the timeout timer fires. CancellationTokenSource cts2 = new CancellationTokenSource(); CancellationToken cts2Token = cts2.Token; // Component A creates a linked token source representing the CT from the user and the "timeout" CT. var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts2Token, userToken); // User calls Cancel() on his CTS and then Dispose() userTokenSource.Cancel(); userTokenSource.Dispose(); // Component B correctly cancels the operation, returns to component A. // ... // Component A now disposes the linked CTS => ObjectDisposedException is thrown by cts.Dispose() because the user CTS was already disposed. linkedTokenSource.Dispose(); } catch (Exception ex) { if (ex is ObjectDisposedException) { Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - ODE Occurred!")); } else { Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - Exception Occurred (not an ODE!!): " + ex)); } } } // Several tests for deriving custom user types from CancellationTokenSource [Fact] public static void DerivedCancellationTokenSource() { // Verify that a derived CTS is functional { CancellationTokenSource c = new DerivedCTS(null); CancellationToken token = c.Token; var task = Task.Factory.StartNew(() => c.Cancel()); task.Wait(); Assert.True(token.IsCancellationRequested, "DerivedCancellationTokenSource: The token should have been cancelled."); } // Verify that callback list on a derived CTS is functional { CancellationTokenSource c = new DerivedCTS(null); CancellationToken token = c.Token; int callbackRan = 0; token.Register(() => Interlocked.Increment(ref callbackRan)); var task = Task.Factory.StartNew(() => c.Cancel()); task.Wait(); SpinWait.SpinUntil(() => callbackRan > 0, 1000); Assert.True(callbackRan == 1, "DerivedCancellationTokenSource: Expected the callback to run once. Instead, it ran " + callbackRan + " times."); } // Test the Dispose path for a class derived from CancellationTokenSource { var disposeTracker = new DisposeTracker(); CancellationTokenSource c = new DerivedCTS(disposeTracker); Assert.True(c.Token.CanBeCanceled, "DerivedCancellationTokenSource: The token should be cancellable."); c.Dispose(); // Dispose() should have prevented the finalizer from running. Give the finalizer a chance to run. If this // results in Dispose(false) getting called, we'll catch the issue. GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(disposeTracker.DisposeTrueCalled, "DerivedCancellationTokenSource: Dispose(true) should have been called."); Assert.False(disposeTracker.DisposeFalseCalled, "DerivedCancellationTokenSource: Dispose(false) should not have been called."); } // Test the finalization code path for a class derived from CancellationTokenSource { var disposeTracker = new DisposeTracker(); // Since the object is not assigned into a variable, it can be GC'd before the current method terminates. // (This is only an issue in the Debug build) new DerivedCTS(disposeTracker); // Wait until the DerivedCTS object is finalized SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return disposeTracker.DisposeTrueCalled; }, 500); Assert.False(disposeTracker.DisposeTrueCalled, "DerivedCancellationTokenSource: Dispose(true) should not have been called."); Assert.True(disposeTracker.DisposeFalseCalled, "DerivedCancellationTokenSource: Dispose(false) should have been called."); } // Verify that Dispose(false) is a no-op on the CTS. Dispose(false) should only release any unmanaged resources, and // CTS does not currently hold any unmanaged resources. { var disposeTracker = new DisposeTracker(); DerivedCTS c = new DerivedCTS(disposeTracker); c.DisposeUnmanaged(); // No exception expected - the CancellationTokenSource should be valid Assert.True(c.Token.CanBeCanceled, "DerivedCancellationTokenSource: The token should still be cancellable."); Assert.False(disposeTracker.DisposeTrueCalled, "DerivedCancellationTokenSource: Dispose(true) should not have been called."); Assert.True(disposeTracker.DisposeFalseCalled, "DerivedCancellationTokenSource: Dispose(false) should have run."); } } // Several tests for deriving custom user types from CancellationTokenSource [Fact] public static void DerivedCancellationTokenSource_Negative() { // Test the Dispose path for a class derived from CancellationTokenSource { var disposeTracker = new DisposeTracker(); CancellationTokenSource c = new DerivedCTS(disposeTracker); c.Dispose(); // Dispose() should have prevented the finalizer from running. Give the finalizer a chance to run. If this // results in Dispose(false) getting called, we'll catch the issue. GC.Collect(); GC.WaitForPendingFinalizers(); Assert.Throws<ObjectDisposedException>( () => { // Accessing the Token property should throw an ObjectDisposedException if (c.Token.CanBeCanceled) Assert.True(false, string.Format("DerivedCancellationTokenSource: Accessing the Token property should throw an ObjectDisposedException, but it did not.")); else Assert.True(false, string.Format("DerivedCancellationTokenSource: Accessing the Token property should throw an ObjectDisposedException, but it did not.")); }); } } [Fact] public static void CancellationTokenSourceWithTimer() { TimeSpan bigTimeSpan = new TimeSpan(2000, 0, 0, 0, 0); TimeSpan reasonableTimeSpan = new TimeSpan(0, 0, 1); CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); // // Test out some int-based timeout logic // cts = new CancellationTokenSource(-1); // should be an infinite timeout CancellationToken token = cts.Token; ManualResetEventSlim mres = new ManualResetEventSlim(false); CancellationTokenRegistration ctr = token.Register(() => mres.Set()); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on infinite timeout (int)!"); cts.CancelAfter(1000000); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (int) !"); cts.CancelAfter(1); Debug.WriteLine("CancellationTokenSourceWithTimer: > About to wait on cancellation that should occur soon (int)... if we hang, something bad happened"); mres.Wait(); cts.Dispose(); // // Test out some TimeSpan-based timeout logic // TimeSpan prettyLong = new TimeSpan(1, 0, 0); cts = new CancellationTokenSource(prettyLong); token = cts.Token; mres = new ManualResetEventSlim(false); ctr = token.Register(() => mres.Set()); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (TimeSpan,1)!"); cts.CancelAfter(prettyLong); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (TimeSpan,2) !"); cts.CancelAfter(new TimeSpan(1000)); Debug.WriteLine("CancellationTokenSourceWithTimer: > About to wait on cancellation that should occur soon (TimeSpan)... if we hang, something bad happened"); mres.Wait(); cts.Dispose(); } [Fact] public static void CancellationTokenSourceWithTimer_Negative() { TimeSpan bigTimeSpan = new TimeSpan(2000, 0, 0, 0, 0); TimeSpan reasonableTimeSpan = new TimeSpan(0, 0, 1); // // Test exception logic // Assert.Throws<ArgumentOutOfRangeException>( () => { new CancellationTokenSource(-2); }); Assert.Throws<ArgumentOutOfRangeException>( () => { new CancellationTokenSource(bigTimeSpan); }); CancellationTokenSource cts = new CancellationTokenSource(); Assert.Throws<ArgumentOutOfRangeException>( () => { cts.CancelAfter(-2); }); Assert.Throws<ArgumentOutOfRangeException>( () => { cts.CancelAfter(bigTimeSpan); }); cts.Dispose(); Assert.Throws<ObjectDisposedException>( () => { cts.CancelAfter(1); }); Assert.Throws<ObjectDisposedException>( () => { cts.CancelAfter(reasonableTimeSpan); }); } [Fact] public static void EnlistWithSyncContext_BeforeCancel() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Install a SynchronizationContext... SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; TestingSynchronizationContext testContext = new TestingSynchronizationContext(); SetSynchronizationContext(testContext); // Main test body // register a null delegate, but use the currently registered syncContext. // the testSyncContext will track that it was used when the delegate is invoked. token.Register(() => { }, true); Task.Run( () => { tokenSource.Cancel(); mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.True(testContext.DidSendOccur, "EnlistWithSyncContext_BeforeCancel: the delegate should have been called via Send to SyncContext."); //Cleanup. SetSynchronizationContext(prevailingSyncCtx); } [Fact] public static void EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Install a SynchronizationContext... SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; TestingSynchronizationContext testContext = new TestingSynchronizationContext(); SetSynchronizationContext(testContext); // Main test body AggregateException caughtException = null; // register a null delegate, but use the currently registered syncContext. // the testSyncContext will track that it was used when the delegate is invoked. token.Register(() => { throw new ArgumentException(); }, true); Task.Run( () => { try { tokenSource.Cancel(); } catch (AggregateException ex) { caughtException = ex; } mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.True(testContext.DidSendOccur, "EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate: the delegate should have been called via Send to SyncContext."); Assert.NotNull(caughtException); Assert.Equal(1, caughtException.InnerExceptions.Count); Assert.True(caughtException.InnerExceptions[0] is ArgumentException, "EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate: The inner exception should be an ArgumentException."); //Cleanup. SetSynchronizationContext(prevailingSyncCtx); } [Fact] public static void EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate_ThrowOnFirst() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Install a SynchronizationContext... SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; TestingSynchronizationContext testContext = new TestingSynchronizationContext(); SetSynchronizationContext(testContext); // Main test body ArgumentException caughtException = null; // register a null delegate, but use the currently registered syncContext. // the testSyncContext will track that it was used when the delegate is invoked. token.Register(() => { throw new ArgumentException(); }, true); Task.Run( () => { try { tokenSource.Cancel(true); } catch (ArgumentException ex) { caughtException = ex; } mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.True(testContext.DidSendOccur, "EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate_ThrowOnFirst: the delegate should have been called via Send to SyncContext."); Assert.NotNull(caughtException); //Cleanup SetSynchronizationContext(prevailingSyncCtx); } // Test that we marshal exceptions back if we run callbacks on a sync context. // (This assumes that a syncContext.Send() may not be doing the marshalling itself). [Fact] public static void SyncContextWithExceptionThrowingCallback() { Exception caughtEx1 = null; AggregateException caughtEx2 = null; SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; SetSynchronizationContext(new ThreadCrossingSynchronizationContext()); // -- Test 1 -- // CancellationTokenSource cts = new CancellationTokenSource(); cts.Token.Register( () => { throw new Exception("testEx1"); }, true); try { cts.Cancel(true); //throw on first exception } catch (Exception ex) { caughtEx1 = (AggregateException)ex; } Assert.NotNull(caughtEx1); // -- Test 2 -- // cts = new CancellationTokenSource(); cts.Token.Register( () => { throw new ArgumentException("testEx2"); }, true); try { cts.Cancel(false); //do not throw on first exception } catch (AggregateException ex) { caughtEx2 = (AggregateException)ex; } Assert.NotNull(caughtEx2); Assert.Equal(1, caughtEx2.InnerExceptions.Count); // clean up SetSynchronizationContext(prevailingSyncCtx); } [Fact] public static void Bug720327_DeregisterFromWithinACallbackIsSafe_SyncContextTest() { Debug.WriteLine("* CancellationTokenTests.Bug720327_DeregisterFromWithinACallbackIsSafe_SyncContextTest()"); Debug.WriteLine(" - this method should complete immediately. Delay to complete indicates a deadlock failure."); //Install our syncContext. SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; ThreadCrossingSynchronizationContext threadCrossingSyncCtx = new ThreadCrossingSynchronizationContext(); SetSynchronizationContext(threadCrossingSyncCtx); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; CancellationTokenRegistration ctr1 = ct.Register(() => { }); CancellationTokenRegistration ctr2 = ct.Register(() => { }); CancellationTokenRegistration ctr3 = ct.Register(() => { }); CancellationTokenRegistration ctr4 = ct.Register(() => { }); ct.Register(() => { ctr1.Dispose(); }, true); // with a custom syncContext ct.Register(() => { ctr2.Dispose(); }, false); // without ct.Register(() => { ctr3.Dispose(); }, true); // with a custom syncContext ct.Register(() => { ctr4.Dispose(); }, false); // without cts.Cancel(); Debug.WriteLine(" - Completed OK."); //cleanup SetSynchronizationContext(prevailingSyncCtx); } #region Helper Classes and Methods private class TestingSynchronizationContext : SynchronizationContext { public bool DidSendOccur = false; override public void Send(SendOrPostCallback d, Object state) { //Note: another idea was to install this syncContext on the executing thread. //unfortunately, the ExecutionContext business gets in the way and reestablishes a default SyncContext. DidSendOccur = true; base.Send(d, state); // call the delegate with our syncContext installed. } } /// <summary> /// This syncContext uses a different thread to run the work /// This is similar to how WindowsFormsSynchronizationContext works. /// </summary> private class ThreadCrossingSynchronizationContext : SynchronizationContext { public bool DidSendOccur = false; override public void Send(SendOrPostCallback d, Object state) { Exception marshalledException = null; Task t = new Task( (passedInState) => { //Debug.WriteLine(" threadCrossingSyncContext..running callback delegate on threadID = " + Thread.CurrentThread.ManagedThreadId); try { d(passedInState); } catch (Exception e) { marshalledException = e; } }, state); t.Start(); t.Wait(); //t.Start(state); //t.Join(); if (marshalledException != null) throw new AggregateException("DUMMY: ThreadCrossingSynchronizationContext.Send captured and propogated an exception", marshalledException); } } /// <summary> /// A test class derived from CancellationTokenSource /// </summary> internal class DerivedCTS : CancellationTokenSource { private DisposeTracker _disposeTracker; public DerivedCTS(DisposeTracker disposeTracker) { _disposeTracker = disposeTracker; } protected override void Dispose(bool disposing) { // Dispose any derived class state. DerivedCTS simply records that Dispose() has been called. if (_disposeTracker != null) { if (disposing) { _disposeTracker.DisposeTrueCalled = true; } else { _disposeTracker.DisposeFalseCalled = true; } } // Dispose the state in the CancellationTokenSource base class base.Dispose(disposing); } /// <summary> /// A helper method to call Dispose(false). That allows us to easily simulate finalization of CTS, while still maintaining /// a reference to the CTS. /// </summary> public void DisposeUnmanaged() { Dispose(false); } ~DerivedCTS() { Dispose(false); } } /// <summary> /// A simple class to track whether Dispose(bool) method has been called and if so, what was the bool flag. /// </summary> internal class DisposeTracker { public bool DisposeTrueCalled = false; public bool DisposeFalseCalled = false; } public static void SetSynchronizationContext(SynchronizationContext sc) { SynchronizationContext.SetSynchronizationContext(sc); } #endregion } }
namespace antlr.debug { using System; using System.Reflection; using Hashtable = System.Collections.Hashtable; using DictionaryEntry = System.Collections.DictionaryEntry; using ArrayList = System.Collections.ArrayList; using antlr.collections.impl; public delegate void MessageEventHandler(object sender, MessageEventArgs e); public delegate void NewLineEventHandler(object sender, NewLineEventArgs e); public delegate void MatchEventHandler(object sender, MatchEventArgs e); public delegate void TokenEventHandler(object sender, TokenEventArgs e); public delegate void SemanticPredicateEventHandler(object sender, SemanticPredicateEventArgs e); public delegate void SyntacticPredicateEventHandler(object sender, SyntacticPredicateEventArgs e); public delegate void TraceEventHandler(object sender, TraceEventArgs e); /// <summary>A class to assist in firing parser events /// NOTE: I intentionally _did_not_ synchronize the event firing and /// add/remove listener methods. This is because the add/remove should /// _only_ be called by the parser at its start/end, and the _same_thread_ /// should be performing the parsing. This should help performance a tad... /// </summary> public class ParserEventSupport { private object source; private Hashtable listeners; private MatchEventArgs matchEvent; private MessageEventArgs messageEvent; private TokenEventArgs tokenEvent; private SemanticPredicateEventArgs semPredEvent; private SyntacticPredicateEventArgs synPredEvent; private TraceEventArgs traceEvent; #pragma warning disable 0414 private NewLineEventArgs newLineEvent; #pragma warning restore 0414 private ParserController controller; private int ruleDepth = 0; public ParserEventSupport(object source) { matchEvent = new MatchEventArgs(); messageEvent = new MessageEventArgs(); tokenEvent = new TokenEventArgs(); traceEvent = new TraceEventArgs(); semPredEvent = new SemanticPredicateEventArgs(); synPredEvent = new SyntacticPredicateEventArgs(); newLineEvent = new NewLineEventArgs(); listeners = new Hashtable(); this.source = source; } public virtual void checkController() { if (controller != null) controller.checkBreak(); } public virtual void addDoneListener(Listener l) { ((Parser)source).Done += new TraceEventHandler(l.doneParsing); listeners[l] = l; } public virtual void addMessageListener(MessageListener l) { ((Parser)source).ErrorReported += new MessageEventHandler(l.reportError); ((Parser)source).WarningReported += new MessageEventHandler(l.reportWarning); //messageListeners.Add(l); addDoneListener(l); } public virtual void addParserListener(ParserListener l) { if (l is ParserController) { ((ParserController) l).ParserEventSupport = this; controller = (ParserController) l; } addParserMatchListener(l); addParserTokenListener(l); addMessageListener(l); addTraceListener(l); addSemanticPredicateListener(l); addSyntacticPredicateListener(l); } public virtual void addParserMatchListener(ParserMatchListener l) { ((Parser)source).MatchedToken += new MatchEventHandler(l.parserMatch); ((Parser)source).MatchedNotToken += new MatchEventHandler(l.parserMatchNot); ((Parser)source).MisMatchedToken += new MatchEventHandler(l.parserMismatch); ((Parser)source).MisMatchedNotToken += new MatchEventHandler(l.parserMismatchNot); //matchListeners.Add(l); addDoneListener(l); } public virtual void addParserTokenListener(ParserTokenListener l) { ((Parser)source).ConsumedToken += new TokenEventHandler(l.parserConsume); ((Parser)source).TokenLA += new TokenEventHandler(l.parserLA); //tokenListeners.Add(l); addDoneListener(l); } public virtual void addSemanticPredicateListener(SemanticPredicateListener l) { ((Parser)source).SemPredEvaluated += new SemanticPredicateEventHandler(l.semanticPredicateEvaluated); //semPredListeners.Add(l); addDoneListener(l); } public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l) { ((Parser)source).SynPredStarted += new SyntacticPredicateEventHandler(l.syntacticPredicateStarted); ((Parser)source).SynPredFailed += new SyntacticPredicateEventHandler(l.syntacticPredicateFailed); ((Parser)source).SynPredSucceeded += new SyntacticPredicateEventHandler(l.syntacticPredicateSucceeded); //synPredListeners.Add(l); addDoneListener(l); } public virtual void addTraceListener(TraceListener l) { ((Parser)source).EnterRule += new TraceEventHandler(l.enterRule); ((Parser)source).ExitRule += new TraceEventHandler(l.exitRule); //traceListeners.Add(l); addDoneListener(l); } public virtual void fireConsume(int c) { TokenEventHandler eventDelegate = (TokenEventHandler)((Parser)source).Events[Parser.LAEventKey]; if (eventDelegate != null) { tokenEvent.setValues(TokenEventArgs.CONSUME, 1, c); eventDelegate(source, tokenEvent); } checkController(); } public virtual void fireDoneParsing() { TraceEventHandler eventDelegate = (TraceEventHandler)((Parser)source).Events[Parser.DoneEventKey]; if (eventDelegate != null) { traceEvent.setValues(TraceEventArgs.DONE_PARSING, 0, 0, 0); eventDelegate(source, traceEvent); } checkController(); } public virtual void fireEnterRule(int ruleNum, int guessing, int data) { ruleDepth++; TraceEventHandler eventDelegate = (TraceEventHandler)((Parser)source).Events[Parser.EnterRuleEventKey]; if (eventDelegate != null) { traceEvent.setValues(TraceEventArgs.ENTER, ruleNum, guessing, data); eventDelegate(source, traceEvent); } checkController(); } public virtual void fireExitRule(int ruleNum, int guessing, int data) { TraceEventHandler eventDelegate = (TraceEventHandler)((Parser)source).Events[Parser.ExitRuleEventKey]; if (eventDelegate != null) { traceEvent.setValues(TraceEventArgs.EXIT, ruleNum, guessing, data); eventDelegate(source, traceEvent); } checkController(); ruleDepth--; if (ruleDepth == 0) fireDoneParsing(); } public virtual void fireLA(int k, int la) { TokenEventHandler eventDelegate = (TokenEventHandler)((Parser)source).Events[Parser.LAEventKey]; if (eventDelegate != null) { tokenEvent.setValues(TokenEventArgs.LA, k, la); eventDelegate(source, tokenEvent); } checkController(); } public virtual void fireMatch(char c, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR, c, c, null, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatch(char c, BitSet b, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR_BITSET, c, b, null, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatch(char c, string target, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR_RANGE, c, target, null, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatch(int c, BitSet b, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.BITSET, c, b, text, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatch(int n, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.TOKEN, n, n, text, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatch(string s, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.STRING, 0, s, null, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatchNot(char c, char n, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchNotEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR, c, n, null, guessing, true, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMatchNot(int c, int n, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MatchNotEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.TOKEN, c, n, text, guessing, true, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatch(char c, char n, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR, c, n, null, guessing, false, false); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatch(char c, BitSet b, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR_BITSET, c, b, null, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatch(char c, string target, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR_RANGE, c, target, null, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatch(int i, int n, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.TOKEN, i, n, text, guessing, false, false); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatch(int i, BitSet b, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.BITSET, i, b, text, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatch(string s, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.STRING, 0, text, s, guessing, false, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatchNot(char v, char c, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchNotEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.CHAR, v, c, null, guessing, true, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireMismatchNot(int i, int n, string text, int guessing) { MatchEventHandler eventDelegate = (MatchEventHandler)((Parser)source).Events[Parser.MisMatchNotEventKey]; if (eventDelegate != null) { matchEvent.setValues(MatchEventArgs.TOKEN, i, n, text, guessing, true, true); eventDelegate(source, matchEvent); } checkController(); } public virtual void fireReportError(System.Exception e) { MessageEventHandler eventDelegate = (MessageEventHandler)((Parser)source).Events[Parser.ReportErrorEventKey]; if (eventDelegate != null) { messageEvent.setValues(MessageEventArgs.ERROR, e.ToString()); eventDelegate(source, messageEvent); } checkController(); } public virtual void fireReportError(string s) { MessageEventHandler eventDelegate = (MessageEventHandler)((Parser)source).Events[Parser.ReportErrorEventKey]; if (eventDelegate != null) { messageEvent.setValues(MessageEventArgs.ERROR, s); eventDelegate(source, messageEvent); } checkController(); } public virtual void fireReportWarning(string s) { MessageEventHandler eventDelegate = (MessageEventHandler)((Parser)source).Events[Parser.ReportWarningEventKey]; if (eventDelegate != null) { messageEvent.setValues(MessageEventArgs.WARNING, s); eventDelegate(source, messageEvent); } checkController(); } public virtual bool fireSemanticPredicateEvaluated(int type, int condition, bool result, int guessing) { SemanticPredicateEventHandler eventDelegate = (SemanticPredicateEventHandler)((Parser)source).Events[Parser.SemPredEvaluatedEventKey]; if (eventDelegate != null) { semPredEvent.setValues(type, condition, result, guessing); eventDelegate(source, semPredEvent); } checkController(); return result; } public virtual void fireSyntacticPredicateFailed(int guessing) { SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((Parser)source).Events[Parser.SynPredFailedEventKey]; if (eventDelegate != null) { synPredEvent.setValues(0, guessing); eventDelegate(source, synPredEvent); } checkController(); } public virtual void fireSyntacticPredicateStarted(int guessing) { SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((Parser)source).Events[Parser.SynPredStartedEventKey]; if (eventDelegate != null) { synPredEvent.setValues(0, guessing); eventDelegate(source, synPredEvent); } checkController(); } public virtual void fireSyntacticPredicateSucceeded(int guessing) { SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((Parser)source).Events[Parser.SynPredSucceededEventKey]; if (eventDelegate != null) { synPredEvent.setValues(0, guessing); eventDelegate(source, synPredEvent); } checkController(); } public virtual void refreshListeners() { Hashtable clonedTable; lock(listeners.SyncRoot) { clonedTable = (Hashtable)listeners.Clone(); } foreach (DictionaryEntry entry in clonedTable) { if (entry.Value != null) { ((Listener) entry.Value).refresh(); } } } public virtual void removeDoneListener(Listener l) { ((Parser)source).Done -= new TraceEventHandler(l.doneParsing); listeners.Remove(l); } public virtual void removeMessageListener(MessageListener l) { ((Parser)source).ErrorReported -= new MessageEventHandler(l.reportError); ((Parser)source).WarningReported -= new MessageEventHandler(l.reportWarning); //messageListeners.Remove(l); removeDoneListener(l); } public virtual void removeParserListener(ParserListener l) { removeParserMatchListener(l); removeMessageListener(l); removeParserTokenListener(l); removeTraceListener(l); removeSemanticPredicateListener(l); removeSyntacticPredicateListener(l); } public virtual void removeParserMatchListener(ParserMatchListener l) { ((Parser)source).MatchedToken -= new MatchEventHandler(l.parserMatch); ((Parser)source).MatchedNotToken -= new MatchEventHandler(l.parserMatchNot); ((Parser)source).MisMatchedToken -= new MatchEventHandler(l.parserMismatch); ((Parser)source).MisMatchedNotToken -= new MatchEventHandler(l.parserMismatchNot); //matchListeners.Remove(l); removeDoneListener(l); } public virtual void removeParserTokenListener(ParserTokenListener l) { ((Parser)source).ConsumedToken -= new TokenEventHandler(l.parserConsume); ((Parser)source).TokenLA -= new TokenEventHandler(l.parserLA); //tokenListeners.Remove(l); removeDoneListener(l); } public virtual void removeSemanticPredicateListener(SemanticPredicateListener l) { ((Parser)source).SemPredEvaluated -= new SemanticPredicateEventHandler(l.semanticPredicateEvaluated); //semPredListeners.Remove(l); removeDoneListener(l); } public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l) { ((Parser)source).SynPredStarted -= new SyntacticPredicateEventHandler(l.syntacticPredicateStarted); ((Parser)source).SynPredFailed -= new SyntacticPredicateEventHandler(l.syntacticPredicateFailed); ((Parser)source).SynPredSucceeded -= new SyntacticPredicateEventHandler(l.syntacticPredicateSucceeded); //synPredListeners.Remove(l); removeDoneListener(l); } public virtual void removeTraceListener(TraceListener l) { ((Parser)source).EnterRule -= new TraceEventHandler(l.enterRule); ((Parser)source).ExitRule -= new TraceEventHandler(l.exitRule); //traceListeners.Remove(l); removeDoneListener(l); } } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Permissive License. // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. // All other rights reserved. using System; namespace VisualUIAVerify.Forms { partial class MainWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.UnmanagedProxiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.highlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.rectangleHighlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fadingRectangleHighlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.raysAndRectangleHighlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.noneHighlightingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.automationElementTreeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.refreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.navigationToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.parentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.firstChildToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.nextSiblingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.prevSiblingToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.lastChildToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.modeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.alwaysOnTopToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.hoverModeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.focusTrackingToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.testsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goLeftToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goUpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goDownToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goRightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator(); this.runSelectedTestToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.filterKnownIssuesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openFilterFileDialog = new System.Windows.Forms.OpenFileDialog(); this.saveLogFileDialog = new System.Windows.Forms.SaveFileDialog(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutVisualUIAVerifyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this._messageToolStrip = new System.Windows.Forms.ToolStripStatusLabel(); this._progressToolStrip = new System.Windows.Forms.ToolStripProgressBar(); this.panel1 = new System.Windows.Forms.Panel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this._automationElementTree = new VisualUIAVerify.Controls.AutomationElementTreeControl(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.refreshElementToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.goToParentToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goToFirstChildToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goToNextSiblingToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goToPrevSiblingToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goToLastChildToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.FocusTrackingToolStripMenuItem = new System.Windows.Forms.ToolStripButton(); this.splitter2 = new System.Windows.Forms.Splitter(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this._automationElementPropertyGrid = new VisualUIAVerify.Controls.AutomationElementPropertyGrid(); this.toolStrip5 = new System.Windows.Forms.ToolStrip(); this.refreshPropertyPaneToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator(); this.showCategoriesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.sortAlphabeticalToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripButton4 = new System.Windows.Forms.ToolStripSeparator(); this.expandAllToolStripButton = new System.Windows.Forms.ToolStripButton(); this.splitter3 = new System.Windows.Forms.Splitter(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this._automationTests = new VisualUIAVerify.Controls.AutomationTestsControl(); this.toolStrip2 = new System.Windows.Forms.ToolStrip(); this.refreshTestsToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator(); this.testsScopeToolStrip = new System.Windows.Forms.ToolStripDropDownButton(); this.testsForSelectedAutomationElementToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.allTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.testTypesMenuToolStrip = new System.Windows.Forms.ToolStripDropDownButton(); this.automationElementTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.patternTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.controlTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.testPrioritiesToolStrip = new System.Windows.Forms.ToolStripDropDownButton(); this.buildVerificationTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.priority0TestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.priority1TestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.priority2TestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.priority3TestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.goLeftToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goUpToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goDownToolStripButton = new System.Windows.Forms.ToolStripButton(); this.goRightToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.runTestToolStripButton = new System.Windows.Forms.ToolStripButton(); this.runTestOnAllChildrenToolStripButton = new System.Windows.Forms.ToolStripButton(); this.splitter4 = new System.Windows.Forms.Splitter(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this._testResults = new VisualUIAVerify.Controls.TestResultsControl(); this._testResultsToolStrip = new System.Windows.Forms.ToolStrip(); this.backToolStripButton = new System.Windows.Forms.ToolStripButton(); this.forwardToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.overallToolStripButton = new System.Windows.Forms.ToolStripButton(); this.allResultsToolStripButton = new System.Windows.Forms.ToolStripButton(); this.FullDetailToolStripButton = new System.Windows.Forms.ToolStripButton(); this.xmlToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.quickFindToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.openInNewWindowToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStrip4 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.menuStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.groupBox3.SuspendLayout(); this.toolStrip5.SuspendLayout(); this.groupBox4.SuspendLayout(); this.toolStrip2.SuspendLayout(); this.groupBox5.SuspendLayout(); this._testResultsToolStrip.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1, this.viewToolStripMenuItem, this.automationElementTreeToolStripMenuItem, this.modeToolStripMenuItem, this.testsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1032, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // toolStripMenuItem1 // this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.UnmanagedProxiesToolStripMenuItem, this.saveLogToolStripMenuItem, this.exitToolStripMenuItem}); this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(37, 20); this.toolStripMenuItem1.Text = "&File"; // // UnmanagedProxiesToolStripMenuItem // this.UnmanagedProxiesToolStripMenuItem.Name = "UnmanagedProxiesToolStripMenuItem"; this.UnmanagedProxiesToolStripMenuItem.Size = new System.Drawing.Size(223, 22); this.UnmanagedProxiesToolStripMenuItem.Text = "Remove Client Side Provider"; this.UnmanagedProxiesToolStripMenuItem.Click += new System.EventHandler(this.UnmanagedProxiesToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(223, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // saveLogToolStripMenuItem // this.saveLogToolStripMenuItem.Name = "saveLogToolStripMenuItem"; this.saveLogToolStripMenuItem.Size = new System.Drawing.Size(223, 22); this.saveLogToolStripMenuItem.Text = "Save Log"; this.saveLogToolStripMenuItem.Click += new System.EventHandler(this.saveLogToolStripMenuItem_Click); // // saveLogFileDialog // this.saveLogFileDialog.Filter = "XML files|*.xml"; this.saveLogFileDialog.RestoreDirectory = true; this.saveLogFileDialog.DefaultExt = "xml"; // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.highlightingToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.viewToolStripMenuItem.Text = "&View"; // // highlightingToolStripMenuItem // this.highlightingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.rectangleHighlightingToolStripMenuItem, this.fadingRectangleHighlightingToolStripMenuItem, this.raysAndRectangleHighlightingToolStripMenuItem, this.toolStripSeparator2, this.noneHighlightingToolStripMenuItem}); this.highlightingToolStripMenuItem.Name = "highlightingToolStripMenuItem"; this.highlightingToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.highlightingToolStripMenuItem.Text = "Highlighting"; // // rectangleHighlightingToolStripMenuItem // this.rectangleHighlightingToolStripMenuItem.Name = "rectangleHighlightingToolStripMenuItem"; this.rectangleHighlightingToolStripMenuItem.Size = new System.Drawing.Size(176, 22); this.rectangleHighlightingToolStripMenuItem.Tag = "Rectangle"; this.rectangleHighlightingToolStripMenuItem.Text = "&Rectangle"; this.rectangleHighlightingToolStripMenuItem.Click += new System.EventHandler(this.highlightingToolStripMenuItem_Click); // // fadingRectangleHighlightingToolStripMenuItem // this.fadingRectangleHighlightingToolStripMenuItem.Name = "fadingRectangleHighlightingToolStripMenuItem"; this.fadingRectangleHighlightingToolStripMenuItem.Size = new System.Drawing.Size(176, 22); this.fadingRectangleHighlightingToolStripMenuItem.Tag = "fadingRectangle"; this.fadingRectangleHighlightingToolStripMenuItem.Text = "&Fading Rectangle"; this.fadingRectangleHighlightingToolStripMenuItem.Click += new System.EventHandler(this.highlightingToolStripMenuItem_Click); // // raysAndRectangleHighlightingToolStripMenuItem // this.raysAndRectangleHighlightingToolStripMenuItem.Name = "raysAndRectangleHighlightingToolStripMenuItem"; this.raysAndRectangleHighlightingToolStripMenuItem.Size = new System.Drawing.Size(176, 22); this.raysAndRectangleHighlightingToolStripMenuItem.Tag = "rays"; this.raysAndRectangleHighlightingToolStripMenuItem.Text = "Ra&ys and Rectangle"; this.raysAndRectangleHighlightingToolStripMenuItem.Click += new System.EventHandler(this.highlightingToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(173, 6); // // noneHighlightingToolStripMenuItem // this.noneHighlightingToolStripMenuItem.Name = "noneHighlightingToolStripMenuItem"; this.noneHighlightingToolStripMenuItem.Size = new System.Drawing.Size(176, 22); this.noneHighlightingToolStripMenuItem.Text = "None"; this.noneHighlightingToolStripMenuItem.Click += new System.EventHandler(this.highlightingToolStripMenuItem_Click); // // automationElementTreeToolStripMenuItem // this.automationElementTreeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refreshToolStripMenuItem, this.navigationToolStripMenuItem1}); this.automationElementTreeToolStripMenuItem.Name = "automationElementTreeToolStripMenuItem"; this.automationElementTreeToolStripMenuItem.Size = new System.Drawing.Size(155, 20); this.automationElementTreeToolStripMenuItem.Text = "&Automation Element Tree"; // // refreshToolStripMenuItem // this.refreshToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.elemtyperefresh; this.refreshToolStripMenuItem.Name = "refreshToolStripMenuItem"; this.refreshToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+F5"; this.refreshToolStripMenuItem.Size = new System.Drawing.Size(284, 22); this.refreshToolStripMenuItem.Text = "&Refresh Selected Element"; this.refreshToolStripMenuItem.Click += new System.EventHandler(this.refreshElementToolStripButton_Click); // // navigationToolStripMenuItem1 // this.navigationToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.parentToolStripMenuItem, this.firstChildToolStripMenuItem, this.nextSiblingToolStripMenuItem, this.prevSiblingToolStripMenuItem1, this.lastChildToolStripMenuItem}); this.navigationToolStripMenuItem1.Name = "navigationToolStripMenuItem1"; this.navigationToolStripMenuItem1.Size = new System.Drawing.Size(284, 22); this.navigationToolStripMenuItem1.Text = "Navigation"; // // parentToolStripMenuItem // this.parentToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotoparent; this.parentToolStripMenuItem.Name = "parentToolStripMenuItem"; this.parentToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+F6"; this.parentToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.parentToolStripMenuItem.Text = "&Parent"; this.parentToolStripMenuItem.Click += new System.EventHandler(this.goToParentToolStripButton_Click); // // firstChildToolStripMenuItem // this.firstChildToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotofirstchild; this.firstChildToolStripMenuItem.Name = "firstChildToolStripMenuItem"; this.firstChildToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+F7"; this.firstChildToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.firstChildToolStripMenuItem.Text = "&First Child"; this.firstChildToolStripMenuItem.Click += new System.EventHandler(this.goToFirstChildToolStripButton_Click); // // nextSiblingToolStripMenuItem // this.nextSiblingToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotonextsibling; this.nextSiblingToolStripMenuItem.Name = "nextSiblingToolStripMenuItem"; this.nextSiblingToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+F8"; this.nextSiblingToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.nextSiblingToolStripMenuItem.Text = "&Next Sibling"; this.nextSiblingToolStripMenuItem.Click += new System.EventHandler(this.goToNextSiblingToolStripButton_Click); // // prevSiblingToolStripMenuItem1 // this.prevSiblingToolStripMenuItem1.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotoprevsibling; this.prevSiblingToolStripMenuItem1.Name = "prevSiblingToolStripMenuItem1"; this.prevSiblingToolStripMenuItem1.ShortcutKeyDisplayString = "Ctrl+Shift+F9"; this.prevSiblingToolStripMenuItem1.Size = new System.Drawing.Size(215, 22); this.prevSiblingToolStripMenuItem1.Text = "&Prev Sibling"; this.prevSiblingToolStripMenuItem1.Click += new System.EventHandler(this.goToPrevSiblingToolStripButton_Click); // // lastChildToolStripMenuItem // this.lastChildToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotolastchild; this.lastChildToolStripMenuItem.Name = "lastChildToolStripMenuItem"; this.lastChildToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+F10"; this.lastChildToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.lastChildToolStripMenuItem.Text = "&Last Child"; this.lastChildToolStripMenuItem.Click += new System.EventHandler(this.goToLastChildToolStripButton_Click); // // modeToolStripMenuItem // this.modeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.alwaysOnTopToolStripMenuItem, this.toolStripSeparator10, this.hoverModeToolStripMenuItem, this.focusTrackingToolStripMenuItem1}); this.modeToolStripMenuItem.Name = "modeToolStripMenuItem"; this.modeToolStripMenuItem.Size = new System.Drawing.Size(50, 20); this.modeToolStripMenuItem.Text = "&Mode"; // // alwaysOnTopToolStripMenuItem // this.alwaysOnTopToolStripMenuItem.CheckOnClick = true; this.alwaysOnTopToolStripMenuItem.Name = "alwaysOnTopToolStripMenuItem"; this.alwaysOnTopToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+T"; this.alwaysOnTopToolStripMenuItem.Size = new System.Drawing.Size(266, 22); this.alwaysOnTopToolStripMenuItem.Text = "&Always On Top"; this.alwaysOnTopToolStripMenuItem.Click += new System.EventHandler(this.alwaysOnTopToolStripMenuItem_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; this.toolStripSeparator10.Size = new System.Drawing.Size(263, 6); // // hoverModeToolStripMenuItem // this.hoverModeToolStripMenuItem.CheckOnClick = true; this.hoverModeToolStripMenuItem.Name = "hoverModeToolStripMenuItem"; this.hoverModeToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+H"; this.hoverModeToolStripMenuItem.Size = new System.Drawing.Size(266, 22); this.hoverModeToolStripMenuItem.Text = "&Hover Mode (use Ctrl)"; this.hoverModeToolStripMenuItem.Click += new System.EventHandler(this.hoverModeToolStripMenuItem_Click); // // focusTrackingToolStripMenuItem1 // this.focusTrackingToolStripMenuItem1.CheckOnClick = true; this.focusTrackingToolStripMenuItem1.Name = "focusTrackingToolStripMenuItem1"; this.focusTrackingToolStripMenuItem1.ShortcutKeyDisplayString = "Ctrl+Shift+F"; this.focusTrackingToolStripMenuItem1.Size = new System.Drawing.Size(266, 22); this.focusTrackingToolStripMenuItem1.Text = "&Focus Tracking"; this.focusTrackingToolStripMenuItem1.Click += new System.EventHandler(this.focusTrackingToolStripMenuItem1_Click); // // testsToolStripMenuItem // this.testsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.goLeftToolStripMenuItem, this.goUpToolStripMenuItem, this.goDownToolStripMenuItem, this.goRightToolStripMenuItem, this.toolStripSeparator13, this.runSelectedTestToolStripMenuItem, this.toolStripSeparator3, this.filterKnownIssuesToolStripMenuItem}); this.testsToolStripMenuItem.Name = "testsToolStripMenuItem"; this.testsToolStripMenuItem.Size = new System.Drawing.Size(46, 20); this.testsToolStripMenuItem.Text = "&Tests"; // // goLeftToolStripMenuItem // this.goLeftToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowLeft; this.goLeftToolStripMenuItem.Name = "goLeftToolStripMenuItem"; this.goLeftToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+7"; this.goLeftToolStripMenuItem.Size = new System.Drawing.Size(363, 22); this.goLeftToolStripMenuItem.Text = "Go &Left"; this.goLeftToolStripMenuItem.Click += new System.EventHandler(this.testArrowToolStripMenuItem_Click); // // goUpToolStripMenuItem // this.goUpToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowUp; this.goUpToolStripMenuItem.Name = "goUpToolStripMenuItem"; this.goUpToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+8"; this.goUpToolStripMenuItem.Size = new System.Drawing.Size(363, 22); this.goUpToolStripMenuItem.Text = "Go &Up"; this.goUpToolStripMenuItem.Click += new System.EventHandler(this.testArrowToolStripMenuItem_Click); // // goDownToolStripMenuItem // this.goDownToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowDown; this.goDownToolStripMenuItem.Name = "goDownToolStripMenuItem"; this.goDownToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+9"; this.goDownToolStripMenuItem.Size = new System.Drawing.Size(363, 22); this.goDownToolStripMenuItem.Text = "Go &Down"; this.goDownToolStripMenuItem.Click += new System.EventHandler(this.testArrowToolStripMenuItem_Click); // // goRightToolStripMenuItem // this.goRightToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowRight; this.goRightToolStripMenuItem.Name = "goRightToolStripMenuItem"; this.goRightToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+0"; this.goRightToolStripMenuItem.Size = new System.Drawing.Size(363, 22); this.goRightToolStripMenuItem.Text = "Go &Right"; this.goRightToolStripMenuItem.Click += new System.EventHandler(this.testArrowToolStripMenuItem_Click); // // toolStripSeparator13 // this.toolStripSeparator13.Name = "toolStripSeparator13"; this.toolStripSeparator13.Size = new System.Drawing.Size(360, 6); // // runSelectedTestToolStripMenuItem // this.runSelectedTestToolStripMenuItem.Image = global::VisualUIAVerify.VisualUIAVerifyResources.testToRun; this.runSelectedTestToolStripMenuItem.Name = "runSelectedTestToolStripMenuItem"; this.runSelectedTestToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift) | System.Windows.Forms.Keys.R))); this.runSelectedTestToolStripMenuItem.Size = new System.Drawing.Size(363, 22); this.runSelectedTestToolStripMenuItem.Text = "Run &Selected Test(s) on Selected Element"; this.runSelectedTestToolStripMenuItem.Click += new System.EventHandler(this.runSelectedTestToolStripMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(360, 6); // // filterKnownIssuesToolStripMenuItem // this.filterKnownIssuesToolStripMenuItem.Checked = true; this.filterKnownIssuesToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.filterKnownIssuesToolStripMenuItem.Name = "filterKnownIssuesToolStripMenuItem"; this.filterKnownIssuesToolStripMenuItem.Size = new System.Drawing.Size(363, 22); this.filterKnownIssuesToolStripMenuItem.Text = "Filter Known Problems"; this.filterKnownIssuesToolStripMenuItem.Click += new System.EventHandler(this.filterKnownIssuesToolStripMenuItem_Click); // // openFilterFileDialog // this.openFilterFileDialog.Filter = "XML files|*.xml"; this.openFilterFileDialog.Multiselect = false; this.openFilterFileDialog.RestoreDirectory = true; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutVisualUIAVerifyToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "&Help"; // // aboutVisualUIAVerifyToolStripMenuItem // this.aboutVisualUIAVerifyToolStripMenuItem.Name = "aboutVisualUIAVerifyToolStripMenuItem"; this.aboutVisualUIAVerifyToolStripMenuItem.Size = new System.Drawing.Size(258, 22); this.aboutVisualUIAVerifyToolStripMenuItem.Text = "&About Visual UI Automation Verify."; this.aboutVisualUIAVerifyToolStripMenuItem.Click += new System.EventHandler(this.aboutVisualUIAVerifyToolStripMenuItem_Click); // // statusStrip1 // this.statusStrip1.Location = new System.Drawing.Point(0, 663); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(1032, 22); this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // _messageToolStrip // this._messageToolStrip.Name = "_messageToolStrip"; this._messageToolStrip.Size = new System.Drawing.Size(233, 17); this._messageToolStrip.Text = "status text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "; this._messageToolStrip.Visible = false; // // _progressToolStrip // this._progressToolStrip.Name = "_progressToolStrip"; this._progressToolStrip.Size = new System.Drawing.Size(100, 16); this._progressToolStrip.Visible = false; // // panel1 // this.panel1.Controls.Add(this.groupBox1); this.panel1.Dock = System.Windows.Forms.DockStyle.Left; this.panel1.Location = new System.Drawing.Point(0, 24); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(316, 639); this.panel1.TabIndex = 4; // // groupBox1 // this.groupBox1.Controls.Add(this._automationElementTree); this.groupBox1.Controls.Add(this.toolStrip1); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(316, 639); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Automation Elements Tree"; // // _automationElementTree // this._automationElementTree.Dock = System.Windows.Forms.DockStyle.Fill; this._automationElementTree.Location = new System.Drawing.Point(3, 41); this._automationElementTree.Name = "_automationElementTree"; this._automationElementTree.Size = new System.Drawing.Size(310, 595); this._automationElementTree.TabIndex = 1; this._automationElementTree.SelectedNodeChanged += new VisualUIAVerify.Controls.SelectedNodeChangedEventDelegate(this._automationElementTree_SelectedNodeChanged); // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refreshElementToolStripButton, this.toolStripSeparator9, this.goToParentToolStripButton, this.goToFirstChildToolStripButton, this.goToNextSiblingToolStripButton, this.goToPrevSiblingToolStripButton, this.goToLastChildToolStripButton, this.toolStripSeparator1, this.FocusTrackingToolStripMenuItem}); this.toolStrip1.Location = new System.Drawing.Point(3, 16); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(310, 25); this.toolStrip1.TabIndex = 2; this.toolStrip1.Text = "toolStrip1"; // // refreshElementToolStripButton // this.refreshElementToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.refreshElementToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.elemtyperefresh; this.refreshElementToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.refreshElementToolStripButton.Name = "refreshElementToolStripButton"; this.refreshElementToolStripButton.Size = new System.Drawing.Size(23, 22); this.refreshElementToolStripButton.Text = "Refresh selected element"; this.refreshElementToolStripButton.Click += new System.EventHandler(this.refreshElementToolStripButton_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; this.toolStripSeparator9.Size = new System.Drawing.Size(6, 25); // // goToParentToolStripButton // this.goToParentToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goToParentToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotoparent; this.goToParentToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goToParentToolStripButton.Name = "goToParentToolStripButton"; this.goToParentToolStripButton.Size = new System.Drawing.Size(23, 22); this.goToParentToolStripButton.Text = "Parent"; this.goToParentToolStripButton.ToolTipText = "Parent (Ctrl+Shift+F6)"; this.goToParentToolStripButton.Click += new System.EventHandler(this.goToParentToolStripButton_Click); // // goToFirstChildToolStripButton // this.goToFirstChildToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goToFirstChildToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotofirstchild; this.goToFirstChildToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goToFirstChildToolStripButton.Name = "goToFirstChildToolStripButton"; this.goToFirstChildToolStripButton.Size = new System.Drawing.Size(23, 22); this.goToFirstChildToolStripButton.Text = "First Child"; this.goToFirstChildToolStripButton.ToolTipText = "First Child (Ctrl+Shift+F7)"; this.goToFirstChildToolStripButton.Click += new System.EventHandler(this.goToFirstChildToolStripButton_Click); // // goToNextSiblingToolStripButton // this.goToNextSiblingToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goToNextSiblingToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotonextsibling; this.goToNextSiblingToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goToNextSiblingToolStripButton.Name = "goToNextSiblingToolStripButton"; this.goToNextSiblingToolStripButton.Size = new System.Drawing.Size(23, 22); this.goToNextSiblingToolStripButton.Text = "Next Sibling"; this.goToNextSiblingToolStripButton.ToolTipText = "Next Sibling (Ctrl+Shift+F8)"; this.goToNextSiblingToolStripButton.Click += new System.EventHandler(this.goToNextSiblingToolStripButton_Click); // // goToPrevSiblingToolStripButton // this.goToPrevSiblingToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goToPrevSiblingToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotoprevsibling; this.goToPrevSiblingToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goToPrevSiblingToolStripButton.Name = "goToPrevSiblingToolStripButton"; this.goToPrevSiblingToolStripButton.Size = new System.Drawing.Size(23, 22); this.goToPrevSiblingToolStripButton.Text = "Prev Sibling"; this.goToPrevSiblingToolStripButton.ToolTipText = "Prev Sibling (Ctrl+Shift+F9)"; this.goToPrevSiblingToolStripButton.Click += new System.EventHandler(this.goToPrevSiblingToolStripButton_Click); // // goToLastChildToolStripButton // this.goToLastChildToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goToLastChildToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.gotolastchild; this.goToLastChildToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goToLastChildToolStripButton.Name = "goToLastChildToolStripButton"; this.goToLastChildToolStripButton.Size = new System.Drawing.Size(23, 22); this.goToLastChildToolStripButton.Text = "Last Child"; this.goToLastChildToolStripButton.ToolTipText = "Last Child (Ctrl+Shift+F0)"; this.goToLastChildToolStripButton.Click += new System.EventHandler(this.goToLastChildToolStripButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // FocusTrackingToolStripMenuItem // this.FocusTrackingToolStripMenuItem.CheckOnClick = true; this.FocusTrackingToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.FocusTrackingToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("FocusTrackingToolStripMenuItem.Image"))); this.FocusTrackingToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.FocusTrackingToolStripMenuItem.Name = "FocusTrackingToolStripMenuItem"; this.FocusTrackingToolStripMenuItem.Size = new System.Drawing.Size(91, 22); this.FocusTrackingToolStripMenuItem.Text = "Focus Tracking"; this.FocusTrackingToolStripMenuItem.Visible = false; this.FocusTrackingToolStripMenuItem.Click += new System.EventHandler(this.FocusTrackingToolStripMenuItem_CheckedChanged); // // splitter2 // this.splitter2.Location = new System.Drawing.Point(316, 24); this.splitter2.Name = "splitter2"; this.splitter2.Size = new System.Drawing.Size(5, 639); this.splitter2.TabIndex = 5; this.splitter2.TabStop = false; // // groupBox3 // this.groupBox3.Controls.Add(this._automationElementPropertyGrid); this.groupBox3.Controls.Add(this.toolStrip5); this.groupBox3.Dock = System.Windows.Forms.DockStyle.Right; this.groupBox3.Location = new System.Drawing.Point(832, 24); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(200, 639); this.groupBox3.TabIndex = 6; this.groupBox3.TabStop = false; this.groupBox3.Text = "Properties"; // // _automationElementPropertyGrid // this._automationElementPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this._automationElementPropertyGrid.Location = new System.Drawing.Point(3, 41); this._automationElementPropertyGrid.Name = "_automationElementPropertyGrid"; this._automationElementPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.CategorizedAlphabetical; this._automationElementPropertyGrid.Size = new System.Drawing.Size(194, 595); this._automationElementPropertyGrid.TabIndex = 0; // // toolStrip5 // this.toolStrip5.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip5.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refreshPropertyPaneToolStripButton, this.toolStripSeparator15, this.showCategoriesToolStripButton, this.sortAlphabeticalToolStripButton, this.toolStripButton4, this.expandAllToolStripButton}); this.toolStrip5.Location = new System.Drawing.Point(3, 16); this.toolStrip5.Name = "toolStrip5"; this.toolStrip5.Size = new System.Drawing.Size(194, 25); this.toolStrip5.TabIndex = 1; this.toolStrip5.Text = "toolStrip5"; // // refreshPropertyPaneToolStripButton // this.refreshPropertyPaneToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.refreshPropertyPaneToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.elemtyperefresh; this.refreshPropertyPaneToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.refreshPropertyPaneToolStripButton.Name = "refreshPropertyPaneToolStripButton"; this.refreshPropertyPaneToolStripButton.Size = new System.Drawing.Size(23, 22); this.refreshPropertyPaneToolStripButton.Text = "toolStripButton3"; this.refreshPropertyPaneToolStripButton.ToolTipText = "Refresh"; this.refreshPropertyPaneToolStripButton.Click += new System.EventHandler(this.refreshPropertyPaneToolStripButton_Click); // // toolStripSeparator15 // this.toolStripSeparator15.Name = "toolStripSeparator15"; this.toolStripSeparator15.Size = new System.Drawing.Size(6, 25); this.toolStripSeparator15.Visible = false; // // showCategoriesToolStripButton // this.showCategoriesToolStripButton.Checked = true; this.showCategoriesToolStripButton.CheckOnClick = true; this.showCategoriesToolStripButton.CheckState = System.Windows.Forms.CheckState.Checked; this.showCategoriesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.showCategoriesToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.orderCategorized; this.showCategoriesToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.showCategoriesToolStripButton.Name = "showCategoriesToolStripButton"; this.showCategoriesToolStripButton.Size = new System.Drawing.Size(23, 22); this.showCategoriesToolStripButton.Text = "Show categories"; this.showCategoriesToolStripButton.Visible = false; this.showCategoriesToolStripButton.Click += new System.EventHandler(this.propertyPaneToolStripButton_Click); // // sortAlphabeticalToolStripButton // this.sortAlphabeticalToolStripButton.Checked = true; this.sortAlphabeticalToolStripButton.CheckOnClick = true; this.sortAlphabeticalToolStripButton.CheckState = System.Windows.Forms.CheckState.Checked; this.sortAlphabeticalToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.sortAlphabeticalToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.orderAlphabetical; this.sortAlphabeticalToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.sortAlphabeticalToolStripButton.Name = "sortAlphabeticalToolStripButton"; this.sortAlphabeticalToolStripButton.Size = new System.Drawing.Size(23, 22); this.sortAlphabeticalToolStripButton.Text = "SortAlphabetical"; this.sortAlphabeticalToolStripButton.Visible = false; this.sortAlphabeticalToolStripButton.Click += new System.EventHandler(this.propertyPaneToolStripButton_Click); // // toolStripButton4 // this.toolStripButton4.Name = "toolStripButton4"; this.toolStripButton4.Size = new System.Drawing.Size(6, 25); this.toolStripButton4.Visible = false; // // expandAllToolStripButton // this.expandAllToolStripButton.CheckOnClick = true; this.expandAllToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.expandAllToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.ExpandAll; this.expandAllToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.expandAllToolStripButton.Name = "expandAllToolStripButton"; this.expandAllToolStripButton.Size = new System.Drawing.Size(23, 22); this.expandAllToolStripButton.Text = "Expand All"; this.expandAllToolStripButton.Click += new System.EventHandler(this.expandAllToolStripButton_Click); // // splitter3 // this.splitter3.Dock = System.Windows.Forms.DockStyle.Right; this.splitter3.Location = new System.Drawing.Point(827, 24); this.splitter3.Name = "splitter3"; this.splitter3.Size = new System.Drawing.Size(5, 639); this.splitter3.TabIndex = 7; this.splitter3.TabStop = false; // // groupBox4 // this.groupBox4.Controls.Add(this._automationTests); this.groupBox4.Controls.Add(this.toolStrip2); this.groupBox4.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox4.Location = new System.Drawing.Point(321, 24); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(506, 286); this.groupBox4.TabIndex = 8; this.groupBox4.TabStop = false; this.groupBox4.Text = "Tests"; // // _automationTests // this._automationTests.Dock = System.Windows.Forms.DockStyle.Fill; this._automationTests.Location = new System.Drawing.Point(3, 41); this._automationTests.Name = "_automationTests"; this._automationTests.Priorities = VisualUIAVerify.TestPriorities.None; this._automationTests.Scope = VisualUIAVerify.TestsScope.SelectedElementTests; this._automationTests.SelectedElement = null; this._automationTests.Size = new System.Drawing.Size(500, 242); this._automationTests.TabIndex = 2; this._automationTests.Types = VisualUIAVerify.TestTypes.None; this._automationTests.RunTestOnAllChildrenRequired += new System.EventHandler(this._automationTests_RunTestOnAllChildrenRequired); this._automationTests.RunTestRequired += new System.EventHandler(this._automationTests_RunTestRequired); // // toolStrip2 // this.toolStrip2.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refreshTestsToolStripButton, this.toolStripSeparator14, this.testsScopeToolStrip, this.toolStripSeparator4, this.testTypesMenuToolStrip, this.testPrioritiesToolStrip, this.toolStripSeparator11, this.goLeftToolStripButton, this.goUpToolStripButton, this.goDownToolStripButton, this.goRightToolStripButton, this.toolStripSeparator12, this.runTestToolStripButton, this.runTestOnAllChildrenToolStripButton}); this.toolStrip2.Location = new System.Drawing.Point(3, 16); this.toolStrip2.Name = "toolStrip2"; this.toolStrip2.Size = new System.Drawing.Size(500, 25); this.toolStrip2.TabIndex = 0; this.toolStrip2.Text = "toolStrip2"; // // refreshTestsToolStripButton // this.refreshTestsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.refreshTestsToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.elemtyperefresh; this.refreshTestsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.refreshTestsToolStripButton.Name = "refreshTestsToolStripButton"; this.refreshTestsToolStripButton.Size = new System.Drawing.Size(23, 22); this.refreshTestsToolStripButton.Text = "Refresh Tests (reload test libraries)"; this.refreshTestsToolStripButton.Visible = false; this.refreshTestsToolStripButton.Click += new System.EventHandler(this.refreshTestsToolStripButton_Click); // // toolStripSeparator14 // this.toolStripSeparator14.Name = "toolStripSeparator14"; this.toolStripSeparator14.Size = new System.Drawing.Size(6, 25); this.toolStripSeparator14.Visible = false; // // testsScopeToolStrip // this.testsScopeToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.testsScopeToolStrip.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.testsForSelectedAutomationElementToolStripMenuItem, this.allTestsToolStripMenuItem}); this.testsScopeToolStrip.Image = ((System.Drawing.Image)(resources.GetObject("testsScopeToolStrip.Image"))); this.testsScopeToolStrip.ImageTransparentColor = System.Drawing.Color.Magenta; this.testsScopeToolStrip.Name = "testsScopeToolStrip"; this.testsScopeToolStrip.Size = new System.Drawing.Size(49, 22); this.testsScopeToolStrip.Text = "Show"; // // testsForSelectedAutomationElementToolStripMenuItem // this.testsForSelectedAutomationElementToolStripMenuItem.Checked = true; this.testsForSelectedAutomationElementToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.testsForSelectedAutomationElementToolStripMenuItem.Name = "testsForSelectedAutomationElementToolStripMenuItem"; this.testsForSelectedAutomationElementToolStripMenuItem.Size = new System.Drawing.Size(279, 22); this.testsForSelectedAutomationElementToolStripMenuItem.Text = "Tests for Selected Automation Element"; this.testsForSelectedAutomationElementToolStripMenuItem.Click += new System.EventHandler(this.testsScopeToolStrip_Click); // // allTestsToolStripMenuItem // this.allTestsToolStripMenuItem.Name = "allTestsToolStripMenuItem"; this.allTestsToolStripMenuItem.Size = new System.Drawing.Size(279, 22); this.allTestsToolStripMenuItem.Text = "All Tests"; this.allTestsToolStripMenuItem.Click += new System.EventHandler(this.testsScopeToolStrip_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // testTypesMenuToolStrip // this.testTypesMenuToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.testTypesMenuToolStrip.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.automationElementTestsToolStripMenuItem, this.patternTestsToolStripMenuItem, this.controlTestsToolStripMenuItem}); this.testTypesMenuToolStrip.Image = ((System.Drawing.Image)(resources.GetObject("testTypesMenuToolStrip.Image"))); this.testTypesMenuToolStrip.ImageTransparentColor = System.Drawing.Color.Magenta; this.testTypesMenuToolStrip.Name = "testTypesMenuToolStrip"; this.testTypesMenuToolStrip.Size = new System.Drawing.Size(46, 22); this.testTypesMenuToolStrip.Text = "Type"; // // automationElementTestsToolStripMenuItem // this.automationElementTestsToolStripMenuItem.Checked = true; this.automationElementTestsToolStripMenuItem.CheckOnClick = true; this.automationElementTestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.automationElementTestsToolStripMenuItem.Name = "automationElementTestsToolStripMenuItem"; this.automationElementTestsToolStripMenuItem.Size = new System.Drawing.Size(214, 22); this.automationElementTestsToolStripMenuItem.Text = "Automation Element Tests"; this.automationElementTestsToolStripMenuItem.Click += new System.EventHandler(this.testTypesMenuToolStrip_Click); // // patternTestsToolStripMenuItem // this.patternTestsToolStripMenuItem.Checked = true; this.patternTestsToolStripMenuItem.CheckOnClick = true; this.patternTestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.patternTestsToolStripMenuItem.Name = "patternTestsToolStripMenuItem"; this.patternTestsToolStripMenuItem.Size = new System.Drawing.Size(214, 22); this.patternTestsToolStripMenuItem.Text = "PatternTests"; this.patternTestsToolStripMenuItem.Click += new System.EventHandler(this.testTypesMenuToolStrip_Click); // // controlTestsToolStripMenuItem // this.controlTestsToolStripMenuItem.Checked = true; this.controlTestsToolStripMenuItem.CheckOnClick = true; this.controlTestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.controlTestsToolStripMenuItem.Name = "controlTestsToolStripMenuItem"; this.controlTestsToolStripMenuItem.Size = new System.Drawing.Size(214, 22); this.controlTestsToolStripMenuItem.Text = "Control Tests"; this.controlTestsToolStripMenuItem.Click += new System.EventHandler(this.testTypesMenuToolStrip_Click); // // testPrioritiesToolStrip // this.testPrioritiesToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.testPrioritiesToolStrip.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.buildVerificationTestsToolStripMenuItem, this.priority0TestsToolStripMenuItem, this.priority1TestsToolStripMenuItem, this.priority2TestsToolStripMenuItem, this.priority3TestsToolStripMenuItem}); this.testPrioritiesToolStrip.Image = ((System.Drawing.Image)(resources.GetObject("testPrioritiesToolStrip.Image"))); this.testPrioritiesToolStrip.ImageTransparentColor = System.Drawing.Color.Magenta; this.testPrioritiesToolStrip.Name = "testPrioritiesToolStrip"; this.testPrioritiesToolStrip.Size = new System.Drawing.Size(66, 22); this.testPrioritiesToolStrip.Text = "Priorities"; // // buildVerificationTestsToolStripMenuItem // this.buildVerificationTestsToolStripMenuItem.Checked = true; this.buildVerificationTestsToolStripMenuItem.CheckOnClick = true; this.buildVerificationTestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.buildVerificationTestsToolStripMenuItem.Name = "buildVerificationTestsToolStripMenuItem"; this.buildVerificationTestsToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.buildVerificationTestsToolStripMenuItem.Text = "Build Verification Tests"; this.buildVerificationTestsToolStripMenuItem.Click += new System.EventHandler(this.testPrioritiesToolStrip_Click); // // priority0TestsToolStripMenuItem // this.priority0TestsToolStripMenuItem.Checked = true; this.priority0TestsToolStripMenuItem.CheckOnClick = true; this.priority0TestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.priority0TestsToolStripMenuItem.Name = "priority0TestsToolStripMenuItem"; this.priority0TestsToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.priority0TestsToolStripMenuItem.Text = "Priority 0 Tests"; this.priority0TestsToolStripMenuItem.Click += new System.EventHandler(this.testPrioritiesToolStrip_Click); // // priority1TestsToolStripMenuItem // this.priority1TestsToolStripMenuItem.Checked = true; this.priority1TestsToolStripMenuItem.CheckOnClick = true; this.priority1TestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.priority1TestsToolStripMenuItem.Name = "priority1TestsToolStripMenuItem"; this.priority1TestsToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.priority1TestsToolStripMenuItem.Text = "Priority 1 Tests"; this.priority1TestsToolStripMenuItem.Click += new System.EventHandler(this.testPrioritiesToolStrip_Click); // // priority2TestsToolStripMenuItem // this.priority2TestsToolStripMenuItem.Checked = true; this.priority2TestsToolStripMenuItem.CheckOnClick = true; this.priority2TestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.priority2TestsToolStripMenuItem.Name = "priority2TestsToolStripMenuItem"; this.priority2TestsToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.priority2TestsToolStripMenuItem.Text = "Priority 2 Tests"; this.priority2TestsToolStripMenuItem.Click += new System.EventHandler(this.testPrioritiesToolStrip_Click); // // priority3TestsToolStripMenuItem // this.priority3TestsToolStripMenuItem.Checked = true; this.priority3TestsToolStripMenuItem.CheckOnClick = true; this.priority3TestsToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.priority3TestsToolStripMenuItem.Name = "priority3TestsToolStripMenuItem"; this.priority3TestsToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.priority3TestsToolStripMenuItem.Text = "Priority 3 Tests"; this.priority3TestsToolStripMenuItem.Click += new System.EventHandler(this.testPrioritiesToolStrip_Click); // // toolStripSeparator11 // this.toolStripSeparator11.Name = "toolStripSeparator11"; this.toolStripSeparator11.Size = new System.Drawing.Size(6, 25); // // goLeftToolStripButton // this.goLeftToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goLeftToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowLeft; this.goLeftToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goLeftToolStripButton.Name = "goLeftToolStripButton"; this.goLeftToolStripButton.Size = new System.Drawing.Size(23, 22); this.goLeftToolStripButton.Text = "Go Left"; this.goLeftToolStripButton.ToolTipText = "Go Left (Ctrl+Shift+7)"; this.goLeftToolStripButton.Click += new System.EventHandler(this.testArrowButton_Click); // // goUpToolStripButton // this.goUpToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goUpToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowUp; this.goUpToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goUpToolStripButton.Name = "goUpToolStripButton"; this.goUpToolStripButton.Size = new System.Drawing.Size(23, 22); this.goUpToolStripButton.Text = "Go Up"; this.goUpToolStripButton.ToolTipText = "Go Up (Ctrl+Shift+8)"; this.goUpToolStripButton.Click += new System.EventHandler(this.testArrowButton_Click); // // goDownToolStripButton // this.goDownToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goDownToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowDown; this.goDownToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goDownToolStripButton.Name = "goDownToolStripButton"; this.goDownToolStripButton.Size = new System.Drawing.Size(23, 22); this.goDownToolStripButton.Text = "Go Down"; this.goDownToolStripButton.ToolTipText = "Go Down (Ctrl+Shift+9)"; this.goDownToolStripButton.Click += new System.EventHandler(this.testArrowButton_Click); // // goRightToolStripButton // this.goRightToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goRightToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.arrowRight; this.goRightToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goRightToolStripButton.Name = "goRightToolStripButton"; this.goRightToolStripButton.Size = new System.Drawing.Size(23, 22); this.goRightToolStripButton.Text = "Go Right"; this.goRightToolStripButton.ToolTipText = "Go Right (Ctrl+Shift+0)"; this.goRightToolStripButton.Click += new System.EventHandler(this.testArrowButton_Click); // // toolStripSeparator12 // this.toolStripSeparator12.Name = "toolStripSeparator12"; this.toolStripSeparator12.Size = new System.Drawing.Size(6, 25); // // runTestToolStripButton // this.runTestToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.runTestToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.testToRun; this.runTestToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.runTestToolStripButton.Name = "runTestToolStripButton"; this.runTestToolStripButton.Size = new System.Drawing.Size(23, 22); this.runTestToolStripButton.Text = "Run Selected Test(s)"; this.runTestToolStripButton.Click += new System.EventHandler(this.runTestToolStripButton_Click); // // runTestOnAllChildrenToolStripButton // this.runTestOnAllChildrenToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.runTestOnAllChildrenToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.testToRunWithChildren; this.runTestOnAllChildrenToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.runTestOnAllChildrenToolStripButton.Name = "runTestOnAllChildrenToolStripButton"; this.runTestOnAllChildrenToolStripButton.Size = new System.Drawing.Size(23, 22); this.runTestOnAllChildrenToolStripButton.Text = "Run Selected Test On Selected Element and All Children Elements"; this.runTestOnAllChildrenToolStripButton.Visible = false; this.runTestOnAllChildrenToolStripButton.Click += new System.EventHandler(this.runTestOnAllChildrenToolStripButton_Click); // // splitter4 // this.splitter4.Dock = System.Windows.Forms.DockStyle.Top; this.splitter4.Location = new System.Drawing.Point(321, 310); this.splitter4.Name = "splitter4"; this.splitter4.Size = new System.Drawing.Size(506, 5); this.splitter4.TabIndex = 9; this.splitter4.TabStop = false; // // groupBox5 // this.groupBox5.Controls.Add(this._testResults); this.groupBox5.Controls.Add(this._testResultsToolStrip); this.groupBox5.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox5.Location = new System.Drawing.Point(321, 315); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(506, 348); this.groupBox5.TabIndex = 10; this.groupBox5.TabStop = false; this.groupBox5.Text = "Test Results"; // // _testResults // this._testResults.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._testResults.Dock = System.Windows.Forms.DockStyle.Fill; this._testResults.Location = new System.Drawing.Point(3, 41); this._testResults.Name = "_testResults"; this._testResults.Size = new System.Drawing.Size(500, 304); this._testResults.TabIndex = 1; this._testResults.NavigationChanged += new VisualUIAVerify.Controls.NavigationChangedEventHandler(this._testResults_NavigationChanged); // // _testResultsToolStrip // this._testResultsToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this._testResultsToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.backToolStripButton, this.forwardToolStripButton, this.toolStripSeparator6, this.overallToolStripButton, this.allResultsToolStripButton, this.FullDetailToolStripButton, this.xmlToolStripButton, this.toolStripSeparator7, this.quickFindToolStripButton, this.toolStripSeparator8, this.openInNewWindowToolStripButton}); this._testResultsToolStrip.Location = new System.Drawing.Point(3, 16); this._testResultsToolStrip.Name = "_testResultsToolStrip"; this._testResultsToolStrip.Size = new System.Drawing.Size(500, 25); this._testResultsToolStrip.TabIndex = 0; this._testResultsToolStrip.Text = "toolStrip4"; // // backToolStripButton // this.backToolStripButton.Enabled = false; this.backToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("backToolStripButton.Image"))); this.backToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.backToolStripButton.Name = "backToolStripButton"; this.backToolStripButton.Size = new System.Drawing.Size(52, 22); this.backToolStripButton.Text = "Back"; this.backToolStripButton.Click += new System.EventHandler(this.backToolStripButton_Click); // // forwardToolStripButton // this.forwardToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.forwardToolStripButton.Enabled = false; this.forwardToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("forwardToolStripButton.Image"))); this.forwardToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.forwardToolStripButton.Name = "forwardToolStripButton"; this.forwardToolStripButton.Size = new System.Drawing.Size(23, 22); this.forwardToolStripButton.Text = "Forward"; this.forwardToolStripButton.Click += new System.EventHandler(this.forwardToolStripButton_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); // // overallToolStripButton // this.overallToolStripButton.Checked = true; this.overallToolStripButton.CheckState = System.Windows.Forms.CheckState.Checked; this.overallToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.overallToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("overallToolStripButton.Image"))); this.overallToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.overallToolStripButton.Name = "overallToolStripButton"; this.overallToolStripButton.Size = new System.Drawing.Size(48, 22); this.overallToolStripButton.Text = "Overall"; this.overallToolStripButton.Click += new System.EventHandler(this._testResultsToolStrip_ButtonClick); // // allResultsToolStripButton // this.allResultsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.allResultsToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("allResultsToolStripButton.Image"))); this.allResultsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.allResultsToolStripButton.Name = "allResultsToolStripButton"; this.allResultsToolStripButton.Size = new System.Drawing.Size(65, 22); this.allResultsToolStripButton.Text = "All Results"; this.allResultsToolStripButton.Click += new System.EventHandler(this._testResultsToolStrip_ButtonClick); // // FullDetailToolStripButton // this.FullDetailToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.FullDetailToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("FullDetailToolStripButton.Image"))); this.FullDetailToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.FullDetailToolStripButton.Name = "FullDetailToolStripButton"; this.FullDetailToolStripButton.Size = new System.Drawing.Size(53, 22); this.FullDetailToolStripButton.Text = "Full Log"; this.FullDetailToolStripButton.Click += new System.EventHandler(this._testResultsToolStrip_ButtonClick); // // xmlToolStripButton // this.xmlToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.xmlToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("xmlToolStripButton.Image"))); this.xmlToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.xmlToolStripButton.Name = "xmlToolStripButton"; this.xmlToolStripButton.Size = new System.Drawing.Size(35, 22); this.xmlToolStripButton.Text = "XML"; this.xmlToolStripButton.Click += new System.EventHandler(this._testResultsToolStrip_ButtonClick); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25); // // quickFindToolStripButton // this.quickFindToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.quickFind; this.quickFindToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.quickFindToolStripButton.Name = "quickFindToolStripButton"; this.quickFindToolStripButton.Size = new System.Drawing.Size(84, 22); this.quickFindToolStripButton.Text = "Quick Find"; this.quickFindToolStripButton.Click += new System.EventHandler(this.quickFindToolStripButton_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25); // // openInNewWindowToolStripButton // this.openInNewWindowToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.openInNewWindowToolStripButton.Image = global::VisualUIAVerify.VisualUIAVerifyResources.ieIcon; this.openInNewWindowToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.openInNewWindowToolStripButton.Name = "openInNewWindowToolStripButton"; this.openInNewWindowToolStripButton.Size = new System.Drawing.Size(23, 22); this.openInNewWindowToolStripButton.Text = "Open in new window"; this.openInNewWindowToolStripButton.Click += new System.EventHandler(this.openInNewWindowToolStripButton_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image"))); this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(60, 22); this.toolStripButton2.Text = "AllDetails"; // // toolStrip4 // this.toolStrip4.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip4.Location = new System.Drawing.Point(3, 16); this.toolStrip4.Name = "toolStrip4"; this.toolStrip4.Size = new System.Drawing.Size(241, 25); this.toolStrip4.TabIndex = 0; this.toolStrip4.Text = "toolStrip4"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(48, 22); this.toolStripButton1.Text = "Overall"; // // MainWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1032, 685); this.Controls.Add(this.groupBox5); this.Controls.Add(this.splitter4); this.Controls.Add(this.groupBox4); this.Controls.Add(this.splitter3); this.Controls.Add(this.groupBox3); this.Controls.Add(this.splitter2); this.Controls.Add(this.panel1); this.Controls.Add(this.menuStrip1); this.Controls.Add(this.statusStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "MainWindow"; this.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultBounds; this.Text = "Visual UI Automation Verify"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.panel1.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.toolStrip5.ResumeLayout(false); this.toolStrip5.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.toolStrip2.ResumeLayout(false); this.toolStrip2.PerformLayout(); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this._testResultsToolStrip.ResumeLayout(false); this._testResultsToolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveLogToolStripMenuItem; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.GroupBox groupBox1; private VisualUIAVerify.Controls.AutomationElementTreeControl _automationElementTree; private System.Windows.Forms.Splitter splitter2; private System.Windows.Forms.ToolStripStatusLabel _messageToolStrip; private System.Windows.Forms.ToolStripProgressBar _progressToolStrip; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem highlightingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem rectangleHighlightingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fadingRectangleHighlightingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem raysAndRectangleHighlightingToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem noneHighlightingToolStripMenuItem; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Splitter splitter3; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.Splitter splitter4; private System.Windows.Forms.GroupBox groupBox5; private Controls.AutomationElementPropertyGrid _automationElementPropertyGrid; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton goToParentToolStripButton; private System.Windows.Forms.ToolStripButton goToFirstChildToolStripButton; private System.Windows.Forms.ToolStripButton goToNextSiblingToolStripButton; private System.Windows.Forms.ToolStripButton goToPrevSiblingToolStripButton; private System.Windows.Forms.ToolStripButton goToLastChildToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStrip toolStrip2; private System.Windows.Forms.ToolStrip _testResultsToolStrip; private System.Windows.Forms.ToolStrip toolStrip5; private VisualUIAVerify.Controls.TestResultsControl _testResults; private System.Windows.Forms.ToolStripMenuItem modeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem alwaysOnTopToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem hoverModeToolStripMenuItem; private System.Windows.Forms.ToolStripButton FocusTrackingToolStripMenuItem; private System.Windows.Forms.ToolStripDropDownButton testsScopeToolStrip; private System.Windows.Forms.ToolStripMenuItem testsForSelectedAutomationElementToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem allTestsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripDropDownButton testTypesMenuToolStrip; private System.Windows.Forms.ToolStripMenuItem automationElementTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem patternTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem controlTestsToolStripMenuItem; private System.Windows.Forms.ToolStripDropDownButton testPrioritiesToolStrip; private System.Windows.Forms.ToolStripMenuItem buildVerificationTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem priority0TestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem priority1TestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem priority2TestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem priority3TestsToolStripMenuItem; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStrip toolStrip4; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton overallToolStripButton; private System.Windows.Forms.ToolStripButton FullDetailToolStripButton; private System.Windows.Forms.ToolStripButton xmlToolStripButton; private System.Windows.Forms.ToolStripButton allResultsToolStripButton; private System.Windows.Forms.ToolStripButton backToolStripButton; private System.Windows.Forms.ToolStripButton forwardToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripButton quickFindToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripButton openInNewWindowToolStripButton; private System.Windows.Forms.ToolStripButton showCategoriesToolStripButton; private System.Windows.Forms.ToolStripButton sortAlphabeticalToolStripButton; private System.Windows.Forms.ToolStripButton refreshElementToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripMenuItem automationElementTreeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem refreshToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem navigationToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem parentToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem firstChildToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem nextSiblingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem prevSiblingToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem lastChildToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private System.Windows.Forms.ToolStripMenuItem focusTrackingToolStripMenuItem1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; private System.Windows.Forms.ToolStripButton goLeftToolStripButton; private System.Windows.Forms.ToolStripButton goUpToolStripButton; private System.Windows.Forms.ToolStripButton goDownToolStripButton; private System.Windows.Forms.ToolStripButton goRightToolStripButton; private System.Windows.Forms.ToolStripMenuItem testsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem goLeftToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem goUpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem goDownToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem goRightToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.ToolStripButton runTestToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator13; private System.Windows.Forms.ToolStripMenuItem runSelectedTestToolStripMenuItem; private System.Windows.Forms.ToolStripButton refreshTestsToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator14; private System.Windows.Forms.ToolStripButton refreshPropertyPaneToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private System.Windows.Forms.ToolStripSeparator toolStripButton4; private System.Windows.Forms.ToolStripButton expandAllToolStripButton; private System.Windows.Forms.ToolStripButton runTestOnAllChildrenToolStripButton; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutVisualUIAVerifyToolStripMenuItem; /// <summary> /// /// </summary> public VisualUIAVerify.Controls.AutomationTestsControl _automationTests; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem filterKnownIssuesToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFilterFileDialog; private System.Windows.Forms.ToolStripMenuItem UnmanagedProxiesToolStripMenuItem; private System.Windows.Forms.SaveFileDialog saveLogFileDialog; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Runtime.Caching; using Abp.Runtime.Security; using Abp.Runtime.Session; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Users { /// <summary> /// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework. /// </summary> public abstract class AbpUserManager<TRole, TUser> : UserManager<TUser, long>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; } protected string LocalizationSourceName { get; set; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } public AbpUserStore<TRole, TUser> AbpStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; protected AbpUserManager( AbpUserStore<TRole, TUser> userStore, AbpRoleManager<TRole, TUser> roleManager, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ILocalizationManager localizationManager, IdentityEmailMessageService emailService, ISettingManager settingManager, IUserTokenProviderAccessor userTokenProviderAccessor) : base(userStore) { AbpStore = userStore; RoleManager = roleManager; LocalizationManager = localizationManager; LocalizationSourceName = AbpZeroConsts.LocalizationSourceName; _settingManager = settingManager; _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; AbpSession = NullAbpSession.Instance; UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; EmailService = emailService; UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>(); } public override async Task<IdentityResult> CreateAsync(TUser user) { user.SetNormalizedNames(); var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } InitializeLockoutSettings(user.TenantId); return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpStore.FindAllAsync(login); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType) { var identity = await base.CreateIdentityAsync(user, authenticationType); if (user.TenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture))); } return identity; } public async override Task<IdentityResult> UpdateAsync(TUser user) { user.SetNormalizedNames(); var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUser<TUser>.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName)); } } return await base.UpdateAsync(user); } public async override Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUser<TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword); if (!result.Succeeded) { return result; } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user.Id, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user.Id, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount)); } } public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } } [UnitOfWork] public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in AbpStore.Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return Task.FromResult(query.ToList()); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in AbpStore.Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return Task.FromResult(query.ToList()); } } public virtual void RegisterTwoFactorProviders(int? tenantId) { TwoFactorProviders.Clear(); if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId)) { return; } if (EmailService != null && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId)) { RegisterTwoFactorProvider( L("Email"), new EmailTokenProvider<TUser, long> { Subject = L("EmailSecurityCodeSubject"), BodyFormat = L("EmailSecurityCodeBody") } ); } if (SmsService != null && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId)) { RegisterTwoFactorProvider( L("Sms"), new PhoneNumberTokenProvider<TUser, long> { MessageFormat = L("SmsSecurityCodeMessage") } ); } } public virtual void InitializeLockoutSettings(int? tenantId) { UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.GetValidTwoFactorProvidersAsync(userId); } public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token); } public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider); } public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpStore.GetUserNameFromDatabaseAsync(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(userId)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } protected virtual string L(string name) { return LocalizationManager.GetString(LocalizationSourceName, name); } protected virtual string L(string name, CultureInfo cultureInfo) { return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias PDB; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; using PDB::Roslyn.Test.MetadataUtilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class Scope { internal readonly int StartOffset; internal readonly int EndOffset; internal readonly ImmutableArray<string> Locals; internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive) { this.StartOffset = startOffset; this.EndOffset = endOffset + (isEndInclusive ? 1 : 0); this.Locals = locals; } internal int Length { get { return this.EndOffset - this.StartOffset + 1; } } internal bool Contains(int offset) { return (offset >= this.StartOffset) && (offset < this.EndOffset); } } internal static class ExpressionCompilerTestHelpers { internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileAssignment( target, expr, ImmutableArray<Alias>.Empty, formatter ?? DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); // This is a crude way to test the language, but it's convenient to share this test helper. var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0; var expectedFlags = error != null ? DkmClrCompilationResultFlags.None : isCSharp ? DkmClrCompilationResultFlags.PotentialSideEffect : DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult; Assert.Equal(expectedFlags, resultProperties.Flags); Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType); Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); return result; } internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileAssignment(target, expr, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = context.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static ReadOnlyCollection<byte> CompileGetLocals( this EvaluationContextBase context, ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, out string typeName, CompilationTestData testData, DiagnosticDescription[] expectedDiagnostics = null) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileGetLocals( locals, argumentsOnly, ImmutableArray<Alias>.Empty, diagnostics, out typeName, testData); diagnostics.Verify(expectedDiagnostics ?? DiagnosticDescription.None); diagnostics.Free(); return result; } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; return CompileExpression(context, expr, out resultProperties, out error, testData, formatter); } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out ResultProperties resultProperties, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray<Alias>.Empty, formatter ?? DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } static internal CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = evaluationContext.CompileExpression( expr, compilationFlags, aliases, formatter ?? DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } /// <summary> /// Compile C# expression and emit assembly with evaluation method. /// </summary> /// <returns> /// Result containing generated assembly, type and method names, and any format specifiers. /// </returns> static internal CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = evaluationContext.CompileExpression(expr, compilationFlags, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = evaluationContext.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, EvaluationContextBase context, ExpressionCompiler.CompileDelegate<CompileResult> compile, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage) { return ExpressionCompiler.CompileWithRetry( metadataBlocks, DiagnosticFormatter.Instance, (blocks, useReferencedModulesOnly) => context, compile, getMetaDataBytesPtr, out errorMessage); } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, string expr, ExpressionCompiler.CreateContextDelegate createContext, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage, out CompilationTestData testData) { var r = ExpressionCompiler.CompileWithRetry( metadataBlocks, DiagnosticFormatter.Instance, createContext, (context, diagnostics) => { var td = new CompilationTestData(); ResultProperties resultProperties; var compileResult = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray<Alias>.Empty, diagnostics, out resultProperties, td); return new CompileExpressionResult(compileResult, td); }, getMetaDataBytesPtr, out errorMessage); testData = r.TestData; return r.CompileResult; } private struct CompileExpressionResult { internal readonly CompileResult CompileResult; internal readonly CompilationTestData TestData; internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData) { this.CompileResult = compileResult; this.TestData = testData; } } internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName) { return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName)); } internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName)); } internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName)); } internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames) { var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray(); Assert.True(expectedNames.SequenceEqual(actualNames)); } internal static AssemblyName GetAssemblyName(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { var metadataReader = reader.GetMetadataReader(); var def = metadataReader.GetAssemblyDefinition(); var name = metadataReader.GetString(def.Name); return new AssemblyName() { Name = name, Version = def.Version }; } } internal static Guid GetModuleVersionId(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { return reader.GetMetadataReader().GetModuleVersionId(); } } internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<string>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var names = ArrayBuilder<string>.GetInstance(); foreach (var scope in scopes) { var locals = scope.GetLocals(); foreach (var local in locals) { var name = local.GetName(); int slot; local.GetAddressField1(out slot); while (names.Count <= slot) { names.Add(null); } names[slot] = name; } } scopes.Free(); return names.ToImmutableAndFree(); } internal static void VerifyIL( this ImmutableArray<byte> assembly, string qualifiedName, string expectedIL, [CallerLineNumber]int expectedValueSourceLine = 0, [CallerFilePath]string expectedValueSourcePath = null) { var parts = qualifiedName.Split('.'); if (parts.Length != 2) { throw new NotImplementedException(); } using (var module = new PEModule(new PEReader(assembly), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0)) { var reader = module.MetadataReader; var typeDef = reader.GetTypeDef(parts[0]); var methodName = parts[1]; var methodHandle = reader.GetMethodDefHandle(typeDef, methodName); var methodBody = module.GetMethodBodyOrThrow(methodHandle); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; var writer = new StringWriter(pooled.Builder); var visualizer = new MetadataVisualizer(reader, writer); visualizer.VisualizeMethodBody(methodBody, methodHandle, emitHeader: false); var actualIL = pooled.ToStringAndFree(); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } } internal static bool EmitAndGetReferences( this Compilation compilation, out byte[] exeBytes, out byte[] pdbBytes, out ImmutableArray<MetadataReference> references) { using (var pdbStream = new MemoryStream()) { using (var exeStream = new MemoryStream()) { var result = compilation.Emit( peStream: exeStream, pdbStream: pdbStream, xmlDocumentationStream: null, win32Resources: null, manifestResources: null, options: EmitOptions.Default, testData: null, getHostDiagnostics: null, cancellationToken: default(CancellationToken)); if (!result.Success) { result.Diagnostics.Verify(); exeBytes = null; pdbBytes = null; references = default(ImmutableArray<MetadataReference>); return false; } exeBytes = exeStream.ToArray(); pdbBytes = pdbStream.ToArray(); } } // Determine the set of references that were actually used // and ignore any references that were dropped in emit. HashSet<string> referenceNames; using (var metadata = ModuleMetadata.CreateFromImage(exeBytes)) { var reader = metadata.MetadataReader; referenceNames = new HashSet<string>(reader.AssemblyReferences.Select(h => GetAssemblyReferenceName(reader, h))); } references = ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames))); return true; } internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<Scope>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), s.GetLocals().SelectAsArray(l => l.GetName()), isEndInclusive)); scopes.Free(); return result; } internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset) { Scope result = null; foreach (var scope in scopes) { if (scope.Contains(offset)) { if ((result == null) || (result.Length > scope.Length)) { result = scope; } } } return result; } private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle) { var reference = reader.GetAssemblyReference(handle); return reader.GetString(reference.Name); } private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames) { var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadata() as AssemblyMetadata; if (assemblyMetadata == null) { // Netmodule. Assume it is referenced. return true; } var name = assemblyMetadata.GetAssembly().Identity.Name; return referenceNames.Contains(name); } /// <summary> /// Verify the set of module metadata blocks /// contains all blocks referenced by the set. /// </summary> internal static void VerifyAllModules(this ImmutableArray<ModuleInstance> modules) { var blocks = modules.SelectAsArray(m => m.MetadataBlock).SelectAsArray(b => ModuleMetadata.CreateFromMetadata(b.Pointer, b.Size)); var names = new HashSet<string>(blocks.Select(b => b.Name)); foreach (var block in blocks) { foreach (var name in block.GetModuleNames()) { Assert.True(names.Contains(name)); } } } internal static ModuleMetadata GetModuleMetadata(this MetadataReference reference) { var metadata = ((MetadataImageReference)reference).GetMetadata(); var assemblyMetadata = metadata as AssemblyMetadata; Assert.True((assemblyMetadata == null) || (assemblyMetadata.GetModules().Length == 1)); return (assemblyMetadata == null) ? (ModuleMetadata)metadata : assemblyMetadata.GetModules()[0]; } internal static ModuleInstance ToModuleInstance( this MetadataReference reference, byte[] fullImage, object symReader, bool includeLocalSignatures = true) { var moduleMetadata = reference.GetModuleMetadata(); var moduleId = moduleMetadata.Module.GetModuleVersionIdOrThrow(); // The Expression Compiler expects metadata only, no headers or IL. var metadataBytes = moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent().ToArray(); return new ModuleInstance( reference, moduleMetadata, moduleId, fullImage, metadataBytes, symReader, includeLocalSignatures); } internal static AssemblyIdentity GetAssemblyIdentity(this MetadataReference reference) { var moduleMetadata = reference.GetModuleMetadata(); var reader = moduleMetadata.MetadataReader; return reader.ReadAssemblyIdentityOrThrow(); } internal static Guid GetModuleVersionId(this MetadataReference reference) { var moduleMetadata = reference.GetModuleMetadata(); var reader = moduleMetadata.MetadataReader; return reader.GetModuleVersionIdOrThrow(); } internal static void VerifyLocal<TMethodSymbol>( this CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName, DkmClrCompilationResultFlags expectedFlags, Action<TMethodSymbol> verifyTypeParameters, string expectedILOpt, bool expectedGeneric, string expectedValueSourcePath, int expectedValueSourceLine) where TMethodSymbol : IMethodSymbol { Assert.Equal(expectedLocalName, localAndMethod.LocalName); Assert.Equal(expectedLocalDisplayName, localAndMethod.LocalDisplayName); Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName, StringComparison.Ordinal), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters. Assert.Equal(expectedFlags, localAndMethod.Flags); var methodData = testData.GetMethodData(typeName + "." + expectedMethodName); verifyTypeParameters((TMethodSymbol)methodData.Method); if (expectedILOpt != null) { string actualIL = methodData.GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences( expectedILOpt, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } Assert.Equal(((Cci.IMethodDefinition)methodData.Method).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default); } internal static ISymUnmanagedReader ConstructSymReaderWithImports(byte[] exeBytes, string methodName, params string[] importStrings) { using (var peReader = new PEReader(ImmutableArray.Create(exeBytes))) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName)); var methodToken = metadataReader.GetToken(methodHandle); return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { importStrings }).Build() }, }.ToImmutableDictionary()); } } internal static readonly MetadataReference IntrinsicAssemblyReference = GetIntrinsicAssemblyReference(); internal static ImmutableArray<MetadataReference> AddIntrinsicAssembly(this ImmutableArray<MetadataReference> references) { var builder = ArrayBuilder<MetadataReference>.GetInstance(); builder.AddRange(references); builder.Add(IntrinsicAssemblyReference); return builder.ToImmutableAndFree(); } private static MetadataReference GetIntrinsicAssemblyReference() { var source = @".assembly extern mscorlib { } .class public Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods { .method public static object GetObjectAtAddress(uint64 address) { ldnull throw } .method public static class [mscorlib]System.Exception GetException() { ldnull throw } .method public static class [mscorlib]System.Exception GetStowedException() { ldnull throw } .method public static object GetReturnValue(int32 index) { ldnull throw } .method public static void CreateVariable(class [mscorlib]System.Type 'type', string name, valuetype [mscorlib]System.Guid customTypeInfoPayloadTypeId, uint8[] customTypeInfoPayload) { ldnull throw } .method public static object GetObjectByAlias(string name) { ldnull throw } .method public static !!T& GetVariableAddress<T>(string name) { ldnull throw } }"; return CommonTestBase.CompileIL(source); } /// <summary> /// Return MetadataReferences to the .winmd assemblies /// for the given namespaces. /// </summary> internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces) { var paths = new HashSet<string>(); foreach (var @namespace in namespaces) { foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null)) { paths.Add(path); } } return ImmutableArray.CreateRange(paths.Select(GetAssembly)); } private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319"; private const string Version1_3String = "WindowsRuntime 1.3"; private const string Version1_4String = "WindowsRuntime 1.4"; private static readonly int s_versionStringLength = Version1_3CLRString.Length; private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength); private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength); private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength); private static byte[] ToByteArray(string str, int length) { var bytes = new byte[length]; for (int i = 0; i < str.Length; i++) { bytes[i] = (byte)str[i]; } return bytes; } internal static byte[] ToVersion1_3(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes); } internal static byte[] ToVersion1_4(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes); } private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to) { int n = bytes.Length; var copy = new byte[n]; Array.Copy(bytes, copy, n); int index = IndexOf(copy, from); Array.Copy(to, 0, copy, index, to.Length); return copy; } private static int IndexOf(byte[] a, byte[] b) { int m = b.Length; int n = a.Length - m; for (int x = 0; x < n; x++) { var matches = true; for (int y = 0; y < m; y++) { if (a[x + y] != b[y]) { matches = false; break; } } if (matches) { return x; } } return -1; } private static MetadataReference GetAssembly(string path) { var bytes = File.ReadAllBytes(path); var metadata = ModuleMetadata.CreateFromImage(bytes); return metadata.GetReference(filePath: path); } internal static int GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber = -1) { int ilOffset; if (symReader == null) { ilOffset = 0; } else { var symMethod = symReader.GetMethod(methodToken); if (symMethod == null) { ilOffset = 0; } else { var sequencePoints = symMethod.GetSequencePoints(); ilOffset = atLineNumber < 0 ? sequencePoints.Where(sp => sp.StartLine != SequencePointList.HiddenSequencePointLine).Select(sp => sp.Offset).FirstOrDefault() : sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset; } } Assert.InRange(ilOffset, 0, int.MaxValue); return ilOffset; } internal static string GetMethodOrTypeSignatureParts(string signature, out string[] parameterTypeNames) { var parameterListStart = signature.IndexOf('('); if (parameterListStart < 0) { parameterTypeNames = null; return signature; } var parameters = signature.Substring(parameterListStart + 1, signature.Length - parameterListStart - 2); var methodName = signature.Substring(0, parameterListStart); parameterTypeNames = (parameters.Length == 0) ? new string[0] : parameters.Split(','); return methodName; } } }
using System; using System.Reflection; using System.Threading.Tasks; using System.Windows.Input; using Mvvm.Properties; namespace Mvvm.Commands { /// <summary> /// An <see cref="ICommand" /> whose delegates can be attached for <see cref="Execute" /> and <see cref="CanExecute" /> /// . /// </summary> /// <typeparam name="T">Parameter type.</typeparam> /// <remarks> /// The constructor deliberately prevents the use of value types. /// Because ICommand takes an object, having a value type for T would cause unexpected behavior when CanExecute(null) /// is called during XAML initialization for command bindings. /// Using default(T) was considered and rejected as a solution because the implementor would not be able to distinguish /// between a valid and defaulted values. /// <para /> /// Instead, callers should support a value type by using a nullable value type and checking the HasValue property /// before using the Value property. /// <example> /// <code> /// public MyClass() /// { /// this.submitCommand = new DelegateCommand&lt;int?&gt;(this.Submit, this.CanSubmit); /// } /// /// private bool CanSubmit(int? customerId) /// { /// return (customerId.HasValue &amp;&amp; customers.Contains(customerId.Value)); /// } /// </code> /// </example> /// </remarks> public class DelegateCommand<T> : DelegateCommandBase { /// <summary> /// Initializes a new instance of <see cref="DelegateCommand{T}" />. /// </summary> /// <param name="executeMethod"> /// Delegate to execute when Execute is called on the command. This can be null to just hook up /// a CanExecute delegate. /// </param> /// <remarks><see cref="CanExecute" /> will always return true.</remarks> public DelegateCommand(Action<T> executeMethod) : this(executeMethod, o => true) { } /// <summary> /// Initializes a new instance of <see cref="DelegateCommand{T}" />. /// </summary> /// <param name="executeMethod"> /// Delegate to execute when Execute is called on the command. This can be null to just hook up /// a CanExecute delegate. /// </param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <param name="isAutomaticRequeryDisabled"></param> /// <exception cref="ArgumentNullException"> /// When both <paramref name="executeMethod" /> and /// <paramref name="canExecuteMethod" /> ar <see langword="null" />. /// </exception> public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod, bool isAutomaticRequeryDisabled = false) : base(o => executeMethod((T) o), o => canExecuteMethod((T) o), isAutomaticRequeryDisabled) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException(nameof(executeMethod), Resources.DelegateCommandDelegatesCannotBeNull); var genericTypeInfo = typeof (T).GetTypeInfo(); // DelegateCommand allows object or Nullable<>. // note: Nullable<> is a struct so we cannot use a class constraint. if (genericTypeInfo.IsValueType) { if ((!genericTypeInfo.IsGenericType) || (!typeof (Nullable<>).GetTypeInfo() .IsAssignableFrom(genericTypeInfo.GetGenericTypeDefinition().GetTypeInfo()))) { throw new InvalidCastException(Resources.DelegateCommandInvalidGenericPayloadType); } } } private DelegateCommand(Func<T, Task> executeMethod) : this(executeMethod, o => true) { } private DelegateCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod, bool isAutomaticRequeryDisabled = false) : base(o => executeMethod((T) o), o => canExecuteMethod((T) o), isAutomaticRequeryDisabled) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException(nameof(executeMethod), Resources.DelegateCommandDelegatesCannotBeNull); } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand{T}" /> from an awaitable handler method. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command.</param> /// <returns>Constructed instance of <see cref="DelegateCommand{T}" /></returns> public static DelegateCommand<T> FromAsyncHandler(Func<T, Task> executeMethod) { return new DelegateCommand<T>(executeMethod); } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand{T}" /> from an awaitable handler method. /// </summary> /// <param name="executeMethod"> /// Delegate to execute when Execute is called on the command. This can be null to just hook up /// a CanExecute delegate. /// </param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <param name="isAutomaticRequeryDisabled"></param> /// <returns>Constructed instance of <see cref="DelegateCommand{T}" /></returns> public static DelegateCommand<T> FromAsyncHandler(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod, bool isAutomaticRequeryDisabled = false) { return new DelegateCommand<T>(executeMethod, canExecuteMethod, isAutomaticRequeryDisabled); } /// <summary> /// Determines if the command can execute by invoked the <see cref="Func{T,Bool}" /> provided during construction. /// </summary> /// <param name="parameter">Data used by the command to determine if it can execute.</param> /// <returns> /// <see langword="true" /> if this command can be executed; otherwise, <see langword="false" />. /// </returns> public virtual bool CanExecute(T parameter) { return base.CanExecute(parameter); } /// <summary> /// Executes the command and invokes the <see cref="Action{T}" /> provided during construction. /// </summary> /// <param name="parameter">Data used by the command.</param> public virtual async Task Execute(T parameter) { await base.Execute(parameter); } } /// <summary> /// An <see cref="ICommand" /> whose delegates do not take any parameters for <see cref="Execute" /> and /// <see cref="CanExecute" />. /// </summary> /// <see cref="DelegateCommandBase" /> /// <see cref="DelegateCommand{T}" /> public class DelegateCommand : DelegateCommandBase { /// <summary> /// Creates a new instance of <see cref="DelegateCommand" /> with the <see cref="Action" /> to invoke on execution. /// </summary> /// <param name="executeMethod">The <see cref="Action" /> to invoke when <see cref="ICommand.Execute" /> is called.</param> public DelegateCommand(Action executeMethod) : this(executeMethod, () => true) { } /// <summary> /// Creates a new instance of <see cref="DelegateCommand" /> with the <see cref="Action" /> to invoke on execution /// and a <see langword="Func" /> to query for determining if the command can execute. /// </summary> /// <param name="executeMethod">The <see cref="Action" /> to invoke when <see cref="ICommand.Execute" /> is called.</param> /// <param name="canExecuteMethod"> /// The <see cref="Func{TResult}" /> to invoke when <see cref="ICommand.CanExecute" /> is /// called /// </param> /// <param name="isAutomaticRequeryDisabled"></param> public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod, bool isAutomaticRequeryDisabled = false) : base(o => executeMethod(), o => canExecuteMethod(), isAutomaticRequeryDisabled) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException(nameof(executeMethod), Resources.DelegateCommandDelegatesCannotBeNull); } private DelegateCommand(Func<Task> executeMethod) : this(executeMethod, () => true) { } private DelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod, bool isAutomaticRequeryDisabled = false) : base(o => executeMethod(), o => canExecuteMethod(), isAutomaticRequeryDisabled) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException(nameof(executeMethod), Resources.DelegateCommandDelegatesCannotBeNull); } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand" /> from an awaitable handler method. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command.</param> /// <returns>Constructed instance of <see cref="DelegateCommand" /></returns> public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod) { return new DelegateCommand(executeMethod); } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand" /> from an awaitable handler method. /// </summary> /// <param name="executeMethod"> /// Delegate to execute when Execute is called on the command. This can be null to just hook up /// a CanExecute delegate. /// </param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <param name="isAutomaticRequeryDisabled"></param> /// <returns>Constructed instance of <see cref="DelegateCommand" /></returns> public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod, Func<bool> canExecuteMethod, bool isAutomaticRequeryDisabled = false) { return new DelegateCommand(executeMethod, canExecuteMethod, isAutomaticRequeryDisabled); } /// <summary> /// Executes the command. /// </summary> public virtual async Task Execute() { await Execute(null); } /// <summary> /// Determines if the command can be executed. /// </summary> /// <returns>Returns <see langword="true" /> if the command can execute, otherwise returns <see langword="false" />.</returns> public virtual bool CanExecute() { return CanExecute(null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; // Gregorian Calendars use Era Info // Note: We shouldn't have to serialize this since the info doesn't change, but we have been. // (We really only need the calendar #, and maybe culture) [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) [OptionalField(VersionAdded = 4)] internal String eraName; // The era name [OptionalField(VersionAdded = 4)] internal String abbrevEraName; // Abbreviated Era Name [OptionalField(VersionAdded = 4)] internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // Strictly these don't need serialized since they can be recreated from the calendar id [OptionalField(VersionAdded = 1)] internal int m_maxYear = 9999; [OptionalField(VersionAdded = 1)] internal int m_minYear; internal Calendar m_Cal; // Era information doesn't need serialized, its constant for the same calendars (ie: we can recreate it from the calendar id) [OptionalField(VersionAdded = 1)] internal EraInfo[] m_EraInfo; [OptionalField(VersionAdded = 1)] internal int[] m_eras = null; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. [OptionalField(VersionAdded = 1)] internal DateTime m_minDate; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. m_minDate = m_Cal.MinSupportedDateTime; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear;; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day)* TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond);; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"), m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException("time", Environment.GetResourceString("ArgumentOutOfRange_Era")); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax/100 - ( y > twoDigitYearMax % 100 ? 1 : 0))*100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
// 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. /*============================================================================= ** ** ** Purpose: An array implementation of a generic stack. ** ** =============================================================================*/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class Stack<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; // Storage for stack elements private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. private Object _syncRoot; private const int DefaultCapacity = 4; /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack"]/*' /> public Stack() { _array = Array.Empty<T>(); } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack1"]/*' /> public Stack(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _array = new T[capacity]; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack2"]/*' /> public Stack(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Count"]/*' /> public int Count { get { return _size; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IsSynchronized"]/*' /> bool System.Collections.ICollection.IsSynchronized { get { return false; } } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.SyncRoot"]/*' /> Object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Clear"]/*' /> public void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Contains"]/*' /> public bool Contains(T item) { int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default; while (count-- > 0) { if (c.Equals(_array[count], item)) { return true; } } return false; } // Copies the stack into an array. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.CopyTo"]/*' /> public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Debug.Assert(array != _array); int srcIndex = 0; int dstIndex = arrayIndex + _size; for (int i = 0; i < _size; i++) array[--dstIndex] = _array[srcIndex++]; } void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Returns an IEnumerator for this Stack. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.GetEnumerator"]/*' /> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { Array.Resize(ref _array, _size); _version++; } } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Peek"]/*' /> public T Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); return _array[_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Pop"]/*' /> public T Pop() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); _version++; T item = _array[--_size]; _array[_size] = default(T); // Free memory quicker. return item; } // Pushes an item to the top of the stack. // /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Push"]/*' /> public void Push(T item) { if (_size == _array.Length) { Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length); } _array[_size++] = item; _version++; } // Copies the Stack to an array, in the same order Pop would return the items. public T[] ToArray() { if (_size == 0) return Array.Empty<T>(); T[] objArray = new T[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator"]/*' /> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private Stack<T> _stack; private int _index; private int _version; private T _currentElement; internal Enumerator(Stack<T> stack) { _stack = stack; _version = _stack._version; _index = -2; _currentElement = default(T); } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Dispose"]/*' /> public void Dispose() { _index = -1; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.MoveNext"]/*' /> public bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = default(T); return retval; } /// <include file='doc\Stack.uex' path='docs/doc[@for="StackEnumerator.Current"]/*' /> public T Current { get { if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _currentElement; } } Object System.Collections.IEnumerator.Current { get { return Current; } } void System.Collections.IEnumerator.Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = default(T); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.IO; using System.Collections.Generic; namespace System.IO.Tests { public class MemoryStream_TryGetBufferTests { [Fact] public static void TryGetBuffer_Constructor_AlwaysReturnsTrue() { var stream = new MemoryStream(); ArraySegment<byte> segment; Assert.True(stream.TryGetBuffer(out segment)); Assert.NotNull(segment.Array); Assert.Equal(0, segment.Offset); Assert.Equal(0, segment.Count); } [Fact] public static void TryGetBuffer_Constructor_Int32_AlwaysReturnsTrue() { var stream = new MemoryStream(512); ArraySegment<byte> segment; Assert.True(stream.TryGetBuffer(out segment)); Assert.Equal(512, segment.Array.Length); Assert.Equal(0, segment.Offset); Assert.Equal(0, segment.Count); } [Fact] public static void TryGetBuffer_Constructor_ByteArray_AlwaysReturnsFalse() { var stream = new MemoryStream(new byte[512]); ArraySegment<byte> segment; Assert.False(stream.TryGetBuffer(out segment)); } [Fact] public static void TryGetBuffer_Constructor_ByteArray_Bool_AlwaysReturnsFalse() { var stream = new MemoryStream(new byte[512], writable: true); ArraySegment<byte> segment; Assert.False(stream.TryGetBuffer(out segment)); } [Fact] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_AlwaysReturnsFalse() { var stream = new MemoryStream(new byte[512], index: 0, count: 512); ArraySegment<byte> segment; Assert.False(stream.TryGetBuffer(out segment)); } [Fact] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_AlwaysReturnsFalse() { var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true); ArraySegment<byte> segment; Assert.False(stream.TryGetBuffer(out segment)); } [Fact] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_FalseAsPubliclyVisible_ReturnsFalse() { var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true, publiclyVisible: false); ArraySegment<byte> segment; Assert.False(stream.TryGetBuffer(out segment)); } [Fact] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_TrueAsPubliclyVisible_ReturnsTrue() { var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true, publiclyVisible: true); ArraySegment<byte> segment; Assert.True(stream.TryGetBuffer(out segment)); Assert.NotNull(segment.Array); Assert.Equal(512, segment.Array.Length); Assert.Equal(0, segment.Offset); Assert.Equal(512, segment.Count); } [Theory] [MemberData(nameof(GetArraysVariedBySize))] public static void TryGetBuffer_Constructor_ByteArray_AlwaysReturnsEmptyArraySegment(byte[] array) { var stream = new MemoryStream(array); ArraySegment<byte> result; Assert.False(stream.TryGetBuffer(out result)); // publiclyVisible = false; Assert.True(default(ArraySegment<byte>).Equals(result)); } [Theory] [MemberData(nameof(GetArraysVariedBySize))] public static void TryGetBuffer_Constructor_ByteArray_Bool_AlwaysReturnsEmptyArraySegment(byte[] array) { var stream = new MemoryStream(array, writable: true); ArraySegment<byte> result; Assert.False(stream.TryGetBuffer(out result)); // publiclyVisible = false; Assert.True(default(ArraySegment<byte>).Equals(result)); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_AlwaysReturnsEmptyArraySegment(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count); ArraySegment<byte> result; Assert.False(stream.TryGetBuffer(out result)); // publiclyVisible = false; Assert.True(default(ArraySegment<byte>).Equals(result)); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_AlwaysReturnsEmptyArraySegment(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true); ArraySegment<byte> result; Assert.False(stream.TryGetBuffer(out result)); // publiclyVisible = false; Assert.True(default(ArraySegment<byte>).Equals(result)); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_FalseAsPubliclyVisible_ReturnsEmptyArraySegment(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: false); ArraySegment<byte> result; Assert.False(stream.TryGetBuffer(out result)); // publiclyVisible = false; Assert.True(default(ArraySegment<byte>).Equals(result)); } [Fact] public static void TryGetBuffer_Constructor_AlwaysReturnsOffsetSetToZero() { var stream = new MemoryStream(); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(0, result.Offset); } [Fact] public static void TryGetBuffer_Constructor_Int32_AlwaysReturnsOffsetSetToZero() { var stream = new MemoryStream(512); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(0, result.Offset); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsIndexAndTrueAsPubliclyVisible_AlwaysReturnsOffsetSetToIndex(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(array.Offset, result.Offset); } [Fact] public static void TryGetBuffer_Constructor_ByDefaultReturnsCountSetToZero() { var stream = new MemoryStream(); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(0, result.Count); } [Theory] [MemberData(nameof(GetArraysVariedBySize))] public static void TryGetBuffer_Constructor_ReturnsCountSetToWrittenLength(byte[] array) { var stream = new MemoryStream(); stream.Write(array, 0, array.Length); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(array.Length, result.Count); } [Fact] public static void TryGetBuffer_Constructor_Int32_ByDefaultReturnsCountSetToZero() { var stream = new MemoryStream(512); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(0, result.Offset); } [Theory] [MemberData(nameof(GetArraysVariedBySize))] public static void TryGetBuffer_Constructor_Int32_ReturnsCountSetToWrittenLength(byte[] array) { var stream = new MemoryStream(512); stream.Write(array, 0, array.Length); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(array.Length, result.Count); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsCountAndTrueAsPubliclyVisible_AlwaysReturnsCountSetToCount(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(array.Count, result.Count); } [Fact] public static void TryGetBuffer_Constructor_ReturnsArray() { var stream = new MemoryStream(); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.NotNull(result.Array); } [Fact] public static void TryGetBuffer_Constructor_MultipleCallsReturnsSameArray() { var stream = new MemoryStream(); ArraySegment<byte> result1; ArraySegment<byte> result2; Assert.True(stream.TryGetBuffer(out result1)); Assert.True(stream.TryGetBuffer(out result2)); Assert.Same(result1.Array, result2.Array); } [Fact] public static void TryGetBuffer_Constructor_Int32_MultipleCallsReturnSameArray() { var stream = new MemoryStream(512); ArraySegment<byte> result1; ArraySegment<byte> result2; Assert.True(stream.TryGetBuffer(out result1)); Assert.True(stream.TryGetBuffer(out result2)); Assert.Same(result1.Array, result2.Array); } [Fact] public static void TryGetBuffer_Constructor_Int32_WhenWritingPastCapacity_ReturnsDifferentArrays() { var stream = new MemoryStream(512); ArraySegment<byte> result1; Assert.True(stream.TryGetBuffer(out result1)); // Force the stream to resize the underlying array stream.Write(new byte[1024], 0, 1024); ArraySegment<byte> result2; Assert.True(stream.TryGetBuffer(out result2)); Assert.NotSame(result1.Array, result2.Array); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsBufferAndTrueAsPubliclyVisible_AlwaysReturnsArraySetToBuffer(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Same(array.Array, result.Array); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_WhenDisposed_ReturnsTrue(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); stream.Dispose(); ArraySegment<byte> segment; Assert.True(stream.TryGetBuffer(out segment)); Assert.Same(array.Array, segment.Array); Assert.Equal(array.Offset, segment.Offset); Assert.Equal(array.Count, segment.Count); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_WhenDisposed_ReturnsOffsetSetToIndex(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); stream.Dispose(); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(array.Offset, result.Offset); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_WhenDisposed_ReturnsCountSetToCount(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); stream.Dispose(); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Equal(array.Count, result.Count); } [Theory] [MemberData(nameof(GetArraysVariedByOffsetAndLength))] public static void TryGetBuffer_WhenDisposed_ReturnsArraySetToBuffer(ArraySegment<byte> array) { var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true); stream.Dispose(); ArraySegment<byte> result; Assert.True(stream.TryGetBuffer(out result)); Assert.Same(array.Array, result.Array); } public static IEnumerable<object[]> GetArraysVariedByOffsetAndLength() { yield return new object[] { new ArraySegment<byte>(new byte[512], 0, 512) }; yield return new object[] { new ArraySegment<byte>(new byte[512], 1, 511) }; yield return new object[] { new ArraySegment<byte>(new byte[512], 2, 510) }; yield return new object[] { new ArraySegment<byte>(new byte[512], 256, 256) }; yield return new object[] { new ArraySegment<byte>(new byte[512], 512, 0) }; yield return new object[] { new ArraySegment<byte>(new byte[512], 511, 1) }; yield return new object[] { new ArraySegment<byte>(new byte[512], 510, 2) }; } public static IEnumerable<object[]> GetArraysVariedBySize() { yield return new object[] { FillWithData(new byte[0]) }; yield return new object[] { FillWithData(new byte[1]) }; yield return new object[] { FillWithData(new byte[2]) }; yield return new object[] { FillWithData(new byte[254]) }; yield return new object[] { FillWithData(new byte[255]) }; yield return new object[] { FillWithData(new byte[256]) }; yield return new object[] { FillWithData(new byte[511]) }; yield return new object[] { FillWithData(new byte[512]) }; yield return new object[] { FillWithData(new byte[513]) }; yield return new object[] { FillWithData(new byte[1023]) }; yield return new object[] { FillWithData(new byte[1024]) }; yield return new object[] { FillWithData(new byte[1025]) }; yield return new object[] { FillWithData(new byte[2047]) }; yield return new object[] { FillWithData(new byte[2048]) }; yield return new object[] { FillWithData(new byte[2049]) }; } private static byte[] FillWithData(byte[] buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)i; } return buffer; } } }
/* 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.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Windows.Forms; using ESRI.ArcGIS.DataSourcesGDB; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; namespace RasterSyncExtensionReg { /// <summary> /// A static class with a Main method for registering the RasterSyncExtension.RasterSyncWorkspaceExtension class. /// </summary> public class RegisterExtension { /// <summary> /// A path to the geodatabase's connection file. /// </summary> private static readonly String workspacePath = @"C:\MyGeodatabase.sde"; /// <summary> /// The type of geodatabase the extension is being registered with. /// </summary> private static readonly GeodatabaseType geodatabaseType = GeodatabaseType.ArcSDE; /// <summary> /// The GUID of the workspace extension to register. /// </summary> private static readonly String extensionGuid = "{97CD2883-37CB-4f76-BD0F-945279C783DC}"; public static void Main(string[] args) { #region Licensing ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); IAoInitialize aoInitialize = new AoInitializeClass(); esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut) { MessageBox.Show("An Advanced License could not be checked out."); return; } #endregion try { // Open the workspace. IWorkspaceFactory workspaceFactory = null; switch (geodatabaseType) { case GeodatabaseType.ArcSDE: workspaceFactory = new SdeWorkspaceFactoryClass(); break; case GeodatabaseType.FileGDB: workspaceFactory = new FileGDBWorkspaceFactoryClass(); break; case GeodatabaseType.PersonalGDB: workspaceFactory = new AccessWorkspaceFactoryClass(); break; } IWorkspace workspace = workspaceFactory.OpenFromFile(workspacePath, 0); IWorkspaceExtensionManager workspaceExtensionManager = (IWorkspaceExtensionManager)workspace; // Create a UID for the workspace extension. UID uid = new UIDClass(); uid.Value = extensionGuid; // Determine whether there are any existing geodatabase-register extensions. // To disambiguate between GDB-register extensions and component category extensions, // check the extension count of a new scratch workspace. IScratchWorkspaceFactory scratchWorkspaceFactory = new FileGDBScratchWorkspaceFactoryClass(); IWorkspace scratchWorkspace = scratchWorkspaceFactory.CreateNewScratchWorkspace(); IWorkspaceExtensionManager scratchExtensionManager = (IWorkspaceExtensionManager)scratchWorkspace; Boolean workspaceExtensionApplied = false; UID gdbRegisteredUID = null; try { workspaceExtensionApplied = (workspaceExtensionManager.ExtensionCount > scratchExtensionManager.ExtensionCount); } catch (COMException comExc) { // This is necessary in case the existing extension could not be initiated. if (comExc.ErrorCode == (int)fdoError.FDO_E_WORKSPACE_EXTENSION_CREATE_FAILED) { // Parse the error message for the current extension's GUID. Regex regex = new Regex("(?<guid>{[^}]+})"); MatchCollection matchCollection = regex.Matches(comExc.Message); if (matchCollection.Count > 0) { Match match = matchCollection[0]; gdbRegisteredUID = new UIDClass(); gdbRegisteredUID.Value = match.Groups["guid"].Value; workspaceExtensionApplied = true; } else { throw comExc; } } else { throw comExc; } } if (workspaceExtensionApplied) { if (gdbRegisteredUID == null) { // There is GDB-registered extension on the SDE workspace. Find the SDE extension that is not // applied to the scratch workspace. for (int i = 0; i < workspaceExtensionManager.ExtensionCount; i++) { IWorkspaceExtension workspaceExtension = workspaceExtensionManager.get_Extension(i); IWorkspaceExtension scratchExtension = scratchExtensionManager.FindExtension(workspaceExtension.GUID); if (scratchExtension == null) { gdbRegisteredUID = workspaceExtension.GUID; } } } } // If the extension could be located, remove it. if (gdbRegisteredUID != null) { workspaceExtensionManager.UnRegisterExtension(gdbRegisteredUID); } // Register the extension. workspaceExtensionManager.RegisterExtension("RasterSyncExtension.RasterSyncWorkspaceExtension", uid); } catch (COMException comExc) { switch (comExc.ErrorCode) { case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_NO_REG_PRIV: MessageBox.Show("The connection file's privileges are insufficient to perform this operation.", "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_CREATE_FAILED: String createErrorMessage = String.Concat("The workspace extension could not be created.", Environment.NewLine, "Ensure that it has been registered for COM Interop."); MessageBox.Show(createErrorMessage, "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_DUP_GUID: case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_DUP_NAME: String dupErrorMessage = String.Concat("A duplicate name or GUID was detected. Make sure any existing GDB-registered", "workspaces are not component category-registered as well."); MessageBox.Show(dupErrorMessage, "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: String otherErrorMessage = String.Format("An unexpected error has occurred:{0}{1}{2}", Environment.NewLine, comExc.Message, comExc.ErrorCode); MessageBox.Show(otherErrorMessage); break; } } catch (Exception exc) { String errorMessage = String.Format("An unexpected error has occurred:{0}{1}", Environment.NewLine, exc.Message); MessageBox.Show(errorMessage); } // Shutdown the AO initializer. aoInitialize.Shutdown(); } } /// <summary> /// An enumeration containing geodatabase types. /// </summary> public enum GeodatabaseType { /// <summary> /// ArcSDE geodatabases. /// </summary> ArcSDE = 0, /// <summary> /// File geodatabases. /// </summary> FileGDB = 1, /// <summary> /// Personal geodatabases. /// </summary> PersonalGDB = 2 } }
// 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.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Used by the class to hold the underlying socket the stream uses. private readonly Socket _streamSocket; // Whether the stream should dispose of the socket when the stream is disposed private readonly bool _ownsSocket; // Used by the class to indicate that the stream is m_Readable. private bool _readable; // Used by the class to indicate that the stream is writable. private bool _writeable; // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket. public NetworkStream(Socket socket) : this(socket, FileAccess.ReadWrite, ownsSocket: false) { } public NetworkStream(Socket socket, bool ownsSocket) : this(socket, FileAccess.ReadWrite, ownsSocket) { } public NetworkStream(Socket socket, FileAccess access) : this(socket, access, ownsSocket: false) { } public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException(nameof(socket)); } if (!socket.Blocking) { throw new IOException(SR.net_sockets_blocking); } if (!socket.Connected) { throw new IOException(SR.net_notconnected); } if (socket.SocketType != SocketType.Stream) { throw new IOException(SR.net_notstream); } _streamSocket = socket; _ownsSocket = ownsSocket; switch (access) { case FileAccess.Read: _readable = true; break; case FileAccess.Write: _writeable = true; break; case FileAccess.ReadWrite: default: // assume FileAccess.ReadWrite _readable = true; _writeable = true; break; } #if DEBUG } #endif } // Socket - provides access to socket for stream closing protected Socket Socket => _streamSocket; // Used by the class to indicate that the stream is m_Readable. protected bool Readable { get { return _readable; } set { _readable = value; } } // Used by the class to indicate that the stream is writable. protected bool Writeable { get { return _writeable; } set { _writeable = value; } } // Indicates that data can be read from the stream. // We return the readability of this stream. This is a read only property. public override bool CanRead => _readable; // Indicates that the stream can seek a specific location // in the stream. This property always returns false. public override bool CanSeek => false; // Indicates that data can be written to the stream. public override bool CanWrite => _writeable; // Indicates whether we can timeout public override bool CanTimeout => true; // Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int ReadTimeout { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Receive, value, false); #if DEBUG } #endif } } // Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int WriteTimeout { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Send, value, false); #if DEBUG } #endif } } // Indicates data is available on the stream to be read. // This property checks to see if at least one byte of data is currently available public virtual bool DataAvailable { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Ask the socket how many bytes are available. If it's // not zero, return true. return _streamSocket.Available != 0; #if DEBUG } #endif } } // The length of data available on the stream. Always throws NotSupportedException. public override long Length { get { throw new NotSupportedException(SR.net_noseek); } } // Gets or sets the position in the stream. Always throws NotSupportedException. public override long Position { get { throw new NotSupportedException(SR.net_noseek); } set { throw new NotSupportedException(SR.net_noseek); } } // Seeks a specific position in the stream. This method is not supported by the // NetworkStream class. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } // Read - provide core Read functionality. // // Provide core read functionality. All we do is call through to the // socket Receive functionality. // // Input: // // Buffer - Buffer to read into. // Offset - Offset into the buffer where we're to read. // Count - Number of bytes to read. // // Returns: // // Number of bytes we read, or 0 if the socket is closed. public override int Read(byte[] buffer, int offset, int size) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } try { return _streamSocket.Receive(buffer, offset, size, 0); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } public override int Read(Span<byte> destination) { if (GetType() != typeof(NetworkStream)) { // NetworkStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload // should use the behavior of Read(byte[],int,int) overload. return base.Read(destination); } if (_cleanedUp) throw new ObjectDisposedException(GetType().FullName); if (!CanRead) throw new InvalidOperationException(SR.net_writeonlystream); int bytesRead = _streamSocket.Receive(destination, SocketFlags.None, out SocketError errorCode); if (errorCode != SocketError.Success) { var exception = new SocketException((int)errorCode); throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } return bytesRead; } public override unsafe int ReadByte() { int b; return Read(new Span<byte>(&b, 1)) == 0 ? -1 : b; } // Write - provide core Write functionality. // // Provide core write functionality. All we do is call through to the // socket Send method.. // // Input: // // Buffer - Buffer to write from. // Offset - Offset into the buffer from where we'll start writing. // Count - Number of bytes to write. // // Returns: // // Number of bytes written. We'll throw an exception if we // can't write everything. It's brutal, but there's no other // way to indicate an error. public override void Write(byte[] buffer, int offset, int size) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } try { // Since the socket is in blocking mode this will always complete // after ALL the requested number of bytes was transferred. _streamSocket.Send(buffer, offset, size, SocketFlags.None); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } public override void Write(ReadOnlySpan<byte> source) { if (GetType() != typeof(NetworkStream)) { // NetworkStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) // overload should use the behavior of Write(byte[],int,int) overload. base.Write(source); return; } if (_cleanedUp) throw new ObjectDisposedException(GetType().FullName); if (!CanWrite) throw new InvalidOperationException(SR.net_readonlystream); _streamSocket.Send(source, SocketFlags.None, out SocketError errorCode); if (errorCode != SocketError.Success) { var exception = new SocketException((int)errorCode); throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } } public override unsafe void WriteByte(byte value) => Write(new ReadOnlySpan<byte>(&value, 1)); private int _closeTimeout = Socket.DefaultCloseTimeout; // -1 = respect linger options public void Close(int timeout) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif if (timeout < -1) { throw new ArgumentOutOfRangeException(nameof(timeout)); } _closeTimeout = timeout; Dispose(); #if DEBUG } #endif } private volatile bool _cleanedUp = false; protected override void Dispose(bool disposing) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif // Mark this as disposed before changing anything else. bool cleanedUp = _cleanedUp; _cleanedUp = true; if (!cleanedUp && disposing) { // The only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. _readable = false; _writeable = false; if (_ownsSocket) { // If we own the Socket (false by default), close it // ignoring possible exceptions (eg: the user told us // that we own the Socket but it closed at some point of time, // here we would get an ObjectDisposedException) _streamSocket.InternalShutdown(SocketShutdown.Both); _streamSocket.Close(_closeTimeout); } } #if DEBUG } #endif base.Dispose(disposing); } ~NetworkStream() { #if DEBUG DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization); #endif Dispose(false); } // BeginRead - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the underlying socket async read. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // // Returns: // // An IASyncResult, representing the read. public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } try { return _streamSocket.BeginReceive( buffer, offset, size, SocketFlags.None, callback, state); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // EndRead - handle the end of an async read. // // This method is called when an async read is completed. All we // do is call through to the core socket EndReceive functionality. // // Returns: // // The number of bytes read. May throw an exception. public override int EndRead(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } try { return _streamSocket.EndReceive(asyncResult); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // BeginWrite - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the underlying socket async send. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to written. // // Returns: // // An IASyncResult, representing the write. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } try { // Call BeginSend on the Socket. return _streamSocket.BeginSend( buffer, offset, size, SocketFlags.None, callback, state); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // Handle the end of an asynchronous write. // This method is called when an async write is completed. All we // do is call through to the core socket EndSend functionality. // Returns: The number of bytes read. May throw an exception. public override void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } try { _streamSocket.EndSend(asyncResult); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // ReadAsync - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the Begin/EndRead methods. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task<int> representing the read. public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } try { return _streamSocket.ReceiveAsync( new ArraySegment<byte>(buffer, offset, size), SocketFlags.None, fromNetworkStream: true); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken) { bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } try { return _streamSocket.ReceiveAsync( destination, SocketFlags.None, fromNetworkStream: true, cancellationToken: cancellationToken); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } } // WriteAsync - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the Begin/EndWrite methods. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to write. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task representing the write. public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { return _streamSocket.SendAsync( new ArraySegment<byte>(buffer, offset, size), SocketFlags.None, fromNetworkStream: true); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } try { ValueTask<int> t = _streamSocket.SendAsync( source, SocketFlags.None, fromNetworkStream: true, cancellationToken: cancellationToken); return t.IsCompletedSuccessfully ? Task.CompletedTask : t.AsTask(); } catch (Exception exception) when (!(exception is OutOfMemoryException)) { // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validate arguments as would the base CopyToAsync StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // And bail early if cancellation has already been requested if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } // Do the copy. We get a copy buffer from the shared pool, and we pass both it and the // socket into the copy as part of the event args so as to avoid additional fields in // the async method's state machine. return CopyToAsyncCore( destination, new AwaitableSocketAsyncEventArgs(_streamSocket, ArrayPool<byte>.Shared.Rent(bufferSize)), cancellationToken); } private static async Task CopyToAsyncCore(Stream destination, AwaitableSocketAsyncEventArgs ea, CancellationToken cancellationToken) { try { while (true) { cancellationToken.ThrowIfCancellationRequested(); int bytesRead = await ea.ReceiveAsync(); if (bytesRead == 0) { break; } await destination.WriteAsync(ea.Buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } finally { ArrayPool<byte>.Shared.Return(ea.Buffer, clearArray: true); ea.Dispose(); } } // Flushes data from the stream. This is meaningless for us, so it does nothing. public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } // Sets the length of the stream. Always throws NotSupportedException public override void SetLength(long value) { throw new NotSupportedException(SR.net_noseek); } private int _currentReadTimeout = -1; private int _currentWriteTimeout = -1; internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, mode, timeout, silent); if (timeout < 0) { timeout = 0; // -1 becomes 0 for the winsock stack } if (mode == SocketShutdown.Send || mode == SocketShutdown.Both) { if (timeout != _currentWriteTimeout) { _streamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent); _currentWriteTimeout = timeout; } } if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both) { if (timeout != _currentReadTimeout) { _streamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent); _currentReadTimeout = timeout; } } } /// <summary>A SocketAsyncEventArgs that can be awaited to get the result of an operation.</summary> internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, ICriticalNotifyCompletion { /// <summary>Sentinel object used to indicate that the operation has completed prior to OnCompleted being called.</summary> private static readonly Action s_completedSentinel = () => { }; /// <summary> /// null if the operation has not completed, <see cref="s_completedSentinel"/> if it has, and another object /// if OnCompleted was called before the operation could complete, in which case it's the delegate to invoke /// when the operation does complete. /// </summary> private Action _continuation; /// <summary>Initializes the event args.</summary> /// <param name="socket">The associated socket.</param> /// <param name="buffer">The buffer to use for all operations.</param> public AwaitableSocketAsyncEventArgs(Socket socket, byte[] buffer) { Debug.Assert(socket != null); Debug.Assert(buffer != null && buffer.Length > 0); // Store the socket into the base's UserToken. This avoids the need for an extra field, at the expense // of an object=>Socket cast when we need to access it, which is only once per operation. UserToken = socket; // Store the buffer for use by all operations with this instance. SetBuffer(buffer, 0, buffer.Length); // Hook up the completed event. Completed += delegate { // When the operation completes, see if OnCompleted was already called to hook up a continuation. // If it was, invoke the continuation. Action c = _continuation; if (c != null) { c(); } else { // We may be racing with OnCompleted, so check with synchronization, trying to swap in our // completion sentinel. If we lose the race and OnCompleted did hook up a continuation, // invoke it. Otherwise, there's nothing more to be done. Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)?.Invoke(); } }; } /// <summary>Initiates a receive operation on the associated socket.</summary> /// <returns>This instance.</returns> public AwaitableSocketAsyncEventArgs ReceiveAsync() { if (!Socket.ReceiveAsync(this)) { _continuation = s_completedSentinel; } return this; } /// <summary>Gets this instance.</summary> public AwaitableSocketAsyncEventArgs GetAwaiter() => this; /// <summary>Gets whether the operation has already completed.</summary> /// <remarks> /// This is not a generically usable IsCompleted operation that suggests the whole operation has completed. /// Rather, it's specifically used as part of the await pattern, and is only usable to determine whether the /// operation has completed by the time the instance is awaited. /// </remarks> public bool IsCompleted => _continuation != null; /// <summary>Same as <see cref="OnCompleted(Action)"/> </summary> public void UnsafeOnCompleted(Action continuation) => OnCompleted(continuation); /// <summary>Queues the provided continuation to be executed once the operation has completed.</summary> public void OnCompleted(Action continuation) { if (ReferenceEquals(_continuation, s_completedSentinel) || ReferenceEquals(Interlocked.CompareExchange(ref _continuation, continuation, null), s_completedSentinel)) { Task.Run(continuation); } } /// <summary>Gets the result of the completion operation.</summary> /// <returns>Number of bytes transferred.</returns> /// <remarks> /// Unlike Task's awaiter's GetResult, this does not block until the operation completes: it must only /// be used once the operation has completed. This is handled implicitly by await. /// </remarks> public int GetResult() { _continuation = null; if (SocketError != SocketError.Success) { ThrowIOSocketException(); } return BytesTransferred; } /// <summary>Gets the associated socket.</summary> internal Socket Socket => (Socket)UserToken; // stored in the base's UserToken to avoid an extra field in the object /// <summary>Throws an IOException wrapping a SocketException using the current <see cref="SocketError"/>.</summary> [MethodImpl(MethodImplOptions.NoInlining)] private void ThrowIOSocketException() { var se = new SocketException((int)SocketError); throw new IOException(SR.Format(SR.net_io_readfailure, se.Message), se); } } } }
using System; using System.Data; using System.Windows.Forms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// /// </summary> public class ConsonantChartTable : DataTable { private DataColumn m_DataColumn = null; private DataRow m_DataRow = null; private DataSet m_DataSet = null; private string m_Id = "ID"; public ConsonantChartTable() { //ID column m_DataColumn = new DataColumn(); m_DataColumn.DataType = System.Type.GetType("System.String"); m_DataColumn.ColumnName = m_Id; m_DataColumn.AutoIncrement = false; m_DataColumn.ReadOnly = false; m_DataColumn.Unique = true; this.Columns.Add(m_DataColumn); //12 Columns string strName = ""; string strCapt = ""; for (int i = 1; i < 13; i++) { switch ( i ) { case 1: strName = "BL"; strCapt = "Bilab"; break; case 2: strName = "LD"; strCapt = "LbDen"; break; case 3: strName = "DE"; strCapt = "Dent"; break; case 4: strName = "AL"; strCapt = "Alveo"; break; case 5: strName = "PO"; strCapt = "Posta"; break; case 6: strName = "RE"; strCapt = "Retro"; break; case 7: strName = "PA"; strCapt = "Palat"; break; case 8: strName = "VE"; strCapt = "Velar"; break; case 9: strName = "LV"; strCapt = "LbVel"; break; case 10: strName = "UV"; strCapt = "Uvula"; break; case 11: strName = "PH"; strCapt = "Phary"; break; case 12: strName = "GL"; strCapt = "Glott"; break; default: strName = ""; strCapt = ""; break; } m_DataColumn = new DataColumn(); m_DataColumn.DataType = System.Type.GetType("System.String"); m_DataColumn.ColumnName = strName; m_DataColumn.Caption = strCapt; m_DataColumn.AutoIncrement = false; m_DataColumn.ReadOnly = false; m_DataColumn.Unique = false; this.Columns.Add(m_DataColumn); } // Create 24 rows and add them to the DataTable string strLabel = ""; for (int i = 1; i < 25; i++) { switch ( i ) { case 1: strLabel = "Vl Stop"; break; case 2: strLabel = "Vd Stop"; break; case 3: strLabel = "Vl Nasal"; break; case 4: strLabel = "Vd Nasal"; break; case 5: strLabel = "Vl Trill"; break; case 6: strLabel = "Vd Trill"; break; case 7: strLabel = "Vl Flap"; break; case 8: strLabel = "Vd Flap"; break; case 9: strLabel = "Vl Fric"; break; case 10: strLabel = "Vd Fric"; break; case 11: strLabel = "Vl Affr"; break; case 12: strLabel = "Vd Affr"; break; case 13: strLabel = "Vl LatFr"; break; case 14: strLabel = "Vd LatFr?"; break; case 15: strLabel = "Vl LatAp"; break; case 16: strLabel = "Vd LatAp"; break; case 17: strLabel = "Vl Appr"; break; case 18: strLabel = "Vd Appr"; break; case 19: strLabel = "Vl Impl"; break; case 20: strLabel = "Vd Impl"; break; case 21: strLabel = "Vl Eject"; break; case 22: strLabel = "Vd Eject"; break; case 23: strLabel = "Vl Click"; break; case 24: strLabel = "Vd Click"; break; default: strLabel = ""; break; } m_DataRow = this.NewRow(); m_DataRow[m_Id] = strLabel; this.Rows.Add(m_DataRow); } // Make the ID column the primary key column. DataColumn[] dcPrimaryKey = new DataColumn[1]; dcPrimaryKey[0] = this.Columns[m_Id]; this.PrimaryKey = dcPrimaryKey; // Add the new DataTable to the DataSet. m_DataSet = new DataSet(); m_DataSet.Tables.Add(this); } public DataSet GetDataSet() { return m_DataSet; } public DataRow GetDataRow(int n) { return this.Rows[n]; } public DataColumn GetDataColumn(int n) { return this.Columns[n]; } public string GetId() { return m_Id; } public void UpdChartCell(string sym, int row, int col) { DataRow dr = this.Rows[row]; object [] ia = dr.ItemArray; ia.SetValue(sym, col); this.AcceptChanges(); this.BeginLoadData(); dr = this.LoadDataRow(ia,false); this.EndLoadData(); } public int GetRowNumber(string strCode) { int nRow = -1; switch (strCode) { case "PL-": nRow = 0; break; case "PL+": nRow = 1; break; case "NA-": nRow = 2; break; case "NA+": nRow = 3; break; case "TR-": nRow = 4; break; case "TR+": nRow = 5; break; case "FL-": nRow = 6; break; case "FL+": nRow = 7; break; case "FR-": nRow = 8; break; case "FR+": nRow = 9; break; case "AF-": nRow = 10; break; case "AF+": nRow = 11; break; case "LF-": nRow = 12; break; case "LF+": nRow = 13; break; case "LA-": nRow = 14; break; case "LA+": nRow = 15; break; case "AP-": nRow = 16; break; case "AP+": nRow = 17; break; case "IM-": nRow = 18; break; case "IM+": nRow = 19; break; case "EJ-": nRow = 20; break; case "EJ+": nRow = 21; break; case "CL-": nRow = 22; break; case "CL+": nRow = 23; break; default: MessageBox.Show("Error: Undefined row in consonant chart"); break; } return nRow; } public int GetColNumber(string strCode) { int nCol = -1; switch (strCode) { case "BL": nCol = 1; break; case "LD": nCol = 2; break; case "DE": nCol = 3; break; case "AL": nCol = 4; break; case "PO": nCol = 5; break; case "RE": nCol = 6; break; case "PA": nCol = 7; break; case "VE": nCol = 8; break; case "LV": nCol = 9; break; case "UV": nCol = 10; break; case "PH": nCol = 11; break; case "GL": nCol = 12; break; default: MessageBox.Show("Error: Undefined column in consonant chart"); break; } return nCol; } public string GetColumnHeaders() { bool fEmptyCol = false; int nColNum = 0; string strColNam = ""; string strHdrs = ""; string strTab = Constants.Tab; foreach (DataColumn dc in this.Columns) { if (dc.ColumnName != this.GetId()) { strColNam = dc.ColumnName; nColNum = this.GetColNumber(strColNam); fEmptyCol = true; foreach (DataRow dr in this.Rows) { if ( dr.ItemArray[nColNum].ToString() != "") { fEmptyCol = false; break; } } if ( fEmptyCol ) dc.Caption = ""; //Column is marked to be skipped else strHdrs += strTab + dc.Caption; } } strHdrs = strHdrs + strTab + Environment.NewLine; strHdrs = Constants.kHCOn + strHdrs + Constants.kHCOff; return strHdrs; } public string GetRows(ConsonantChartSearch search) { string strRow = ""; string strTbl = ""; bool fEmptyRow = false; string str = ""; int nSize = 0;; bool fLabialized = search.Labialized; bool fPalatalized = search.Palatalized; bool fVelarized = search.Velarized; bool fPrenasalized = search.Prenasalized; bool fSyllabic = search.Syllabic; bool fAspirated = search.Aspirated; bool fLong = search.Long; bool fGlottalized = search.Glottalized; foreach (DataRow dr in this.Rows) { fEmptyRow = true; nSize = dr.ItemArray.Length; for (int i = 1; i < nSize; i++) { str = dr.ItemArray[i].ToString(); if (str != "") { fEmptyRow = false; break; } } if ( !fEmptyRow ) { DataColumn dc = null; strRow = Constants.kHCOn + dr[this.GetId()].ToString() + Constants.Tab + Constants.kHCOff; for (int i = 1; i < nSize; i++) { dc =this.GetDataColumn(i); // if Column is not to be skipped if (dc.Caption != "") { strRow += dr.ItemArray[i] + Constants.Tab; } } strTbl += strRow + Environment.NewLine; } } return strTbl; } } }
/** Copyright 2014-2021 Robert McNeel and Associates 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.Drawing; using System.Linq; using System.Threading; using ccl; using Rhino; using Rhino.DocObjects; using Rhino.Render; using Rhino.UI; using RhinoCyclesCore.Core; using RhinoCyclesCore.Settings; using sdd = System.Diagnostics.Debug; namespace RhinoCyclesCore.RenderEngines { public class ModalRenderEngine : RenderEngine { public ModalRenderEngine(RhinoDoc doc, Guid pluginId, ViewInfo view, bool isProductRender) : this(doc, pluginId, view, null, null, isProductRender) { } public ModalRenderEngine(RhinoDoc doc, Guid pluginId, ViewInfo view, ViewportInfo viewport, Rhino.Display.DisplayPipelineAttributes attributes, bool isProductRender) : base(pluginId, doc.RuntimeSerialNumber, view, viewport, attributes, false) { IsProductRender = isProductRender; Quality = doc.RenderSettings.AntialiasLevel; ModalRenderEngineCommonConstruct(); } AntialiasLevel Quality { get; set; } public bool IsProductRender { get; set; } public bool FastPreview { get; set; } = false; private void ModalRenderEngineCommonConstruct() { Client = new Client(); State = State.Rendering; Database.ViewChanged += MRE_Database_ViewChanged; #region create callbacks for Cycles m_update_callback = UpdateCallback; m_update_render_tile_callback = null; m_write_render_tile_callback = null; m_test_cancel_callback = null; m_display_update_callback = null; CSycles.log_to_stdout(false); #endregion } private void MRE_Database_ViewChanged(object sender, Database.ChangeDatabase.ViewChangedEventArgs e) { //ViewCrc = e.Crc; } bool capturing = false; public void SetCallbackForCapture() { capturing = true; m_update_render_tile_callback = null; m_logger_callback = null; m_write_render_tile_callback = null; } /// <summary> /// Entry point for a new render process. This is to be done in a separate thread. /// </summary> public void Renderer() { var cyclesEngine = this; EngineDocumentSettings eds = new EngineDocumentSettings(m_doc_serialnumber); var rw = cyclesEngine.RenderWindow; if (rw == null) return; // we don't have a window to write to... var requestedChannels = rw.GetRequestedRenderChannelsAsStandardChannels(); List<RenderWindow.StandardChannels> reqChanList = requestedChannels .Distinct() .Where(chan => chan != RenderWindow.StandardChannels.AlbedoRGB) .ToList(); List<ccl.PassType> reqPassTypes = reqChanList .Select(chan => PassTypeForStandardChannel(chan)) .ToList(); var client = cyclesEngine.Client; var size = cyclesEngine.RenderDimension; IAllSettings engineSettings = eds; #region pick a render device HandleDevice(eds); if (FastPreview) { engineSettings = new FastPreviewEngineSettings(eds); } else { if (!eds.UseDocumentSamples) { switch (Quality) { case AntialiasLevel.Draft: engineSettings = new DraftPresetEngineSettings(eds); break; case AntialiasLevel.Good: engineSettings = new GoodPresetEngineSettings(eds); break; case AntialiasLevel.High: engineSettings = new FinalPresetEngineSettings(eds); break; case AntialiasLevel.None: default: engineSettings = new LowPresetEngineSettings(eds); break; } } } MaxSamples = Attributes?.RealtimeRenderPasses ?? engineSettings.Samples; MaxSamples = (MaxSamples < 1) ? engineSettings.Samples : MaxSamples; (bool isReady, Device possibleRenderDevice) = RcCore.It.IsDeviceReady(RenderDevice); RenderDevice = possibleRenderDevice; IsFallbackRenderDevice = !isReady; /*if (engineSettings.Verbose) sdd.WriteLine( $"Using device {RenderDevice.Name + " " + RenderDevice.Description}");*/ #endregion #region set up session parameters var sessionParams = new SessionParameters(client, RenderDevice) { Experimental = false, Samples = MaxSamples, TileSize = TileSize(RenderDevice), TileOrder = TileOrder.Center, Threads = (uint)(RenderDevice.IsGpu ? 0 : engineSettings.Threads), ShadingSystem = ShadingSystem.SVM, SkipLinearToSrgbConversion = true, DisplayBufferLinear = true, Background = false, ProgressiveRefine = true, Progressive = true, PixelSize = 1, }; #endregion if (cyclesEngine.CancelRender) return; #region create session for scene cyclesEngine.Session = RcCore.It.CreateSession(client, sessionParams); #endregion CreateScene(client, Session, RenderDevice, cyclesEngine, engineSettings); HandleIntegrator(eds); // Set up passes foreach (var reqPass in reqPassTypes) { Session.AddPass(reqPass); } // register callbacks before starting any rendering cyclesEngine.SetCallbacks(); // main render loop, including restarts #region start the rendering loop, wait for it to complete, we're rendering now! if (cyclesEngine.CancelRender) return; cyclesEngine.Database?.Flush(); var rc = cyclesEngine.UploadData(); bool goodrender = rc; if (rc) { cyclesEngine.Session.PrepareRun(); long lastUpdate = DateTime.Now.Ticks; long curUpdate = DateTime.Now.Ticks; // remember, 10000 ticks in a millisecond const long updateInterval = 1000 * 10000; // lets first reset session if (cyclesEngine.Session.Reset(size.Width, size.Height, MaxSamples, BufferRectangle.X, BufferRectangle.Top, FullSize.Width, FullSize.Height)==0) { // and actually start bool stillrendering = true; var throttle = Math.Max(0, engineSettings.ThrottleMs); int sample = -1; while (stillrendering) { if (cyclesEngine.IsRendering) { sample = cyclesEngine.Session.Sample(); stillrendering = sample > -1; curUpdate = DateTime.Now.Ticks; if (sample == -13) { goodrender = false; stillrendering = false; cyclesEngine.CancelRender = true; } else if (!capturing && stillrendering && (sample >= 0 || (curUpdate - lastUpdate) > updateInterval)) { lastUpdate = curUpdate; cyclesEngine.BlitPixelsToRenderWindowChannel(); cyclesEngine.RenderWindow.Invalidate(); if (sample >= 0) { cyclesEngine.Database.ResetChangeQueue(); } } } Thread.Sleep(throttle); if (cyclesEngine.IsStopped) break; } } else { goodrender = false; cyclesEngine.CancelRender = true; } if (!cyclesEngine.CancelRender) { cyclesEngine.BlitPixelsToRenderWindowChannel(); cyclesEngine.RenderWindow.Invalidate(); } } #endregion /*if (engineSettings.SaveDebugImages) { var tmpf = RenderEngine.TempPathForFile($"RC_modal_renderer.png"); cyclesEngine.RenderWindow.SaveRenderImageAs(tmpf, true); }*/ cyclesEngine?.Database.ResetChangeQueue(); // we're done now, so lets clean up our session. RcCore.It.ReleaseSession(cyclesEngine.Session); cyclesEngine.Database?.Dispose(); cyclesEngine.Database = null; cyclesEngine.State = State.Stopped; if (!capturing && goodrender) { // set final status string and progress to 1.0f to signal completed render cyclesEngine.SetProgress(rw, String.Format(Localization.LocalizeString("Render ready {0} samples, duration {1}", 39), cyclesEngine.RenderedSamples + 1, cyclesEngine.TimeString), 1.0f); } if (!goodrender) { rw.SetProgress(Localization.LocalizeString("An error occured while trying to render. The render may be incomplete or not started.", 65), 1.0f); Action showErrorDialog = () => { CrashReporterDialog dlg = new CrashReporterDialog(Localization.LocalizeString("Error while rendering", 66), Localization.LocalizeString( @"An error was detected while rendering with Rhino Render. If there is a result visible you can save it still. Please click the link below for more information.", 67)); dlg.ShowModal(RhinoEtoApp.MainWindow); }; RhinoApp.InvokeOnUiThread(showErrorDialog); } cyclesEngine.CancelRender = true; } public bool SupportsPause() { return true; } public void ResumeRendering() { State = State.Rendering; } public void PauseRendering() { State = State.Waiting; } private bool isDisposed = false; public override void Dispose(bool isDisposing) { if(isDisposing) { if(!isDisposed) { isDisposed = true; } } base.Dispose(isDisposing); } } }
//----------------------------------------------------------------------- // <copyright file="TangoPrefabInspectorHelper.cs" company="Google"> // // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace Tango { using System.Collections; using Tango; using UnityEditor; using UnityEngine; /// <summary> /// Helper methods to display GUI warnings for common setup incompatibilities /// in Tango prefab components. /// </summary> internal static class TangoPrefabInspectorHelper { /// <summary> /// Check for a usable tango application component in the scene. Draw warning if /// one could not be found. /// /// Should be called first before using any other TangoPrefabInspectorHelper function /// during a given frame, to determine if a valid TangoApplication reference exists /// with which to call other TangoPrefabInspectorHelper methods. /// </summary> /// <returns><c>true</c>, if a tango application on an active GameObject can be identified, /// <c>false</c> otherwise.</returns> /// <param name="inspectedBehaviour">Prefab behavior that's being inspected.</param> /// <param name="tangoApplication">Prefab inspector's reference to Tango Application, or /// null if no Tango Application on an active GameObject can be identified.</param> public static bool CheckForTangoApplication(MonoBehaviour inspectedBehaviour, ref TangoApplication tangoApplication) { if (tangoApplication == null || !tangoApplication.gameObject.activeInHierarchy) { tangoApplication = GameObject.FindObjectOfType<TangoApplication>(); } // Note: .isActiveAndEnabled is the appropriate thing to check here because all Register() // calls on existing Tango prefabs are called in Start(), which won't occur until both the // behaviour is enabled and the game object it is attached to is active. // // Conversely, if any of the tango prefabs called Register() in Awake(), the correct thing // to check against would be .gameObject.activeInHeirarchy, since Awake is called when the // game object it is attached to is active, regardless of whether the behaviour itself is // enabled. if (tangoApplication == null && inspectedBehaviour.isActiveAndEnabled) { EditorGUILayout.HelpBox("Could not find an active TangoApplication component in the scene.\n\n" + "Component will not function correctly if it cannot find " + "an active TangoApplication component at runtime.", MessageType.Warning); return false; } return tangoApplication != null; } /// <summary> /// Checks whether motion tracking permissions are selected and draws a warning if they are not. /// </summary> /// <returns><c>true</c>, if motion tracking permissions are enabled, <c>false</c> otherwise.</returns> /// <param name="tangoApplication">Prefab inspector's reference to Tango Application.</param> public static bool CheckMotionTrackingPermissions(TangoApplication tangoApplication) { bool hasPermissions = tangoApplication.m_enableMotionTracking; if (!hasPermissions) { EditorGUILayout.HelpBox("This component needs motion tracking to be enabled in " + "TangoApplication to function.", MessageType.Warning); } return hasPermissions; } /// <summary> /// Checks whether area description permissions are selected (on the assumption we're /// dealing with a prefab that has an m_useAreaDescriptionPose option) and draws /// a warning if they seem to be set inappropriately. /// </summary> /// <returns><c>true</c>, if area description permissions are enabled, <c>false</c> otherwise.</returns> /// <param name="tangoApplication">Prefab inspector's reference to Tango Application.</param> /// <param name="shouldUsePermissions">If set to <c>true</c> should use permissions.</param> public static bool CheckAreaDescriptionPermissions(TangoApplication tangoApplication, bool shouldUsePermissions) { bool hasPermissions = tangoApplication.m_enableAreaDescriptions; if (!hasPermissions && shouldUsePermissions) { EditorGUILayout.HelpBox("\"Use Area Description Pose\" option selected but active " + "TangoApplication component does not have Area " + "Descriptions enabled.", MessageType.Warning); } else if (hasPermissions && !shouldUsePermissions) { EditorGUILayout.HelpBox("TangoApplication has Area Descriptions enabled but \"Use " + "Area Description Pose\" option is not selected.\n\n" + "If left as-is, this script will use the Start of Service " + "pose even if an area description is loaded and/or area learning is enabled", MessageType.Warning); } return hasPermissions == tangoApplication.m_enableAreaDescriptions; } /// <summary> /// Checks whether depth permissions are selected and draws a warning if they are not. /// </summary> /// <returns><c>true</c>, if depth permissions are enabled, <c>false</c> otherwise.</returns> /// <param name="tangoApplication">Prefab inspector's reference to Tango Application.</param> public static bool CheckDepthPermissions(TangoApplication tangoApplication) { bool hasPermissions = tangoApplication.m_enableDepth; if (!hasPermissions) { EditorGUILayout.HelpBox("This component needs Depth to be enabled in TangoApplication to function.", MessageType.Warning); } return hasPermissions; } /// <summary> /// Checks whether video overlay permissions are selected and draws a warning if they are not. /// </summary> /// <returns><c>true</c>, if appropriate video permissions are enabled, <c>false</c> otherwise.</returns> /// <param name="tangoApplication">Prefab inspector's reference to Tango Application.</param> /// <param name="textureIdMethodRequired"><c>true</c> if texture ID method is required.</param> /// <param name="byteBufferMethodRequired"><c>true</c> if byte buffer method is required.</param> public static bool CheckVideoOverlayPermissions(TangoApplication tangoApplication, bool textureIdMethodRequired, bool byteBufferMethodRequired) { bool hasNeededVideoPermissions = tangoApplication.m_enableVideoOverlay; if (textureIdMethodRequired && !tangoApplication.m_videoOverlayUseTextureMethod) { hasNeededVideoPermissions = false; } else if (byteBufferMethodRequired && !tangoApplication.m_videoOverlayUseByteBufferMethod) { hasNeededVideoPermissions = false; } if (!hasNeededVideoPermissions) { if (textureIdMethodRequired || byteBufferMethodRequired) { string requirementsString; if (textureIdMethodRequired && byteBufferMethodRequired) { requirementsString = "\"Both\""; } else if (textureIdMethodRequired) { requirementsString = "\"Texture ID\" or \"Both\""; } else { requirementsString = "\"Raw Bytes\" or \"Both\""; } EditorGUILayout.HelpBox("This component needs Video Overlay to be enabled and set to method of " + requirementsString + " in TangoApplication to function.", MessageType.Warning); } else { EditorGUILayout.HelpBox("This component needs Video Overlay to be enabled in " + "TangoApplication to function.", MessageType.Warning); } } return hasNeededVideoPermissions; } /// <summary> /// Checks whether 3D Reconstruction permissions are selected and draws a warning if they are not. /// </summary> /// <returns><c>true</c>, if 3D Reconstruction permissions are enabled, <c>false</c> otherwise.</returns> /// <param name="tangoApplication">Prefab inspector's reference to Tango Application.</param> public static bool Check3dReconstructionPermissions(TangoApplication tangoApplication) { bool hasPermissions = tangoApplication.m_enable3DReconstruction; if (!hasPermissions) { EditorGUILayout.HelpBox("This component needs 3D Reconstruction to be enabled in " + "TangoApplication to function.", MessageType.Warning); } return hasPermissions; } } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Text; using YesSql.Sql; namespace YesSql.Provider { /// <summary> /// Used to create custom dialects. /// </summary> public abstract class BaseDialect : ISqlDialect { public readonly Dictionary<string, ISqlFunction> Methods = new Dictionary<string, ISqlFunction>(StringComparer.OrdinalIgnoreCase); protected static Dictionary<Type, DbType> _propertyTypes; public DbType ToDbType(Type type) { DbType dbType; if (_propertyTypes.TryGetValue(type, out dbType)) { return dbType; } if (type.IsEnum) { return DbType.Int32; } // Nullable<T> ? if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { var nullable = Nullable.GetUnderlyingType(type); if (nullable != null) { return ToDbType(nullable); } } return DbType.Object; } public virtual object TryConvert(object source) { if (source == null) { return source; } if (_typeHandlers.Count > 0) { if (_typeHandlers.TryGetValue(source.GetType(), out var handlers) && handlers.Count > 0) { foreach (var handler in handlers) { source = handler(source); } return source; } } if (source.GetType().IsEnum) { return Convert.ToInt32(source); } return source; } public abstract string Name { get; } public virtual string InOperator(string values) { if (values.StartsWith("@") && !values.Contains(",")) { return " IN " + values; } else { return " IN (" + values + ") "; } } public virtual string NotInOperator(string values) { return " NOT" + InOperator(values); } public virtual string InSelectOperator(string values) { return " IN (" + values + ") "; } public virtual string NotInSelectOperator(string values) { return " NOT IN (" + values + ") "; } public virtual string CreateTableString => "create table"; public virtual bool HasDataTypeInIdentityColumn => false; public abstract string IdentitySelectString { get; } public abstract string IdentityLastId { get; } public virtual string IdentityColumnString => "[int] IDENTITY(1,1) primary key"; public virtual string NullColumnString => String.Empty; public virtual string PrimaryKeyString => "primary key"; public abstract string RandomOrderByClause { get; } public virtual bool SupportsBatching => true; public virtual bool SupportsIdentityColumns => true; public virtual bool SupportsUnique => true; public virtual bool SupportsForeignKeyConstraintInAlterTable => true; public virtual string FormatKeyName(string name) => name; public virtual string FormatIndexName(string name) => name; public virtual string GetAddForeignKeyConstraintString(string name, string[] srcColumns, string destTable, string[] destColumns, bool primaryKey) { var res = new StringBuilder(200); if (SupportsForeignKeyConstraintInAlterTable) { res.Append(" add"); } res.Append(" constraint ") .Append(name) .Append(" foreign key (") #if NETSTANDARD2_1 .AppendJoin(", ", srcColumns) #else .Append(String.Join(", ", srcColumns)) #endif .Append(") references ") .Append(destTable); if (!primaryKey) { res.Append(" (") .Append(String.Join(", ", destColumns)) .Append(')'); } return res.ToString(); } public virtual string GetDropForeignKeyConstraintString(string name) { return " drop constraint " + name; } public virtual bool SupportsIfExistsBeforeTableName => false; public virtual string CascadeConstraintsString => String.Empty; public virtual bool SupportsIfExistsAfterTableName => false; public virtual string GetDropTableString(string name) { var sb = new StringBuilder("drop table "); if (SupportsIfExistsBeforeTableName) { sb.Append("if exists "); } sb.Append(QuoteForTableName(name)).Append(CascadeConstraintsString); if (SupportsIfExistsAfterTableName) { sb.Append(" if exists"); } return sb.ToString(); } public abstract string GetDropIndexString(string indexName, string tableName); public abstract string QuoteForColumnName(string columnName); public abstract string QuoteForTableName(string tableName); public virtual string QuoteString => "\""; public virtual string DoubleQuoteString => "\"\""; public virtual string SingleQuoteString => "'"; public virtual string DoubleSingleQuoteString => "''"; public virtual string DefaultValuesInsert => "DEFAULT VALUES"; public virtual bool PrefixIndex => false; public abstract byte DefaultDecimalPrecision { get; } public abstract byte DefaultDecimalScale { get; } public virtual int MaxCommandsPageSize => int.MaxValue; public virtual int MaxParametersPerCommand => int.MaxValue; protected virtual string Quote(string value) { return SingleQuoteString + value.Replace(SingleQuoteString, DoubleSingleQuoteString) + SingleQuoteString; } public abstract string GetTypeName(DbType dbType, int? length, byte? precision, byte? scale); public virtual string GetSqlValue(object value) { if (value == null) { return "null"; } switch (Convert.GetTypeCode(value)) { case TypeCode.Object: case TypeCode.String: case TypeCode.Char: return Quote(value.ToString()); case TypeCode.Boolean: return (bool)value ? "1" : "0"; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return Convert.ToString(value, CultureInfo.InvariantCulture); case TypeCode.DateTime: return String.Concat("'", Convert.ToString(value, CultureInfo.InvariantCulture), "'"); } return "null"; } public abstract void Page(ISqlBuilder sqlBuilder, string offset, string limit); public virtual ISqlBuilder CreateBuilder(string tablePrefix) { return new SqlBuilder(tablePrefix, this); } public string RenderMethod(string name, string[] args) { if (Methods.TryGetValue(name, out var method)) { return method.Render(args); } return name + "(" + String.Join(", ", args) + ")"; } public virtual void Concat(IStringBuilder builder, params Action<IStringBuilder>[] generators) { builder.Append("("); for (var i = 0; i < generators.Length; i++) { if (i > 0) { builder.Append(" || "); } generators[i](builder); } builder.Append(")"); } public virtual List<string> GetDistinctOrderBySelectString(List<string> select, List<string> orderBy) { // Most databases (PostgreSql and SqlServer) requires all ordered fields to be part of the select when DISTINCT is used foreach (var o in orderBy) { var trimmed = o.Trim(); // Each order segment can be a field name, or a punctuation, so we filter out the punctuations if (trimmed != "," && trimmed != "DESC" && trimmed != "ASC" && !select.Contains(o)) { select.Add(","); select.Add(o); } } return select; } private readonly Dictionary<Type, List<Func<object, object>>> _typeHandlers = new Dictionary<Type, List<Func<object, object>>>(); public void ResetTypeHandlers() { _typeHandlers.Clear(); } public void AddTypeHandler<T, U>(Func<T, U> handler) { if (!_typeHandlers.TryGetValue(typeof(T), out var handlers)) { _typeHandlers[typeof(T)] = handlers = new List<Func<object, object>>(); } handlers.Add(i => handler((T)i)); } } }
// *********************************************************************** // Assembly : Cql.Core.Web // Author : jeremy.bell // Created : 09-14-2017 // // Last Modified By : jeremy.bell // Last Modified On : 09-15-2017 // *********************************************************************** // <copyright file="OperationResult.cs" company="CQL;Jeremy Bell"> // 2017 Cql Incorporated // </copyright> // <summary></summary> // *********************************************************************** namespace Cql.Core.Web { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; /// <summary> /// Wraps the result of a service call with information indicating success or failure of the operation. /// </summary> /// <seealso cref="Cql.Core.Web.IOperationResult" /> public class OperationResult : IOperationResult { /// <summary> /// Gets or sets the default error message. /// </summary> /// <value>The default error message.</value> [NotNull] public static string DefaultErrorMessage { get; set; } = "An error occurred."; /// <summary> /// Gets or sets the default validation message. /// </summary> /// <value>The default validation message.</value> [NotNull] public static string DefaultValidationMessage { get; set; } = "The model is not valid."; /// <summary> /// Gets or sets the data. /// </summary> /// <value>The data.</value> public object Data { get; set; } /// <summary> /// Gets or sets the message. /// </summary> /// <value>The message.</value> public string Message { get; set; } /// <summary> /// Gets or sets the result. /// </summary> /// <value>The result.</value> public OperationResultType Result { get; set; } /// <summary> /// Gets or sets the validation results. /// </summary> /// <value>The validation results.</value> public IEnumerable<ValidationResult> ValidationResults { get; set; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating failure with an error message. /// </summary> /// <param name="ex">The ex.</param> /// <returns>An OperationResult.</returns> [NotNull] public static OperationResult Error([CanBeNull] Exception ex = null) { return Error(ex?.Message ?? DefaultErrorMessage); } /// <summary> /// Returns an <see cref="OperationResult" /> indicating failure with an error message. /// </summary> /// <param name="message">The message.</param> /// <returns>An OperationResult.</returns> [NotNull] public static OperationResult Error([CanBeNull] string message) { if (string.IsNullOrWhiteSpace(message)) { message = DefaultErrorMessage; } return new OperationResult { Message = message, Result = OperationResultType.Error }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating failure with an error message. /// </summary> /// <typeparam name="T">The operation result type</typeparam> /// <param name="ex">The exception.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> Error<T>([CanBeNull] Exception ex = null) { return Error<T>(ex?.Message ?? DefaultErrorMessage); } /// <summary> /// Returns an <see cref="OperationResult" /> indicating failure with an error message. /// </summary> /// <typeparam name="T">The operation result type</typeparam> /// <param name="message">The message.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> Error<T>([CanBeNull] string message) { if (string.IsNullOrWhiteSpace(message)) { message = DefaultErrorMessage; } return new OperationResult<T> { Message = message, Result = OperationResultType.Error }; } /// <summary> /// Creates a new operation result with the return type of <typeparamref name="T" /> with all of the same values. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="other">The other operation.</param> /// <param name="data">The result data (optional).</param> /// <returns>A OperationResult&lt;T&gt;.</returns> /// <exception cref="ArgumentNullException">The <paramref name="other" /> cannot be null</exception> [NotNull] public static OperationResult<T> FromOperationResult<T>([NotNull] IOperationResult other, [CanBeNull] T data = default(T)) { if (other == null) { throw new ArgumentNullException(nameof(other)); } return new OperationResult<T> { Message = other.Message, Result = other.Result, ValidationResults = other.ValidationResults, Data = data }; } /// <summary> /// Returns a NotFound result if they specified <paramref name="value" /> is NULL; otherwise an OK result is returned. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="value">The value.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> FromValue<T>([CanBeNull] T value) { return EqualityComparer<T>.Default.Equals(value, default(T)) ? NotFound<T>("No results") : Ok(value); } /// <summary> /// Returns a NotFound result if the result of the specified <paramref name="valueTask" /> is NULL; otherwise an OK /// result is returned. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="valueTask">The value task.</param> /// <returns>An operation result of type <typeparamref name="T" /></returns> /// <exception cref="ArgumentNullException">The <paramref name="valueTask" /> cannot be null</exception> [ItemNotNull] public static async Task<OperationResult<T>> FromValue<T>([NotNull] Task<T> valueTask) { if (valueTask == null) { throw new ArgumentNullException(nameof(valueTask)); } return FromValue(await valueTask); } /// <summary> /// Returns an <see cref="OperationResult" /> indicating validation errors with the specified /// <paramref name="message" />. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="message">The validation message.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> Invalid<T>([CanBeNull] string message) { if (string.IsNullOrEmpty(message)) { message = DefaultValidationMessage; } return new OperationResult<T> { ValidationResults = new List<ValidationResult> { new ValidationResult(message) }, Result = OperationResultType.Invalid, Message = message }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating validation errors with the specified /// <paramref name="validationResults" />. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="validationResults">The validation results.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> Invalid<T>([CanBeNull] IEnumerable<ValidationResult> validationResults = null) { return new OperationResult<T> { ValidationResults = validationResults ?? new List<ValidationResult> { new ValidationResult(DefaultValidationMessage) }, Result = OperationResultType.Invalid, Message = validationResults?.Select(x => x.ErrorMessage).FirstOrDefault() ?? DefaultValidationMessage }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating validation errors with the specified /// <paramref name="validationResults" />. /// </summary> /// <param name="validationResults">The validation results.</param> /// <returns>An OperationResult.</returns> [NotNull] public static OperationResult Invalid([CanBeNull] IEnumerable<ValidationResult> validationResults = null) { return new OperationResult { ValidationResults = validationResults ?? new List<ValidationResult> { new ValidationResult(DefaultValidationMessage) }, Result = OperationResultType.Invalid, Message = validationResults?.Select(x => x.ErrorMessage).FirstOrDefault() ?? DefaultValidationMessage }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating that the operation resulted in a null or not found result. /// </summary> /// <param name="message">The message.</param> /// <returns>An OperationResult.</returns> [NotNull] public static OperationResult NotFound([CanBeNull] string message = null) { return new OperationResult { Message = message, Result = OperationResultType.NotFound }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating that the operation resulted in a null or not found result. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="message">The message.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> NotFound<T>([CanBeNull] string message = null) { return new OperationResult<T> { Message = message, Result = OperationResultType.NotFound }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating that the operation was successful. /// </summary> /// <param name="data">The data.</param> /// <returns>An OperationResult.</returns> [NotNull] public static OperationResult Ok([CanBeNull] object data = null) { return new OperationResult { Data = data, Result = OperationResultType.Ok }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating that the operation was successful. /// </summary> /// <typeparam name="T">The result type</typeparam> /// <param name="data">The data.</param> /// <returns>An OperationResult.</returns> [NotNull] public static OperationResult<T> Ok<T>([CanBeNull] T data = default(T)) { return new OperationResult<T> { Data = data, Result = OperationResultType.Ok }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating unauthorized access with an error message. /// </summary> /// <param name="message">The message.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult Unauthorized([CanBeNull] string message = null) { return new OperationResult { Message = message, Result = OperationResultType.Unauthorized }; } /// <summary> /// Returns an <see cref="OperationResult" /> indicating unauthorized access with an error message. /// </summary> /// <typeparam name="T">The operation result type</typeparam> /// <param name="message">The message.</param> /// <returns>An OperationResult&lt;T&gt;.</returns> [NotNull] public static OperationResult<T> Unauthorized<T>([CanBeNull] string message = null) { return new OperationResult<T> { Message = message, Result = OperationResultType.Unauthorized }; } } /// <summary> /// Wraps the result of a service call with a strongly typed result containing information indicating success or failure of /// the operation. /// </summary> /// <typeparam name="T">The strongly typed result</typeparam> /// <seealso cref="Cql.Core.Web.OperationResult" /> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed. Suppression is OK here.")] public class OperationResult<T> : OperationResult { /// <summary> /// Gets or sets the data. /// </summary> /// <value>The data.</value> public new T Data { get => (T)base.Data; set => base.Data = value; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Android.App; using Android.OS; using Android.Runtime; using Org.Json; using Sensus; using Sensus.Probes.Apps; using Xamarin.Facebook; using Xamarin.Facebook.Login; using System.Reflection; using Sensus.Exceptions; namespace Sensus.Android.Probes.Apps { /// <summary> /// Probes Facebook information. To generate key hashes: /// * Debug: keytool -exportcert -alias androiddebugkey -keystore ~/.local/share/Xamarin/Mono\ for\ Android/debug.keystore | openssl sha1 -binary | openssl base64 /// * Play store: TODO /// </summary> public class AndroidFacebookProbe : FacebookProbe { private class FacebookCallback<TResult> : Java.Lang.Object, IFacebookCallback where TResult : Java.Lang.Object { public Action<TResult> HandleSuccess { get; set; } public Action HandleCancel { get; set; } public Action<FacebookException> HandleError { get; set; } public void OnSuccess(Java.Lang.Object result) { if (HandleSuccess != null) HandleSuccess(result.JavaCast<TResult>()); } public void OnCancel() { if (HandleCancel != null) HandleCancel(); } public void OnError(FacebookException error) { if (HandleError != null) HandleError(error); } } private bool HasValidAccessToken { get { return FacebookSdk.IsInitialized && AccessToken.CurrentAccessToken != null && !AccessToken.CurrentAccessToken.IsExpired; } } private void ObtainAccessToken(string[] permissionNames) { lock (LoginLocker) { if (HasValidAccessToken) { SensusServiceHelper.Get().Logger.Log("Facebook access token present.", LoggingLevel.Normal, GetType()); } else { ManualResetEvent loginWait = new ManualResetEvent(false); bool loginCancelled = false; string accessTokenError = null; #region prompt user to log in from main activity (SensusServiceHelper.Get() as AndroidSensusServiceHelper).RunActionUsingMainActivityAsync(mainActivity => { try { FacebookCallback<LoginResult> loginCallback = new FacebookCallback<LoginResult> { HandleSuccess = loginResult => { SensusServiceHelper.Get().Logger.Log("Facebook login succeeded.", LoggingLevel.Normal, GetType()); AccessToken.CurrentAccessToken = loginResult.AccessToken; loginWait.Set(); }, HandleCancel = () => { SensusServiceHelper.Get().Logger.Log("Facebook login cancelled.", LoggingLevel.Normal, GetType()); AccessToken.CurrentAccessToken = null; loginCancelled = true; loginWait.Set(); }, HandleError = loginResult => { SensusServiceHelper.Get().Logger.Log("Facebook login failed.", LoggingLevel.Normal, GetType()); AccessToken.CurrentAccessToken = null; loginWait.Set(); } }; LoginManager.Instance.RegisterCallback(mainActivity.FacebookCallbackManager, loginCallback); LoginManager.Instance.LogInWithReadPermissions(mainActivity, permissionNames); } catch (Exception ex) { accessTokenError = ex.Message; loginWait.Set(); } }, true, false); #endregion loginWait.WaitOne(); if (accessTokenError != null) { SensusServiceHelper.Get().Logger.Log("Error while initializing Facebook SDK and/or logging in: " + accessTokenError, LoggingLevel.Normal, GetType()); } // if the access token is still not valid after logging in, consider it a fail. if (!HasValidAccessToken) { string message = "Failed to obtain access token."; SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType()); // if the user cancelled the login, don't prompt them to log in again if (loginCancelled) { throw new NotSupportedException(message + " User cancelled login."); } // if the user did not cancel the login, allow the login to be presented again when the health test is run else { throw new Exception(message); } } } } } protected override void Initialize() { base.Initialize(); ObtainAccessToken(GetRequiredPermissionNames()); } protected override IEnumerable<Datum> Poll(CancellationToken cancellationToken) { List<Datum> data = new List<Datum>(); if (HasValidAccessToken) { string[] missingPermissions = GetRequiredPermissionNames().Where(p => !AccessToken.CurrentAccessToken.Permissions.Contains(p)).ToArray(); if (missingPermissions.Length > 0) { ObtainAccessToken(missingPermissions); } } else { ObtainAccessToken(GetRequiredPermissionNames()); } if (HasValidAccessToken) { GraphRequestBatch graphRequestBatch = new GraphRequestBatch(); foreach (Tuple<string, List<string>> edgeFieldQuery in GetEdgeFieldQueries()) { Bundle parameters = new Bundle(); if (edgeFieldQuery.Item2.Count > 0) { parameters.PutString("fields", string.Concat(edgeFieldQuery.Item2.Select(field => field + ",")).Trim(',')); } GraphRequest request = new GraphRequest( AccessToken.CurrentAccessToken, "/me" + (edgeFieldQuery.Item1 == null ? "" : "/" + edgeFieldQuery.Item1), parameters, HttpMethod.Get); request.Version = "v2.8"; graphRequestBatch.Add(request); } if (graphRequestBatch.Size() == 0) { throw new Exception("User has not granted any Facebook permissions."); } else { foreach (GraphResponse response in graphRequestBatch.ExecuteAndWait()) { if (response.Error == null) { FacebookDatum datum = new FacebookDatum(DateTimeOffset.UtcNow); JSONObject responseJSON = response.JSONObject; JSONArray jsonFields = responseJSON.Names(); bool valuesSet = false; for (int i = 0; i < jsonFields.Length(); ++i) { string jsonField = jsonFields.GetString(i); PropertyInfo property; if (FacebookDatum.TryGetProperty(jsonField, out property)) { object value = null; if (property.PropertyType == typeof(string)) { value = responseJSON.GetString(jsonField); } else if (property.PropertyType == typeof(bool?)) { value = responseJSON.GetBoolean(jsonField); } else if (property.PropertyType == typeof(DateTimeOffset?)) { value = DateTimeOffset.Parse(responseJSON.GetString(jsonField)); } else if (property.PropertyType == typeof(List<string>)) { List<string> values = new List<string>(); JSONArray jsonValues = responseJSON.GetJSONArray(jsonField); for (int j = 0; j < jsonValues.Length(); ++j) { values.Add(jsonValues.GetString(j)); } value = values; } else { throw SensusException.Report("Unrecognized FacebookDatum property type: " + property.PropertyType); } if (value != null) { property.SetValue(datum, value); valuesSet = true; } } else if (jsonField != "data" && jsonField != "paging" && jsonField != "summary") { SensusServiceHelper.Get().Logger.Log("Unrecognized JSON field in Facebook query response: " + jsonField, LoggingLevel.Verbose, GetType()); } } if (valuesSet) { data.Add(datum); } } else { throw new Exception("Error received while querying Facebook graph API: " + response.Error.ErrorMessage); } } } } else { throw new Exception("Attempted to poll Facebook probe without a valid access token."); } return data; } public override bool TestHealth(ref List<Tuple<string, Dictionary<string, string>>> events) { bool restart = base.TestHealth(ref events); if (!HasValidAccessToken) { restart = true; } return restart; } protected override ICollection<string> GetGrantedPermissions() { if (HasValidAccessToken) { return AccessToken.CurrentAccessToken.Permissions; } else { return new string[0]; } } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using log4net.Core; namespace log4net.Util { /// <summary> /// Delegate type used for LogicalThreadContextStack's callbacks. /// </summary> #if NET_2_0 || MONO_2_0 public delegate void TwoArgAction<T1, T2>(T1 t1, T2 t2); #else public delegate void TwoArgAction(string t1, LogicalThreadContextStack t2); #endif /// <summary> /// Implementation of Stack for the <see cref="log4net.LogicalThreadContext"/> /// </summary> /// <remarks> /// <para> /// Implementation of Stack for the <see cref="log4net.LogicalThreadContext"/> /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class LogicalThreadContextStack : IFixingRequired { #region Private Instance Fields /// <summary> /// The stack store. /// </summary> private Stack m_stack = new Stack(); /// <summary> /// The name of this <see cref="log4net.Util.LogicalThreadContextStack"/> within the /// <see cref="log4net.Util.LogicalThreadContextProperties"/>. /// </summary> private string m_propertyKey; /// <summary> /// The callback used to let the <see cref="log4net.Util.LogicalThreadContextStacks"/> register a /// new instance of a <see cref="log4net.Util.LogicalThreadContextStack"/>. /// </summary> #if NET_2_0 || MONO_2_0 private TwoArgAction<string, LogicalThreadContextStack> m_registerNew; #else private TwoArgAction m_registerNew; #endif #endregion Private Instance Fields #region Public Instance Constructors /// <summary> /// Internal constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LogicalThreadContextStack" /> class. /// </para> /// </remarks> #if NET_2_0 || MONO_2_0 internal LogicalThreadContextStack(string propertyKey, TwoArgAction<string, LogicalThreadContextStack> registerNew) #else internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) #endif { m_propertyKey = propertyKey; m_registerNew = registerNew; } #endregion Public Instance Constructors #region Public Properties /// <summary> /// The number of messages in the stack /// </summary> /// <value> /// The current number of messages in the stack /// </value> /// <remarks> /// <para> /// The current number of messages in the stack. That is /// the number of times <see cref="Push"/> has been called /// minus the number of times <see cref="Pop"/> has been called. /// </para> /// </remarks> public int Count { get { return m_stack.Count; } } #endregion // Public Properties #region Public Methods /// <summary> /// Clears all the contextual information held in this stack. /// </summary> /// <remarks> /// <para> /// Clears all the contextual information held in this stack. /// Only call this if you think that this thread is being reused after /// a previous call execution which may not have completed correctly. /// You do not need to use this method if you always guarantee to call /// the <see cref="IDisposable.Dispose"/> method of the <see cref="IDisposable"/> /// returned from <see cref="Push"/> even in exceptional circumstances, /// for example by using the <c>using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message"))</c> /// syntax. /// </para> /// </remarks> public void Clear() { m_registerNew(m_propertyKey, new LogicalThreadContextStack(m_propertyKey, m_registerNew)); } /// <summary> /// Removes the top context from this stack. /// </summary> /// <returns>The message in the context that was removed from the top of this stack.</returns> /// <remarks> /// <para> /// Remove the top context from this stack, and return /// it to the caller. If this stack is empty then an /// empty string (not <see langword="null"/>) is returned. /// </para> /// </remarks> public string Pop() { // copy current stack Stack stack = new Stack(new Stack(m_stack)); string result = ""; if (stack.Count > 0) { result = ((StackFrame)(stack.Pop())).Message; } LogicalThreadContextStack ltcs = new LogicalThreadContextStack(m_propertyKey, m_registerNew); ltcs.m_stack = stack; m_registerNew(m_propertyKey, ltcs); return result; } /// <summary> /// Pushes a new context message into this stack. /// </summary> /// <param name="message">The new context message.</param> /// <returns> /// An <see cref="IDisposable"/> that can be used to clean up the context stack. /// </returns> /// <remarks> /// <para> /// Pushes a new context onto this stack. An <see cref="IDisposable"/> /// is returned that can be used to clean up this stack. This /// can be easily combined with the <c>using</c> keyword to scope the /// context. /// </para> /// </remarks> /// <example>Simple example of using the <c>Push</c> method with the <c>using</c> keyword. /// <code lang="C#"> /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) /// { /// log.Warn("This should have an ThreadContext Stack message"); /// } /// </code> /// </example> public IDisposable Push(string message) { // do modifications on a copy Stack stack = new Stack(new Stack(m_stack)); stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); LogicalThreadContextStack contextStack = new LogicalThreadContextStack(m_propertyKey, m_registerNew); contextStack.m_stack = stack; m_registerNew(m_propertyKey, contextStack); return new AutoPopStackFrame(contextStack, stack.Count - 1); } #endregion Public Methods #region Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>The current context information.</returns> internal string GetFullMessage() { Stack stack = m_stack; if (stack.Count > 0) { return ((StackFrame)(stack.Peek())).FullMessage; } return null; } /// <summary> /// Gets and sets the internal stack used by this <see cref="LogicalThreadContextStack"/> /// </summary> /// <value>The internal storage stack</value> /// <remarks> /// <para> /// This property is provided only to support backward compatability /// of the <see cref="NDC"/>. Tytpically the internal stack should not /// be modified. /// </para> /// </remarks> internal Stack InternalStack { get { return m_stack; } set { m_stack = value; } } #endregion Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>Gets the current context information</returns> /// <remarks> /// <para> /// Gets the current context information for this stack. /// </para> /// </remarks> public override string ToString() { return GetFullMessage(); } /// <summary> /// Get a portable version of this object /// </summary> /// <returns>the portable instance of this object</returns> /// <remarks> /// <para> /// Get a cross thread portable version of this object /// </para> /// </remarks> object IFixingRequired.GetFixedObject() { return GetFullMessage(); } /// <summary> /// Inner class used to represent a single context frame in the stack. /// </summary> /// <remarks> /// <para> /// Inner class used to represent a single context frame in the stack. /// </para> /// </remarks> private sealed class StackFrame { #region Private Instance Fields private readonly string m_message; private readonly StackFrame m_parent; private string m_fullMessage = null; #endregion #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="message">The message for this context.</param> /// <param name="parent">The parent context in the chain.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="StackFrame" /> class /// with the specified message and parent context. /// </para> /// </remarks> internal StackFrame(string message, StackFrame parent) { m_message = message; m_parent = parent; if (parent == null) { m_fullMessage = message; } } #endregion Internal Instance Constructors #region Internal Instance Properties /// <summary> /// Get the message. /// </summary> /// <value>The message.</value> /// <remarks> /// <para> /// Get the message. /// </para> /// </remarks> internal string Message { get { return m_message; } } /// <summary> /// Gets the full text of the context down to the root level. /// </summary> /// <value> /// The full text of the context down to the root level. /// </value> /// <remarks> /// <para> /// Gets the full text of the context down to the root level. /// </para> /// </remarks> internal string FullMessage { get { if (m_fullMessage == null && m_parent != null) { m_fullMessage = string.Concat(m_parent.FullMessage, " ", m_message); } return m_fullMessage; } } #endregion Internal Instance Properties } /// <summary> /// Struct returned from the <see cref="LogicalThreadContextStack.Push"/> method. /// </summary> /// <remarks> /// <para> /// This struct implements the <see cref="IDisposable"/> and is designed to be used /// with the <see langword="using"/> pattern to remove the stack frame at the end of the scope. /// </para> /// </remarks> private struct AutoPopStackFrame : IDisposable { #region Private Instance Fields /// <summary> /// The depth to trim the stack to when this instance is disposed /// </summary> private int m_frameDepth; /// <summary> /// The outer LogicalThreadContextStack. /// </summary> private LogicalThreadContextStack m_logicalThreadContextStack; #endregion Private Instance Fields #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="logicalThreadContextStack">The internal stack used by the ThreadContextStack.</param> /// <param name="frameDepth">The depth to return the stack to when this object is disposed.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="AutoPopStackFrame" /> class with /// the specified stack and return depth. /// </para> /// </remarks> internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) { m_frameDepth = frameDepth; m_logicalThreadContextStack = logicalThreadContextStack; } #endregion Internal Instance Constructors #region Implementation of IDisposable /// <summary> /// Returns the stack to the correct depth. /// </summary> /// <remarks> /// <para> /// Returns the stack to the correct depth. /// </para> /// </remarks> public void Dispose() { if (m_frameDepth >= 0 && m_logicalThreadContextStack.m_stack != null) { Stack stack = new Stack(new Stack(m_logicalThreadContextStack.m_stack)); while (stack.Count > m_frameDepth) { stack.Pop(); } LogicalThreadContextStack ltcs = new LogicalThreadContextStack(m_logicalThreadContextStack.m_propertyKey, m_logicalThreadContextStack.m_registerNew); ltcs.m_stack = stack; m_logicalThreadContextStack.m_registerNew(m_logicalThreadContextStack.m_propertyKey, ltcs); } } #endregion Implementation of IDisposable } } }
// // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER // REMAINS UNCHANGED. // // Email: [email protected] // // Copyright (C) 2002-2003 Idael Cardoso. // using System; using System.Runtime.InteropServices; namespace Ripper { public class CDBufferFiller { byte[] BufferArray; int WritePosition = 0; public CDBufferFiller(byte[] aBuffer) { BufferArray = aBuffer; } public void OnCdDataRead(object sender, DataReadEventArgs ea) { Buffer.BlockCopy(ea.Data, 0, BufferArray, WritePosition, (int)ea.DataSize); WritePosition += (int)ea.DataSize; } } /// <summary> /// /// </summary> public class CDDrive: IDisposable { private IntPtr cdHandle; private bool TocValid = false; private Win32Functions.CDROM_TOC Toc = null; private char m_Drive = '\0'; private DeviceChangeNotificationWindow NotWnd = null; public event EventHandler CDInserted; public event EventHandler CDRemoved; public CDDrive() { Toc = new Win32Functions.CDROM_TOC(); cdHandle = IntPtr.Zero; } public bool Open(char Drive) { Close(); if ( Win32Functions.GetDriveType(Drive+":\\") == Win32Functions.DriveTypes.DRIVE_CDROM ) { cdHandle = Win32Functions.CreateFile("\\\\.\\"+Drive+':', Win32Functions.GENERIC_READ, Win32Functions.FILE_SHARE_READ, IntPtr.Zero, Win32Functions.OPEN_EXISTING, 0, IntPtr.Zero); if ( ((int)cdHandle != -1) && ((int)cdHandle != 0) ) { m_Drive = Drive; NotWnd = new DeviceChangeNotificationWindow(); NotWnd.DeviceChange +=new DeviceChangeEventHandler(NotWnd_DeviceChange); return true; } else { return true; } } else { return false; } } public void Close() { UnLockCD(); if ( NotWnd != null ) { NotWnd.DestroyHandle(); NotWnd = null; } if ( ((int)cdHandle != -1) && ((int)cdHandle != 0) ) { Win32Functions.CloseHandle(cdHandle); } cdHandle = IntPtr.Zero; m_Drive = '\0'; TocValid = false; } public bool IsOpened { get { return ((int)cdHandle != -1) && ((int)cdHandle != 0); } } public void Dispose() { Close(); GC.SuppressFinalize(this); } ~CDDrive() { Dispose(); } protected bool ReadTOC() { if ( ((int)cdHandle != -1) && ((int)cdHandle != 0) ) { uint BytesRead = 0; TocValid = Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_CDROM_READ_TOC, IntPtr.Zero, 0, Toc, (uint)Marshal.SizeOf(Toc), ref BytesRead, IntPtr.Zero) != 0; } else { TocValid = false; } return TocValid; } protected int GetStartSector(int track) { if ( TocValid && (track >= Toc.FirstTrack) && (track <= Toc.LastTrack) ) { Win32Functions.TRACK_DATA td = Toc.TrackData[track-1]; return (td.Address_1*60*75 + td.Address_2*75 + td.Address_3)-150; } else { return -1; } } protected int GetEndSector(int track) { if ( TocValid && (track >= Toc.FirstTrack) && (track <= Toc.LastTrack) ) { Win32Functions.TRACK_DATA td = Toc.TrackData[track]; return (td.Address_1*60*75 + td.Address_2*75 + td.Address_3)-151; } else { return -1; } } protected const int NSECTORS = 13; protected const int UNDERSAMPLING = 1; protected const int CB_CDDASECTOR = 2368; protected const int CB_QSUBCHANNEL = 16; protected const int CB_CDROMSECTOR = 2048; protected const int CB_AUDIO = (CB_CDDASECTOR-CB_QSUBCHANNEL); /// <summary> /// Read Audio Sectors /// </summary> /// <param name="sector">The sector where to start to read</param> /// <param name="Buffer">The length must be at least CB_CDDASECTOR*Sectors bytes</param> /// <param name="NumSectors">Number of sectors to read</param> /// <returns>True on success</returns> protected bool ReadSector(int sector, byte[] Buffer, int NumSectors) { if ( TocValid && ((sector+NumSectors) <= GetEndSector(Toc.LastTrack)) && (Buffer.Length >= CB_AUDIO*NumSectors)) { Win32Functions.RAW_READ_INFO rri = new Win32Functions.RAW_READ_INFO(); rri.TrackMode = Win32Functions.TRACK_MODE_TYPE.CDDA; rri.SectorCount = (uint)NumSectors; rri.DiskOffset = sector*CB_CDROMSECTOR; uint BytesRead = 0; if ( Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_CDROM_RAW_READ, rri, (uint)Marshal.SizeOf(rri), Buffer, (uint)NumSectors*CB_AUDIO, ref BytesRead, IntPtr.Zero) != 0) { return true; } else { return false; } } else { return false; } } /// <summary> /// Lock the CD drive /// </summary> /// <returns>True on success</returns> public bool LockCD() { if (((int)cdHandle != -1) && ((int)cdHandle != 0)) { uint Dummy = 0; Win32Functions.PREVENT_MEDIA_REMOVAL pmr = new Win32Functions.PREVENT_MEDIA_REMOVAL(); pmr.PreventMediaRemoval = 1; return Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_STORAGE_MEDIA_REMOVAL, pmr, (uint)Marshal.SizeOf(pmr), IntPtr.Zero, 0, ref Dummy, IntPtr.Zero) != 0; } else { return false; } } /// <summary> /// Unlock CD drive /// </summary> /// <returns>True on success</returns> public bool UnLockCD() { if (((int)cdHandle != -1) && ((int)cdHandle != 0)) { uint Dummy = 0; Win32Functions.PREVENT_MEDIA_REMOVAL pmr = new Win32Functions.PREVENT_MEDIA_REMOVAL(); pmr.PreventMediaRemoval = 0; return Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_STORAGE_MEDIA_REMOVAL, pmr, (uint)Marshal.SizeOf(pmr), IntPtr.Zero, 0, ref Dummy, IntPtr.Zero) != 0; } else { return false; } } /// <summary> /// Close the CD drive door /// </summary> /// <returns>True on success</returns> public bool LoadCD() { TocValid = false; if (((int)cdHandle != -1) && ((int)cdHandle != 0)) { uint Dummy = 0; return Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, ref Dummy, IntPtr.Zero) != 0; } else { return false; } } /// <summary> /// Open the CD drive door /// </summary> /// <returns>True on success</returns> public bool EjectCD() { TocValid = false; if (((int)cdHandle != -1) && ((int)cdHandle != 0)) { uint Dummy = 0; return Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, ref Dummy, IntPtr.Zero) != 0; } else { return false; } } /// <summary> /// Check if there is CD in the drive /// </summary> /// <returns>True on success</returns> public bool IsCDReady() { if (((int)cdHandle != -1) && ((int)cdHandle != 0)) { uint Dummy = 0; if (Win32Functions.DeviceIoControl(cdHandle, Win32Functions.IOCTL_STORAGE_CHECK_VERIFY, IntPtr.Zero, 0, IntPtr.Zero, 0, ref Dummy, IntPtr.Zero) != 0) { return true; } else { TocValid = false; return false; } } else { TocValid = false; return false; } } /// <summary> /// If there is a CD in the drive read its TOC /// </summary> /// <returns>True on success</returns> public bool Refresh() { if ( IsCDReady() ) { return ReadTOC(); } else { return false; } } /// <summary> /// Return the number of tracks on the CD /// </summary> /// <returns>-1 on error</returns> public int GetNumTracks() { if ( TocValid ) { return Toc.LastTrack - Toc.FirstTrack + 1; } else return -1; } /// <summary> /// Return the number of audio tracks on the CD /// </summary> /// <returns>-1 on error</returns> public int GetNumAudioTracks() { if ( TocValid ) { int tracks = 0; for (int i = Toc.FirstTrack - 1; i < Toc.LastTrack; i++) { if (Toc.TrackData[i].Control == 0 ) tracks++; } return tracks; } else { return -1; } } /// <summary> /// Read the digital data of the track /// </summary> /// <param name="track">Track to read</param> /// <param name="Data">Buffer that will receive the data</param> /// <param name="DataSize">On return the size needed to read the track</param> /// <param name="StartSecond">First second of the track to read, 0 means to start at beginning of the track</param> /// <param name="Seconds2Read">Number of seconds to read, 0 means to read until the end of the track</param> /// <param name="OnProgress">Delegate to indicate the reading progress</param> /// <returns>Negative value means an error. On success returns the number of bytes read</returns> public int ReadTrack(int track, byte[] Data, ref uint DataSize, uint StartSecond, uint Seconds2Read, CdReadProgressEventHandler ProgressEvent) { if ( TocValid && (track >= Toc.FirstTrack) && (track <= Toc.LastTrack) ) { int StartSect = GetStartSector(track); int EndSect = GetEndSector(track); if ( (StartSect += (int)StartSecond*75) >= EndSect ) { StartSect -= (int)StartSecond*75; } if ( (Seconds2Read > 0) && ( (int)(StartSect + Seconds2Read*75) < EndSect ) ) { EndSect = StartSect + (int)Seconds2Read*75; } DataSize = (uint)(EndSect - StartSect)*CB_AUDIO; if ( Data != null) { if ( Data.Length >= DataSize ) { CDBufferFiller BufferFiller = new CDBufferFiller(Data); return ReadTrack(track, new CdDataReadEventHandler(BufferFiller.OnCdDataRead), StartSecond, Seconds2Read, ProgressEvent); } else { return 0; } } else { return 0; } } else { return -1; } } /// <summary> /// Read the digital data of the track /// </summary> /// <param name="track">Track to read</param> /// <param name="Data">Buffer that will receive the data</param> /// <param name="DataSize">On return the size needed to read the track</param> /// <param name="OnProgress">Delegate to indicate the reading progress</param> /// <returns>Negative value means an error. On success returns the number of bytes read</returns> public int ReadTrack(int track, byte[] Data, ref uint DataSize, CdReadProgressEventHandler ProgressEvent) { return ReadTrack(track, Data, ref DataSize, 0, 0, ProgressEvent); } /// <summary> /// Read the digital data of the track /// </summary> /// <param name="track">Track to read</param> /// <param name="OnDataRead">Call each time data is read</param> /// <param name="StartSecond">First second of the track to read, 0 means to start at beginning of the track</param> /// <param name="Seconds2Read">Number of seconds to read, 0 means to read until the end of the track</param> /// <param name="OnProgress">Delegate to indicate the reading progress</param> /// <returns>Negative value means an error. On success returns the number of bytes read</returns> public int ReadTrack(int track, CdDataReadEventHandler DataReadEvent, uint StartSecond, uint Seconds2Read, CdReadProgressEventHandler ProgressEvent) { if ( TocValid && (track >= Toc.FirstTrack) && (track <= Toc.LastTrack) && (DataReadEvent != null) ) { int StartSect = GetStartSector(track); int EndSect = GetEndSector(track); if ( (StartSect += (int)StartSecond*75) >= EndSect ) { StartSect -= (int)StartSecond*75; } if ( (Seconds2Read > 0) && ( (int)(StartSect + Seconds2Read*75) < EndSect ) ) { EndSect = StartSect + (int)Seconds2Read*75; } uint Bytes2Read = (uint)(EndSect - StartSect)*CB_AUDIO; uint BytesRead = 0; byte[] Data = new byte[CB_AUDIO*NSECTORS]; bool Cont = true; bool ReadOk = true; if ( ProgressEvent != null ) { ReadProgressEventArgs rpa = new ReadProgressEventArgs(Bytes2Read, 0); ProgressEvent(this, rpa); Cont = !rpa.CancelRead; } for (int sector = StartSect; (sector < EndSect) && (Cont) && (ReadOk); sector+=NSECTORS) { int Sectors2Read = ( (sector + NSECTORS) < EndSect )?NSECTORS:(EndSect-sector); ReadOk = ReadSector(sector, Data, Sectors2Read); if ( ReadOk ) { DataReadEventArgs dra = new DataReadEventArgs(Data, (uint)(CB_AUDIO*Sectors2Read)); DataReadEvent(this, dra); BytesRead += (uint)(CB_AUDIO*Sectors2Read); if ( ProgressEvent != null ) { ReadProgressEventArgs rpa = new ReadProgressEventArgs(Bytes2Read, BytesRead); ProgressEvent(this, rpa); Cont = !rpa.CancelRead; } } } if ( ReadOk ) { return (int)BytesRead; } else { return -1; } } else { return -1; } } /// <summary> /// Read the digital data of the track /// </summary> /// <param name="track">Track to read</param> /// <param name="OnDataRead">Call each time data is read</param> /// <param name="OnProgress">Delegate to indicate the reading progress</param> /// <returns>Negative value means an error. On success returns the number of bytes read</returns> public int ReadTrack(int track, CdDataReadEventHandler DataReadEvent, CdReadProgressEventHandler ProgressEvent) { return ReadTrack(track, DataReadEvent, 0, 0, ProgressEvent); } /// <summary> /// Get track size /// </summary> /// <param name="track">Track</param> /// <returns>Size in bytes of track data</returns> public uint TrackSize(int track) { uint Size = 0; ReadTrack(track, null, ref Size, null); return Size; } public bool IsAudioTrack(int track) { if ( (TocValid) && (track >= Toc.FirstTrack) && (track <= Toc.LastTrack) ) { return (Toc.TrackData[track-1].Control & 4) == 0; } else { return false; } } public static char[] GetCDDriveLetters() { string res = ""; for ( char c = 'C'; c <= 'Z'; c++) { if ( Win32Functions.GetDriveType(c+":") == Win32Functions.DriveTypes.DRIVE_CDROM ) { res += c; } } return res.ToCharArray(); } private void OnCDInserted() { if ( CDInserted != null ) { CDInserted(this, EventArgs.Empty); } } private void OnCDRemoved() { if ( CDRemoved != null ) { CDRemoved(this, EventArgs.Empty); } } private void NotWnd_DeviceChange(object sender, DeviceChangeEventArgs ea) { if ( ea.Drive == m_Drive ) { TocValid = false; switch ( ea.ChangeType ) { case DeviceChangeEventType.DeviceInserted : OnCDInserted(); break; case DeviceChangeEventType.DeviceRemoved : OnCDRemoved(); break; } } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Binding; #if FEATURE_CORE_DLR using MSAst = System.Linq.Expressions; #else using MSAst = Microsoft.Scripting.Ast; #endif using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; public class WithStatement : Statement { private int _headerIndex; private readonly Expression _contextManager; private readonly Expression _var; private Statement _body; public WithStatement(Expression contextManager, Expression var, Statement body) { _contextManager = contextManager; _var = var; _body = body; } public int HeaderIndex { set { _headerIndex = value; } } public new Expression Variable { get { return _var; } } public Expression ContextManager { get { return _contextManager; } } public Statement Body { get { return _body; } } /// <summary> /// WithStatement is translated to the DLR AST equivalent to /// the following Python code snippet (from with statement spec): /// /// mgr = (EXPR) /// exit = mgr.__exit__ # Not calling it yet /// value = mgr.__enter__() /// exc = True /// try: /// VAR = value # Only if "as VAR" is present /// BLOCK /// except: /// # The exceptional case is handled here /// exc = False /// if not exit(*sys.exc_info()): /// raise /// # The exception is swallowed if exit() returns true /// finally: /// # The normal and non-local-goto cases are handled here /// if exc: /// exit(None, None, None) /// /// </summary> public override MSAst.Expression Reduce() { // Five statements in the result... ReadOnlyCollectionBuilder<MSAst.Expression> statements = new ReadOnlyCollectionBuilder<MSAst.Expression>(6); ReadOnlyCollectionBuilder<MSAst.ParameterExpression> variables = new ReadOnlyCollectionBuilder<MSAst.ParameterExpression>(6); MSAst.ParameterExpression lineUpdated = Ast.Variable(typeof(bool), "$lineUpdated_with"); variables.Add(lineUpdated); //****************************************************************** // 1. mgr = (EXPR) //****************************************************************** MSAst.ParameterExpression manager = Ast.Variable(typeof(object), "with_manager"); variables.Add(manager); statements.Add( GlobalParent.AddDebugInfo( Ast.Assign( manager, _contextManager ), new SourceSpan(GlobalParent.IndexToLocation(StartIndex), GlobalParent.IndexToLocation(_headerIndex)) ) ); //****************************************************************** // 2. exit = mgr.__exit__ # Not calling it yet //****************************************************************** MSAst.ParameterExpression exit = Ast.Variable(typeof(object), "with_exit"); variables.Add(exit); statements.Add( MakeAssignment( exit, GlobalParent.Get( "__exit__", manager ) ) ); //****************************************************************** // 3. value = mgr.__enter__() //****************************************************************** MSAst.ParameterExpression value = Ast.Variable(typeof(object), "with_value"); variables.Add(value); statements.Add( GlobalParent.AddDebugInfoAndVoid( MakeAssignment( value, Parent.Invoke( new CallSignature(0), Parent.LocalContext, GlobalParent.Get( "__enter__", manager ) ) ), new SourceSpan(GlobalParent.IndexToLocation(StartIndex), GlobalParent.IndexToLocation(_headerIndex)) ) ); //****************************************************************** // 4. exc = True //****************************************************************** MSAst.ParameterExpression exc = Ast.Variable(typeof(bool), "with_exc"); variables.Add(exc); statements.Add( MakeAssignment( exc, AstUtils.Constant(true) ) ); //****************************************************************** // 5. The final try statement: // // try: // VAR = value # Only if "as VAR" is present // BLOCK // except: // # The exceptional case is handled here // exc = False // if not exit(*sys.exc_info()): // raise // # The exception is swallowed if exit() returns true // finally: // # The normal and non-local-goto cases are handled here // if exc: // exit(None, None, None) //****************************************************************** MSAst.ParameterExpression exception; statements.Add( // try: AstUtils.Try( AstUtils.Try(// try statement body PushLineUpdated(false, lineUpdated), _var != null ? (MSAst.Expression)Ast.Block( // VAR = value _var.TransformSet(SourceSpan.None, value, PythonOperationKind.None), // BLOCK _body, AstUtils.Empty() ) : // BLOCK (MSAst.Expression)_body // except:, // try statement location ).Catch(exception = Ast.Variable(typeof(Exception), "exception"), // Python specific exception handling code TryStatement.GetTracebackHeader( this, exception, GlobalParent.AddDebugInfoAndVoid( Ast.Block( // exc = False MakeAssignment( exc, AstUtils.Constant(false) ), // if not exit(*sys.exc_info()): // raise AstUtils.IfThen( GlobalParent.Convert( typeof(bool), ConversionResultKind.ExplicitCast, GlobalParent.Operation( typeof(bool), PythonOperationKind.IsFalse, MakeExitCall(exit, exception) ) ), UpdateLineUpdated(true), Ast.Throw( Ast.Call( AstMethods.MakeRethrowExceptionWorker, exception ) ) ) ), _body.Span ) ), PopLineUpdated(lineUpdated), Ast.Empty() ) // finally: ).Finally( // if exc: // exit(None, None, None) AstUtils.IfThen( exc, GlobalParent.AddDebugInfoAndVoid( Ast.Block( MSAst.DynamicExpression.Dynamic( GlobalParent.PyContext.Invoke( new CallSignature(3) // signature doesn't include function ), typeof(object), new MSAst.Expression[] { Parent.LocalContext, exit, AstUtils.Constant(null), AstUtils.Constant(null), AstUtils.Constant(null) } ), Ast.Empty() ), _contextManager.Span ) ) ) ); statements.Add(AstUtils.Empty()); return Ast.Block(variables.ToReadOnlyCollection(), statements.ToReadOnlyCollection()); } private MSAst.Expression MakeExitCall(MSAst.ParameterExpression exit, MSAst.Expression exception) { // The 'with' statement's exceptional clause explicitly does not set the thread's current exception information. // So while the pseudo code says: // exit(*sys.exc_info()) // we'll actually do: // exit(*PythonOps.GetExceptionInfoLocal($exception)) return GlobalParent.Convert( typeof(bool), ConversionResultKind.ExplicitCast, Parent.Invoke( new CallSignature(ArgumentType.List), Parent.LocalContext, exit, Ast.Call( AstMethods.GetExceptionInfoLocal, Parent.LocalContext, exception ) ) ); } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { if (_contextManager != null) { _contextManager.Walk(walker); } if (_var != null) { _var.Walk(walker); } if (_body != null) { _body.Walk(walker); } } walker.PostWalk(this); } } }
//------------------------------------------------------------------------------ // <copyright file="GenericEnumRowCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Data; using System.Linq; using System.Diagnostics; using System.Linq.Expressions; using System.Collections.ObjectModel; using System.Data.DataSetExtensions; namespace System.Data { /// <summary> /// Provides an entry point so that Cast operator call can be intercepted within an extension method. /// </summary> public abstract class EnumerableRowCollection : IEnumerable { internal abstract Type ElementType { get; } internal abstract DataTable Table { get; } internal EnumerableRowCollection() { } IEnumerator IEnumerable.GetEnumerator() { return null; } } /// <summary> /// This class provides a wrapper for DataTables to allow for querying via LINQ. /// </summary> public class EnumerableRowCollection<TRow> : EnumerableRowCollection, IEnumerable<TRow> { private readonly DataTable _table; private readonly IEnumerable<TRow> _enumerableRows; private readonly List<Func<TRow, bool>> _listOfPredicates; // Stores list of sort expression in the order provided by user. E.g. order by, thenby, thenby descending.. private readonly SortExpressionBuilder<TRow> _sortExpression; private readonly Func<TRow, TRow> _selector; #region Properties internal override Type ElementType { get { return typeof(TRow); } } internal IEnumerable<TRow> EnumerableRows { get { return _enumerableRows; } } internal override DataTable Table { get { return _table; } } #endregion Properties #region Constructors /// <summary> /// This constructor is used when Select operator is called with output Type other than input row Type. /// Basically fail on GetLDV(), but other LINQ operators must work. /// </summary> internal EnumerableRowCollection(IEnumerable<TRow> enumerableRows, bool isDataViewable, DataTable table) { Debug.Assert(!isDataViewable || table != null, "isDataViewable bug table is null"); _enumerableRows = enumerableRows; if (isDataViewable) { _table = table; } _listOfPredicates = new List<Func<TRow, bool>>(); _sortExpression = new SortExpressionBuilder<TRow>(); } /// <summary> /// Basic Constructor /// </summary> internal EnumerableRowCollection(DataTable table) { _table = table; _enumerableRows = table.Rows.Cast<TRow>(); _listOfPredicates = new List<Func<TRow, bool>>(); _sortExpression = new SortExpressionBuilder<TRow>(); } /// <summary> /// Copy Constructor that sets the input IEnumerable as enumerableRows /// Used to maintain IEnumerable that has linq operators executed in the same order as the user /// </summary> internal EnumerableRowCollection(EnumerableRowCollection<TRow> source, IEnumerable<TRow> enumerableRows, Func<TRow, TRow> selector) { Debug.Assert(null != enumerableRows, "null enumerableRows"); _enumerableRows = enumerableRows; _selector = selector; if (null != source) { if (null == source._selector) { _table = source._table; } _listOfPredicates = new List<Func<TRow, bool>>(source._listOfPredicates); _sortExpression = source._sortExpression.Clone(); //deep copy the List } else { _listOfPredicates = new List<Func<TRow, bool>>(); _sortExpression = new SortExpressionBuilder<TRow>(); } } #endregion Constructors #region PublicInterface IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// This method returns an strongly typed iterator /// for the underlying DataRow collection. /// </summary> /// <returns> /// A strongly typed iterator. /// </returns> public IEnumerator<TRow> GetEnumerator() { return _enumerableRows.GetEnumerator(); } #endregion PublicInterface /// <summary> /// Evaluates filter and sort if necessary and returns /// a LinqDataView representing the LINQ query this class has collected. /// </summary> /// <returns>LinqDataView repesenting the LINQ query</returns> internal LinqDataView GetLinqDataView() //Called by AsLinqDataView { if ((null == _table) || !typeof(DataRow).IsAssignableFrom(typeof(TRow))) { throw DataSetUtil.NotSupported(Strings.ToLDVUnsupported); } LinqDataView view = null; #region BuildSinglePredicate Func<DataRow, bool> finalPredicate = null; //Conjunction of all .Where(..) predicates if ((null != _selector) && (0 < _listOfPredicates.Count)) { // Hook up all individual predicates into one predicate // This delegate is a conjunction of multiple predicates set by the user // Note: This is a Short-Circuit Conjunction finalPredicate = delegate(DataRow row) { if (!Object.ReferenceEquals(row, _selector((TRow)(object)row))) { throw DataSetUtil.NotSupported(Strings.ToLDVUnsupported); } foreach (Func<TRow, bool> pred in _listOfPredicates) { if (!pred((TRow)(object)row)) { return false; } } return true; }; } else if (null != _selector) { finalPredicate = delegate(DataRow row) { if (!Object.ReferenceEquals(row, _selector((TRow)(object)row))) { throw DataSetUtil.NotSupported(Strings.ToLDVUnsupported); } return true; }; } else if (0 < _listOfPredicates.Count) { finalPredicate = delegate(DataRow row) { foreach (Func<TRow, bool> pred in _listOfPredicates) { if (!pred((TRow)(object)row)) { return false; } } return true; }; } #endregion BuildSinglePredicate #region Evaluate Filter/Sort // All of this mess below is because we want to create index only once. // // If we only have filter, we set _view.Predicate - 1 index creation // If we only have sort, we set _view.SortExpression() - 1 index creation // If we have BOTH, we set them through the constructor - 1 index creation // // Filter AND Sort if ((null != finalPredicate) && (0 < _sortExpression.Count)) { // A lot more work here because constructor does not know type K, // so the responsibility to create appropriate delegate comparers // is outside of the constructor. view = new LinqDataView( _table, finalPredicate, //Func() Predicate delegate(DataRow row) //System.Predicate { return finalPredicate(row); }, delegate(DataRow a, DataRow b) //Comparison for DV for Index creation { return _sortExpression.Compare( _sortExpression.Select((TRow)(object)a), _sortExpression.Select((TRow)(object)b) ); }, delegate(object key, DataRow row) //Comparison_K_T for DV's Find() { return _sortExpression.Compare( (List<object>)key, _sortExpression.Select((TRow)(object)row) ); }, _sortExpression.CloneCast<DataRow>()); } else if (null != finalPredicate) { //Only Filtering view = new LinqDataView( _table, finalPredicate, delegate(DataRow row) //System.Predicate { return finalPredicate(row); }, null, null, _sortExpression.CloneCast<DataRow>()); } else if (0 < _sortExpression.Count) { //Only Sorting view = new LinqDataView( _table, null, null, delegate(DataRow a, DataRow b) { return _sortExpression.Compare(_sortExpression.Select((TRow)(object)a), _sortExpression.Select((TRow)(object)b)); }, delegate(object key, DataRow row) { return _sortExpression.Compare((List<object>)key, _sortExpression.Select((TRow)(object)row)); }, _sortExpression.CloneCast<DataRow>()); } else { view = new LinqDataView(_table, _sortExpression.CloneCast<DataRow>()); } #endregion Evaluate Filter and Sort return view; } #region Add Single Filter/Sort Expression /// <summary> /// Used to add a filter predicate. /// A conjunction of all predicates are evaluated in LinqDataView /// </summary> internal void AddPredicate(Func<TRow, bool> pred) { Debug.Assert(pred != null); _listOfPredicates.Add(pred); } /// <summary> /// Adds a sort expression when Keyselector is provided but not Comparer /// </summary> internal void AddSortExpression<TKey>(Func<TRow, TKey> keySelector, bool isDescending, bool isOrderBy) { AddSortExpression<TKey>(keySelector, Comparer<TKey>.Default, isDescending, isOrderBy); } /// <summary> /// Adds a sort expression when Keyselector and Comparer are provided. /// </summary> internal void AddSortExpression<TKey>( Func<TRow, TKey> keySelector, IComparer<TKey> comparer, bool isDescending, bool isOrderBy) { DataSetUtil.CheckArgumentNull(keySelector, "keySelector"); DataSetUtil.CheckArgumentNull(comparer, "comparer"); _sortExpression.Add( delegate(TRow input) { return (object)keySelector(input); }, delegate(object val1, object val2) { return (isDescending ? -1 : 1) * comparer.Compare((TKey)val1, (TKey)val2); }, isOrderBy); } #endregion Add Single Filter/Sort Expression } }
using Lucene.Net.Support; using Lucene.Net.Support.IO; using System; using System.Diagnostics; using System.IO; namespace Lucene.Net.Store { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /// <summary> /// An <see cref="FSDirectory"/> implementation that uses <see cref="FileStream"/>'s /// positional read, which allows multiple threads to read from the same file /// without synchronizing. /// <para/> /// This class only uses <see cref="FileStream"/> when reading; writing is achieved with /// <see cref="FSDirectory.FSIndexOutput"/>. /// <para> /// <b>NOTE</b>: <see cref="NIOFSDirectory"/> is not recommended on Windows because of a bug in /// how FileChannel.read is implemented in Sun's JRE. Inside of the /// implementation the position is apparently synchronized. See <a /// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265734">here</a> /// for details. /// </para> /// <para> /// <font color="red"><b>NOTE:</b> Accessing this class either directly or /// indirectly from a thread while it's interrupted can close the /// underlying file descriptor immediately if at the same time the thread is /// blocked on IO. The file descriptor will remain closed and subsequent access /// to <see cref="NIOFSDirectory"/> will throw a <see cref="ObjectDisposedException"/>. If /// your application uses either <see cref="System.Threading.Thread.Interrupt()"/> or /// <see cref="System.Threading.Tasks.Task"/> you should use <see cref="SimpleFSDirectory"/> in /// favor of <see cref="NIOFSDirectory"/>.</font> /// </para> /// </summary> public class NIOFSDirectory : FSDirectory { /// <summary> /// Create a new <see cref="NIOFSDirectory"/> for the named location. /// </summary> /// <param name="path"> the path of the directory </param> /// <param name="lockFactory"> the lock factory to use, or null for the default /// (<see cref="NativeFSLockFactory"/>); </param> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public NIOFSDirectory(DirectoryInfo path, LockFactory lockFactory) : base(path, lockFactory) { } /// <summary> /// Create a new <see cref="NIOFSDirectory"/> for the named location and <see cref="NativeFSLockFactory"/>. /// </summary> /// <param name="path"> the path of the directory </param> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public NIOFSDirectory(DirectoryInfo path) : base(path, null) { } /// <summary> /// Create a new <see cref="NIOFSDirectory"/> for the named location. /// <para/> /// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>. /// </summary> /// <param name="path"> the path of the directory </param> /// <param name="lockFactory"> the lock factory to use, or null for the default /// (<see cref="NativeFSLockFactory"/>); </param> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public NIOFSDirectory(string path, LockFactory lockFactory) : this(new DirectoryInfo(path), lockFactory) { } /// <summary> /// Create a new <see cref="NIOFSDirectory"/> for the named location and <see cref="NativeFSLockFactory"/>. /// <para/> /// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>. /// </summary> /// <param name="path"> the path of the directory </param> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public NIOFSDirectory(string path) : this(path, null) { } /// <summary> /// Creates an <see cref="IndexInput"/> for the file with the given name. </summary> public override IndexInput OpenInput(string name, IOContext context) { EnsureOpen(); var path = new FileInfo(Path.Combine(Directory.FullName, name)); var fc = new FileStream(path.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return new NIOFSIndexInput("NIOFSIndexInput(path=\"" + path + "\")", fc, context); } public override IndexInputSlicer CreateSlicer(string name, IOContext context) { EnsureOpen(); var path = new FileInfo(Path.Combine(Directory.FullName, name)); var fc = new FileStream(path.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return new IndexInputSlicerAnonymousInnerClassHelper(context, path, fc); } private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer { private readonly IOContext context; private readonly FileInfo path; private readonly FileStream descriptor; public IndexInputSlicerAnonymousInnerClassHelper(IOContext context, FileInfo path, FileStream descriptor) { this.context = context; this.path = path; this.descriptor = descriptor; } protected override void Dispose(bool disposing) { if (disposing) { descriptor.Dispose(); } } public override IndexInput OpenSlice(string sliceDescription, long offset, long length) { return new NIOFSIndexInput("NIOFSIndexInput(" + sliceDescription + " in path=\"" + path + "\" slice=" + offset + ":" + (offset + length) + ")", descriptor, offset, length, BufferedIndexInput.GetBufferSize(context)); } [Obsolete("Only for reading CFS files from 3.x indexes.")] public override IndexInput OpenFullSlice() { try { return OpenSlice("full-slice", 0, descriptor.Length); } catch (IOException ex) { throw new Exception(ex.ToString(), ex); } } } /// <summary> /// Reads bytes with the <see cref="FileStreamExtensions.Read(FileStream, ByteBuffer, long)"/> /// extension method for <see cref="FileStream"/>. /// </summary> protected class NIOFSIndexInput : BufferedIndexInput { /// <summary> /// The maximum chunk size for reads of 16384 bytes. /// </summary> private const int CHUNK_SIZE = 16384; /// <summary> /// the file channel we will read from </summary> protected readonly FileStream m_channel; /// <summary> /// is this instance a clone and hence does not own the file to close it </summary> internal bool isClone = false; /// <summary> /// start offset: non-zero in the slice case </summary> protected readonly long m_off; /// <summary> /// end offset (start+length) </summary> protected readonly long m_end; private ByteBuffer byteBuf; // wraps the buffer for NIO public NIOFSIndexInput(string resourceDesc, FileStream fc, IOContext context) : base(resourceDesc, context) { this.m_channel = fc; this.m_off = 0L; this.m_end = fc.Length; } public NIOFSIndexInput(string resourceDesc, FileStream fc, long off, long length, int bufferSize) : base(resourceDesc, bufferSize) { this.m_channel = fc; this.m_off = off; this.m_end = off + length; this.isClone = true; } protected override void Dispose(bool disposing) { if (disposing && !isClone) { m_channel.Dispose(); } } public override object Clone() { NIOFSIndexInput clone = (NIOFSIndexInput)base.Clone(); clone.isClone = true; return clone; } public override sealed long Length { get { return m_end - m_off; } } protected override void NewBuffer(byte[] newBuffer) { base.NewBuffer(newBuffer); byteBuf = ByteBuffer.Wrap(newBuffer); } protected override void ReadInternal(byte[] b, int offset, int len) { ByteBuffer bb; // Determine the ByteBuffer we should use if (b == m_buffer && 0 == offset) { // Use our own pre-wrapped byteBuf: Debug.Assert(byteBuf != null); byteBuf.Clear(); byteBuf.Limit = len; bb = byteBuf; } else { bb = ByteBuffer.Wrap(b, offset, len); } int readOffset = bb.Position; int readLength = bb.Limit - readOffset; long pos = GetFilePointer() + m_off; if (pos + len > m_end) { throw new EndOfStreamException("read past EOF: " + this); } try { while (readLength > 0) { int limit; if (readLength > CHUNK_SIZE) { limit = readOffset + CHUNK_SIZE; } else { limit = readOffset + readLength; } bb.Limit = limit; int i = m_channel.Read(bb, pos); if (i <= 0) // be defensive here, even though we checked before hand, something could have changed { throw new Exception("read past EOF: " + this + " off: " + offset + " len: " + len + " pos: " + pos + " chunkLen: " + readLength + " end: " + m_end); } pos += i; readOffset += i; readLength -= i; } Debug.Assert(readLength == 0); } catch (IOException ioe) { throw new IOException(ioe.ToString() + ": " + this, ioe); } } protected override void SeekInternal(long pos) { } } } }
// // MediaPlayer.cs // // Authors: // John Millikin <[email protected]> // Bertrand Lorentz <[email protected]> // // Copyright (C) 2009 John Millikin // Copyright (C) 2010 Bertrand Lorentz // // 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.Linq; using System.Text; using DBus; using Hyena; using Banshee.Gui; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Playlist; using Banshee.ServiceStack; using Banshee.Sources; namespace Banshee.Mpris { public class MediaPlayer : IMediaPlayer, IPlayer, IPlaylists, IProperties { private static string mediaplayer_interface_name = "org.mpris.MediaPlayer2"; private static string player_interface_name = "org.mpris.MediaPlayer2.Player"; private static string playlists_interface_name = "org.mpris.MediaPlayer2.Playlists"; private PlaybackControllerService playback_service; private PlayerEngineService engine_service; private Gtk.ToggleAction fullscreen_action; private Dictionary<string, AbstractPlaylistSource> playlist_sources; private Dictionary<string, object> current_properties; private Dictionary<string, object> changed_properties; private List<string> invalidated_properties; private static ObjectPath path = new ObjectPath ("/org/mpris/MediaPlayer2"); public static ObjectPath Path { get { return path; } } private event PropertiesChangedHandler properties_changed; event PropertiesChangedHandler IProperties.PropertiesChanged { add { properties_changed += value; } remove { properties_changed -= value; } } private event DBusPlayerSeekedHandler dbus_seeked; event DBusPlayerSeekedHandler IPlayer.Seeked { add { dbus_seeked += value; } remove { dbus_seeked -= value; } } private event PlaylistChangedHandler playlist_changed; event PlaylistChangedHandler IPlaylists.PlaylistChanged { add { playlist_changed += value; } remove { playlist_changed -= value; } } public MediaPlayer () { playback_service = ServiceManager.PlaybackController; engine_service = ServiceManager.PlayerEngine; playlist_sources = new Dictionary<string, AbstractPlaylistSource> (); changed_properties = new Dictionary<string, object> (); current_properties = new Dictionary<string, object> (); invalidated_properties = new List<string> (); var interface_service = ServiceManager.Get<InterfaceActionService> (); fullscreen_action = interface_service.ViewActions["FullScreenAction"] as Gtk.ToggleAction; } #region IMediaPlayer public bool CanQuit { get { return true; } } public bool CanRaise { get { return true; } } public bool Fullscreen { get { if (fullscreen_action != null) { return fullscreen_action.Active; } return false; } set { if (fullscreen_action != null) { fullscreen_action.Active = value; } } } public bool CanSetFullscreen { get { return true; } } public bool HasTrackList { get { return false; } } public string Identity { get { return "Banshee"; } } public string DesktopEntry { get { return "banshee"; } } // This is just a list of commonly supported MIME types. // We don't know exactly which ones are supported by the PlayerEngine private static string [] supported_mimetypes = { "application/ogg", "audio/flac", "audio/mp3", "audio/mp4", "audio/mpeg", "audio/ogg", "audio/vorbis", "audio/wav", "audio/x-flac", "audio/x-vorbis+ogg", "video/avi", "video/mp4", "video/mpeg" }; public string [] SupportedMimeTypes { get { return supported_mimetypes; } } // We can't use the PlayerEngine.SourceCapabilities property here, because // the OpenUri method only supports "file" and "http". private static string [] supported_uri_schemes = { "file", "http" }; public string [] SupportedUriSchemes { get { return supported_uri_schemes; } } public void Raise () { if (!CanRaise) { return; } ServiceManager.Get<GtkElementsService> ().PrimaryWindow.SetVisible (true); } public void Quit () { if (!CanQuit) { return; } Application.Shutdown (); } #endregion #region IPlayer public bool CanControl { get { return true; } } // We don't really know if we can actually go next or previous public bool CanGoNext { get { return CanControl; } } public bool CanGoPrevious { get { return CanControl; } } public bool CanPause { get { return engine_service.CanPause; } } public bool CanPlay { get { return CanControl; } } public bool CanSeek { get { return engine_service.CanSeek; } } public double MaximumRate { get { return 1.0; } } public double MinimumRate { get { return 1.0; } } public double Rate { get { return 1.0; } set {} } public bool Shuffle { get { return !(playback_service.ShuffleMode == "off"); } set { playback_service.ShuffleMode = value ? "song" : "off"; } } public string LoopStatus { get { string loop_status; switch (playback_service.RepeatMode) { case PlaybackRepeatMode.None: loop_status = "None"; break; case PlaybackRepeatMode.RepeatSingle: loop_status = "Track"; break; case PlaybackRepeatMode.RepeatAll: loop_status = "Playlist"; break; default: loop_status = "None"; break; } return loop_status; } set { switch (value) { case "None": playback_service.RepeatMode = PlaybackRepeatMode.None; break; case "Track": playback_service.RepeatMode = PlaybackRepeatMode.RepeatSingle; break; case "Playlist": playback_service.RepeatMode = PlaybackRepeatMode.RepeatAll; break; } } } public string PlaybackStatus { get { string status; switch (engine_service.CurrentState) { case PlayerState.Playing: status = "Playing"; break; case PlayerState.Paused: status = "Paused"; break; default: status = "Stopped"; break; } return status; } } public IDictionary<string, object> Metadata { get { var metadata = new Metadata (engine_service.CurrentTrack); return metadata.DataStore; } } public double Volume { get { return engine_service.Volume / 100.0; } set { engine_service.Volume = (ushort)Math.Round (value * 100); } } // Position is expected in microseconds public long Position { get { return (long)engine_service.Position * 1000; } } public void Next () { playback_service.Next (); } public void Previous () { playback_service.Previous (); } public void Pause () { engine_service.Pause (); } public void PlayPause () { engine_service.TogglePlaying (); } public void Stop () { engine_service.Close (); } public void Play () { engine_service.Play (); } public void SetPosition (ObjectPath trackid, long position) { if (!CanSeek) { return; } if (trackid == null || trackid != (ObjectPath)Metadata["mpris:trackid"]) { return; } // position is in microseconds, we speak in milliseconds long position_ms = position / 1000; if (position_ms < 0 || position_ms > engine_service.CurrentTrack.Duration.TotalMilliseconds) { return; } engine_service.Position = (uint)position_ms; } public void Seek (long position) { if (!CanSeek) { return; } // position is in microseconds, relative to the current position and can be negative long new_pos = (int)engine_service.Position + (position / 1000); if (new_pos < 0) { engine_service.Position = 0; } else { engine_service.Position = (uint)new_pos; } } public void OpenUri (string uri) { Banshee.Streaming.RadioTrackInfo.OpenPlay (uri); } #endregion #region IPlaylists public uint PlaylistCount { get { return (uint)ServiceManager.SourceManager.FindSources<AbstractPlaylistSource> ().Count (); } } private static string [] supported_playlist_orderings = { "Alphabetical", "UserDefined" }; public string [] Orderings { get { return supported_playlist_orderings; } } private static Playlist dummy_playlist = new Playlist { Id = new ObjectPath (DBusServiceManager.ObjectRoot), Name = "", Icon = "" }; public MaybePlaylist ActivePlaylist { get { // We want the source that is currently playing var playlist_source = ServiceManager.PlaybackController.Source as AbstractPlaylistSource; if (playlist_source == null) { return new MaybePlaylist { Valid = false, Playlist = dummy_playlist }; } else { return new MaybePlaylist { Valid = true, Playlist = BuildPlaylistFromSource (playlist_source) }; } } } private ObjectPath MakeObjectPath (AbstractPlaylistSource playlist) { StringBuilder object_path_builder = new StringBuilder (); object_path_builder.Append (DBusServiceManager.ObjectRoot); if (playlist.Parent != null) { object_path_builder.AppendFormat ("/{0}", DBusServiceManager.MakeDBusSafeString (playlist.Parent.TypeName)); } object_path_builder.Append ("/Playlists/"); object_path_builder.Append (DBusServiceManager.MakeDBusSafeString (playlist.UniqueId)); string object_path = object_path_builder.ToString (); playlist_sources[object_path] = playlist; return new ObjectPath (object_path); } private string GetIconPath (Source source) { string icon_name = "image-missing"; Type icon_type = source.Properties.GetType ("Icon.Name"); if (icon_type == typeof (string)) { icon_name = source.Properties.Get<string> ("Icon.Name"); } else if (icon_type == typeof (string [])) { icon_name = source.Properties.Get<string[]> ("Icon.Name")[0]; } string icon_path = Paths.Combine (Paths.GetInstalledDataDirectory ("icons"), "hicolor", "22x22", "categories", String.Concat (icon_name, ".png")); return String.Concat ("file://", icon_path); } private Playlist BuildPlaylistFromSource (AbstractPlaylistSource source) { var mpris_playlist = new Playlist (); mpris_playlist.Name = source.Name; mpris_playlist.Id = MakeObjectPath (source); mpris_playlist.Icon = GetIconPath (source); return mpris_playlist; } public void ActivatePlaylist (ObjectPath playlist_id) { // TODO: Maybe try to find the playlist if it's not in the dictionary ? var playlist = playlist_sources[playlist_id.ToString ()]; if (playlist != null) { Log.DebugFormat ("MPRIS activating playlist {0}", playlist.Name); ServiceManager.SourceManager.SetActiveSource (playlist); ServiceManager.PlaybackController.Source = playlist; ServiceManager.PlaybackController.First (); } } public Playlist [] GetPlaylists (uint index, uint max_count, string order, bool reverse_order) { var playlist_sources = ServiceManager.SourceManager.FindSources<AbstractPlaylistSource> (); switch (order) { case "Alphabetical": playlist_sources = playlist_sources.OrderBy (p => p.Name); break; case "UserDefined": playlist_sources = playlist_sources.OrderBy (p => p.Order); break; } if (reverse_order) { playlist_sources = playlist_sources.Reverse (); } var playlists = new List<Playlist> (); foreach (var pl in playlist_sources.Skip ((int)index).Take ((int)max_count)) { playlists.Add (BuildPlaylistFromSource (pl)); } return playlists.ToArray (); } #endregion #region Signals private void HandlePropertiesChange (string interface_name) { PropertiesChangedHandler handler = properties_changed; if (handler != null) { lock (changed_properties) { try { handler (interface_name, changed_properties, invalidated_properties.ToArray ()); } catch (Exception e) { Log.Exception (e); } changed_properties.Clear (); invalidated_properties.Clear (); } } } public void HandleSeek () { DBusPlayerSeekedHandler dbus_handler = dbus_seeked; if (dbus_handler != null) { dbus_handler (Position); } } public void HandlePlaylistChange (AbstractPlaylistSource source) { PlaylistChangedHandler playlist_handler = playlist_changed; if (playlist_handler != null) { try { playlist_handler (BuildPlaylistFromSource (source)); } catch (Exception e) { Log.Exception (e); } } } public void AddPropertyChange (params PlayerProperties [] properties) { AddPropertyChange (player_interface_name, properties.Select (p => p.ToString())); } public void AddPropertyChange (params MediaPlayerProperties [] properties) { AddPropertyChange (mediaplayer_interface_name, properties.Select (p => p.ToString())); } public void AddPropertyChange (params PlaylistProperties [] properties) { AddPropertyChange (playlists_interface_name, properties.Select (p => p.ToString())); } private void AddPropertyChange (string interface_name, IEnumerable<string> property_names) { lock (changed_properties) { foreach (string prop_name in property_names) { object current_value = null; current_properties.TryGetValue (prop_name, out current_value); var new_value = Get (interface_name, prop_name); if ((current_value == null) || !(current_value.Equals (new_value))) { changed_properties [prop_name] = new_value; current_properties [prop_name] = new_value; } } if (changed_properties.Count > 0) { HandlePropertiesChange (interface_name); } } } #endregion #region Dbus.Properties private static string [] mediaplayer_properties = { "CanQuit", "CanRaise", "CanSetFullscreen", "Fullscreen", "HasTrackList", "Identity", "DesktopEntry", "SupportedMimeTypes", "SupportedUriSchemes" }; private static string [] player_properties = { "CanControl", "CanGoNext", "CanGoPrevious", "CanPause", "CanPlay", "CanSeek", "LoopStatus", "MaximumRate", "Metadata", "MinimumRate", "PlaybackStatus", "Position", "Rate", "Shuffle", "Volume" }; private static string [] playlist_properties = { "Orderings", "PlaylistCount", "ActivePlaylist" }; public object Get (string interface_name, string propname) { if (interface_name == mediaplayer_interface_name) { switch (propname) { case "CanQuit": return CanQuit; case "CanRaise": return CanRaise; case "Fullscreen": return Fullscreen; case "CanSetFullscreen": return CanSetFullscreen; case "HasTrackList": return HasTrackList; case "Identity": return Identity; case "DesktopEntry": return DesktopEntry; case "SupportedMimeTypes": return SupportedMimeTypes; case "SupportedUriSchemes": return SupportedUriSchemes; default: return null; } } else if (interface_name == player_interface_name) { switch (propname) { case "CanControl": return CanControl; case "CanGoNext": return CanGoNext; case "CanGoPrevious": return CanGoPrevious; case "CanPause": return CanPause; case "CanPlay": return CanPlay; case "CanSeek": return CanSeek; case "MinimumRate": return MinimumRate; case "MaximumRate": return MaximumRate; case "Rate": return Rate; case "Shuffle": return Shuffle; case "LoopStatus": return LoopStatus; case "PlaybackStatus": return PlaybackStatus; case "Position": return Position; case "Metadata": return Metadata; case "Volume": return Volume; default: return null; } } else if (interface_name == playlists_interface_name) { switch (propname) { case "Orderings": return Orderings; case "PlaylistCount": return PlaylistCount; case "ActivePlaylist": return ActivePlaylist; default: return null; } } else { return null; } } public void Set (string interface_name, string propname, object value) { if (interface_name == player_interface_name) { switch (propname) { case "LoopStatus": string s = value as string; if (!String.IsNullOrEmpty (s)) { LoopStatus = s; } break; case "Shuffle": if (value is bool) { Shuffle = (bool)value; } break; case "Volume": if (value is double) { Volume = (double)value; } break; } } else if (interface_name == mediaplayer_interface_name) { switch (propname) { case "Fullscreen": if (value is bool) { Fullscreen = (bool)value; } break; } } } public IDictionary<string, object> GetAll (string interface_name) { var props = new Dictionary<string, object> (); if (interface_name == mediaplayer_interface_name) { foreach (string prop in mediaplayer_properties) { props.Add (prop, Get (interface_name, prop)); } } else if (interface_name == player_interface_name) { foreach (string prop in player_properties) { props.Add (prop, Get (interface_name, prop)); } } else if (interface_name == playlists_interface_name) { foreach (string prop in playlist_properties) { props.Add (prop, Get (interface_name, prop)); } } return props; } } #endregion // Those are all the properties from the Player interface that can trigger the PropertiesChanged signal // The names must match exactly the names of the properties public enum PlayerProperties { CanControl, CanGoNext, CanGoPrevious, CanPause, CanPlay, CanSeek, MinimumRate, MaximumRate, Rate, Shuffle, LoopStatus, PlaybackStatus, Metadata, Volume } // Those are all the properties from the MediaPlayer interface that can trigger the PropertiesChanged signal // The names must match exactly the names of the properties public enum MediaPlayerProperties { Fullscreen } // Those are all the properties from the Playlist interface that can trigger the PropertiesChanged signal // The names must match exactly the names of the properties public enum PlaylistProperties { PlaylistCount, ActivePlaylist } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; // // Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it. // namespace System { /// <summary> /// Helper so we can call some tuple methods recursively without knowing the underlying types. /// </summary> internal interface ITupleInternal : ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); } public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); } public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); } public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8)); } // From System.Web.Util.HashCodeCombiner internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); } internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1> objTuple = other as Tuple<T1>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1> objTuple = other as Tuple<T1>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } return comparer.Compare(m_Item1, objTuple.m_Item1); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 1; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return Item1; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2> objTuple = other as Tuple<T1, T2>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2> objTuple = other as Tuple<T1, T2>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; return comparer.Compare(m_Item2, objTuple.m_Item2); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 2; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public Tuple(T1 item1, T2 item2, T3 item3) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; return comparer.Compare(m_Item3, objTuple.m_Item3); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 3; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; return comparer.Compare(m_Item4, objTuple.m_Item4); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 4; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; return comparer.Compare(m_Item5, objTuple.m_Item5); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 5; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) private readonly T6 m_Item6; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public T6 Item6 { get { return m_Item6; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; return comparer.Compare(m_Item6, objTuple.m_Item6); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 6; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) private readonly T6 m_Item6; // Do not rename (binary serialization) private readonly T7 m_Item7; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public T6 Item6 { get { return m_Item6; } } public T7 Item7 { get { return m_Item7; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; c = comparer.Compare(m_Item6, objTuple.m_Item6); if (c != 0) return c; return comparer.Compare(m_Item7, objTuple.m_Item7); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(")"); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 7; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; case 6: return Item7; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) private readonly T6 m_Item6; // Do not rename (binary serialization) private readonly T7 m_Item7; // Do not rename (binary serialization) private readonly TRest m_Rest; // Do not rename (binary serialization) public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public T6 Item6 { get { return m_Item6; } } public T7 Item7 { get { return m_Item7; } } public TRest Rest { get { return m_Rest; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is ITupleInternal)) { throw new ArgumentException(SR.ArgumentException_TupleLastArgumentNotATuple); } m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; m_Rest = rest; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other"); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; c = comparer.Compare(m_Item6, objTuple.m_Item6); if (c != 0) return c; c = comparer.Compare(m_Item7, objTuple.m_Item7); if (c != 0) return c; return comparer.Compare(m_Rest, objTuple.m_Rest); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple ITupleInternal t = (ITupleInternal)m_Rest; if (t.Length >= 8) { return t.GetHashCode(comparer); } // In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest int k = 8 - t.Length; switch (k) { case 1: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 2: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 3: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 4: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 5: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 6: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 7: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); } Debug.Fail("Missed all cases for computing Tuple hash code"); return -1; } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(", "); return ((ITupleInternal)m_Rest).ToString(sb); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length { get { return 7 + ((ITupleInternal)Rest).Length; } } /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; case 6: return Item7; } return ((ITupleInternal)Rest)[index - 7]; } } } }
// -------------------------------------------------- // 3DS Theme Editor - ColorPickerSharedData.cs // -------------------------------------------------- using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Input; using System.Windows.Media; using Xceed.Wpf.Toolkit; namespace ThemeEditor.WPF.Templating { public class ColorPickerSharedData : DependencyObject, INotifyPropertyChanged { private const double EPSILON = 0.01; private const string FORMAT34 = @"(?<Format>\w{1,})\((?<Data>(?:(?:[\d.]*?,)){2,3}([\d.]*?))\)"; private const string HEX6 = @"(?<Format>#)(?<Data>[A-Fa-f0-9]{6})"; private const string HEX8 = @"(?<Format>#)(?<Data>[A-Fa-f0-9]{8})"; private static readonly Regex ColorRegex = new Regex($"{HEX8}|{HEX6}|{FORMAT34}", RegexOptions.Compiled); private ColorMode _colorMode; private ObservableCollection<ColorItem> _recentColors; public ColorMode ColorMode { get { return _colorMode; } set { if (value == _colorMode) return; _colorMode = value; OnPropertyChanged(nameof(ColorMode)); } } public static ICommand CopyCommand { get; } public static ColorPickerSharedData Instance { get; } = new ColorPickerSharedData(); public static ICommand PasteCommand { get; } public ObservableCollection<ColorItem> RecentColors { get { return _recentColors; } set { if (value == _recentColors) return; _recentColors = value; OnPropertyChanged(nameof(RecentColors)); } } static ColorPickerSharedData() { CopyCommand = new RelayCommand<ColorPicker>(ColorPickerCopy_Execute); PasteCommand = new RelayCommand<ColorPicker>(ColorPickerPaste_Execute, ColorPickerPaste_CanExecute); } private ColorPickerSharedData() {} public static bool CanParseColor(string colorString) { string[] validDataTypes = {"rgb", "rgba", "hsl", "hsla", "hsv", "hsva", "#"}; var ismatch = ColorRegex.IsMatch(colorString); if (!ismatch) return false; var m = ColorRegex.Match(colorString); var dataType = m.Groups["Format"].Value; return validDataTypes.Contains(dataType); } public static Color ColorFromHsl(double hue, double sat, double bright, double alpha = 1.0) { //bright = Math.Min(1,bright); hue %= 360.0f; sat = sat.Clamp(0, 1); bright = bright.Clamp(0, 1); var chroma = (1 - Math.Abs((2 * bright) - 1)) * sat; var hueIndex = hue / 60.0 % 6.0; var factor = chroma * (1 - Math.Abs((hueIndex % 2) - 1)); double red = 0, green = 0, blue = 0; switch ((int) Math.Floor(hueIndex)) { case 0: red = chroma; green = factor; break; case 1: red = factor; green = chroma; break; case 2: green = chroma; blue = factor; break; case 3: green = factor; blue = chroma; break; case 4: red = factor; blue = chroma; break; case 5: red = chroma; blue = factor; break; } var m = bright - (chroma / 2.0); var alphaByte = Convert.ToByte(alpha * 255); var redByte = Convert.ToByte((red + m) * 255); var greenByte = Convert.ToByte((green + m) * 255); var blueByte = Convert.ToByte((blue + m) * 255); return Color.FromArgb(alphaByte, redByte, greenByte, blueByte); } public static Color ColorFromHsv(double hue, double sat, double value, double alpha = 1.0) { var chroma = value * sat; var hueIndex = hue / 60.0 % 6.0; var factor = chroma * (1 - Math.Abs((hueIndex % 2) - 1)); double red = 0, green = 0, blue = 0; switch ((int) Math.Floor(hueIndex)) { case 0: red = chroma; green = factor; break; case 1: red = factor; green = chroma; break; case 2: green = chroma; blue = factor; break; case 3: green = factor; blue = chroma; break; case 4: red = factor; blue = chroma; break; case 5: red = chroma; blue = factor; break; } var m = value - chroma; var alphaByte = Convert.ToByte(alpha * 255); var redByte = Convert.ToByte((red + m) * 255); var greenByte = Convert.ToByte((green + m) * 255); var blueByte = Convert.ToByte((blue + m) * 255); return Color.FromArgb(alphaByte, redByte, greenByte, blueByte); } public static void ColorToHsl(Color col, out double h, out double s, out double l) { var r = col.R / 255.0; var g = col.G / 255.0; var b = col.B / 255.0; var max = Math.Max(r, Math.Max(g, b)); var min = Math.Min(r, Math.Min(g, b)); l = (max + min) / 2.0f; if (Math.Abs(max - min) < EPSILON) { h = 0; s = 0; } else { var delta = (max - min); if (Math.Abs(max - r) < EPSILON) { if (g >= b) { h = 60 * (g - b) / delta; } else { h = 60 * (g - b) / delta + 360; } } else if (Math.Abs(max - g) < EPSILON) { h = 60 * (b - r) / delta + 120; } else { h = 60 * (r - g) / delta + 240; } s = delta / (1 - Math.Abs(2 * l - 1)); // Weird Colors at l < 0.5 //s = delta / (max + min); //s = delta / max; } } public static void ColorToHsv(Color col, out double h, out double s, out double v) { var r = col.R / 255.0; var g = col.G / 255.0; var b = col.B / 255.0; var max = Math.Max(r, Math.Max(g, b)); var min = Math.Min(r, Math.Min(g, b)); v = max; if (Math.Abs(max - min) < EPSILON) { h = 0; s = 0; } else { if (Math.Abs(max - r) < EPSILON) { if (g >= b) { h = 60 * (g - b) / (max - min); } else { h = 60 * (g - b) / (max - min) + 360; } } else if (Math.Abs(max - g) < EPSILON) { h = 60 * (b - r) / (max - min) + 120; } else { h = 60 * (r - g) / (max - min) + 240; } s = (max - min) / max; } } public static bool TryParseColor(string colorString, out Color color) { try { var errorColor = Color.FromRgb(0, 0, 0); if (!CanParseColor(colorString)) { color = errorColor; return false; } var match = ColorRegex.Match(colorString); var format = match.Groups["Format"].Value; var data = match.Groups["Data"].Value; byte[] dataBytes; double[] doubleValues; switch (format.ToLower()) { case "#": { dataBytes = Enumerable.Range(0, data.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(data.Substring(x, 2), 16)) .ToArray(); if (dataBytes.Length == 4) errorColor = Color.FromArgb(dataBytes[0], dataBytes[1], dataBytes[2], dataBytes[3]); if (dataBytes.Length == 3) errorColor = Color.FromRgb(dataBytes[0], dataBytes[1], dataBytes[2]); break; } case "rgb": case "rgba": { dataBytes = data.Split(',') .Select(s => Convert.ToByte(s)) .ToArray(); if (dataBytes.Length == 3) errorColor = Color.FromRgb(dataBytes[0], dataBytes[1], dataBytes[2]); if (dataBytes.Length == 4) errorColor = Color.FromArgb(dataBytes[3], dataBytes[0], dataBytes[1], dataBytes[2]); break; } case "hsv": case "hsva": { doubleValues = data.Split(',') .Select(s => Convert.ToDouble(s, CultureInfo.InvariantCulture)) .ToArray(); if (doubleValues.Length == 3) errorColor = ColorFromHsv(doubleValues[0], doubleValues[1], doubleValues[2]); if (doubleValues.Length == 4) errorColor = ColorFromHsv (doubleValues[0], doubleValues[1], doubleValues[2], doubleValues[3]); break; } case "hsl": case "hsla": { doubleValues = data.Split(',') .Select(s => Convert.ToDouble(s, CultureInfo.InvariantCulture)) .ToArray(); if (doubleValues.Length == 3) errorColor = ColorFromHsl(doubleValues[0], doubleValues[1], doubleValues[2]); if (doubleValues.Length == 4) errorColor = ColorFromHsl (doubleValues[0], doubleValues[1], doubleValues[2], doubleValues[3]); break; } } color = errorColor; return true; } catch { color = Color.FromRgb(0, 0, 0); return false; } } private static void ColorPickerCopy_Execute(ColorPicker colorPicker) { try { if (!colorPicker.SelectedColor.HasValue) return; var c = colorPicker.SelectedColor.Value; var str = c.ToString(); Clipboard.SetText(str); } catch (COMException) { // Ignore } } private static bool ColorPickerPaste_CanExecute(ColorPicker obj) { try { var strColor = Clipboard.GetText(); return CanParseColor(strColor); } catch (COMException) { return false; } } private static void ColorPickerPaste_Execute(ColorPicker colorPicker) { try { var strColor = Clipboard.GetText(); Color parsedColor; if (TryParseColor(strColor, out parsedColor)) colorPicker.SelectedColor = parsedColor; } catch (COMException) { // Ignore } } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Linq; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// ProductTypeUpdatedByRootList (read only list).<br/> /// This is a generated <see cref="ProductTypeUpdatedByRootList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// Updated by ProductTypeEdit /// </remarks> [Serializable] #if WINFORMS public partial class ProductTypeUpdatedByRootList : ReadOnlyBindingListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #else public partial class ProductTypeUpdatedByRootList : ReadOnlyListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="ProductTypeUpdatedByRootInfo"/> item is in the collection. /// </summary> /// <param name="productTypeId">The ProductTypeId of the item to search for.</param> /// <returns><c>true</c> if the ProductTypeUpdatedByRootInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int productTypeId) { foreach (var productTypeUpdatedByRootInfo in this) { if (productTypeUpdatedByRootInfo.ProductTypeId == productTypeId) { return true; } } return false; } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="ProductTypeUpdatedByRootList"/> collection.</returns> public static ProductTypeUpdatedByRootList GetProductTypeUpdatedByRootList() { return DataPortal.Fetch<ProductTypeUpdatedByRootList>(); } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetProductTypeUpdatedByRootList(EventHandler<DataPortalResult<ProductTypeUpdatedByRootList>> callback) { DataPortal.BeginFetch<ProductTypeUpdatedByRootList>(callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeUpdatedByRootList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeUpdatedByRootList() { // Use factory methods and do not use direct creation. ProductTypeEditSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="ProductTypeEdit"/> to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (ProductTypeEdit)e.NewObject; if (((ProductTypeEdit)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(ProductTypeUpdatedByRootInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((ProductTypeEdit)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductTypeUpdatedByRootList"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.GetProductTypeUpdatedByRootList", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="ProductTypeUpdatedByRootList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(DataPortal.FetchChild<ProductTypeUpdatedByRootInfo>(dr)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <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); #endregion #region ProductTypeEditSaved nested class // TODO: edit "ProductTypeUpdatedByRootList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeEditSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="ProductTypeEdit"/> /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> private static class ProductTypeEditSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a ProductTypeUpdatedByRootList instance to handle Saved events. /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="obj">The ProductTypeUpdatedByRootList instance.</param> public static void Register(ProductTypeUpdatedByRootList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (ProductTypeUpdatedByRootList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) ProductTypeEdit.ProductTypeEditSaved += ProductTypeEditSavedHandler; } /// <summary> /// Handles Saved events of <see cref="ProductTypeEdit"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((ProductTypeUpdatedByRootList) reference.Target).ProductTypeEditSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered ProductTypeUpdatedByRootList instances. /// </summary> public static void Unregister() { ProductTypeEdit.ProductTypeEditSaved -= ProductTypeEditSavedHandler; _references = null; } } #endregion } }
// <copyright file="ComplexTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 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 NUnit.Framework; namespace MathNet.Numerics.UnitTests.ComplexTests { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Complex extension methods tests. /// </summary> [TestFixture] public class ComplexExtensionTest { /// <summary> /// Can compute exponential. /// </summary> /// <param name="real">Real part.</param> /// <param name="imag">Imaginary part.</param> /// <param name="expectedReal">Expected real part.</param> /// <param name="expectedImag">Expected imaginary part.</param> [TestCase(0.0, 0.0, 1.0, 0.0)] [TestCase(0.0, 1.0, 0.54030230586813977, 0.8414709848078965)] [TestCase(-1.0, 1.0, 0.19876611034641295, 0.30955987565311222)] [TestCase(-111.1, 111.1, -2.3259065941590448e-49, -5.1181940185795617e-49)] public void CanComputeExponential(double real, double imag, double expectedReal, double expectedImag) { var value = new Complex(real, imag); var expected = new Complex(expectedReal, expectedImag); AssertHelpers.AlmostEqualRelative(expected, value.Exp(), 15); } /// <summary> /// Can compute natural logarithm. /// </summary> /// <param name="real">Real part.</param> /// <param name="imag">Imaginary part.</param> /// <param name="expectedReal">Expected real part.</param> /// <param name="expectedImag">Expected imaginary part.</param> [TestCase(0.0, 0.0, double.NegativeInfinity, 0.0)] [TestCase(0.0, 1.0, 0.0, 1.5707963267948966)] [TestCase(-1.0, 1.0, 0.34657359027997264, 2.3561944901923448)] [TestCase(-111.1, 111.1, 5.0570042869255571, 2.3561944901923448)] [TestCase(111.1, -111.1, 5.0570042869255571, -0.78539816339744828)] public void CanComputeNaturalLogarithm(double real, double imag, double expectedReal, double expectedImag) { var value = new Complex(real, imag); var expected = new Complex(expectedReal, expectedImag); AssertHelpers.AlmostEqualRelative(expected, value.Ln(), 14); } /// <summary> /// Can compute power. /// </summary> [Test] public void CanComputePower() { var a = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); var b = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(9.99998047207974718744e-1, -1.76553541154378695012e-6), a.Power(b), 14); a = new Complex(0.0, 1.19209289550780998537e-7); b = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(1.00000018725172576491, 1.90048076369011843105e-6), a.Power(b), 14); a = new Complex(0.0, -1.19209289550780998537e-7); b = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(-2.56488189382693049636e-1, -2.17823120666116144959), a.Power(b), 14); a = new Complex(0.0, 0.5); b = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(2.06287223508090495171, 7.45007062179724087859e-1), a.Power(b), 14); a = new Complex(0.0, -0.5); b = new Complex(0.0, 1.0); AssertHelpers.AlmostEqualRelative(new Complex(3.70040633557002510874, -3.07370876701949232239), a.Power(b), 14); a = new Complex(0.0, 2.0); b = new Complex(0.0, -2.0); AssertHelpers.AlmostEqualRelative(new Complex(4.24532146387429353891, -2.27479427903521192648e1), a.Power(b), 14); a = new Complex(0.0, -8.388608e6); b = new Complex(1.19209289550780998537e-7, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(1.00000190048219620166, -1.87253870018168043834e-7), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(0.0, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(1.0, 0.0), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(1.0, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(0.0, 0.0), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(-1.0, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(double.PositiveInfinity, 0.0), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(-1.0, 1.0); AssertHelpers.AlmostEqualRelative(new Complex(double.PositiveInfinity, double.PositiveInfinity), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(0.0, 1.0); Assert.That(a.Power(b).IsNaN()); } /// <summary> /// Can compute root. /// </summary> [Test] public void CanComputeRoot() { var a = new Complex(0.0, -1.19209289550780998537e-7); var b = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.038550761943650161, 0.019526430428319544), a.Root(b), 13); a = new Complex(0.0, 0.5); b = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.007927894711475968, -0.042480480425152213), a.Root(b), 13); a = new Complex(0.0, -0.5); b = new Complex(0.0, 1.0); AssertHelpers.AlmostEqualRelative(new Complex(0.15990905692806806, 0.13282699942462053), a.Root(b), 13); a = new Complex(0.0, 2.0); b = new Complex(0.0, -2.0); AssertHelpers.AlmostEqualRelative(new Complex(0.42882900629436788, 0.15487175246424678), a.Root(b), 13); //a = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); //b = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); //AssertHelpers.AlmostEqual(new Complex(0.0, 0.0), a.Root(b), 15); a = new Complex(0.0, -8.388608e6); b = new Complex(1.19209289550780998537e-7, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(double.PositiveInfinity, double.NegativeInfinity), a.Root(b), 14); } /// <summary> /// Can compute square. /// </summary> [Test] public void CanComputeSquare() { var complex = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(0, 2.8421709430403888e-14), complex.Square(), 15); complex = new Complex(0.0, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(-1.4210854715201944e-14, 0.0), complex.Square(), 15); complex = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(-1.4210854715201944e-14, 0.0), complex.Square(), 15); complex = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(-0.25, 0.0), complex.Square(), 15); complex = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(-0.25, 0.0), complex.Square(), 15); complex = new Complex(0.0, -8.388608e6); AssertHelpers.AlmostEqualRelative(new Complex(-70368744177664.0, 0.0), complex.Square(), 15); } /// <summary> /// Can compute square root. /// </summary> [Test] public void CanComputeSquareRoot() { var complex = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(0.00037933934912842666, 0.00015712750315077684), complex.SquareRoot(), 14); complex = new Complex(0.0, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(0.00024414062499999973, 0.00024414062499999976), complex.SquareRoot(), 14); complex = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(0.00024414062499999973, -0.00024414062499999976), complex.SquareRoot(), 14); complex = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.5, 0.5), complex.SquareRoot(), 14); complex = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.5, -0.5), complex.SquareRoot(), 14); complex = new Complex(0.0, -8.388608e6); AssertHelpers.AlmostEqualRelative(new Complex(2048.0, -2048.0), complex.SquareRoot(), 14); complex = new Complex(8.388608e6, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(2896.3093757400989, 2.0579515874459933e-11), complex.SquareRoot(), 14); complex = new Complex(0.0, 0.0); AssertHelpers.AlmostEqualRelative(Complex.Zero, complex.SquareRoot(), 14); } /// <summary> /// Can determine if imaginary is unit. /// </summary> [Test] public void CanDetermineIfImaginaryUnit() { var complex = new Complex(0, 1); Assert.IsTrue(complex.IsImaginaryOne(), "Imaginary unit"); } /// <summary> /// Can determine if a complex is infinity. /// </summary> [Test] public void CanDetermineIfInfinity() { var complex = new Complex(double.PositiveInfinity, 1); Assert.IsTrue(complex.IsInfinity(), "Real part is infinity."); complex = new Complex(1, double.NegativeInfinity); Assert.IsTrue(complex.IsInfinity(), "Imaginary part is infinity."); complex = new Complex(double.NegativeInfinity, double.PositiveInfinity); Assert.IsTrue(complex.IsInfinity(), "Both parts are infinity."); } /// <summary> /// Can determine if a complex is not a number. /// </summary> [Test] public void CanDetermineIfNaN() { var complex = new Complex(double.NaN, 1); Assert.IsTrue(complex.IsNaN(), "Real part is NaN."); complex = new Complex(1, double.NaN); Assert.IsTrue(complex.IsNaN(), "Imaginary part is NaN."); complex = new Complex(double.NaN, double.NaN); Assert.IsTrue(complex.IsNaN(), "Both parts are NaN."); } /// <summary> /// Can determine Complex number with a value of one. /// </summary> [Test] public void CanDetermineIfOneValueComplexNumber() { var complex = new Complex(1, 0); Assert.IsTrue(complex.IsOne(), "Complex number with a value of one."); } /// <summary> /// Can determine if a complex is a real non-negative number. /// </summary> [Test] public void CanDetermineIfRealNonNegativeNumber() { var complex = new Complex(1, 0); Assert.IsTrue(complex.IsReal(), "Is a real non-negative number."); } /// <summary> /// Can determine if a complex is a real number. /// </summary> [Test] public void CanDetermineIfRealNumber() { var complex = new Complex(-1, 0); Assert.IsTrue(complex.IsReal(), "Is a real number."); } /// <summary> /// Can determine if a complex is a zero number. /// </summary> [Test] public void CanDetermineIfZeroValueComplexNumber() { var complex = new Complex(0, 0); Assert.IsTrue(complex.IsZero(), "Zero complex number."); } } }
using System; using System.Diagnostics; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues; /// <summary> /// A range filter built on top of a cached multi-valued term field (in <see cref="IFieldCache"/>). /// /// <para>Like <see cref="FieldCacheRangeFilter"/>, this is just a specialized range query versus /// using a <see cref="TermRangeQuery"/> with <see cref="DocTermOrdsRewriteMethod"/>: it will only do /// two ordinal to term lookups.</para> /// </summary> public abstract class DocTermOrdsRangeFilter : Filter { internal readonly string field; internal readonly BytesRef lowerVal; internal readonly BytesRef upperVal; internal readonly bool includeLower; internal readonly bool includeUpper; private DocTermOrdsRangeFilter(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { this.field = field; this.lowerVal = lowerVal; this.upperVal = upperVal; this.includeLower = includeLower; this.includeUpper = includeUpper; } /// <summary> /// This method is implemented for each data type </summary> public override abstract DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs); /// <summary> /// Creates a BytesRef range filter using <see cref="IFieldCache.GetTermsIndex(Index.AtomicReader, string, float)"/>. This works with all /// fields containing zero or one term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> public static DocTermOrdsRangeFilter NewBytesRefRange(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { return new DocTermOrdsRangeFilterAnonymousInnerClassHelper(field, lowerVal, upperVal, includeLower, includeUpper); } private class DocTermOrdsRangeFilterAnonymousInnerClassHelper : DocTermOrdsRangeFilter { public DocTermOrdsRangeFilterAnonymousInnerClassHelper(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) : base(field, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { SortedSetDocValues docTermOrds = FieldCache.DEFAULT.GetDocTermOrds(context.AtomicReader, field); long lowerPoint = lowerVal == null ? -1 : docTermOrds.LookupTerm(lowerVal); long upperPoint = upperVal == null ? -1 : docTermOrds.LookupTerm(upperVal); long inclusiveLowerPoint, inclusiveUpperPoint; // Hints: // * binarySearchLookup returns -1, if value was null. // * the value is <0 if no exact hit was found, the returned value // is (-(insertion point) - 1) if (lowerPoint == -1 && lowerVal == null) { inclusiveLowerPoint = 0; } else if (includeLower && lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint; } else if (lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint + 1; } else { inclusiveLowerPoint = Math.Max(0, -lowerPoint - 1); } if (upperPoint == -1 && upperVal == null) { inclusiveUpperPoint = long.MaxValue; } else if (includeUpper && upperPoint >= 0) { inclusiveUpperPoint = upperPoint; } else if (upperPoint >= 0) { inclusiveUpperPoint = upperPoint - 1; } else { inclusiveUpperPoint = -upperPoint - 2; } if (inclusiveUpperPoint < 0 || inclusiveLowerPoint > inclusiveUpperPoint) { return null; } Debug.Assert(inclusiveLowerPoint >= 0 && inclusiveUpperPoint >= 0); return new FieldCacheDocIdSetAnonymousInnerClassHelper(this, context.AtomicReader.MaxDoc, acceptDocs, docTermOrds, inclusiveLowerPoint, inclusiveUpperPoint); } private class FieldCacheDocIdSetAnonymousInnerClassHelper : FieldCacheDocIdSet { private readonly DocTermOrdsRangeFilterAnonymousInnerClassHelper outerInstance; private readonly SortedSetDocValues docTermOrds; private readonly long inclusiveLowerPoint; private readonly long inclusiveUpperPoint; public FieldCacheDocIdSetAnonymousInnerClassHelper(DocTermOrdsRangeFilterAnonymousInnerClassHelper outerInstance, int maxDoc, IBits acceptDocs, SortedSetDocValues docTermOrds, long inclusiveLowerPoint, long inclusiveUpperPoint) : base(maxDoc, acceptDocs) { this.outerInstance = outerInstance; this.docTermOrds = docTermOrds; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override sealed bool MatchDoc(int doc) { docTermOrds.SetDocument(doc); long ord; while ((ord = docTermOrds.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { if (ord > inclusiveUpperPoint) { return false; } else if (ord >= inclusiveLowerPoint) { return true; } } return false; } } } public override sealed string ToString() { StringBuilder sb = (new StringBuilder(field)).Append(":"); return sb.Append(includeLower ? '[' : '{') .Append((lowerVal == null) ? "*" : lowerVal.ToString()) .Append(" TO ") .Append((upperVal == null) ? "*" : upperVal.ToString()) .Append(includeUpper ? ']' : '}') .ToString(); } public override sealed bool Equals(object o) { if (this == o) { return true; } if (!(o is DocTermOrdsRangeFilter)) { return false; } DocTermOrdsRangeFilter other = (DocTermOrdsRangeFilter)o; if (!this.field.Equals(other.field, StringComparison.Ordinal) || this.includeLower != other.includeLower || this.includeUpper != other.includeUpper) { return false; } if (this.lowerVal != null ? !this.lowerVal.Equals(other.lowerVal) : other.lowerVal != null) { return false; } if (this.upperVal != null ? !this.upperVal.Equals(other.upperVal) : other.upperVal != null) { return false; } return true; } public override sealed int GetHashCode() { int h = field.GetHashCode(); h ^= (lowerVal != null) ? lowerVal.GetHashCode() : 550356204; h = (h << 1) | ((int)((uint)h >> 31)); // rotate to distinguish lower from upper h ^= (upperVal != null) ? upperVal.GetHashCode() : -1674416163; h ^= (includeLower ? 1549299360 : -365038026) ^ (includeUpper ? 1721088258 : 1948649653); return h; } /// <summary> /// Returns the field name for this filter </summary> public virtual string Field => field; /// <summary> /// Returns <c>true</c> if the lower endpoint is inclusive </summary> public virtual bool IncludesLower => includeLower; /// <summary> /// Returns <c>true</c> if the upper endpoint is inclusive </summary> public virtual bool IncludesUpper => includeUpper; /// <summary> /// Returns the lower value of this range filter </summary> public virtual BytesRef LowerVal => lowerVal; /// <summary> /// Returns the upper value of this range filter </summary> public virtual BytesRef UpperVal => upperVal; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus.Fluent { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// TopicsOperations operations. /// </summary> public partial interface ITopicsOperations { /// <summary> /// Gets all the topics in a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639388.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<TopicInner>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a topic in the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639409.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a topic resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TopicInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, TopicInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a topic from the specified namespace and resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639404.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a description for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639399.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TopicInner>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets authorization rules for a topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleInner>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates an authorizatio rule for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720678.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='rights'> /// The rights associated with the rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleInner>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, IList<AccessRights?> rights, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the specified authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720676.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleInner>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a topic authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720677.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeysInner>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates primary or secondary connection strings for the topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720679.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='policykey'> /// Key that needs to be regenerated. Possible values include: /// 'PrimaryKey', 'SecondaryKey' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeysInner>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Policykey? policykey = default(Policykey?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the topics in a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639388.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<TopicInner>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets authorization rules for a topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleInner>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma warning disable 1634 // Stops compiler from warning about unknown warnings (for Presharp) using System.IO; using System.Text; using System.Xml; using System.Security; namespace System.Runtime.Serialization.Json { // This wrapper does not support seek. // Supports: UTF-8, Unicode, BigEndianUnicode // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers. internal class JsonEncodingStreamWrapper : Stream { private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false); private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false); private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false); private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true); private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true); private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true); private const int BufferLength = 128; private byte[] _byteBuffer = new byte[1]; private int _byteCount; private int _byteOffset; private byte[] _bytes; private char[] _chars; private Decoder _dec; private Encoder _enc; private Encoding _encoding; private SupportedEncoding _encodingCode; private bool _isReading; private Stream _stream; public JsonEncodingStreamWrapper(Stream stream, Encoding encoding, bool isReader) { _isReading = isReader; if (isReader) { InitForReading(stream, encoding); } else { if (encoding == null) { throw new ArgumentNullException("encoding"); } InitForWriting(stream, encoding); } } private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } // This stream wrapper does not support duplex public override bool CanRead { get { if (!_isReading) { return false; } return _stream.CanRead; } } // The encoding conversion and buffering breaks seeking. public override bool CanSeek { get { return false; } } // Delegate properties public override bool CanTimeout { get { return _stream.CanTimeout; } } // This stream wrapper does not support duplex public override bool CanWrite { get { if (_isReading) { return false; } return _stream.CanWrite; } } public override long Length { get { return _stream.Length; } } // The encoding conversion and buffering breaks seeking. public override long Position { get { #pragma warning suppress 56503 // The contract for non seekable stream is to throw exception throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } public static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { try { SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); SupportedEncoding dataEnc; if (count < 2) { dataEnc = SupportedEncoding.UTF8; } else { dataEnc = ReadEncoding(buffer[offset], buffer[offset + 1]); } if ((expectedEnc != SupportedEncoding.None) && (expectedEnc != dataEnc)) { ThrowExpectedEncodingMismatch(expectedEnc, dataEnc); } // Fastpath: UTF-8 if (dataEnc == SupportedEncoding.UTF8) { return new ArraySegment<byte>(buffer, offset, count); } // Convert to UTF-8 return new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(dataEnc).GetChars(buffer, offset, count))); } catch (DecoderFallbackException e) { throw new XmlException(SR.JsonInvalidBytes, e); } } protected override void Dispose(bool disposing) { Flush(); _stream.Dispose(); base.Dispose(disposing); } public override void Flush() { _stream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { try { if (_byteCount == 0) { if (_encodingCode == SupportedEncoding.UTF8) { return _stream.Read(buffer, offset, count); } // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); // Check for end of stream if (_byteCount == 0) { return 0; } // Fix up incomplete chars CleanupCharBreak(); // Change encoding int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) { count = _byteCount; } Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; } catch (DecoderFallbackException ex) { throw new XmlException(SR.JsonInvalidBytes, ex); } } public override int ReadByte() { if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8) { return _stream.ReadByte(); } if (Read(_byteBuffer, 0, 1) == 0) { return -1; } return _byteBuffer[0]; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } // Delegate methods public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { // Optimize UTF-8 case if (_encodingCode == SupportedEncoding.UTF8) { _stream.Write(buffer, offset, count); return; } while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false); _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; } } public override void WriteByte(byte b) { if (_encodingCode == SupportedEncoding.UTF8) { _stream.WriteByte(b); return; } _byteBuffer[0] = b; Write(_byteBuffer, 0, 1); } private static Encoding GetEncoding(SupportedEncoding e) { switch (e) { case SupportedEncoding.UTF8: return s_validatingUTF8; case SupportedEncoding.UTF16LE: return s_validatingUTF16; case SupportedEncoding.UTF16BE: return s_validatingBEUTF16; default: throw new XmlException(SR.JsonEncodingNotSupported); } } private static string GetEncodingName(SupportedEncoding enc) { switch (enc) { case SupportedEncoding.UTF8: return "utf-8"; case SupportedEncoding.UTF16LE: return "utf-16LE"; case SupportedEncoding.UTF16BE: return "utf-16BE"; default: throw new XmlException(SR.JsonEncodingNotSupported); } } private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) { return SupportedEncoding.None; } if (encoding.WebName == s_validatingUTF8.WebName) { return SupportedEncoding.UTF8; } else if (encoding.WebName == s_validatingUTF16.WebName) { return SupportedEncoding.UTF16LE; } else if (encoding.WebName == s_validatingBEUTF16.WebName) { return SupportedEncoding.UTF16BE; } else { throw new XmlException(SR.JsonEncodingNotSupported); } } private static SupportedEncoding ReadEncoding(byte b1, byte b2) { if (b1 == 0x00 && b2 != 0x00) { return SupportedEncoding.UTF16BE; } else if (b1 != 0x00 && b2 == 0x00) { // 857 It's possible to misdetect UTF-32LE as UTF-16LE, but that's OK. return SupportedEncoding.UTF16LE; } else if (b1 == 0x00 && b2 == 0x00) { // UTF-32BE not supported throw new XmlException(SR.JsonInvalidBytes); } else { return SupportedEncoding.UTF8; } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw new XmlException(SR.Format(SR.JsonExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))); } private void CleanupCharBreak() { int max = _byteOffset + _byteCount; // Read on 2 byte boundaries if ((_byteCount % 2) != 0) { int b = _stream.ReadByte(); if (b < 0) { throw new XmlException(SR.JsonUnexpectedEndOfFile); } _bytes[max++] = (byte)b; _byteCount++; } // Don't cut off a surrogate character int w; if (_encodingCode == SupportedEncoding.UTF16LE) { w = _bytes[max - 2] + (_bytes[max - 1] << 8); } else { w = _bytes[max - 1] + (_bytes[max - 2] << 8); } if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); if (b2 < 0) { throw new XmlException(SR.JsonUnexpectedEndOfFile); } _bytes[max++] = (byte)b1; _bytes[max++] = (byte)b2; _byteCount += 2; } } private void EnsureBuffers() { EnsureByteBuffer(); if (_chars == null) { _chars = new char[BufferLength]; } } private void EnsureByteBuffer() { if (_bytes != null) { return; } _bytes = new byte[BufferLength * 4]; _byteOffset = 0; _byteCount = 0; } private void FillBuffer(int count) { count -= _byteCount; while (count > 0) { int read = _stream.Read(_bytes, _byteOffset + _byteCount, count); if (read == 0) { break; } _byteCount += read; count -= read; } } private void InitForReading(Stream inputStream, Encoding expectedEncoding) { try { //this.stream = new BufferedStream(inputStream); _stream = inputStream; SupportedEncoding expectedEnc = GetSupportedEncoding(expectedEncoding); SupportedEncoding dataEnc = ReadEncoding(); if ((expectedEnc != SupportedEncoding.None) && (expectedEnc != dataEnc)) { ThrowExpectedEncodingMismatch(expectedEnc, dataEnc); } // Fastpath: UTF-8 (do nothing) if (dataEnc != SupportedEncoding.UTF8) { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); _encodingCode = dataEnc; _encoding = GetEncoding(dataEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); } } catch (DecoderFallbackException ex) { throw new XmlException(SR.JsonInvalidBytes, ex); } } private void InitForWriting(Stream outputStream, Encoding writeEncoding) { _encoding = writeEncoding; //this.stream = new BufferedStream(outputStream); _stream = outputStream; // Set the encoding code _encodingCode = GetSupportedEncoding(writeEncoding); if (_encodingCode != SupportedEncoding.UTF8) { EnsureBuffers(); _dec = s_validatingUTF8.GetDecoder(); _enc = _encoding.GetEncoder(); } } private SupportedEncoding ReadEncoding() { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); EnsureByteBuffer(); SupportedEncoding e; if (b1 == -1) { e = SupportedEncoding.UTF8; _byteCount = 0; } else if (b2 == -1) { e = SupportedEncoding.UTF8; _bytes[0] = (byte)b1; _byteCount = 1; } else { e = ReadEncoding((byte)b1, (byte)b2); _bytes[0] = (byte)b1; _bytes[1] = (byte)b2; _byteCount = 2; } return e; } } }
using System; using System.Collections.Specialized; using System.Collections.Generic; using System.Text; using Mono.Security.X509; using DNXServer.Net; using System.Management.Instrumentation; using System.Diagnostics; using System.Threading; namespace DNXServer.Action { public class BattleAction: BaseAction { public BattleAction() { } public static List <RoomData> ListRoom = new List<RoomData>(); public static int BattleRoomId = 1; public string FindRoom(SessionData so, string roomID) { if(string.IsNullOrEmpty(roomID)) { roomID = Convert.ToString (so.RoomId); } bool isFindRoom = false; int roomIndex = 0; for (roomIndex = 0; roomIndex < ListRoom.Count; roomIndex++) { if (ListRoom[roomIndex].RoomId == Convert.ToInt32(roomID)) { isFindRoom = true; break; } } string response = Convert.ToString (isFindRoom) + "~" + Convert.ToString (roomIndex); return response; } public bool CheckMonster(SessionData so, string monsterQRID) { StringDictionary check; using (Command (@" SELECT user_id,version FROM monster_cards WHERE mons_card_qrid = :mons ")) { AddParameter("mons", monsterQRID); check = ExecuteRow(); } if (check==null || Convert.ToInt32 (check ["user_id"]) != so.UserId || Convert.ToInt32(check ["version"]) <= 1) { return false; } return true; } public bool CheckItem(SessionData so, string item1 , string item2, string item3) { string[] item = new string[3]{item1,item2,item3}; StringDictionary battleItem; bool isValid = true; foreach (string row in item) { if(row != string.Empty) { using (Command (@" SELECT user_id FROM item_cards WHERE item_card_qrid = :item ")) { AddParameter ("item", row); battleItem = ExecuteRow(); } if(battleItem == null || Convert.ToInt32(battleItem["user_id"])!=so.UserId) { isValid = false; break; } } } return isValid; } public string CreateRoom(SessionData so , string monsterQRID) { // user who create room is treated as Room Master, they always join the room if the process is successful bool isCreated = false; for (int roomIndex = 0; roomIndex < ListRoom.Count; roomIndex++) { if (ListRoom [roomIndex].RoomMaster.UserId == so.UserId) { isCreated = true; //return error return (int)CommandResponseEnum.CreateRoomResult + "`" + "-1" + "~" + "Room already been created by this user" + "`"; } } //check monster validity bool isValidMonster = CheckMonster(so,monsterQRID); if (isValidMonster == false) { return (int)CommandResponseEnum.CreateRoomResult + "`" + "-2" + "~" + "Monster is not valid" + "`"; } //create the room if (isCreated == false) { if(so.IsRoomGuest == false && so.RoomId == 0) { RoomData room = new RoomData(so,BattleRoomId); BattleRoomId++; // if (roomPassword != string.Empty) { // room.RoomPassword = roomPassword; // } else { // room.RoomPassword = string.Empty; // } ListRoom.Add (room); // make the player join the room that just created for (int roomIndex = 0; roomIndex < ListRoom.Count; roomIndex++) { if (ListRoom [roomIndex].RoomMaster.UserId == so.UserId) { ListRoom [roomIndex].JoinRoom(so,monsterQRID); return (int)CommandResponseEnum.CreateRoomResult + "`" +"1"+"~"+ "Create room successfull" + "`"; } } } else { return (int)CommandResponseEnum.CreateRoomResult + "`" +"-3"+"~"+ "Create room failed, you already join a room" + "`"; } } return (int)CommandResponseEnum.CreateRoomResult + "`" +"-4"+"~"+ "Create room failed" + "`"; } public string GetRoomList() { //if (ListRoom.Count != 0) { StringBuilder sb = new StringBuilder (); for (int j = 0; j < ListRoom.Count; j++) { // dont show if(ListRoom[j].IsBattle == false && ListRoom[j].RoomGuest == null) { sb.Append (ListRoom [j].RoomId); sb.Append ("~"); sb.Append (ListRoom [j].monsterRM.MonsterTemplate); sb.Append ("~"); sb.Append (ListRoom [j].monsterRM.MonsterTemplateName); sb.Append ("~"); sb.Append (ListRoom [j].monsterRM.Version); sb.Append ("~"); sb.Append (ListRoom [j].monsterRM.Subversion); sb.Append ("~"); sb.Append (ListRoom [j].monsterRM.Win); sb.Append ("~"); sb.Append (ListRoom [j].monsterRM.Lose); sb.Append ("~"); sb.Append (ListRoom [j].RoomMaster.Flee); sb.Append ("`"); } } if(sb.Length >0) { sb.Length--; } return (int)CommandResponseEnum.RoomListResult + "`" + sb.ToString () + "`"; // } else { // return (int)CommandResponseEnum.RoomListResult + "``"; // } } public string JoinRoom(SessionData so, string roomId,string monsterQRID) { // int roomNumber = Convert.ToInt32(roomId); // bool isFindRoom = false; // int roomIndex = 0; // // for (roomIndex = 0; roomIndex < ListRoom.Count; roomIndex++) // { // if (ListRoom[roomIndex].RoomId == roomNumber) // { // isFindRoom = true; // break; // } // } // ambil user picture FB string checkRoom = FindRoom (so, roomId); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); // check monster validity bool isValidMonster = CheckMonster (so, monsterQRID); if (!isValidMonster) { return (int)CommandResponseEnum.JoinRoomResult + "`" + "-1" + "~" + "Monster is not valid" + "`"; } if (isFindRoom) { if (ListRoom[roomIndex].RoomGuest == null || ListRoom[roomIndex].RoomMaster == null) { // if (ListRoom[roomIndex].IsPassworded) // { // if (ListRoom[roomIndex].RoomPassword == roomPassword) // { // if (so.RoomId == 0) { // so.RoomId = ListRoom [roomIndex].RoomId; // if(so.RoomMaster == true) // { // ListRoom[roomIndex].JoinRoom(so,monsterQRID); // return (int)CommandResponseEnum.JoinRoomResult + "`" + "1" +"~"+ "Join Room successfull" + "`"; // } // else // { // ListRoom[roomIndex].JoinRoom(so,monsterQRID); // //string monsRM = ListRoom[roomIndex].JoinRoom(so,monsterQRID); // //return (int)CommandResponseEnum.JoinRoomResult + "`" + "1" +"~"+ "Join Room successfull" + "~" + monsRM + "`"; // } // } // } // else // { // return (int)CommandResponseEnum.JoinRoomResult + "`" + "-3"+ "~" + "Wrong room password" + "`"; // } // } // else // { if (so.RoomId == 0) { so.RoomId = ListRoom [roomIndex].RoomId; if(so.IsRoomMaster == true && so.UserId == ListRoom[roomIndex].RoomMaster.UserId) { ListRoom[roomIndex].JoinRoom(so,monsterQRID); //return (int)CommandResponseEnum.JoinRoomResult + "`" + "1" +"~"+ "Join Room successfull" + "`"; } else if(so.IsRoomMaster == true && so.UserId != ListRoom[roomIndex].RoomMaster.UserId) { return (int)CommandResponseEnum.JoinRoomResult + "`" + "-4" + "You cannot join another room because you already create a room" + "`"; } else { ListRoom[roomIndex].JoinRoom(so,monsterQRID); } } //} } else { return (int)CommandResponseEnum.JoinRoomResult + "`" + "-2" +"~"+ "Room is full" + "`" + "`" + "`"; } } else if(isFindRoom == false) { return (int)CommandResponseEnum.JoinRoomResult + "`" + "-3" +"~"+ "Room not found or room master has left the room" + "`" + "`" + "`"; } return string.Empty; } public string SetPlayerItems(SessionData so, string item1, string item2, string item3) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; bool isValidItem = CheckItem (so, item1, item2, item3); if(isValidItem == false) { return (int)CommandResponseEnum.SetBattleItemResult + "`" + "-1" + "~" + "Item is not valid" + "`"; } if (isFindRoom) { ListRoom [roomIndex].SetBattleItem (so, item1, item2, item3); return string.Empty; //return (int)CommandResponseEnum.SetBattleItemResult + "`" + "1" +"~"+ "Item is set" + "`"; } else{ //return error return (int)CommandResponseEnum.SetBattleItemResult + "`" + "-3" +"~"+ "Room not found" + "`"; } } public string SetPlayerReady(SessionData so) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; if (isFindRoom) { if (so.UserId == ListRoom [roomIndex].RoomMaster.UserId) { //ListRoom [roomIndex].SetPlayerReady (so); return (int)CommandResponseEnum.BattleReadyResult + "`" + "-2" +"~"+ "You are the room master" + "`"; } else if (so.UserId == ListRoom [roomIndex].RoomGuest.UserId) { ListRoom [roomIndex].SetPlayerReady (so); return string.Empty; //return (int)CommandResponseEnum.BattleReadyResult + "`" + "1" +"~"+ "Room Guest is ready" + "`"; } else { //return error return (int)CommandResponseEnum.BattleReadyResult + "`" + "-3" + "~" + "You are not joining a room" + "`"; } } else { //return error return (int)CommandResponseEnum.BattleReadyResult + "`" + "-4" +"~"+ "Room not found" + "`"; } } public string UnsetPlayerReady(SessionData so) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; if (isFindRoom) { if (so.UserId == ListRoom [roomIndex].RoomMaster.UserId) { //ListRoom [roomIndex].UnsetPlayerReady (so); return (int)CommandResponseEnum.BattleReadyResult + "`" + "-2" +"~"+ "You are the room master" + "`"; } else if (so.UserId == ListRoom [roomIndex].RoomGuest.UserId) { ListRoom [roomIndex].UnsetPlayerReady (so); return string.Empty; //return (int)CommandResponseEnum.BattleReadyResult + "`" + "-1" +"~"+ "Room Guest is unready" + "`"; } else { //return error return (int)CommandResponseEnum.BattleReadyResult + "`" + "-3" + "~" + "You are not joining a room" + "`"; } } else { //return error return (int)CommandResponseEnum.BattleReadyResult + "`" + "-4" +"~"+ "Room not found" + "`"; } } public string KickGuest(SessionData so) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; if (isFindRoom) { if (so.UserId == ListRoom [roomIndex].RoomMaster.UserId) { ListRoom [roomIndex].KickGuest (so); } } return string.Empty; } public string StartOnlineBattle(SessionData so) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; if (isFindRoom) { if (so.UserId == ListRoom [roomIndex].RoomMaster.UserId) { ListRoom [roomIndex].StartBattle (); return string.Empty; } else if (so.UserId == ListRoom [roomIndex].RoomGuest.UserId) { return (int)CommandResponseEnum.StartOnlineBattleResult + "`" + "-2" +"~"+ "You are the Room Guest" + "`"; } else { return (int)CommandResponseEnum.StartOnlineBattleResult + "`" + "-3" + "~" + "You are not joining a room" + "`"; } } else { return (int)CommandResponseEnum.StartOnlineBattleResult + "`" + "-4" + "Room not found"; } } public string OnlineBattleAction(SessionData so, string action , string item) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; if (isFindRoom) { ListRoom [roomIndex].SetBattleAction (so,Convert.ToInt32(action),item); } else { return (int)CommandResponseEnum.SendBattleActionResult + "`" + "-1" +"~"+ "Room not found" + "`"; } return string.Empty; } public string SuddenDeath(SessionData so) { string checkRoom = FindRoom (so, null); var split = checkRoom.Split ('~'); bool isFindRoom = Convert.ToBoolean(split[0]); int roomIndex = Convert.ToInt32 (split [1]); int roomId = so.RoomId; if (isFindRoom) { if (so.UserId == ListRoom [roomIndex].RoomMaster.UserId || so.UserId == ListRoom[roomIndex].RoomGuest.UserId) { ListRoom [roomIndex].SendSuddenDeathResult (so); } else { return (int)CommandResponseEnum.SendBattleActionResult + "`" + "-2" + "~" + "You are not joining a room" + "`"; } } else { return (int)CommandResponseEnum.SendBattleActionResult + "`" + "-1" +"~"+ "Room not found" + "`"; } return string.Empty; } public string QuitRoom(SessionData so) { int roomId = so.RoomId; bool isFindRoom = false; int roomIndex = 0; for (roomIndex = 0; roomIndex < ListRoom.Count; roomIndex++) { if (ListRoom[roomIndex].RoomId == roomId) { isFindRoom = true; break; } } if (isFindRoom) { if (so.UserId == ListRoom [roomIndex].RoomMaster.UserId || so.UserId == ListRoom [roomIndex].RoomGuest.UserId) { ListRoom [roomIndex].QuitRoom (so); } else { return (int)CommandResponseEnum.QuitRoomResult + "`" + "-1" + "~" + "You are not joining any room" + "`"; } } else { return (int)CommandResponseEnum.QuitRoomResult + "`" + "-2" + "~" + "Room not found" + "`"; } return string.Empty; } public string OnlineBattleResult(SessionData so) { string response = string.Empty; int roomId = so.RoomId; bool isFindRoom = false; int roomIndex = 0; for (roomIndex = 0; roomIndex < ListRoom.Count; roomIndex++) { if (ListRoom[roomIndex].RoomId == roomId) { isFindRoom = true; break; } } if (isFindRoom) { if (so.UserId == ListRoom[roomIndex].RoomMaster.UserId || so.UserId == ListRoom[roomIndex].RoomGuest.UserId) { ListRoom[roomIndex].BattleResult(so); } else { return (int)CommandResponseEnum.QuitRoomResult + "`" + "-1" + "~" + "You are not joining any room" + "`"; } } else { return (int)CommandResponseEnum.QuitRoomResult + "`" + "-2" + "~" + "Room not found" + "`"; } return string.Empty; } public string LocalBattleResult(SessionData so, string winMons, string loseMons, string winItems, string loseItems) { // WinMonsterQR~LoseMonsterQR~WinItemQR!WinItemQR!WinItemQR!~LoseItemQR!LoseItemQR!LoseItemQR! string[] winItem = winItems.Split(new char[] { '!' }); string[] loseItem = loseItems.Split(new char[] { '!' }); string loser; string winner; string winnerID; string loserID; int winCoin = 100; int loseCoin = 25; StringDictionary winCollection; StringDictionary loseCollection; using(Command(@" SELECT user_id, hunger, happiness, clean, discipline, sick, exp_needed, exp, exp_mult, version, subversion, hp, mp, p_atk, m_atk, p_def, m_def, acc, eva, mons_card_id FROM monster_cards WHERE mons_card_qrid = :win ")) { AddParameter("win", winMons); winCollection = ExecuteRow(); winner = winCollection["user_id"]; winnerID = winCollection["mons_card_id"]; } using(Command(@" SELECT user_id, hunger, happiness, clean, discipline, sick, exp_needed, exp, exp_mult, version, subversion, hp, mp, p_atk, m_atk, p_def, m_def, acc, eva, mons_card_id FROM monster_cards WHERE mons_card_qrid = :lose ")) { AddParameter("lose", loseMons); loseCollection = ExecuteRow(); loser = loseCollection["user_id"]; loserID = loseCollection["mons_card_id"]; } string battleId; using(Command(@" INSERT INTO battle_log(win_user_id, win_mons_id, lose_user_id, lose_mons_id, time) VALUES (:win, :winmons, :lose, :losemons, CURRENT_TIMESTAMP) RETURNING battle_id as bid ")) { AddParameter("win", winner); AddParameter("winmons", winnerID); AddParameter("lose", loser); AddParameter("losemons", loserID); battleId = ExecuteRow()["bid"]; } // give coins to player using(Command(@" UPDATE user_list SET mobile_coins = mobile_coins + :win_coin WHERE user_id = :winner ")) { AddParameter ("win_coin", winCoin); AddParameter ("winner", winner); ExecuteRow() ; } using(Command(@" UPDATE user_list SET mobile_coins = mobile_coins + :lose_coin WHERE user_id = :loser ")) { AddParameter ("lose_coin", loseCoin); AddParameter ("loser", loser); ExecuteRow (); } // exp point calculation const int baseWinXP = 1000; const int baseLoseXP = 250; double winMult = (double)(100 + Convert.ToInt32(winCollection["hunger"]) + Convert.ToInt32(winCollection["happiness"]) + Convert.ToInt32(winCollection["clean"]) + Convert.ToInt32(winCollection["discipline"]) + Convert.ToInt32(winCollection["sick"])) / 300.0F; double loseMult = (double)(100 + Convert.ToInt32(winCollection["hunger"]) + Convert.ToInt32(winCollection["happiness"]) + Convert.ToInt32(winCollection["clean"]) + Convert.ToInt32(winCollection["discipline"]) + Convert.ToInt32(winCollection["sick"])) / 300.0F; int winXP = (int)(baseWinXP * winMult); int loseXP = (int)(baseLoseXP * loseMult); bool winLvlUp = false; bool loseLvlUp = false; int nextWinNeededXP = 0; int nextLoseNeededXP = 0; int winVersion = 0; int winSubversion = 0; int loseVersion = 0; int loseSubversion = 0; int currWinXP = winXP + Convert.ToInt32(winCollection["exp"]); if(currWinXP >= Convert.ToInt32(winCollection["exp_needed"])) { currWinXP = currWinXP - Convert.ToInt32(winCollection["exp_needed"]); winLvlUp = true; int nextLvlWin = Convert.ToInt32(winCollection["version"]) * 10 + Convert.ToInt32(winCollection["subversion"]) + 1; winVersion = Convert.ToInt32(nextLvlWin.ToString().Substring(0, 1)); winSubversion = Convert.ToInt32(nextLvlWin.ToString().Substring(1, 1)); if(nextLvlWin < 30) { using(Command(@" SELECT level, exp FROM base_exp_req WHERE level = :lvl ")) { AddParameter("lvl", nextLvlWin); nextWinNeededXP = Convert.ToInt32(ExecuteRow()["exp"]); } } } int currLoseXP = loseXP + Convert.ToInt32(loseCollection["exp"]); if(currLoseXP >= Convert.ToInt32(loseCollection["exp_needed"])) { currLoseXP = currLoseXP - Convert.ToInt32(loseCollection["exp_needed"]); loseLvlUp = true; int nextLvlLose = Convert.ToInt32(loseCollection["version"]) * 10 + Convert.ToInt32(loseCollection["subversion"]) + 1; loseVersion = Convert.ToInt32(nextLvlLose.ToString().Substring(0, 1)); loseSubversion = Convert.ToInt32(nextLvlLose.ToString().Substring(1,1)); if(nextLvlLose < 30) { using(Command(@" SELECT level, exp FROM base_exp_req WHERE level = :lvl ")) { AddParameter("lvl", nextLvlLose); nextLoseNeededXP = Convert.ToInt32(ExecuteRow()["exp"]); } } } byte[] evaqriWin = new byte[2]; new Random().NextBytes(evaqriWin); int evaWin = evaqriWin[0] < 15 ? 1 : 0; int criWin = evaqriWin[1] < 15 ? 1 : 0; byte[] evaqriLose = new byte[2]; new Random().NextBytes(evaqriLose); int evaLose = evaqriLose[0] < 15 ? 1 : 0; int criLose = evaqriLose[1] < 15 ? 1 : 0; // update winner stats if(winLvlUp) { using(Command(@" UPDATE monster_cards SET wins = wins + 1, hp = hp + 20 + round(random() * 5), -- hp = hp + random(20, 25) hp_regen = hp_regen + 1, p_atk = p_atk + 1 + round(random() * 2), -- p_atk = p_atk + random(1, 3) m_atk = m_atk + 1 + round(random() * 2), -- m_atk = m_atk + random(1, 3) p_def = p_def + 1 + round(random() * 2), -- p_def = p_def + random(1, 3) m_def = m_def + 1 + round(random() * 2), -- m_def = m_def + random(1, 3) acc = acc + 1 + round(random()), -- acc = acc + random(1, 2) eva = eva + :eva, cri = cri + :cri, spd = spd + 1 + round(random()), -- spd = spd + random(1, 2) version =:version, subversion =:subversion, exp = :newexp, exp_needed = :newexpneeded, hunger = greatest(hunger - round(random() * 25), 0), happiness = greatest(happiness - round(random() * 25), 0), clean = greatest(clean - round(random() * 25), 0), discipline = greatest(discipline - round(random() * 25), 0), sick = greatest(sick - round(random() * 25), 0) WHERE mons_card_qrid = :winmons ")) { AddParameter("winmons", winMons); AddParameter("eva", evaWin); AddParameter("cri", criWin); AddParameter ("version", winVersion); AddParameter ("subversion", winSubversion); AddParameter("newexpneeded", nextWinNeededXP); AddParameter("newexp", currWinXP); ExecuteWrite(); } } else { using(Command(@" UPDATE monster_cards SET wins = wins + 1, exp = :newexp, hunger = greatest(hunger - round(random() * 25), 0), happiness = greatest(happiness - round(random() * 25), 0), clean = greatest(clean - round(random() * 25), 0), discipline = greatest(discipline - round(random() * 25), 0), sick = greatest(sick - round(random() * 25), 0) WHERE mons_card_qrid = :winmons ")) { AddParameter("winmons", winMons); AddParameter("newexp", currWinXP); ExecuteWrite(); } } // update loser stats if(loseLvlUp) { using(Command(@" UPDATE monster_cards SET loses = loses + 1, hp = hp + 20 + round(random() * 5), -- hp = hp + random(20, 25) hp_regen = hp_regen + 1, p_atk = p_atk + 1 + round(random() * 2), -- p_atk = p_atk + random(1, 3) m_atk = m_atk + 1 + round(random() * 2), -- m_atk = m_atk + random(1, 3) p_def = p_def + 1 + round(random() * 2), -- p_def = p_def + random(1, 3) m_def = m_def + 1 + round(random() * 2), -- m_def = m_def + random(1, 3) acc = acc + 1 + round(random()), -- acc = acc + random(1, 2) eva = eva + :eva, cri = cri + :cri, spd = spd + 1 + round(random()), -- spd = spd + random(1, 2) version =:version, subversion =:subversion, exp = :newexp, exp_needed = :newexpneeded, hunger = greatest(hunger - round(random() * 25), 0), happiness = greatest(happiness - round(random() * 25), 0), clean = greatest(clean - round(random() * 25), 0), discipline = greatest(discipline - round(random() * 25), 0), sick = greatest(sick - round(random() * 25), 0) WHERE mons_card_qrid = :losemons ")) { AddParameter("losemons", loseMons); AddParameter("eva", evaLose); AddParameter("cri", criLose); AddParameter ("version", loseVersion); AddParameter ("subversion", loseSubversion); AddParameter("newexpneeded", nextLoseNeededXP); AddParameter("newexp", currLoseXP); ExecuteWrite(); } } else { using(Command(@" UPDATE monster_cards SET loses = loses + 1, exp = :newexp, hunger = greatest(hunger - round(random() * 25), 0), happiness = greatest(happiness - round(random() * 25), 0), clean = greatest(clean - round(random() * 25), 0), discipline = greatest(discipline - round(random() * 25), 0), sick = greatest(sick - round(random() * 25), 0) WHERE mons_card_qrid = :losemons ")) { AddParameter("losemons", loseMons); AddParameter("newexp", currLoseXP); ExecuteWrite(); } } // update item quantity foreach(string row in winItem) { using(Command(@" UPDATE item_cards SET qty = qty - 1 WHERE item_card_qrid = :item ")) { AddParameter("item", row); ExecuteWrite(); } using(Command(@" INSERT INTO battle_log_detail(battle_id, user_id, mons_id, item_id) SELECT :battle, :winner, :winmons, item_card_id FROM item_cards WHERE item_card_qrid = :item ")) { AddParameter("battle", battleId); AddParameter("winner", winner); AddParameter("winmons", winnerID); AddParameter("item", row); ExecuteWrite(); } } foreach(string row in loseItem) { using(Command(@" UPDATE item_cards SET qty = qty - 1 WHERE item_card_qrid = :item ")) { AddParameter("item", row); ExecuteWrite(); } using(Command(@" INSERT INTO battle_log_detail(battle_id, user_id, mons_id, item_id) SELECT :battle, :loser, :losemons, item_card_id FROM item_cards WHERE item_card_qrid = :item ")) { AddParameter("battle", battleId); AddParameter("loser", loser); AddParameter("losemons", loserID); AddParameter("item", row); ExecuteWrite(); } } //MonsterQRID~EXP`MonsterQRID~EXP` StringDictionary newWin = new StringDictionary(); StringDictionary newLose = new StringDictionary(); using(Command(@" SELECT hp, mp, version, subversion, p_atk, m_atk, p_def, m_def, acc, eva FROM monster_cards WHERE mons_card_qrid = :mons ")) { AddParameter("mons", winMons); newWin = ExecuteRow(); } using(Command(@" SELECT hp, mp, version, subversion, p_atk, m_atk, p_def, m_def, acc, eva FROM monster_cards WHERE mons_card_qrid = :mons ")) { AddParameter("mons", loseMons); newLose = ExecuteRow(); } string winString = winMons + "~" + winXP; if(winLvlUp) { int versionNew = Convert.ToInt32 (newWin ["version"]); int subversionNew = Convert.ToInt32 (newWin ["subversion"]); // int atkOld = Convert.ToInt32(winCollection["p_atk"]) + Convert.ToInt32(winCollection["m_atk"]); int atkNew = Convert.ToInt32(newWin["p_atk"]) + Convert.ToInt32(newWin["m_atk"]); //int atkDelta = (atkNew - atkOld) / 2; // int defOld = Convert.ToInt32(winCollection["p_def"]) + Convert.ToInt32(winCollection["m_def"]); int defNew = Convert.ToInt32(newWin["p_def"]) + Convert.ToInt32(newWin["m_def"]); // int defDelta = (defNew - defOld) / 2; // int accDelta = Convert.ToInt32(newWin["acc"]) - Convert.ToInt32(winCollection["acc"]); // int evaDelta = Convert.ToInt32(newWin["eva"]) - Convert.ToInt32(winCollection["eva"]); int accNew = Convert.ToInt32 (newWin ["acc"]); int evaNew = Convert.ToInt32 (newWin ["eva"]); winString += "~" + versionNew + "~" + subversionNew + "~" + atkNew + "~" + defNew + "~" + accNew + "~" + evaNew; } string loseString = loseMons + "~" + loseXP; if(loseLvlUp) { int versionNew = Convert.ToInt32 (newLose ["version"]); int subversionNew = Convert.ToInt32 (newLose ["subversion"]); // int atkOld = Convert.ToInt32(loseCollection["p_atk"]) + Convert.ToInt32(loseCollection["m_atk"]); int atkNew = Convert.ToInt32(newLose["p_atk"]) + Convert.ToInt32(newLose["m_atk"]); // int atkDelta = (atkNew - atkOld) / 2; // int defOld = Convert.ToInt32(loseCollection["p_def"]) + Convert.ToInt32(loseCollection["m_def"]); int defNew = Convert.ToInt32(newLose["p_def"]) + Convert.ToInt32(newLose["m_def"]); // int defDelta = (defNew - defOld) / 2; // int accDelta = Convert.ToInt32(newLose["acc"]) - Convert.ToInt32(loseCollection["acc"]); // int evaDelta = Convert.ToInt32(newLose["eva"]) - Convert.ToInt32(loseCollection["eva"]); int accNew = Convert.ToInt32 (newLose ["acc"]); int evaNew = Convert.ToInt32 (newLose ["eva"]); loseString += "~" + versionNew + "~" + subversionNew + "~" + atkNew + "~" + defNew + "~" + accNew + "~" + evaNew; } string winStats = new CardAction ().GetMonsterStat (winMons); string loseStats = new CardAction ().GetMonsterStat (loseMons); //MonsterQRID~EXP~ATK~DEF~ACC~EVA~`MonsterQRID~EXP~ATK~DEF~ACC~EVA~` return (int)CommandResponseEnum.BattleResult + "`" + winString + "~" + winCoin + "`" + loseString + "~" + loseCoin + "`" + winStats + "`" + loseStats + "`"; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using System.Xml; using OpenMetaverse; namespace OpenSim.Framework.Communications.Capabilities { /// <summary> /// Borrowed from (a older version of) libsl for now, as their new llsd code doesn't work we our decoding code. /// </summary> public static class LLSD { /// <summary> /// /// </summary> public class LLSDParseException : Exception { public LLSDParseException(string message) : base(message) { } } /// <summary> /// /// </summary> public class LLSDSerializeException : Exception { public LLSDSerializeException(string message) : base(message) { } } /// <summary> /// /// </summary> /// <param name="b"></param> /// <returns></returns> public static object LLSDDeserialize(byte[] b) { return LLSDDeserialize(new MemoryStream(b, false)); } /// <summary> /// /// </summary> /// <param name="st"></param> /// <returns></returns> public static object LLSDDeserialize(Stream st) { XmlTextReader reader = new XmlTextReader(st); reader.Read(); SkipWS(reader); if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd") throw new LLSDParseException("Expected <llsd>"); reader.Read(); object ret = LLSDParseOne(reader); SkipWS(reader); if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd") throw new LLSDParseException("Expected </llsd>"); return ret; } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public static byte[] LLSDSerialize(object obj) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.None; writer.WriteStartElement(String.Empty, "llsd", String.Empty); LLSDWriteOne(writer, obj); writer.WriteEndElement(); writer.Close(); return Encoding.UTF8.GetBytes(sw.ToString()); } /// <summary> /// /// </summary> /// <param name="writer"></param> /// <param name="obj"></param> public static void LLSDWriteOne(XmlTextWriter writer, object obj) { if (obj == null) { writer.WriteStartElement(String.Empty, "undef", String.Empty); writer.WriteEndElement(); return; } if (obj is string) { writer.WriteStartElement(String.Empty, "string", String.Empty); writer.WriteString((string) obj); writer.WriteEndElement(); } else if (obj is int) { writer.WriteStartElement(String.Empty, "integer", String.Empty); writer.WriteString(obj.ToString()); writer.WriteEndElement(); } else if (obj is double) { writer.WriteStartElement(String.Empty, "real", String.Empty); writer.WriteString(obj.ToString()); writer.WriteEndElement(); } else if (obj is bool) { bool b = (bool) obj; writer.WriteStartElement(String.Empty, "boolean", String.Empty); writer.WriteString(b ? "1" : "0"); writer.WriteEndElement(); } else if (obj is ulong) { throw new Exception("ulong in LLSD is currently not implemented, fix me!"); } else if (obj is UUID) { UUID u = (UUID) obj; writer.WriteStartElement(String.Empty, "uuid", String.Empty); writer.WriteString(u.ToString()); writer.WriteEndElement(); } else if (obj is Hashtable) { Hashtable h = obj as Hashtable; writer.WriteStartElement(String.Empty, "map", String.Empty); foreach (string key in h.Keys) { writer.WriteStartElement(String.Empty, "key", String.Empty); writer.WriteString(key); writer.WriteEndElement(); LLSDWriteOne(writer, h[key]); } writer.WriteEndElement(); } else if (obj is ArrayList) { ArrayList a = obj as ArrayList; writer.WriteStartElement(String.Empty, "array", String.Empty); foreach (object item in a) { LLSDWriteOne(writer, item); } writer.WriteEndElement(); } else if (obj is byte[]) { byte[] b = obj as byte[]; writer.WriteStartElement(String.Empty, "binary", String.Empty); writer.WriteStartAttribute(String.Empty, "encoding", String.Empty); writer.WriteString("base64"); writer.WriteEndAttribute(); //// Calculate the length of the base64 output //long length = (long)(4.0d * b.Length / 3.0d); //if (length % 4 != 0) length += 4 - (length % 4); //// Create the char[] for base64 output and fill it //char[] tmp = new char[length]; //int i = Convert.ToBase64CharArray(b, 0, b.Length, tmp, 0); //writer.WriteString(new String(tmp)); writer.WriteString(Convert.ToBase64String(b)); writer.WriteEndElement(); } else { throw new LLSDSerializeException("Unknown type " + obj.GetType().Name); } } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static object LLSDParseOne(XmlTextReader reader) { SkipWS(reader); if (reader.NodeType != XmlNodeType.Element) throw new LLSDParseException("Expected an element"); string dtype = reader.LocalName; object ret = null; switch (dtype) { case "undef": { if (reader.IsEmptyElement) { reader.Read(); return null; } reader.Read(); SkipWS(reader); ret = null; break; } case "boolean": { if (reader.IsEmptyElement) { reader.Read(); return false; } reader.Read(); string s = reader.ReadString().Trim(); if (String.IsNullOrEmpty(s) || s == "false" || s == "0") ret = false; else if (s == "true" || s == "1") ret = true; else throw new LLSDParseException("Bad boolean value " + s); break; } case "integer": { if (reader.IsEmptyElement) { reader.Read(); return 0; } reader.Read(); ret = Convert.ToInt32(reader.ReadString().Trim()); break; } case "real": { if (reader.IsEmptyElement) { reader.Read(); return 0.0f; } reader.Read(); ret = Convert.ToDouble(reader.ReadString().Trim()); break; } case "uuid": { if (reader.IsEmptyElement) { reader.Read(); return UUID.Zero; } reader.Read(); ret = new UUID(reader.ReadString().Trim()); break; } case "string": { if (reader.IsEmptyElement) { reader.Read(); return String.Empty; } reader.Read(); ret = reader.ReadString(); break; } case "binary": { if (reader.IsEmptyElement) { reader.Read(); return new byte[0]; } if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64") { throw new LLSDParseException("Unknown encoding: " + reader.GetAttribute("encoding")); } reader.Read(); FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); byte[] inp = Encoding.UTF8.GetBytes(reader.ReadString()); ret = b64.TransformFinalBlock(inp, 0, inp.Length); break; } case "date": { reader.Read(); throw new Exception("LLSD TODO: date"); } case "map": { return LLSDParseMap(reader); } case "array": { return LLSDParseArray(reader); } default: throw new LLSDParseException("Unknown element <" + dtype + ">"); } if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != dtype) { throw new LLSDParseException("Expected </" + dtype + ">"); } reader.Read(); return ret; } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static Hashtable LLSDParseMap(XmlTextReader reader) { Hashtable ret = new Hashtable(); if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map") throw new LLSDParseException("Expected <map>"); if (reader.IsEmptyElement) { reader.Read(); return ret; } reader.Read(); while (true) { SkipWS(reader); if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map") { reader.Read(); break; } if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key") throw new LLSDParseException("Expected <key>"); string key = reader.ReadString(); if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key") throw new LLSDParseException("Expected </key>"); reader.Read(); object val = LLSDParseOne(reader); ret[key] = val; } return ret; // TODO } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ArrayList LLSDParseArray(XmlTextReader reader) { ArrayList ret = new ArrayList(); if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array") throw new LLSDParseException("Expected <array>"); if (reader.IsEmptyElement) { reader.Read(); return ret; } reader.Read(); while (true) { SkipWS(reader); if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array") { reader.Read(); break; } ret.Insert(ret.Count, LLSDParseOne(reader)); } return ret; // TODO } /// <summary> /// /// </summary> /// <param name="count"></param> /// <returns></returns> private static string GetSpaces(int count) { StringBuilder b = new StringBuilder(); for (int i = 0; i < count; i++) b.Append(" "); return b.ToString(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="indent"></param> /// <returns></returns> public static String LLSDDump(object obj, int indent) { if (obj == null) { return GetSpaces(indent) + "- undef\n"; } else if (obj is string) { return GetSpaces(indent) + "- string \"" + (string) obj + "\"\n"; } else if (obj is int) { return GetSpaces(indent) + "- integer " + obj.ToString() + "\n"; } else if (obj is double) { return GetSpaces(indent) + "- float " + obj.ToString() + "\n"; } else if (obj is UUID) { return GetSpaces(indent) + "- uuid " + ((UUID) obj).ToString() + Environment.NewLine; } else if (obj is Hashtable) { StringBuilder ret = new StringBuilder(); ret.Append(GetSpaces(indent) + "- map" + Environment.NewLine); Hashtable map = (Hashtable) obj; foreach (string key in map.Keys) { ret.Append(GetSpaces(indent + 2) + "- key \"" + key + "\"" + Environment.NewLine); ret.Append(LLSDDump(map[key], indent + 3)); } return ret.ToString(); } else if (obj is ArrayList) { StringBuilder ret = new StringBuilder(); ret.Append(GetSpaces(indent) + "- array\n"); ArrayList list = (ArrayList) obj; foreach (object item in list) { ret.Append(LLSDDump(item, indent + 2)); } return ret.ToString(); } else if (obj is byte[]) { return GetSpaces(indent) + "- binary\n" + Utils.BytesToHexString((byte[]) obj, GetSpaces(indent)) + Environment.NewLine; } else { return GetSpaces(indent) + "- unknown type " + obj.GetType().Name + Environment.NewLine; } } public static object ParseTerseLLSD(string llsd) { int notused; return ParseTerseLLSD(llsd, out notused); } public static object ParseTerseLLSD(string llsd, out int endPos) { if (String.IsNullOrEmpty(llsd)) { endPos = 0; return null; } // Identify what type of object this is switch (llsd[0]) { case '!': throw new LLSDParseException("Undefined value type encountered"); case '1': endPos = 1; return true; case '0': endPos = 1; return false; case 'i': { if (llsd.Length < 2) throw new LLSDParseException("Integer value type with no value"); int value; endPos = FindEnd(llsd, 1); if (Int32.TryParse(llsd.Substring(1, endPos - 1), out value)) return value; else throw new LLSDParseException("Failed to parse integer value type"); } case 'r': { if (llsd.Length < 2) throw new LLSDParseException("Real value type with no value"); double value; endPos = FindEnd(llsd, 1); if (Double.TryParse(llsd.Substring(1, endPos - 1), NumberStyles.Float, Utils.EnUsCulture.NumberFormat, out value)) return value; else throw new LLSDParseException("Failed to parse double value type"); } case 'u': { if (llsd.Length < 17) throw new LLSDParseException("UUID value type with no value"); UUID value; endPos = FindEnd(llsd, 1); if (UUID.TryParse(llsd.Substring(1, endPos - 1), out value)) return value; else throw new LLSDParseException("Failed to parse UUID value type"); } case 'b': //byte[] value = new byte[llsd.Length - 1]; // This isn't the actual binary LLSD format, just the terse format sent // at login so I don't even know if there is a binary type throw new LLSDParseException("Binary value type is unimplemented"); case 's': case 'l': if (llsd.Length < 2) throw new LLSDParseException("String value type with no value"); endPos = FindEnd(llsd, 1); return llsd.Substring(1, endPos - 1); case 'd': // Never seen one before, don't know what the format is throw new LLSDParseException("Date value type is unimplemented"); case '[': { if (llsd.IndexOf(']') == -1) throw new LLSDParseException("Invalid array"); int pos = 0; ArrayList array = new ArrayList(); while (llsd[pos] != ']') { ++pos; // Advance past comma if need be if (llsd[pos] == ',') ++pos; // Allow a single whitespace character if (pos < llsd.Length && llsd[pos] == ' ') ++pos; int end; array.Add(ParseTerseLLSD(llsd.Substring(pos), out end)); pos += end; } endPos = pos + 1; return array; } case '{': { if (llsd.IndexOf('}') == -1) throw new LLSDParseException("Invalid map"); int pos = 0; Hashtable hashtable = new Hashtable(); while (llsd[pos] != '}') { ++pos; // Advance past comma if need be if (llsd[pos] == ',') ++pos; // Allow a single whitespace character if (pos < llsd.Length && llsd[pos] == ' ') ++pos; if (llsd[pos] != '\'') throw new LLSDParseException("Expected a map key"); int endquote = llsd.IndexOf('\'', pos + 1); if (endquote == -1 || (endquote + 1) >= llsd.Length || llsd[endquote + 1] != ':') throw new LLSDParseException("Invalid map format"); string key = llsd.Substring(pos, endquote - pos); key = key.Replace("'", String.Empty); pos += (endquote - pos) + 2; int end; hashtable.Add(key, ParseTerseLLSD(llsd.Substring(pos), out end)); pos += end; } endPos = pos + 1; return hashtable; } default: throw new Exception("Unknown value type"); } } private static int FindEnd(string llsd, int start) { int end = llsd.IndexOfAny(new char[] {',', ']', '}'}); if (end == -1) end = llsd.Length - 1; return end; } /// <summary> /// /// </summary> /// <param name="reader"></param> private static void SkipWS(XmlTextReader reader) { while ( reader.NodeType == XmlNodeType.Comment || reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace || reader.NodeType == XmlNodeType.XmlDeclaration) { reader.Read(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Net; using System.Net.Sockets; using System.Runtime; using System.Text; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal abstract class SocketConnection : IConnection { // common state protected TimeSpan _sendTimeout; protected TimeSpan _receiveTimeout; protected CloseState _closeState; protected bool _aborted; // close state protected TimeoutHelper _closeTimeoutHelper; private bool _isShutdown; // read state protected int _asyncReadSize; protected byte[] _readBuffer; protected int _asyncReadBufferSize; protected object _asyncReadState; protected Action<object> _asyncReadCallback; protected Exception _asyncReadException; protected bool _asyncReadPending; // write state protected object _asyncWriteState; protected Action<object> _asyncWriteCallback; protected Exception _asyncWriteException; protected bool _asyncWritePending; protected string _timeoutErrorString; protected TransferOperation _timeoutErrorTransferOperation; private ConnectionBufferPool _connectionBufferPool; private string _remoteEndpointAddressString; public SocketConnection(ConnectionBufferPool connectionBufferPool) { Contract.Assert(connectionBufferPool != null, "Argument connectionBufferPool cannot be null"); _closeState = CloseState.Open; _connectionBufferPool = connectionBufferPool; _readBuffer = _connectionBufferPool.Take(); _asyncReadBufferSize = _readBuffer.Length; _sendTimeout = _receiveTimeout = TimeSpan.MaxValue; } public int AsyncReadBufferSize { get { return _asyncReadBufferSize; } } public byte[] AsyncReadBuffer { get { return _readBuffer; } } protected object ThisLock { get { return this; } } protected abstract IPEndPoint RemoteEndPoint { get; } protected string RemoteEndpointAddressString { get { if (_remoteEndpointAddressString == null) { IPEndPoint remote = RemoteEndPoint; if (remote == null) { return string.Empty; } _remoteEndpointAddressString = remote.Address + ":" + remote.Port; } return _remoteEndpointAddressString; } } protected static void OnReceiveTimeout(SocketConnection socketConnection) { try { socketConnection.Abort(SR.Format(SR.SocketAbortedReceiveTimedOut, socketConnection._receiveTimeout), TransferOperation.Read); } catch (SocketException) { // Guard against unhandled SocketException in timer callbacks } } protected static void OnSendTimeout(SocketConnection socketConnection) { try { socketConnection.Abort(4, // TraceEventType.Warning SR.Format(SR.SocketAbortedSendTimedOut, socketConnection._sendTimeout), TransferOperation.Write); } catch (SocketException) { // Guard against unhandled SocketException in timer callbacks } } public void Abort() { Abort(null, TransferOperation.Undefined); } protected void Abort(string timeoutErrorString, TransferOperation transferOperation) { int traceEventType = 4; // TraceEventType.Warning; // we could be timing out a cached connection Abort(traceEventType, timeoutErrorString, transferOperation); } protected void Abort(int traceEventType) { Abort(traceEventType, null, TransferOperation.Undefined); } protected abstract void Abort(int traceEventType, string timeoutErrorString, TransferOperation transferOperation); protected abstract void AbortRead(); public void Close(TimeSpan timeout, bool asyncAndLinger) { lock (ThisLock) { if (_closeState == CloseState.Closing || _closeState == CloseState.Closed) { // already closing or closed, so just return return; } _closeState = CloseState.Closing; } _closeTimeoutHelper = new TimeoutHelper(timeout); // first we shutdown our send-side Shutdown(timeout); CloseCore(asyncAndLinger); } protected abstract void CloseCore(bool asyncAndLinger); private void Shutdown(TimeSpan timeout) { lock (ThisLock) { if (_isShutdown) { return; } _isShutdown = true; } ShutdownCore(timeout); } protected abstract void ShutdownCore(TimeSpan timeout); protected void ThrowIfNotOpen() { if (_closeState == CloseState.Closing || _closeState == CloseState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertObjectDisposedException(new ObjectDisposedException( this.GetType().ToString(), SR.SocketConnectionDisposed), TransferOperation.Undefined)); } } protected void ThrowIfClosed() { if (_closeState == CloseState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertObjectDisposedException(new ObjectDisposedException( this.GetType().ToString(), SR.SocketConnectionDisposed), TransferOperation.Undefined)); } } protected Exception ConvertSendException(SocketException socketException, TimeSpan remainingTime) { return ConvertTransferException(socketException, _sendTimeout, socketException, TransferOperation.Write, _aborted, _timeoutErrorString, _timeoutErrorTransferOperation, this, remainingTime); } protected Exception ConvertReceiveException(SocketException socketException, TimeSpan remainingTime) { return ConvertTransferException(socketException, _receiveTimeout, socketException, TransferOperation.Read, _aborted, _timeoutErrorString, _timeoutErrorTransferOperation, this, remainingTime); } internal static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException) { return ConvertTransferException(socketException, timeout, originalException, TransferOperation.Undefined, false, null, TransferOperation.Undefined, null, TimeSpan.MaxValue); } protected Exception ConvertObjectDisposedException(ObjectDisposedException originalException, TransferOperation transferOperation) { if (_timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, _timeoutErrorString, _timeoutErrorTransferOperation); } else if (_aborted) { return new CommunicationObjectAbortedException(SR.SocketConnectionDisposed, originalException); } else { return originalException; } } private static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException, TransferOperation transferOperation, bool aborted, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation, SocketConnection socketConnection, TimeSpan remainingTime) { if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE) { return new CommunicationObjectAbortedException(socketException.Message, socketException); } if (timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, timeoutErrorString, timeoutErrorTransferOperation); } // 10053 can occur due to our timeout sockopt firing, so map to TimeoutException in that case if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNABORTED && remainingTime <= TimeSpan.Zero) { TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException); return timeoutException; } if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETRESET || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNABORTED || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNRESET) { if (aborted) { return new CommunicationObjectAbortedException(SR.TcpLocalConnectionAborted, originalException); } else { CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpConnectionResetError, timeout), originalException); return communicationException; } } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAETIMEDOUT) { TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException); return timeoutException; } else { if (aborted) { return new CommunicationObjectAbortedException(SR.Format(SR.TcpTransferError, (int)socketException.SocketErrorCode, socketException.Message), originalException); } else { CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpTransferError, (int)socketException.SocketErrorCode, socketException.Message), originalException); return communicationException; } } } private static Exception ConvertTimeoutErrorException(Exception originalException, TransferOperation transferOperation, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation) { Contract.Assert(timeoutErrorString != null, "Argument timeoutErrorString must not be null."); if (transferOperation == timeoutErrorTransferOperation) { return new TimeoutException(timeoutErrorString, originalException); } else { return new CommunicationException(timeoutErrorString, originalException); } } public AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, Action<object> callback, object state) { if (WcfEventSource.Instance.SocketAsyncWriteStartIsEnabled()) { TraceWriteStart(size, true); } return BeginWriteCore(buffer, offset, size, immediate, timeout, callback, state); } protected abstract void TraceWriteStart(int size, bool async); protected abstract AsyncCompletionResult BeginWriteCore(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, Action<object> callback, object state); public void EndWrite() { EndWriteCore(); } protected abstract void EndWriteCore(); protected void FinishWrite() { Action<object> asyncWriteCallback = _asyncWriteCallback; object asyncWriteState = _asyncWriteState; _asyncWriteState = null; _asyncWriteCallback = null; asyncWriteCallback(asyncWriteState); } public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { WriteCore(buffer, offset, size, immediate, timeout); } protected abstract void WriteCore(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout); public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager) { try { Write(buffer, offset, size, immediate, timeout); } finally { bufferManager.ReturnBuffer(buffer); } } public int Read(byte[] buffer, int offset, int size, TimeSpan timeout) { ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); ThrowIfNotOpen(); int bytesRead = ReadCore(buffer, offset, size, timeout, false); if (WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(bytesRead, false); } return bytesRead; } protected abstract int ReadCore(byte[] buffer, int offset, int size, TimeSpan timeout, bool closing); public virtual AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action<object> callback, object state) { ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size); this.ThrowIfNotOpen(); var completionResult = this.BeginReadCore(offset, size, timeout, callback, state); if (completionResult == AsyncCompletionResult.Completed && WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } return completionResult; } protected abstract void TraceSocketReadStop(int bytesRead, bool async); protected abstract AsyncCompletionResult BeginReadCore(int offset, int size, TimeSpan timeout, Action<object> callback, object state); protected void FinishRead() { if (_asyncReadException != null && WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } Action<object> asyncReadCallback = _asyncReadCallback; object asyncReadState = _asyncReadState; _asyncReadState = null; _asyncReadCallback = null; asyncReadCallback(asyncReadState); } // Both BeginRead/ReadAsync paths completed themselves. EndRead's only job is to deliver the result. public int EndRead() { return EndReadCore(); } protected abstract int EndReadCore(); // This method should be called inside ThisLock protected void ReturnReadBuffer() { // We release the buffer only if there is no outstanding I/O this.TryReturnReadBuffer(); } // This method should be called inside ThisLock protected void TryReturnReadBuffer() { // The buffer must not be returned and nulled when an abort occurs. Since the buffer // is also accessed by higher layers, code that has not yet realized the stack is // aborted may be attempting to read from the buffer. if (_readBuffer != null && !_aborted) { _connectionBufferPool.Return(_readBuffer); _readBuffer = null; } } public abstract object GetCoreTransport(); protected enum CloseState { Open, Closing, Closed, } protected enum TransferOperation { Write, Read, Undefined, } } internal abstract class SocketConnectionInitiator : IConnectionInitiator { private int _bufferSize; protected ConnectionBufferPool _connectionBufferPool; public SocketConnectionInitiator(int bufferSize) { _bufferSize = bufferSize; _connectionBufferPool = new ConnectionBufferPool(bufferSize); } protected abstract IConnection CreateConnection(IPAddress address, int port); protected abstract Task<IConnection> CreateConnectionAsync(IPAddress address, int port); public static Exception ConvertConnectException(SocketException socketException, Uri remoteUri, TimeSpan timeSpent, Exception innerException) { if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE) { return new CommunicationObjectAbortedException(socketException.Message, socketException); } if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEADDRNOTAVAIL || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNREFUSED || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETDOWN || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETUNREACH || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEHOSTDOWN || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEHOSTUNREACH || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAETIMEDOUT) { if (timeSpent == TimeSpan.MaxValue) { return new EndpointNotFoundException(SR.Format(SR.TcpConnectError, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message), innerException); } else { return new EndpointNotFoundException(SR.Format(SR.TcpConnectErrorWithTimeSpan, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message, timeSpent), innerException); } } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENOBUFS) { return new OutOfMemoryException(SR.TcpConnectNoBufs, innerException); } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY || (int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_NO_SYSTEM_RESOURCES || (int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_OUTOFMEMORY) { return new OutOfMemoryException(SR.InsufficentMemory, socketException); } else { if (timeSpent == TimeSpan.MaxValue) { return new CommunicationException(SR.Format(SR.TcpConnectError, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message), innerException); } else { return new CommunicationException(SR.Format(SR.TcpConnectErrorWithTimeSpan, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message, timeSpent), innerException); } } } private static async Task<IPAddress[]> GetIPAddressesAsync(Uri uri) { if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6) { IPAddress ipAddress = IPAddress.Parse(uri.DnsSafeHost); return new IPAddress[] { ipAddress }; } IPAddress[] addresses = null; try { addresses = await DnsCache.ResolveAsync(uri); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.UnableToResolveHost, uri.Host), socketException)); } if (addresses.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.UnableToResolveHost, uri.Host))); } return addresses; } private static TimeoutException CreateTimeoutException(Uri uri, TimeSpan timeout, IPAddress[] addresses, int invalidAddressCount, SocketException innerException) { StringBuilder addressStringBuilder = new StringBuilder(); for (int i = 0; i < invalidAddressCount; i++) { if (addresses[i] == null) { continue; } if (addressStringBuilder.Length > 0) { addressStringBuilder.Append(", "); } addressStringBuilder.Append(addresses[i].ToString()); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.TcpConnectingToViaTimedOut, uri.AbsoluteUri, timeout.ToString(), invalidAddressCount, addresses.Length, addressStringBuilder.ToString()), innerException)); } public IConnection Connect(Uri uri, TimeSpan timeout) { int port = uri.Port; IPAddress[] addresses = SocketConnectionInitiator.GetIPAddressesAsync(uri).GetAwaiter().GetResult(); IConnection socketConnection = null; SocketException lastException = null; if (port == -1) { port = TcpUri.DefaultPort; } int invalidAddressCount = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < addresses.Length; i++) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException)); } DateTime connectStartTime = DateTime.UtcNow; try { socketConnection = CreateConnection(addresses[i], port); lastException = null; break; } catch (SocketException socketException) { invalidAddressCount++; lastException = socketException; } } if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionInitiator.ConvertConnectException(lastException, uri, timeoutHelper.ElapsedTime(), lastException)); } return socketConnection; } public async Task<IConnection> ConnectAsync(Uri uri, TimeSpan timeout) { int port = uri.Port; IPAddress[] addresses = await SocketConnectionInitiator.GetIPAddressesAsync(uri); IConnection socketConnection = null; SocketException lastException = null; if (port == -1) { port = TcpUri.DefaultPort; } int invalidAddressCount = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < addresses.Length; i++) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException)); } DateTime connectStartTime = DateTime.UtcNow; try { socketConnection = await CreateConnectionAsync(addresses[i], port); lastException = null; break; } catch (SocketException socketException) { invalidAddressCount++; lastException = socketException; } } if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionInitiator.ConvertConnectException(lastException, uri, timeoutHelper.ElapsedTime(), lastException)); } return socketConnection; } } }
#region File Information //----------------------------------------------------------------------------- // TriangleSphereCollisionDetection.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using System.Collections.Generic; #endregion Using Statements namespace MarbleMazeGame { /// <summary> /// Represents a simple triangle by the vertices at each corner. /// </summary> public class Triangle { #region Fields public Vector3 A; public Vector3 B; public Vector3 C; #endregion #region Initialization public Triangle() { A = Vector3.Zero; B = Vector3.Zero; C = Vector3.Zero; } public Triangle(Vector3 v0, Vector3 v1, Vector3 v2) { A = v0; B = v1; C = v2; } #endregion #region Public Functions /// <summary> /// Get a normal that faces away from the point specified (faces in) /// </summary> public void InverseNormal(ref Vector3 point, out Vector3 inverseNormal) { Normal(out inverseNormal); // The direction from any corner of the triangle to the point Vector3 inverseDirection = point - A; ; // Roughly facing the same way if (Vector3.Dot(inverseNormal, inverseDirection) > 0) { // Same direction therefore invert the normal to face away from the direction // to face the point Vector3.Multiply(ref inverseNormal, -1.0f, out inverseNormal); } } /// <summary> /// A unit length vector at right angles to the plane of the triangle /// </summary> public void Normal(out Vector3 normal) { normal = Vector3.Zero; Vector3 side1 = B - A; Vector3 side2 = C - A; normal = Vector3.Normalize(Vector3.Cross(side1, side2)); } #endregion } /// <summary> /// Triangle-Sphere based collision test /// </summary> public static class TriangleSphereCollisionDetection { const float epsilon = float.Epsilon; #region Collision Detection /// <summary> /// Shoot a ray into the triangle and get the distance from the point /// it hits and if the distance is smaller than the radius we hit the triangle /// </summary> /// <param name="sphere">Sphere to check collision with triangles</param> /// <param name="triangle">List of triangles</param> /// <returns></returns> public static bool LightSphereTriangleCollision(ref BoundingSphere sphere, ref Triangle triangle) { Ray ray = new Ray(); ray.Position = sphere.Center; // Create a vector facing towards the triangle from the // ray starting point. Vector3 inverseNormal; TriangleInverseNormal(ref ray.Position, out inverseNormal, ref triangle); ray.Direction = inverseNormal; // Check if the ray hits the triangle float? distance = RayTriangleIntersects(ref ray, ref triangle); if (distance != null && distance > 0 && distance <= sphere.Radius) { // Hit the surface of the triangle return true; } return false; } /// <summary> /// Shoot a ray into the triangle and get the distance from the point /// it hits and if the distance is smaller than the radius we hit the triangle /// and check collision with the edges /// </summary> /// <param name="sphere">Sphere to check collision with triangles</param> /// <param name="triangle">List of triangles</param> /// <returns></returns> public static bool SphereTriangleCollision(ref BoundingSphere sphere, ref Triangle triangle) { // First check if any corner point is inside the sphere // This is necessary because the other tests can easily miss // small triangles that are fully inside the sphere. if (sphere.Contains(triangle.A) != ContainmentType.Disjoint || sphere.Contains(triangle.B) != ContainmentType.Disjoint || sphere.Contains(triangle.C) != ContainmentType.Disjoint) { // A point is inside the sphere return true; } // Test the edges of the triangle using a ray // If any hit then check the distance to the hit is less than the length of the side // The distance from a point of a small triangle inside the sphere coule be longer // than the edge of the small triangle, hence the test for points inside above. Vector3 side = triangle.B - triangle.A; // Important: The direction of the ray MUST // be normalised otherwise the resulting length // of any intersect is wrong! Ray ray = new Ray(triangle.A, Vector3.Normalize(side)); float distSq = 0; float? length = null; sphere.Intersects(ref ray, out length); if (length != null) { distSq = (float)length * (float)length; if (length > 0 && distSq < side.LengthSquared()) { // Hit edge return true; } } // Stay at A and change the direction to C side = triangle.C - triangle.A; ray.Direction = Vector3.Normalize(side); length = null; sphere.Intersects(ref ray, out length); if (length != null) { distSq = (float)length * (float)length; if (length > 0 && distSq < side.LengthSquared()) { // Hit edge return true; } } // Change to corner B and edge to C side = triangle.C - triangle.B; ray.Position = triangle.B; ray.Direction = Vector3.Normalize(side); length = null; sphere.Intersects(ref ray, out length); if (length != null) { distSq = (float)length * (float)length; if (length > 0 && distSq < side.LengthSquared()) { // Hit edge return true; } } // If we get this far we are not touching the edges of the triangle // Calculate the InverseNormal of the triangle from the centre of the sphere // Do a ray intersection from the centre of the sphere to the triangle. // If the triangle is too small the ray could miss a small triangle inside // the sphere hence why the points were tested above. ray.Position = sphere.Center; // This will always create a vector facing towards the triangle from the // ray starting point. TriangleInverseNormal(ref ray.Position, out side, ref triangle); ray.Direction = side; length = RayTriangleIntersects(ref ray, ref triangle); if (length != null && length > 0 && length < sphere.Radius) { // Hit the surface of the triangle return true; } // Only if we get this far have we missed the triangle return false; } /// <summary> /// Check if sphere collide with triangles /// </summary> /// <param name="vertices">List of triangles vertices</param> /// <param name="boundingSphere">Sphere</param> /// <param name="triangle">Return which triangle collide with the sphere</param> /// <param name="light">Use light or full detection</param> /// <returns>If sphere collide with triangle</returns> public static bool IsSphereCollideWithTringles(List<Vector3> vertices, BoundingSphere boundingSphere, out Triangle triangle, bool light) { bool res = false; triangle = null; for (int i = 0; i < vertices.Count; i += 3) { // Create triangle from the tree vertices Triangle t = new Triangle(vertices[i], vertices[i + 1], vertices[i + 2]); // Check if the sphere collide with the triangle if (light) { res = TriangleSphereCollisionDetection.LightSphereTriangleCollision(ref boundingSphere, ref t); } else { res = TriangleSphereCollisionDetection.SphereTriangleCollision(ref boundingSphere, ref t); } if (res) { triangle = t; return res; } } return res; } /// <summary> /// Check if bounding box Collide with triangles by checking the bounding box /// contains any vertices /// </summary> /// <param name="vertices">List of triangles vertices</param> /// <param name="boundingBox">Box</param> /// <returns>If box collide with triangle</returns> public static bool IsBoxCollideWithTringles(List<Vector3> vertices, BoundingBox boundingBox, out Triangle triangle) { bool res = false; triangle = null; for (int i = 0; i < vertices.Count; i += 3) { // Create triangle from the tree vertices Triangle t = new Triangle(vertices[i], vertices[i + 1], vertices[i + 2]); // Check if the box collide with the triangle res = (boundingBox.Contains(t.A) != ContainmentType.Disjoint) || (boundingBox.Contains(t.B) != ContainmentType.Disjoint) || (boundingBox.Contains(t.C) != ContainmentType.Disjoint); if (res) { triangle = t; return res; } } return res; } /// <summary> /// Check if sphere collide with triangles /// </summary> /// <param name="vertices">List of triangles vertices</param> /// <param name="boundingSphere">Sphere</param> /// <param name="triangles">Return which triangles collide with the sphere</param> /// /// <param name="light">Use light or full detection</param> /// <returns>If sphere collide with triangle</returns> public static bool IsSphereCollideWithTringles(List<Vector3> vertices, BoundingSphere boundingSphere, out IEnumerable<Triangle> triangles, bool light) { bool res = false; List<Triangle> resualt = new List<Triangle>(); for (int i = 0; i < vertices.Count; i += 3) { // Create triangle from the tree vertices Triangle t = new Triangle(vertices[i], vertices[i + 1], vertices[i + 2]); // Check if the shpere collide with the triangle bool tmp; if (light) { tmp = TriangleSphereCollisionDetection.LightSphereTriangleCollision(ref boundingSphere, ref t); } else { tmp = TriangleSphereCollisionDetection.SphereTriangleCollision(ref boundingSphere, ref t); } if (tmp) { resualt.Add(t); res = true; } } triangles = resualt; return res; } /// <summary> /// Check if bounding box Collide with triangles by checking the bounding box /// contains any vertices /// </summary> /// <param name="vertices">List of triangles vertices</param> /// <param name="boundingBox">Box</param> /// <param name="triangles">Return which triangles collide with the sphere</param> /// <returns>If box collide with triangle</returns> public static bool IsBoxCollideWithTringles(List<Vector3> vertices, BoundingBox boundingBox, out IEnumerable<Triangle> triangles) { bool res = false; List<Triangle> resualt = new List<Triangle>(); for (int i = 0; i < vertices.Count; i += 3) { // Create triangle from the tree vertices Triangle t = new Triangle(vertices[i], vertices[i + 1], vertices[i + 2]); // Check if the box collide with the triangle if ((boundingBox.Contains(t.A) != ContainmentType.Disjoint) || (boundingBox.Contains(t.B) != ContainmentType.Disjoint) || (boundingBox.Contains(t.C) != ContainmentType.Disjoint)) { resualt.Add(t); res = true; } } triangles = resualt; return res; } #endregion #region Triangle-Ray /// <summary> /// Determine whether the triangle (v0,v1,v2) intersects the given ray. If there is intersection, /// returns the parametric value of the intersection point on the ray. Otherwise returns null. /// </summary> /// <param name="ray"></param> /// <param name="v0"></param> /// <param name="v1"></param> /// <param name="v2"></param> /// <returns></returns> public static float? RayTriangleIntersects(ref Ray ray, ref Vector3 v0, ref Vector3 v1, ref Vector3 v2) { // The algorithm is based on Moller, Tomas and Trumbore, "Fast, Minimum Storage // Ray-Triangle Intersection", Journal of Graphics Tools, vol. 2, no. 1, // pp 21-28, 1997. Vector3 e1 = v1 - v0; Vector3 e2 = v2 - v0; Vector3 p = Vector3.Cross(ray.Direction, e2); float det = Vector3.Dot(e1, p); float t; if (det >= epsilon) { // Determinate is positive (front side of the triangle). Vector3 s = ray.Position - v0; float u = Vector3.Dot(s, p); if (u < 0 || u > det) return null; Vector3 q = Vector3.Cross(s, e1); float v = Vector3.Dot(ray.Direction, q); if (v < 0 || ((u + v) > det)) return null; t = Vector3.Dot(e2, q); if (t < 0) return null; } else if (det <= -epsilon) { // Determinate is negative (back side of the triangle). Vector3 s = ray.Position - v0; float u = Vector3.Dot(s, p); if (u > 0 || u < det) return null; Vector3 q = Vector3.Cross(s, e1); float v = Vector3.Dot(ray.Direction, q); if (v > 0 || ((u + v) < det)) return null; t = Vector3.Dot(e2, q); if (t > 0) return null; } else { // Parallel ray. return null; } return t / det; } /// <summary> /// Determine whether the given triangle intersects the given ray. If there is intersection, /// returns the parametric value of the intersection point on the ray. Otherwise returns null. /// </summary> /// <param name="ray"></param> /// <param name="triangle"></param> /// <returns></returns> public static float? RayTriangleIntersects(ref Ray ray, ref Triangle triangle) { return RayTriangleIntersects(ref ray, ref triangle.A, ref triangle.B, ref triangle.C); } /// <summary> /// A unit length vector at a right angle to the plane of the triangle /// </summary> public static void TriangleNormal(out Vector3 normal, ref Triangle triangle) { normal = Vector3.Zero; // Get the two sides of the triangle Vector3 side1 = triangle.B - triangle.A; Vector3 side2 = triangle.C - triangle.A; // Then do a cross product between the two sides // to get a vector perpendicular to the triangle normal = Vector3.Cross(side1, side2); // Normalize the vector so we get it at unit length normal = Vector3.Normalize(normal); } /// <summary> /// Get a normal that faces towards the triangle from the point given /// </summary> public static void TriangleInverseNormal(ref Vector3 point, out Vector3 inverseNormal, ref Triangle triangle) { // Get the normal of the triangle TriangleNormal(out inverseNormal, ref triangle); // The direction from 1 corner of the triangle to the // to the given point Vector3 inverseDirection = point - triangle.A; // Check if the inverseNormal and inverseDirection is pointing in the same direction if (Vector3.Dot(inverseNormal, inverseDirection) > 0) { // Same direction therefore invert the normal to face away from the direction // to face the point Vector3.Multiply(ref inverseNormal, -1.0f, out inverseNormal); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Security; using System.Threading; namespace System.Net { // This is used by ContextAwareResult to cache callback closures between similar calls. Create one of these and // pass it in to FinishPostingAsyncOp() to prevent the context from being captured in every iteration of a looped async call. // // It was decided not to make the delegate and state into weak references because: // - The delegate is very likely to be abandoned by the user right after calling BeginXxx, making caching it useless. There's // no easy way to weakly reference just the target. // - We want to support identifying state via object.Equals() (especially value types), which means we need to keep a // reference to the original. Plus, if we're holding the target, might as well hold the state too. // The user will need to disable caching if they want their target/state to be instantly collected. // // For now the state is not included as part of the closure. It is too common a pattern (for example with socket receive) // to have several pending IOs differentiated by their state object. We don't want that pattern to break the cache. internal class CallbackClosure { private AsyncCallback _savedCallback; private ExecutionContext _savedContext; internal CallbackClosure(ExecutionContext context, AsyncCallback callback) { if (callback != null) { _savedCallback = callback; _savedContext = context; } } internal bool IsCompatible(AsyncCallback callback) { if (callback == null || _savedCallback == null) { return false; } // Delegates handle this ok. AsyncCallback is sealed and immutable, so if this succeeds, we are safe to use // the passed-in instance. if (!object.Equals(_savedCallback, callback)) { return false; } return true; } internal AsyncCallback AsyncCallback { get { return _savedCallback; } } internal ExecutionContext Context { get { return _savedContext; } } } // This class will ensure that the correct context is restored on the thread before invoking // a user callback. internal partial class ContextAwareResult : LazyAsyncResult { [Flags] private enum StateFlags : byte { None = 0x00, CaptureIdentity = 0x01, CaptureContext = 0x02, ThreadSafeContextCopy = 0x04, PostBlockStarted = 0x08, PostBlockFinished = 0x10, } // This needs to be volatile so it's sure to make it over to the completion thread in time. private volatile ExecutionContext _context; private object _lock; private StateFlags _flags; internal ContextAwareResult(object myObject, object myState, AsyncCallback myCallBack) : this(false, false, myObject, myState, myCallBack) { } // Setting captureIdentity enables the Identity property. This will be available even if ContextCopy isn't, either because // flow is suppressed or it wasn't needed. (If ContextCopy isn't available, Identity may or may not be. But if it is, it // should be used instead of ContextCopy for impersonation - ContextCopy might not include the identity.) // // Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified. (The context is // always captured if a callback is given.) internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object myState, AsyncCallback myCallBack) : this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack) { } internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { if (forceCaptureContext) { _flags = StateFlags.CaptureContext; } if (captureIdentity) { _flags |= StateFlags.CaptureIdentity; } if (threadSafeContextCopy) { _flags |= StateFlags.ThreadSafeContextCopy; } } // This can be used to establish a context during an async op for something like calling a delegate or demanding a permission. // May block briefly if the context is still being produced. // // Returns null if called from the posting thread. internal ExecutionContext ContextCopy { get { if (InternalPeekCompleted) { if ((_flags & StateFlags.ThreadSafeContextCopy) == 0) { NetEventSource.Fail(this, "Called on completed result."); } throw new InvalidOperationException(SR.net_completed_result); } ExecutionContext context = _context; if (context != null) { return context; // No need to copy on CoreCLR; ExecutionContext is immutable } // Make sure the context was requested. if (AsyncCallback == null && (_flags & StateFlags.CaptureContext) == 0) { NetEventSource.Fail(this, "No context captured - specify a callback or forceCaptureContext."); } // Just use the lock to block. We might be on the thread that owns the lock which is great, it means we // don't need a context anyway. if ((_flags & StateFlags.PostBlockFinished) == 0) { if (_lock == null) { NetEventSource.Fail(this, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp)."); } lock (_lock) { } } if (InternalPeekCompleted) { if ((_flags & StateFlags.ThreadSafeContextCopy) == 0) { NetEventSource.Fail(this, "Result became completed during call."); } throw new InvalidOperationException(SR.net_completed_result); } return _context; // No need to copy on CoreCLR; ExecutionContext is immutable } } #if DEBUG // Want to be able to verify that the Identity was requested. If it was requested but isn't available // on the Identity property, it's either available via ContextCopy or wasn't needed (synchronous). internal bool IdentityRequested { get { return (_flags & StateFlags.CaptureIdentity) != 0; } } #endif internal object StartPostingAsyncOp() { return StartPostingAsyncOp(true); } // If ContextCopy or Identity will be used, the return value should be locked until FinishPostingAsyncOp() is called // or the operation has been aborted (e.g. by BeginXxx throwing). Otherwise, this can be called with false to prevent the lock // object from being created. internal object StartPostingAsyncOp(bool lockCapture) { if (InternalPeekCompleted) { NetEventSource.Fail(this, "Called on completed result."); } DebugProtectState(true); _lock = lockCapture ? new object() : null; _flags |= StateFlags.PostBlockStarted; return _lock; } // Call this when returning control to the user. internal bool FinishPostingAsyncOp() { // Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called. if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted) { return false; } _flags |= StateFlags.PostBlockFinished; ExecutionContext cachedContext = null; return CaptureOrComplete(ref cachedContext, false); } // Call this when returning control to the user. Allows a cached Callback Closure to be supplied and used // as appropriate, and replaced with a new one. internal bool FinishPostingAsyncOp(ref CallbackClosure closure) { // Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called. if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted) { return false; } _flags |= StateFlags.PostBlockFinished; // Need a copy of this ref argument since it can be used in many of these calls simultaneously. CallbackClosure closureCopy = closure; ExecutionContext cachedContext; if (closureCopy == null) { cachedContext = null; } else { if (!closureCopy.IsCompatible(AsyncCallback)) { // Clear the cache as soon as a method is called with incompatible parameters. closure = null; cachedContext = null; } else { // If it succeeded, we want to replace our context/callback with the one from the closure. // Using the closure's instance of the callback is probably overkill, but safer. AsyncCallback = closureCopy.AsyncCallback; cachedContext = closureCopy.Context; } } bool calledCallback = CaptureOrComplete(ref cachedContext, true); // Set up new cached context if we didn't use the previous one. if (closure == null && AsyncCallback != null && cachedContext != null) { closure = new CallbackClosure(cachedContext, AsyncCallback); } return calledCallback; } protected override void Cleanup() { base.Cleanup(); if (NetEventSource.IsEnabled) NetEventSource.Info(this); CleanupInternal(); } // This must be called right before returning the result to the user. It might call the callback itself, // to avoid flowing context. Even if the operation completes before this call, the callback won't have been // called. // // Returns whether the operation completed sync or not. private bool CaptureOrComplete(ref ExecutionContext cachedContext, bool returnContext) { if ((_flags & StateFlags.PostBlockStarted) == 0) { NetEventSource.Fail(this, "Called without calling StartPostingAsyncOp."); } // See if we're going to need to capture the context. bool capturingContext = AsyncCallback != null || (_flags & StateFlags.CaptureContext) != 0; // Peek if we've already completed, but don't fix CompletedSynchronously yet // Capture the identity if requested, unless we're going to capture the context anyway, unless // capturing the context won't be sufficient. if ((_flags & StateFlags.CaptureIdentity) != 0 && !InternalPeekCompleted && (!capturingContext)) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting identity capture"); SafeCaptureIdentity(); } // No need to flow if there's no callback, unless it's been specifically requested. // Note that Capture() can return null, for example if SuppressFlow() is in effect. if (capturingContext && !InternalPeekCompleted) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting capture"); if (cachedContext == null) { cachedContext = ExecutionContext.Capture(); } if (cachedContext != null) { if (!returnContext) { _context = cachedContext; cachedContext = null; } else { _context = cachedContext; } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context:{_context}"); } else { // Otherwise we have to have completed synchronously, or not needed the context. if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Skipping capture"); cachedContext = null; if (AsyncCallback != null && !CompletedSynchronously) { NetEventSource.Fail(this, "Didn't capture context, but didn't complete synchronously!"); } } // Now we want to see for sure what to do. We might have just captured the context for no reason. // This has to be the first time the state has been queried "for real" (apart from InvokeCallback) // to guarantee synchronization with Complete() (otherwise, Complete() could try to call the // callback without the context having been gotten). DebugProtectState(false); if (CompletedSynchronously) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Completing synchronously"); base.Complete(IntPtr.Zero); return true; } return false; } // This method is guaranteed to be called only once. If called with a non-zero userToken, the context is not flowed. protected override void Complete(IntPtr userToken) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context(set):{_context != null} userToken:{userToken}"); // If no flowing, just complete regularly. if ((_flags & StateFlags.PostBlockStarted) == 0) { base.Complete(userToken); return; } // At this point, IsCompleted is set and CompletedSynchronously is fixed. If it's synchronous, then we want to hold // the completion for the CaptureOrComplete() call to avoid the context flow. If not, we know CaptureOrComplete() has completed. if (CompletedSynchronously) { return; } ExecutionContext context = _context; // If the context is being abandoned or wasn't captured (SuppressFlow, null AsyncCallback), just // complete regularly, as long as CaptureOrComplete() has finished. // if (userToken != IntPtr.Zero || context == null) { base.Complete(userToken); return; } ExecutionContext.Run(context, s => ((ContextAwareResult)s).CompleteCallback(), this); } private void CompleteCallback() { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Context set, calling callback."); base.Complete(IntPtr.Zero); } } }
namespace Nancy { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Security.Cryptography.X509Certificates; using IO; using Nancy.Extensions; using Session; /// <summary> /// Encapsulates HTTP-request information to an Nancy application. /// </summary> public class Request : IDisposable { private readonly List<HttpFile> files = new List<HttpFile>(); private dynamic form = new DynamicDictionary(); private IDictionary<string, string> cookies; /// <summary> /// Initializes a new instance of the <see cref="Request"/> class. /// </summary> /// <param name="method">The HTTP data transfer method used by the client.</param> /// <param name="path">The path of the requested resource, relative to the "Nancy root". This should not include the scheme, host name, or query portion of the URI.</param> /// <param name="scheme">The HTTP protocol that was used by the client.</param> public Request(string method, string path, string scheme) : this(method, new Url { Path = path, Scheme = scheme }) { } /// <summary> /// Initializes a new instance of the <see cref="Request"/> class. /// </summary> /// <param name="method">The HTTP data transfer method used by the client.</param> /// <param name="url">The <see cref="Url"/>url of the requested resource</param> /// <param name="headers">The headers that was passed in by the client.</param> /// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param> /// <param name="ip">The client's IP address</param> /// <param name="certificate">The client's certificate when present.</param> /// <param name="protocolVersion">The HTTP protocol version.</param> public Request(string method, Url url, RequestStream body = null, IDictionary<string, IEnumerable<string>> headers = null, string ip = null, byte[] certificate = null, string protocolVersion = null) { if (String.IsNullOrEmpty(method)) { throw new ArgumentOutOfRangeException("method"); } if (url == null) { throw new ArgumentNullException("url"); } if (url.Path == null) { throw new ArgumentNullException("url.Path"); } if (String.IsNullOrEmpty(url.Scheme)) { throw new ArgumentOutOfRangeException("url.Scheme"); } this.UserHostAddress = ip; this.Url = url; this.Method = method; this.Query = url.Query.AsQueryDictionary(); this.Body = body ?? RequestStream.FromStream(new MemoryStream()); this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>()); this.Session = new NullSessionProvider(); if (certificate != null && certificate.Length != 0) { this.ClientCertificate = new X509Certificate2(certificate); } this.ProtocolVersion = protocolVersion ?? string.Empty; if (String.IsNullOrEmpty(this.Url.Path)) { this.Url.Path = "/"; } this.ParseFormData(); this.RewriteMethod(); } /// <summary> /// Gets the certificate sent by the client. /// </summary> public X509Certificate ClientCertificate { get; private set; } /// <summary> /// Gets the HTTP protocol version. /// </summary> public string ProtocolVersion { get; private set; } /// <summary> /// Gets the IP address of the client /// </summary> public string UserHostAddress { get; private set; } /// <summary> /// Gets or sets the HTTP data transfer method used by the client. /// </summary> /// <value>The method.</value> public string Method { get; private set; } /// <summary> /// Gets the url /// </summary> public Url Url { get; private set; } /// <summary> /// Gets the request path, relative to the base path. /// Used for route matching etc. /// </summary> public string Path { get { return this.Url.Path; } } /// <summary> /// Gets the query string data of the requested resource. /// </summary> /// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of query string data.</value> public dynamic Query { get; set; } /// <summary> /// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body /// </summary> /// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value> public RequestStream Body { get; private set; } /// <summary> /// Gets the request cookies. /// </summary> public IDictionary<string, string> Cookies { get { return this.cookies ?? (this.cookies = this.GetCookieData()); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get; set; } /// <summary> /// Gets the cookie data from the request header if it exists /// </summary> /// <returns>Cookies dictionary</returns> private IDictionary<string, string> GetCookieData() { var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (!this.Headers.Cookie.Any()) { return cookieDictionary; } var values = this.Headers["cookie"].First().TrimEnd(';').Split(';'); foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2))) { var cookieName = parts[0].Trim(); string cookieValue; if (parts.Length == 1) { //Cookie attribute cookieValue = string.Empty; } else { cookieValue = parts[1]; } cookieDictionary[cookieName] = cookieValue; } return cookieDictionary; } /// <summary> /// Gets a collection of files sent by the client- /// </summary> /// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value> public IEnumerable<HttpFile> Files { get { return this.files; } } /// <summary> /// Gets the form data of the request. /// </summary> /// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value> /// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks> public dynamic Form { get { return this.form; } } /// <summary> /// Gets the HTTP headers sent by the client. /// </summary> /// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value> /// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks> public RequestHeaders Headers { get; private set; } public void Dispose() { ((IDisposable)this.Body).Dispose(); } private void ParseFormData() { if (string.IsNullOrEmpty(this.Headers.ContentType)) { return; } var contentType = this.Headers["content-type"].First(); var mimeType = contentType.Split(';').First(); if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { var reader = new StreamReader(this.Body); this.form = reader.ReadToEnd().AsQueryDictionary(); this.Body.Position = 0; } if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase)) { return; } var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value; var multipart = new HttpMultipart(this.Body, boundary); var formValues = new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase); foreach (var httpMultipartBoundary in multipart.GetBoundaries()) { if (string.IsNullOrEmpty(httpMultipartBoundary.Filename)) { var reader = new StreamReader(httpMultipartBoundary.Value); formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd()); } else { this.files.Add(new HttpFile(httpMultipartBoundary)); } } foreach (var key in formValues.AllKeys.Where(key => key != null)) { this.form[key] = formValues[key]; } this.Body.Position = 0; } private void RewriteMethod() { if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { return; } var overrides = new List<Tuple<string, string>> { Tuple.Create("_method form input element", (string)this.Form["_method"]), Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]), Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault()) }; var providedOverride = overrides.Where(x => !string.IsNullOrEmpty(x.Item2)); if (!providedOverride.Any()) { return; } if (providedOverride.Count() > 1) { var overrideSources = string.Join(", ", providedOverride); var errorMessage = string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources); throw new InvalidOperationException(errorMessage); } this.Method = providedOverride.Single().Item2; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ServiceModel.Channels; using System.ServiceModel; using System.Collections.ObjectModel; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Tokens; using System.IdentityModel.Selectors; using System.Security.Cryptography; using System.ServiceModel.Security.Tokens; using System.Text; using System.Runtime.Serialization; using Microsoft.Xml; using System.ComponentModel; namespace System.ServiceModel.Security { public abstract class SecurityAlgorithmSuite { private static SecurityAlgorithmSuite s_basic256; private static SecurityAlgorithmSuite s_basic192; private static SecurityAlgorithmSuite s_basic128; private static SecurityAlgorithmSuite s_tripleDes; private static SecurityAlgorithmSuite s_basic256Rsa15; private static SecurityAlgorithmSuite s_basic192Rsa15; private static SecurityAlgorithmSuite s_basic128Rsa15; private static SecurityAlgorithmSuite s_tripleDesRsa15; private static SecurityAlgorithmSuite s_basic256Sha256; private static SecurityAlgorithmSuite s_basic192Sha256; private static SecurityAlgorithmSuite s_basic128Sha256; private static SecurityAlgorithmSuite s_tripleDesSha256; private static SecurityAlgorithmSuite s_basic256Sha256Rsa15; private static SecurityAlgorithmSuite s_basic192Sha256Rsa15; private static SecurityAlgorithmSuite s_basic128Sha256Rsa15; private static SecurityAlgorithmSuite s_tripleDesSha256Rsa15; static internal SecurityAlgorithmSuite KerberosDefault { get { return Basic128; } } static public SecurityAlgorithmSuite Default { get { return Basic256; } } static public SecurityAlgorithmSuite Basic256 { get { if (s_basic256 == null) s_basic256 = new Basic256SecurityAlgorithmSuite(); return s_basic256; } } static public SecurityAlgorithmSuite Basic192 { get { if (s_basic192 == null) s_basic192 = new Basic192SecurityAlgorithmSuite(); return s_basic192; } } static public SecurityAlgorithmSuite Basic128 { get { if (s_basic128 == null) s_basic128 = new Basic128SecurityAlgorithmSuite(); return s_basic128; } } static public SecurityAlgorithmSuite TripleDes { get { if (s_tripleDes == null) s_tripleDes = new TripleDesSecurityAlgorithmSuite(); return s_tripleDes; } } static public SecurityAlgorithmSuite Basic256Rsa15 { get { if (s_basic256Rsa15 == null) s_basic256Rsa15 = new Basic256Rsa15SecurityAlgorithmSuite(); return s_basic256Rsa15; } } static public SecurityAlgorithmSuite Basic192Rsa15 { get { if (s_basic192Rsa15 == null) s_basic192Rsa15 = new Basic192Rsa15SecurityAlgorithmSuite(); return s_basic192Rsa15; } } static public SecurityAlgorithmSuite Basic128Rsa15 { get { if (s_basic128Rsa15 == null) s_basic128Rsa15 = new Basic128Rsa15SecurityAlgorithmSuite(); return s_basic128Rsa15; } } static public SecurityAlgorithmSuite TripleDesRsa15 { get { if (s_tripleDesRsa15 == null) s_tripleDesRsa15 = new TripleDesRsa15SecurityAlgorithmSuite(); return s_tripleDesRsa15; } } static public SecurityAlgorithmSuite Basic256Sha256 { get { if (s_basic256Sha256 == null) s_basic256Sha256 = new Basic256Sha256SecurityAlgorithmSuite(); return s_basic256Sha256; } } static public SecurityAlgorithmSuite Basic192Sha256 { get { if (s_basic192Sha256 == null) s_basic192Sha256 = new Basic192Sha256SecurityAlgorithmSuite(); return s_basic192Sha256; } } static public SecurityAlgorithmSuite Basic128Sha256 { get { if (s_basic128Sha256 == null) s_basic128Sha256 = new Basic128Sha256SecurityAlgorithmSuite(); return s_basic128Sha256; } } static public SecurityAlgorithmSuite TripleDesSha256 { get { if (s_tripleDesSha256 == null) s_tripleDesSha256 = new TripleDesSha256SecurityAlgorithmSuite(); return s_tripleDesSha256; } } static public SecurityAlgorithmSuite Basic256Sha256Rsa15 { get { if (s_basic256Sha256Rsa15 == null) s_basic256Sha256Rsa15 = new Basic256Sha256Rsa15SecurityAlgorithmSuite(); return s_basic256Sha256Rsa15; } } static public SecurityAlgorithmSuite Basic192Sha256Rsa15 { get { if (s_basic192Sha256Rsa15 == null) s_basic192Sha256Rsa15 = new Basic192Sha256Rsa15SecurityAlgorithmSuite(); return s_basic192Sha256Rsa15; } } static public SecurityAlgorithmSuite Basic128Sha256Rsa15 { get { if (s_basic128Sha256Rsa15 == null) s_basic128Sha256Rsa15 = new Basic128Sha256Rsa15SecurityAlgorithmSuite(); return s_basic128Sha256Rsa15; } } static public SecurityAlgorithmSuite TripleDesSha256Rsa15 { get { if (s_tripleDesSha256Rsa15 == null) s_tripleDesSha256Rsa15 = new TripleDesSha256Rsa15SecurityAlgorithmSuite(); return s_tripleDesSha256Rsa15; } } public abstract string DefaultCanonicalizationAlgorithm { get; } public abstract string DefaultDigestAlgorithm { get; } public abstract string DefaultEncryptionAlgorithm { get; } public abstract int DefaultEncryptionKeyDerivationLength { get; } public abstract string DefaultSymmetricKeyWrapAlgorithm { get; } public abstract string DefaultAsymmetricKeyWrapAlgorithm { get; } public abstract string DefaultSymmetricSignatureAlgorithm { get; } public abstract string DefaultAsymmetricSignatureAlgorithm { get; } public abstract int DefaultSignatureKeyDerivationLength { get; } public abstract int DefaultSymmetricKeyLength { get; } internal virtual XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return null; } } protected SecurityAlgorithmSuite() { } public virtual bool IsCanonicalizationAlgorithmSupported(string algorithm) { return algorithm == DefaultCanonicalizationAlgorithm; } public virtual bool IsDigestAlgorithmSupported(string algorithm) { return algorithm == DefaultDigestAlgorithm; } public virtual bool IsEncryptionAlgorithmSupported(string algorithm) { return algorithm == DefaultEncryptionAlgorithm; } public virtual bool IsEncryptionKeyDerivationAlgorithmSupported(string algorithm) { return (algorithm == SecurityAlgorithms.Psha1KeyDerivation) || (algorithm == SecurityAlgorithms.Psha1KeyDerivationDec2005); } public virtual bool IsSymmetricKeyWrapAlgorithmSupported(string algorithm) { return algorithm == DefaultSymmetricKeyWrapAlgorithm; } public virtual bool IsAsymmetricKeyWrapAlgorithmSupported(string algorithm) { return algorithm == DefaultAsymmetricKeyWrapAlgorithm; } public virtual bool IsSymmetricSignatureAlgorithmSupported(string algorithm) { return algorithm == DefaultSymmetricSignatureAlgorithm; } public virtual bool IsAsymmetricSignatureAlgorithmSupported(string algorithm) { return algorithm == DefaultAsymmetricSignatureAlgorithm; } public virtual bool IsSignatureKeyDerivationAlgorithmSupported(string algorithm) { return (algorithm == SecurityAlgorithms.Psha1KeyDerivation) || (algorithm == SecurityAlgorithms.Psha1KeyDerivationDec2005); } public abstract bool IsSymmetricKeyLengthSupported(int length); public abstract bool IsAsymmetricKeyLengthSupported(int length); internal static bool IsRsaSHA256(SecurityAlgorithmSuite suite) { if (suite == null) return false; return (suite == Basic128Sha256 || suite == Basic128Sha256Rsa15 || suite == Basic192Sha256 || suite == Basic192Sha256Rsa15 || suite == Basic256Sha256 || suite == Basic256Sha256Rsa15 || suite == TripleDesSha256 || suite == TripleDesSha256Rsa15); } internal string GetEncryptionKeyDerivationAlgorithm(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) return derivationAlgorithm; else return null; } internal int GetEncryptionKeyDerivationLength(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) { if (this.DefaultEncryptionKeyDerivationLength % 8 != 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRServiceModel.Psha1KeyLengthInvalid, this.DefaultEncryptionKeyDerivationLength))); return this.DefaultEncryptionKeyDerivationLength / 8; } else return 0; } internal void GetKeyWrapAlgorithm(SecurityToken token, out string keyWrapAlgorithm, out XmlDictionaryString keyWrapAlgorithmDictionaryString) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); if (SecurityUtils.IsSupportedAlgorithm(this.DefaultSymmetricKeyWrapAlgorithm, token)) { keyWrapAlgorithm = this.DefaultSymmetricKeyWrapAlgorithm; keyWrapAlgorithmDictionaryString = this.DefaultSymmetricKeyWrapAlgorithmDictionaryString; } else { keyWrapAlgorithm = this.DefaultAsymmetricKeyWrapAlgorithm; keyWrapAlgorithmDictionaryString = this.DefaultAsymmetricKeyWrapAlgorithmDictionaryString; } } internal void GetSignatureAlgorithmAndKey(SecurityToken token, out string signatureAlgorithm, out SecurityKey key, out XmlDictionaryString signatureAlgorithmDictionaryString) { ReadOnlyCollection<SecurityKey> keys = token.SecurityKeys; if (keys == null || keys.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SigningTokenHasNoKeys, token))); } for (int i = 0; i < keys.Count; i++) { if (keys[i].IsSupportedAlgorithm(this.DefaultSymmetricSignatureAlgorithm)) { signatureAlgorithm = this.DefaultSymmetricSignatureAlgorithm; signatureAlgorithmDictionaryString = this.DefaultSymmetricSignatureAlgorithmDictionaryString; key = keys[i]; return; } else if (keys[i].IsSupportedAlgorithm(this.DefaultAsymmetricSignatureAlgorithm)) { signatureAlgorithm = this.DefaultAsymmetricSignatureAlgorithm; signatureAlgorithmDictionaryString = this.DefaultAsymmetricSignatureAlgorithmDictionaryString; key = keys[i]; return; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SigningTokenHasNoKeysSupportingTheAlgorithmSuite, token, this))); } internal string GetSignatureKeyDerivationAlgorithm(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) return derivationAlgorithm; else return null; } internal int GetSignatureKeyDerivationLength(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) { if (this.DefaultSignatureKeyDerivationLength % 8 != 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRServiceModel.Psha1KeyLengthInvalid, this.DefaultSignatureKeyDerivationLength))); return this.DefaultSignatureKeyDerivationLength / 8; } else return 0; } internal void EnsureAcceptableSymmetricSignatureAlgorithm(string algorithm) { if (!IsSymmetricSignatureAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(string.Format(SRServiceModel.SuiteDoesNotAcceptAlgorithm, algorithm, "SymmetricSignature", this))); } } } public class Basic256SecurityAlgorithmSuite : SecurityAlgorithmSuite { public Basic256SecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 256; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 192; } } public override int DefaultSymmetricKeyLength { get { return 256; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length == 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes256Encryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes256KeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "Basic256"; } } public class Basic192SecurityAlgorithmSuite : SecurityAlgorithmSuite { public Basic192SecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 192; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 192; } } public override int DefaultSymmetricKeyLength { get { return 192; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length >= 192 && length <= 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes192Encryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes192KeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "Basic192"; } } public class Basic128SecurityAlgorithmSuite : SecurityAlgorithmSuite { public Basic128SecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return this.DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return this.DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return this.DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 128; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return this.DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return this.DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return this.DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return this.DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 128; } } public override int DefaultSymmetricKeyLength { get { return 128; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length >= 128 && length <= 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes128Encryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes128KeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "Basic128"; } } public class TripleDesSecurityAlgorithmSuite : SecurityAlgorithmSuite { public TripleDesSecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 192; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return this.DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 192; } } public override int DefaultSymmetricKeyLength { get { return 192; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length >= 192 && length <= 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.TripleDesEncryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.TripleDesKeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "TripleDes"; } } internal class Basic128Rsa15SecurityAlgorithmSuite : Basic128SecurityAlgorithmSuite { public Basic128Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "Basic128Rsa15"; } } internal class Basic192Rsa15SecurityAlgorithmSuite : Basic192SecurityAlgorithmSuite { public Basic192Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "Basic192Rsa15"; } } internal class Basic256Rsa15SecurityAlgorithmSuite : Basic256SecurityAlgorithmSuite { public Basic256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "Basic256Rsa15"; } } internal class TripleDesRsa15SecurityAlgorithmSuite : TripleDesSecurityAlgorithmSuite { public TripleDesRsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "TripleDesRsa15"; } } internal class Basic256Sha256SecurityAlgorithmSuite : Basic256SecurityAlgorithmSuite { public Basic256Sha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic256Sha256"; } } internal class Basic192Sha256SecurityAlgorithmSuite : Basic192SecurityAlgorithmSuite { public Basic192Sha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic192Sha256"; } } internal class Basic128Sha256SecurityAlgorithmSuite : Basic128SecurityAlgorithmSuite { public Basic128Sha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic128Sha256"; } } internal class TripleDesSha256SecurityAlgorithmSuite : TripleDesSecurityAlgorithmSuite { public TripleDesSha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "TripleDesSha256"; } } internal class Basic256Sha256Rsa15SecurityAlgorithmSuite : Basic256Rsa15SecurityAlgorithmSuite { public Basic256Sha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic256Sha256Rsa15"; } } internal class Basic192Sha256Rsa15SecurityAlgorithmSuite : Basic192Rsa15SecurityAlgorithmSuite { public Basic192Sha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic192Sha256Rsa15"; } } internal class Basic128Sha256Rsa15SecurityAlgorithmSuite : Basic128Rsa15SecurityAlgorithmSuite { public Basic128Sha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic128Sha256Rsa15"; } } internal class TripleDesSha256Rsa15SecurityAlgorithmSuite : TripleDesRsa15SecurityAlgorithmSuite { public TripleDesSha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "TripleDesSha256Rsa15"; } } }
#region License, Terms and Author(s) // // Gurtle - IBugTraqProvider for Google Code // Copyright (c) 2008, 2009 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace Gurtle { #region Imports using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Web; #endregion internal static class StringExtensions { /// <summary> /// Masks an empty string with a given mask such that the result /// is never an empty string. If the input string is null or /// empty then it is masked, otherwise the original is returned. /// </summary> /// <remarks> /// Use this method to guarantee that you never get an empty /// string. Note that if the mask itself is an empty string then /// this method could yield an empty string! /// </remarks> [DebuggerStepThrough] public static string MaskEmpty(this string str, string mask) { return !string.IsNullOrEmpty(str) ? str : mask; } [DebuggerStepThrough] public static string MaskEmpty(this string str) { return !string.IsNullOrEmpty(str) ? str : string.Empty; } /// <summary> /// Masks the null value. If the given string is null then the /// result is an empty string otherwise it is the original string. /// </summary> /// <remarks> /// Use this method to guarantee that you never get a null string /// and where the distinction between a null and an empty string /// is irrelevant. /// </remarks> [DebuggerStepThrough] public static string MaskNull(this string str) { return str ?? string.Empty; } [DebuggerStepThrough] public static string MaskNull(this string str, string mask) { return str ?? mask.MaskNull(); } /// <summary> /// Returns a section of a string. /// </summary> /// <remarks> /// The slice method copies up to, but not including, the element /// indicated by end. If start is negative, it is treated as length + /// start where length is the length of the string. If end is negative, /// it is treated as length + end where length is the length of the /// string. If end occurs before start, no characters are copied to the /// new string. /// </remarks> public static string Slice(this string str, int? start, int? end) { return Slice(str, start ?? 0, end ?? str.MaskNull().Length); } public static string Slice(this string str, int start) { return Slice(str, start, null); } public static string Slice(this string str, int start, int end) { var length = str.MaskNull().Length; if (start < 0) { start = length + start; if (start < 0) start = 0; } else { if (start > length) start = length; } if (end < 0) { end = length + end; if (end < 0) end = 0; } else { if (end > length) end = length; } var sliceLength = end - start; return sliceLength > 0 ? str.Substring(start, sliceLength) : string.Empty; } public static string FormatWith(this string format, params object[] args) { return format.FormatWith(null, null, args); } public static string FormatWith(this string format, IFormatProvider provider, params object[] args) { return format.FormatWith(provider, null, args); } public static string FormatWith(this string format, Func<string, object[], IFormatProvider, string> binder, params object[] args) { return format.FormatWith(null, binder, args); } public static string FormatWith(this string format, IFormatProvider provider, Func<string, object[], IFormatProvider, string> binder, params object[] args) { return format.FormatWithImpl(provider, binder ?? FormatTokenBinder, args); } private static string FormatWithImpl(this string format, IFormatProvider provider, Func<string, object[], IFormatProvider, string> binder, params object[] args) { if (format == null) throw new ArgumentNullException("format"); Debug.Assert(binder != null); var result = new StringBuilder(format.Length * 2); var token = new StringBuilder(); var e = format.GetEnumerator(); while (e.MoveNext()) { var ch = e.Current; if (ch == '{') { while (true) { if (!e.MoveNext()) throw new FormatException(); ch = e.Current; if (ch == '}') { if (token.Length == 0) throw new FormatException(); result.Append(binder(token.ToString(), args, provider)); token.Length = 0; break; } if (ch == '{') { result.Append(ch); break; } token.Append(ch); } } else if (ch == '}') { if (!e.MoveNext() || e.Current != '}') throw new FormatException(); result.Append('}'); } else { result.Append(ch); } } return result.ToString(); } private static string FormatTokenBinder(string token, object[] args, IFormatProvider provider) { Debug.Assert(token != null); var source = args[0]; var dotIndex = token.IndexOf('.'); int sourceIndex; if (dotIndex > 0 && int.TryParse(token.Substring(0, dotIndex), NumberStyles.None, CultureInfo.InvariantCulture, out sourceIndex)) { source = args[sourceIndex]; token = token.Substring(dotIndex + 1); } var format = string.Empty; var colonIndex = token.IndexOf(':'); if (colonIndex > 0) { format = "{0:" + token.Substring(colonIndex + 1) + "}"; token = token.Substring(0, colonIndex); } if (int.TryParse(token, NumberStyles.None, CultureInfo.InvariantCulture, out sourceIndex)) { source = args[sourceIndex]; token = null; } object result; try { result = source.DataBind(token) ?? string.Empty; } catch (HttpException e) { throw new FormatException(e.Message, e); } return !string.IsNullOrEmpty(format) ? string.Format(provider, format, result) : result.ToString(); } /// <summary> /// Splits a string into a key and a value part using a specified /// character to separate the two. /// </summary> /// <remarks> /// The key or value of the resulting pair is never <c>null</c>. /// </remarks> public static KeyValuePair<string, string> SplitPair(this string str, char separator) { if (str == null) throw new ArgumentNullException("str"); return SplitPair(str, str.IndexOf(separator), 1); } /// <summary> /// Splits a string into a key and a value part using any of a /// specified set of characters to separate the two. /// </summary> /// <remarks> /// The key or value of the resulting pair is never <c>null</c>. /// </remarks> public static KeyValuePair<string, string> SplitPair(this string str, params char[] separators) { if (str == null) throw new ArgumentNullException("str"); return separators == null || separators.Length == 0 ? new KeyValuePair<string, string>(str, string.Empty) : SplitPair(str, str.IndexOfAny(separators), 1); } /// <summary> /// Splits a string into a key and a value part by removing a /// portion of the string. /// </summary> /// <remarks> /// The key or value of the resulting pair is never <c>null</c>. /// </remarks> public static KeyValuePair<string, string> SplitPair(this string str, int index, int count) { if (str == null) throw new ArgumentNullException("str"); if (count <= 0) throw new ArgumentOutOfRangeException("count", count, null); return new KeyValuePair<string, string>( /* key */ index < 0 ? str : str.Substring(0, index), /* value */ index < 0 || index + 1 >= str.Length ? string.Empty : str.Substring(index + count)); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.Messaging; namespace MGTK.Controls { public class InnerScrollbar : Control { private int totalNrItems; private int nrItemsPerPage; private int index = 0; private double sizePerItem = 1; private bool mouseDown = false; private int sbPosWhenMouseDown = 0; private int mousePosWhenMouseDown = 0; private int indexWhenMouseDown = 0; private double TotalMilliseconds = 0; private double LastUpdateNextPage = 0; private int MsToNextPage = 300; public ScrollBarType Type; public int TotalNrItems { get { return totalNrItems; } set { if (totalNrItems != value) { totalNrItems = value; ConfigureBar(); } } } public int NrItemsPerPage { get { return nrItemsPerPage; } set { if (nrItemsPerPage != value) { nrItemsPerPage = value; ConfigureBar(); } } } public int Index { get { return index; } set { if (value != index) { int _si = index; index = value; if (index < 0) index = 0; else { if (TotalNrItems >= NrItemsPerPage) { if (index > TotalNrItems - NrItemsPerPage) index = TotalNrItems - NrItemsPerPage; } else index = 0; } if (IndexChanged != null && _si != index) IndexChanged(this, new EventArgs()); ConfigureBar(); } } } public double SizePerItem { get { return sizePerItem; } set { if (value != sizePerItem) { sizePerItem = value; ConfigureBar(); } } } public event EventHandler IndexChanged; Button Bar; public InnerScrollbar(Form formowner) : base(formowner) { Bar = new Button(formowner); Bar.FramePressed = Theme.Frame; Bar.MouseLeftPressed += new EventHandler(Bar_MouseLeftPressed); Bar.Parent = this; Bar.DepressImageOnPress = false; Controls.Add(Bar); this.Init += new EventHandler(InnerScrollbar_Init); } void InnerScrollbar_Init(object sender, EventArgs e) { Bar.Image = Type == ScrollBarType.Horizontal ? Theme.HorizontalHandle : Theme.VerticalHandle; } void Bar_MouseLeftPressed(object sender, EventArgs e) { if (!mouseDown) { sbPosWhenMouseDown = GetScrollBarPos(); mousePosWhenMouseDown = GetMousePos(); indexWhenMouseDown = Index; mouseDown = true; } } private int GetMousePos() { return Type == ScrollBarType.Horizontal ? WindowManager.MouseX : WindowManager.MouseY; } public override void Update() { TotalMilliseconds = gameTime.TotalGameTime.TotalMilliseconds; if (!WindowManager.MouseLeftPressed) mouseDown = false; if (mouseDown) Index = (int)(indexWhenMouseDown + (GetMousePos() - mousePosWhenMouseDown) / SizePerItem); base.Update(); } private int GetScrollBarSize() { int sbSize; int opposedSize = Type == ScrollBarType.Horizontal ? Width : Height; if (NrItemsPerPage > TotalNrItems) sbSize = opposedSize; else sbSize = (int)(opposedSize - (TotalNrItems - NrItemsPerPage) * SizePerItem); return sbSize; } private int GetScrollBarPos() { int sbPos; if (NrItemsPerPage > totalNrItems) sbPos = 0; else sbPos = (int)(Index * SizePerItem); return sbPos; } public void ConfigureBar() { int sizeUsed = Type == ScrollBarType.Horizontal ? Width : Height; if (sizeUsed > 0 && (TotalNrItems - NrItemsPerPage) * SizePerItem > sizeUsed) SizePerItem = (double)sizeUsed / (double)TotalNrItems; if (Type == ScrollBarType.Horizontal) { Bar.Width = GetScrollBarSize(); Bar.Height = Height; Bar.X = GetScrollBarPos(); Bar.Y = 0; } else { Bar.Width = Width; Bar.Height = GetScrollBarSize(); Bar.X = 0; Bar.Y = GetScrollBarPos(); } } public override bool ReceiveMessage(MessageEnum message, object msgTag) { switch (message) { case MessageEnum.MouseLeftDown: if (Focused && MouseIsOnControl()) { if (TotalMilliseconds - LastUpdateNextPage > MsToNextPage) { if (Type == ScrollBarType.Horizontal) { if ((WindowManager.MouseX < OwnerX + Bar.X) || (WindowManager.MouseX > OwnerX + Bar.X + Bar.Width)) Index += ((WindowManager.MouseX < OwnerX + Bar.X) ? -1 : 1) * NrItemsPerPage; } else { if ((WindowManager.MouseY < OwnerY + Bar.Y) || (WindowManager.MouseY > OwnerY + Bar.Y + Bar.Height)) Index += ((WindowManager.MouseY < OwnerY + Bar.Y) ? -1 : 1) * NrItemsPerPage; } LastUpdateNextPage = TotalMilliseconds; } } break; } return base.ReceiveMessage(message, msgTag); } } public enum ScrollBarType { Horizontal = 0, Vertical = 1 } }
using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; using Orleans.Runtime.Scheduler; using Orleans.Providers; using System.Collections.Generic; namespace Orleans.Hosting { public static class LegacyClusterConfigurationExtensions { /// <summary> /// Specifies the configuration to use for this silo. /// </summary> /// <param name="builder">The host builder.</param> /// <param name="configuration">The configuration.</param> /// <remarks>This method may only be called once per builder instance.</remarks> /// <returns>The silo builder.</returns> public static ISiloHostBuilder UseConfiguration(this ISiloHostBuilder builder, ClusterConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); return builder.ConfigureServices((context, services) => { services.AddLegacyClusterConfigurationSupport(configuration); }); } /// <summary> /// Loads <see cref="ClusterConfiguration"/> using <see cref="ClusterConfiguration.StandardLoad"/>. /// </summary> /// <param name="builder">The host builder.</param> /// <returns>The silo builder.</returns> public static ISiloHostBuilder LoadClusterConfiguration(this ISiloHostBuilder builder) { var configuration = new ClusterConfiguration(); configuration.StandardLoad(); return builder.UseConfiguration(configuration); } /// <summary> /// Configures a localhost silo. /// </summary> /// <param name="builder">The host builder.</param> /// <param name="siloPort">The silo-to-silo communication port.</param> /// <param name="gatewayPort">The client-to-silo communication port.</param> /// <returns>The silo builder.</returns> public static ISiloHostBuilder ConfigureLocalHostPrimarySilo(this ISiloHostBuilder builder, int siloPort = 22222, int gatewayPort = 40000) { builder.ConfigureSiloName(Silo.PrimarySiloName); return builder.UseConfiguration(ClusterConfiguration.LocalhostPrimarySilo(siloPort, gatewayPort)); } public static IServiceCollection AddLegacyClusterConfigurationSupport(this IServiceCollection services, ClusterConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); if (services.TryGetClusterConfiguration() != null) { throw new InvalidOperationException("Cannot configure legacy ClusterConfiguration support twice"); } // these will eventually be removed once our code doesn't depend on the old ClientConfiguration services.AddSingleton(configuration); services.TryAddSingleton<LegacyConfigurationWrapper>(); services.TryAddSingleton(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().ClusterConfig.Globals); services.TryAddTransient(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().NodeConfig); services.TryAddSingleton<Factory<NodeConfiguration>>( sp => { var initializationParams = sp.GetRequiredService<LegacyConfigurationWrapper>(); return () => initializationParams.NodeConfig; }); services.Configure<ClusterOptions>(options => { if (string.IsNullOrWhiteSpace(options.ClusterId) && !string.IsNullOrWhiteSpace(configuration.Globals.ClusterId)) { options.ClusterId = configuration.Globals.ClusterId; } if (options.ServiceId == Guid.Empty) { options.ServiceId = configuration.Globals.ServiceId; } }); services.Configure<MultiClusterOptions>(options => { var globals = configuration.Globals; if (globals.HasMultiClusterNetwork) { options.HasMultiClusterNetwork = true; options.BackgroundGossipInterval = globals.BackgroundGossipInterval; options.DefaultMultiCluster = globals.DefaultMultiCluster?.ToList(); options.GlobalSingleInstanceNumberRetries = globals.GlobalSingleInstanceNumberRetries; options.GlobalSingleInstanceRetryInterval = globals.GlobalSingleInstanceRetryInterval; options.MaxMultiClusterGateways = globals.MaxMultiClusterGateways; options.UseGlobalSingleInstanceByDefault = globals.UseGlobalSingleInstanceByDefault; foreach(GlobalConfiguration.GossipChannelConfiguration channelConfig in globals.GossipChannels) { options.GossipChannels.Add(GlobalConfiguration.Remap(channelConfig.ChannelType), channelConfig.ConnectionString); } } }); services.TryAddFromExisting<IMessagingConfiguration, GlobalConfiguration>(); services.AddOptions<SiloStatisticsOptions>() .Configure<NodeConfiguration>((options, nodeConfig) => LegacyConfigurationExtensions.CopyStatisticsOptions(nodeConfig, options)) .Configure<GlobalConfiguration>((options, config) => { options.DeploymentLoadPublisherRefreshTime = config.DeploymentLoadPublisherRefreshTime; }); services.AddOptions<LoadSheddingOptions>() .Configure<NodeConfiguration>((options, nodeConfig) => { options.LoadSheddingEnabled = nodeConfig.LoadSheddingEnabled; options.LoadSheddingLimit = nodeConfig.LoadSheddingLimit; }); // Translate legacy configuration to new Options services.AddOptions<SiloMessagingOptions>() .Configure<GlobalConfiguration>((options, config) => { LegacyConfigurationExtensions.CopyCommonMessagingOptions(config, options); options.SiloSenderQueues = config.SiloSenderQueues; options.GatewaySenderQueues = config.GatewaySenderQueues; options.MaxForwardCount = config.MaxForwardCount; options.ClientDropTimeout = config.ClientDropTimeout; options.ClientRegistrationRefresh = config.ClientRegistrationRefresh; options.MaxRequestProcessingTime = config.MaxRequestProcessingTime; options.AssumeHomogenousSilosForTesting = config.AssumeHomogenousSilosForTesting; }) .Configure<NodeConfiguration>((options, config) => { options.PropagateActivityId = config.PropagateActivityId; LimitValue requestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS); options.MaxEnqueuedRequestsSoftLimit = requestLimit.SoftLimitThreshold; options.MaxEnqueuedRequestsHardLimit = requestLimit.HardLimitThreshold; LimitValue statelessWorkerRequestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER); options.MaxEnqueuedRequestsSoftLimit_StatelessWorker = statelessWorkerRequestLimit.SoftLimitThreshold; options.MaxEnqueuedRequestsHardLimit_StatelessWorker = statelessWorkerRequestLimit.HardLimitThreshold; }); services.Configure<NetworkingOptions>(options => LegacyConfigurationExtensions.CopyNetworkingOptions(configuration.Globals, options)); services.AddOptions<EndpointOptions>() .Configure<IOptions<SiloOptions>>((options, siloOptions) => { var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName); if (!string.IsNullOrEmpty(nodeConfig.HostNameOrIPAddress) || nodeConfig.Port != 0) { options.AdvertisedIPAddress = nodeConfig.Endpoint.Address; options.SiloPort = nodeConfig.Endpoint.Port; } }); services.Configure<SerializationProviderOptions>(options => { options.SerializationProviders = configuration.Globals.SerializationProviders; options.FallbackSerializationProvider = configuration.Globals.FallbackSerializationProvider; }); services.Configure<TelemetryOptions>(options => { LegacyConfigurationExtensions.CopyTelemetryOptions(configuration.Defaults.TelemetryConfiguration, services, options); }); services.AddOptions<GrainClassOptions>().Configure<IOptions<SiloOptions>>((options, siloOptions) => { var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName); options.ExcludedGrainTypes.AddRange(nodeConfig.ExcludedGrainTypes); }); LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, services); services.AddOptions<SchedulingOptions>() .Configure<GlobalConfiguration>((options, config) => { options.AllowCallChainReentrancy = config.AllowCallChainReentrancy; options.PerformDeadlockDetection = config.PerformDeadlockDetection; }) .Configure<NodeConfiguration>((options, nodeConfig) => { options.MaxActiveThreads = nodeConfig.MaxActiveThreads; options.DelayWarningThreshold = nodeConfig.DelayWarningThreshold; options.ActivationSchedulingQuantum = nodeConfig.ActivationSchedulingQuantum; options.TurnWarningLengthThreshold = nodeConfig.TurnWarningLengthThreshold; options.EnableWorkerThreadInjection = nodeConfig.EnableWorkerThreadInjection; LimitValue itemLimit = nodeConfig.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS); options.MaxPendingWorkItemsSoftLimit = itemLimit.SoftLimitThreshold; options.MaxPendingWorkItemsHardLimit = itemLimit.HardLimitThreshold; }); services.AddOptions<GrainCollectionOptions>().Configure<GlobalConfiguration>((options, config) => { options.CollectionQuantum = config.CollectionQuantum; options.CollectionAge = config.Application.DefaultCollectionAgeLimit; foreach (GrainTypeConfiguration grainConfig in config.Application.ClassSpecific) { if(grainConfig.CollectionAgeLimit.HasValue) { options.ClassSpecificCollectionAge.Add(grainConfig.FullTypeName, grainConfig.CollectionAgeLimit.Value); } }; }); LegacyProviderConfigurator<ISiloLifecycle>.ConfigureServices(configuration.Globals.ProviderConfigurations, services); services.AddOptions<GrainPlacementOptions>().Configure<GlobalConfiguration>((options, config) => { options.DefaultPlacementStrategy = config.DefaultPlacementStrategy; options.ActivationCountPlacementChooseOutOf = config.ActivationCountBasedPlacementChooseOutOf; }); services.AddOptions<StaticClusterDeploymentOptions>().Configure<ClusterConfiguration>((options, config) => { options.SiloNames = config.Overrides.Keys.ToList(); }); // add grain service configs as keyed services short id = 0; foreach (IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values) { services.AddSingletonKeyedService<long, IGrainServiceConfiguration>(id++, (sp, k) => grainServiceConfiguration); } // populate grain service options id = 0; services.AddOptions<GrainServiceOptions>().Configure<GlobalConfiguration>((options, config) => { foreach(IGrainServiceConfiguration grainServiceConfiguration in config.GrainServiceConfigurations.GrainServices.Values) { options.GrainServices.Add(new KeyValuePair<string, short>(grainServiceConfiguration.ServiceType, id++)); } }); services.AddOptions<ConsistentRingOptions>().Configure<GlobalConfiguration>((options, config) => { options.UseVirtualBucketsConsistentRing = config.UseVirtualBucketsConsistentRing; options.NumVirtualBucketsConsistentRing = config.NumVirtualBucketsConsistentRing; }); services.AddOptions<MembershipOptions>() .Configure<GlobalConfiguration>((options, config) => { options.NumMissedTableIAmAliveLimit = config.NumMissedTableIAmAliveLimit; options.LivenessEnabled = config.LivenessEnabled; options.ProbeTimeout = config.ProbeTimeout; options.TableRefreshTimeout = config.TableRefreshTimeout; options.DeathVoteExpirationTimeout = config.DeathVoteExpirationTimeout; options.IAmAliveTablePublishTimeout = config.IAmAliveTablePublishTimeout; options.MaxJoinAttemptTime = config.MaxJoinAttemptTime; options.ExpectedClusterSize = config.ExpectedClusterSize; options.ValidateInitialConnectivity = config.ValidateInitialConnectivity; options.NumMissedProbesLimit = config.NumMissedProbesLimit; options.UseLivenessGossip = config.UseLivenessGossip; options.NumProbedSilos = config.NumProbedSilos; options.NumVotesForDeathDeclaration = config.NumVotesForDeathDeclaration; }) .Configure<ClusterConfiguration>((options, config) => { options.IsRunningAsUnitTest = config.IsRunningAsUnitTest; }); LegacyRemindersConfigurator.Configure(configuration.Globals, services); services.AddOptions<GrainVersioningOptions>() .Configure<GlobalConfiguration>((options, config) => { options.DefaultCompatibilityStrategy = config.DefaultCompatibilityStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_COMPATABILITY_STRATEGY; options.DefaultVersionSelectorStrategy = config.DefaultVersionSelectorStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_VERSION_SELECTOR_STRATEGY; }); services.AddOptions<PerformanceTuningOptions>() .Configure<NodeConfiguration>((options, config) => { options.DefaultConnectionLimit = config.DefaultConnectionLimit; options.Expect100Continue = config.Expect100Continue; options.UseNagleAlgorithm = config.UseNagleAlgorithm; options.MinDotNetThreadPoolSize = config.MinDotNetThreadPoolSize; }); services.AddOptions<TypeManagementOptions>() .Configure<GlobalConfiguration>((options, config) => { options.TypeMapRefreshInterval = config.TypeMapRefreshInterval; }); services.AddOptions<GrainDirectoryOptions>() .Configure<GlobalConfiguration>((options, config) => { options.CachingStrategy = Remap(config.DirectoryCachingStrategy); options.CacheSize = config.CacheSize; options.InitialCacheTTL = config.InitialCacheTTL; options.MaximumCacheTTL = config.MaximumCacheTTL; options.CacheTTLExtensionFactor = config.CacheTTLExtensionFactor; options.LazyDeregistrationDelay = config.DirectoryLazyDeregistrationDelay; }); return services; } public static ClusterConfiguration TryGetClusterConfiguration(this IServiceCollection services) { return services .FirstOrDefault(s => s.ServiceType == typeof(ClusterConfiguration)) ?.ImplementationInstance as ClusterConfiguration; } private static GrainDirectoryOptions.CachingStrategyType Remap(GlobalConfiguration.DirectoryCachingStrategyType type) { switch (type) { case GlobalConfiguration.DirectoryCachingStrategyType.None: return GrainDirectoryOptions.CachingStrategyType.None; case GlobalConfiguration.DirectoryCachingStrategyType.LRU: return GrainDirectoryOptions.CachingStrategyType.LRU; case GlobalConfiguration.DirectoryCachingStrategyType.Adaptive: return GrainDirectoryOptions.CachingStrategyType.Adaptive; default: throw new NotSupportedException($"DirectoryCachingStrategyType {type} is not supported"); } } } }
using System; using Xunit; namespace KellyStuard.Noip.UnitTest { public sealed class QueryStringBuilderTests { [Fact] public void NewBuilderShouldBeEmpty() { // arrange var builder = new QueryStringBuilder(); // act var result = builder.ToString(); // assert Assert.Equal("", result); } [Fact] public void BuilderWithNullsShouldThrow() { // arrange var builder = new QueryStringBuilder(); // act Action result = () => builder.Add(null, (string)null); // assert Assert.Throws<ArgumentNullException>("name", result); } [Fact] public void BuilderWithNullNameShouldThrow() { // arrange var builder = new QueryStringBuilder(); // act Action result = () => builder.Add(null, "bar"); // assert Assert.Throws<ArgumentNullException>("name", result); } [Fact] public void BuilderWithNullValueShouldThrow() { // arrange var builder = new QueryStringBuilder(); // act Action result = () => builder.Add("foo", (string)null); // assert Assert.Throws<ArgumentNullException>("value", result); } [Fact] public void BuilderWithNullValuesShouldThrow() { // arrange var builder = new QueryStringBuilder(); // act Action result = () => builder.Add("foo", new string[] { null }); // assert Assert.Throws<ArgumentNullException>("value", result); } [Fact] public void BuilderWithSingleAddShouldHaveSingleParam() { // arrange var builder = new QueryStringBuilder(); // act builder.Add("first", "value"); var result = builder.ToString(); // assert Assert.Equal("?first=value", result); } [Fact] public void BuilderWithDoubleAddShouldHaveDoubleParam() { // arrange var builder = new QueryStringBuilder(); // act builder.Add("first", "value1"); builder.Add("second", "value2"); var result = builder.ToString(); // assert Assert.Equal("?first=value1&second=value2", result); } [Fact] public void BuilderWithDoubleAddSameKeyShouldHaveSingleParam() { // arrange var builder = new QueryStringBuilder(); // act builder.Add("first", "value1"); builder.Add("first", "value2"); var result = builder.ToString(); // assert Assert.Equal("?first=value1,value2", result); } [Fact] public void BuilderWithSingleAddListShouldHaveSingleParam() { // arrange var builder = new QueryStringBuilder(); // act builder.Add("first", "value1", "value2"); var result = builder.ToString(); // assert Assert.Equal("?first=value1,value2", result); } [Fact] public void BuilderWithRemoveNullShouldThrow() { // arrange var builder = new QueryStringBuilder(); // act Action result = () => builder.Remove(null); // assert Assert.Throws<ArgumentNullException>("name", result); } [Fact] public void BuilderWithRemoveEmptyShouldHaveReturnFalseAndBeEmpty() { // arrange var builder = new QueryStringBuilder(); // act var removed = builder.Remove("first"); var result = builder.ToString(); // assert Assert.False(removed); Assert.Equal("", result); } [Fact] public void BuilderWithAddRemoveShouldHaveReturnTrueAndBeEmpty() { // arrange var builder = new QueryStringBuilder(); // act builder.Add("first", "value"); var removed = builder.Remove("first"); var result = builder.ToString(); // assert Assert.True(removed); Assert.Equal("", result); } [Fact] public void BuilderWithEmptyResetShouldBeEmpty() { // arrange var builder = new QueryStringBuilder(); // act builder.Reset(); var result = builder.ToString(); // assert Assert.Equal("", result); } [Fact] public void BuilderWithSingleAddResetShouldBeEmpty() { // arrange var builder = new QueryStringBuilder(); // act builder.Add("first", "value"); builder.Reset(); var result = builder.ToString(); // assert Assert.Equal("", result); } [Fact] public void EmptyBuilderToStringShouldBeEmpty() { // arrange var builder = new QueryStringBuilder(); // act var result = builder.ToString(); // assert Assert.Equal("", result); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Primitives; using Xunit; namespace NetEscapades.Configuration.KubeSecrets.Tests { public class KubeSecretsConfigurationTests { [Fact] public void ThrowsWhenNotOptionalAndNoSecrets() { Assert.Throws<DirectoryNotFoundException>( () => new ConfigurationBuilder() .AddKubeSecrets(new NonExistantDirectoryProvider()) .Build()); } [Fact] public void ThrowsWhenProviderReturnsNull() { var provider = new NullFileProvider(); var error = Assert.Throws<DirectoryNotFoundException>(() => new ConfigurationBuilder().AddKubeSecrets(provider, optional: false).Build()); } [Fact] public void DoesNotThrowWhenOptionalAndNoSecrets() { new ConfigurationBuilder() .AddKubeSecrets(new TestFileProvider(), optional: true) .Build(); } [Fact] public void CanLoadMultipleSecrets() { var testFileProvider = new TestFileProvider( new TestFile("Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2")); var config = new ConfigurationBuilder() .AddKubeSecrets(testFileProvider) .Build(); Assert.Equal("SecretValue1", config["Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanLoadMultipleSecretsWithDirectory() { var testFileProvider = new TestFileProvider( new TestFile("Secret1", "SecretValue1"), new TestFile("Secret2", "SecretValue2"), new TestFile("directory")); var config = new ConfigurationBuilder() .AddKubeSecrets(testFileProvider) .Build(); Assert.Equal("SecretValue1", config["Secret1"]); Assert.Equal("SecretValue2", config["Secret2"]); } [Fact] public void CanLoadNestedKeys() { var testFileProvider = new TestFileProvider( new TestFile("Secret0__Secret1__Secret2__Key", "SecretValue2"), new TestFile("Secret0__Secret1__Key", "SecretValue1"), new TestFile("Secret0__Key", "SecretValue0")); var config = new ConfigurationBuilder() .AddKubeSecrets(testFileProvider) .Build(); Assert.Equal("SecretValue0", config["Secret0:Key"]); Assert.Equal("SecretValue1", config["Secret0:Secret1:Key"]); Assert.Equal("SecretValue2", config["Secret0:Secret1:Secret2:Key"]); } } class NonExistantDirectoryProvider : IFileProvider { public IDirectoryContents GetDirectoryContents(string subpath) { return new NonExistantDirectory(); } public IFileInfo GetFileInfo(string subpath) => throw new NotImplementedException(); public IChangeToken Watch(string filter) => throw new NotImplementedException(); } class NullFileProvider : IFileProvider { public IDirectoryContents GetDirectoryContents(string subpath) { return null; } public IFileInfo GetFileInfo(string subpath) { return null; } public IChangeToken Watch(string filter) { return null; } } class NonExistantDirectory : IDirectoryContents { public bool Exists => false; public IEnumerator<IFileInfo> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } class TestFileProvider : IFileProvider { IDirectoryContents _contents; public TestFileProvider(params IFileInfo[] files) { _contents = new TestDirectoryContents(files); } public IDirectoryContents GetDirectoryContents(string subpath) { return _contents; } public IFileInfo GetFileInfo(string subpath) { throw new NotImplementedException(); } public IChangeToken Watch(string filter) { throw new NotImplementedException(); } } class TestDirectoryContents : IDirectoryContents { List<IFileInfo> _list; public TestDirectoryContents(params IFileInfo[] files) { _list = new List<IFileInfo>(files); } public bool Exists { get { return true; } } public IEnumerator<IFileInfo> GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } //TODO: Probably need a directory and file type. class TestFile : IFileInfo { private string _name; private string _contents; public bool Exists { get { return true; } } public bool IsDirectory { get; } public DateTimeOffset LastModified { get { throw new NotImplementedException(); } } public long Length { get { throw new NotImplementedException(); } } public string Name { get { return _name; } } public string PhysicalPath { get { throw new NotImplementedException(); } } public TestFile(string name) { _name = name; IsDirectory = true; } public TestFile(string name, string contents) { _name = name; _contents = contents; } public Stream CreateReadStream() { if (IsDirectory) { throw new InvalidOperationException("Cannot create stream from directory"); } return new MemoryStream(Encoding.UTF8.GetBytes(_contents)); } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Threading; using log4net; using MindTouch.Collections; using MindTouch.Tasking; namespace MindTouch.Threading { internal sealed class DispatchThread { //--- Class Fields --- [ThreadStatic] public static DispatchThread CurrentThread; private static readonly ILog _log = LogUtils.CreateLog(); //--- Class Methods --- public static bool TryQueueWorkItem(IDispatchQueue queue, Action callback) { DispatchThread current = CurrentThread; if((current != null) && ReferenceEquals(Async.CurrentDispatchQueue, queue)) { // NOTE (steveb): next call can never fail since we're calling the queue work-item method of the current thread current.QueueWorkItem(callback); return true; } return false; } //--- Fields --- private readonly WorkStealingDeque<Action> _inbox = new WorkStealingDeque<Action>(); private readonly int _id; private volatile IDispatchHost _host; private IDispatchQueue _queue; //--- Constructors --- internal DispatchThread() { // create new thread var thread = Async.MaxStackSize.HasValue ? new Thread(DispatchLoop, Async.MaxStackSize.Value) { IsBackground = true } : new Thread(DispatchLoop) { IsBackground = true }; // assign ID _id = thread.ManagedThreadId; thread.Name = "DispatchThread #" + _id; _log.DebugFormat("DispatchThread #{0} created", _id); // kick-off new thread thread.Start(); } //--- Properties --- public int Id { get { return _id; } } public int PendingWorkItemCount { get { return _inbox.Count; } } public IDispatchQueue DispatchQueue { get { return _queue; } } public IDispatchHost Host { get { return _host; } internal set { // check if host is being set or cleared if(value != null) { if(_host != null) { throw new InvalidOperationException(string.Format("DispatchThread #{0} already assigned to {1}", _id, _host)); } #if EXTRA_DEBUG _log.DebugFormat("DispatchThread #{0} assigned to {1}", _id, value); #endif } else { #if EXTRA_DEBUG if(_host != null) { _log.DebugFormat("DispatchThread #{0} unassigned from {1}", _id, _host); } #endif } // update state _host = value; } } //--- Methods --- public bool TryStealWorkItem(out Action callback) { return _inbox.TrySteal(out callback); } public void EvictWorkItems() { // clear CurrentThread to avoid having the evicted items being immediately added back again to the thread (i.e. infinite loop) CurrentThread = null; try { Action item; // remove up to 100 items from the current threads work queue for(int i = 0; (i < 100) && _inbox.TryPop(out item); ++i) { _queue.QueueWorkItem(item); } } finally { // restore CurrentThread before we exit CurrentThread = this; } } private void QueueWorkItem(Action callback) { // NOTE (steveb): this method MUST be called from the dispatcher's associated thread // increase work-item counter and enqueue item _inbox.Push(callback); } private void DispatchLoop() { // set thread-local self-reference CurrentThread = this; // begin thread loop try { while(true) { // check if queue has a work-item Action callback; if(!_inbox.TryPop(out callback)) { var result = new Result<DispatchWorkItem>(TimeSpan.MaxValue); // reset the dispatch queue for this thread Async.CurrentDispatchQueue = null; // check if thread is associated with a host already if(_host == null) { // NOTE (steveb): this is a brand new thread without a host yet // return the thread to the dispatch scheduler DispatchThreadScheduler.ReleaseThread(this, result); } else { // request another work-item _host.RequestWorkItem(this, result); } // block until a work item is available result.Block(); // check if we received a work item or an exception to shutdown if(result.HasException && (result.Exception is DispatchThreadShutdownException)) { // time to shut down _log.DebugFormat("DispatchThread #{0} destroyed", _id); return; } callback = result.Value.WorkItem; _queue = result.Value.DispatchQueue; // TODO (steveb): handle the weird case where _queue is null // set the dispatch queue for this thread Async.CurrentDispatchQueue = _queue; } // execute work-item if(callback != null) { try { callback(); } catch(Exception e) { _log.Warn("an unhandled exception occurred while executing the work-item", e); } } } } catch(Exception e) { // something went wrong that shouldn't have! _log.ErrorExceptionMethodCall(e, string.Format("DispatchLoop #{0}: FATAL ERROR", _id)); // TODO (steveb): tell _host about untimely exit; post items in queue to host inbox (o/w we lose them) } finally { CurrentThread = null; } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ASC.Api.Calendar.iCalParser; using ASC.Api.Calendar.Wrappers; using ASC.Common.Security; using ASC.Common.Security.Authorizing; using ASC.Specific; using ASC.Web.Core.Calendars; namespace ASC.Api.Calendar.BusinessObjects { public static class CalendarExtention { public static bool IsiCalStream(this BaseCalendar calendar) { return (calendar is BusinessObjects.Calendar && !String.IsNullOrEmpty((calendar as BusinessObjects.Calendar).iCalUrl)); } public static bool IsExistTodo(this BaseCalendar calendar) { return (calendar is BusinessObjects.Calendar && (calendar as BusinessObjects.Calendar).IsTodo != 0); } public static BaseCalendar GetUserCalendar(this BaseCalendar calendar, UserViewSettings userViewSettings) { var cal = (BaseCalendar)calendar.Clone(); if (userViewSettings == null) return cal; //name if (!String.IsNullOrEmpty(userViewSettings.Name)) cal.Name = userViewSettings.Name; //backgroundColor if (!String.IsNullOrEmpty(userViewSettings.BackgroundColor)) cal.Context.HtmlBackgroundColor = userViewSettings.BackgroundColor; //textColor if (!String.IsNullOrEmpty(userViewSettings.TextColor)) cal.Context.HtmlTextColor = userViewSettings.TextColor; //TimeZoneInfo if (userViewSettings.TimeZone != null) cal.TimeZone = userViewSettings.TimeZone; //alert type cal.EventAlertType = userViewSettings.EventAlertType; return cal; } public static List<EventWrapper> GetEventWrappers(this BaseCalendar calendar, Guid userId, ApiDateTime startDate, ApiDateTime endDate) { var result = new List<EventWrapper>(); if (calendar != null) { var events = calendar.LoadEvents(userId, startDate.UtcTime, endDate.UtcTime); foreach (var e in events) { var wrapper = new EventWrapper(e, userId, calendar.TimeZone); var listWrapper = wrapper.GetList(startDate.UtcTime, endDate.UtcTime); result.AddRange(listWrapper); } } return result; } public static List<TodoWrapper> GetTodoWrappers(this BaseCalendar calendar, Guid userId, ApiDateTime startDate, ApiDateTime endDate) { var result = new List<TodoWrapper>(); if (calendar != null) { using (var provider = new DataProvider()) { var cal = provider.GetCalendarById(Convert.ToInt32(calendar.Id)); if (cal != null) { var todos = provider.LoadTodos(Convert.ToInt32(calendar.Id), userId, cal.TenantId, startDate, endDate) .Cast<ITodo>() .ToList(); foreach (var t in todos) { var wrapper = new TodoWrapper(t, userId, calendar.TimeZone); var listWrapper = wrapper.GetList(); result.AddRange(listWrapper); } return result; } } } return null; } } [DataContract(Name = "calendar", Namespace = "")] public class Calendar : BaseCalendar, ISecurityObject { public static string DefaultTextColor { get { return "#000000"; } } public static string DefaultBackgroundColor { get { return "#9bb845"; } } public static string DefaultTodoBackgroundColor { get { return "#ffb45e"; } } public Calendar() { this.ViewSettings = new List<UserViewSettings>(); this.Context.CanChangeAlertType = true; this.Context.CanChangeTimeZone = true; } public int TenantId { get; set; } public List<UserViewSettings> ViewSettings { get; set; } public string iCalUrl { get; set; } public string calDavGuid { get; set; } public int IsTodo { get; set; } #region ISecurityObjectId Members /// <inheritdoc/> public object SecurityId { get { return this.Id; } } /// <inheritdoc/> public Type ObjectType { get { return typeof(Calendar); } } #endregion #region ISecurityObjectProvider Members public IEnumerable<ASC.Common.Security.Authorizing.IRole> GetObjectRoles(ASC.Common.Security.Authorizing.ISubject account, ISecurityObjectId objectId, SecurityCallContext callContext) { List<IRole> roles = new List<IRole>(); if (account.ID.Equals(this.OwnerId)) roles.Add(ASC.Common.Security.Authorizing.Constants.Owner); return roles; } public ISecurityObjectId InheritFrom(ISecurityObjectId objectId) { throw new NotImplementedException(); } public bool InheritSupported { get { return false; } } public bool ObjectRolesSupported { get { return true; } } #endregion public override List<IEvent> LoadEvents(Guid userId, DateTime utcStartDate, DateTime utcEndDate) { if (!String.IsNullOrEmpty(iCalUrl)) { try { var cal = iCalendar.GetFromUrl(iCalUrl, this.Id); return cal.LoadEvents(userId, utcStartDate, utcEndDate); } catch { return new List<IEvent>(); } } using (var provider = new DataProvider()) { return provider.LoadEvents(Convert.ToInt32(this.Id), userId, TenantId, utcStartDate, utcEndDate) .Cast<IEvent>() .ToList(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights.Models { using Azure; using Management; using CustomerInsights; using Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Defines the KPI Threshold limits. /// </summary> public partial class KpiDefinition { /// <summary> /// Initializes a new instance of the KpiDefinition class. /// </summary> public KpiDefinition() { } /// <summary> /// Initializes a new instance of the KpiDefinition class. /// </summary> /// <param name="entityType">The mapping entity type. Possible values /// include: 'None', 'Profile', 'Interaction', 'Relationship'</param> /// <param name="entityTypeName">The mapping entity name.</param> /// <param name="calculationWindow">The calculation window. Possible /// values include: 'Lifetime', 'Hour', 'Day', 'Week', 'Month'</param> /// <param name="function">The computation function for the KPI. /// Possible values include: 'Sum', 'Avg', 'Min', 'Max', 'Last', /// 'Count', 'None', 'CountDistinct'</param> /// <param name="expression">The computation expression for the /// KPI.</param> /// <param name="tenantId">The hub name.</param> /// <param name="kpiName">The KPI name.</param> /// <param name="displayName">Localized display name for the /// KPI.</param> /// <param name="description">Localized description for the /// KPI.</param> /// <param name="calculationWindowFieldName">Name of calculation window /// field.</param> /// <param name="unit">The unit of measurement for the KPI.</param> /// <param name="filter">The filter expression for the KPI.</param> /// <param name="groupBy">the group by properties for the KPI.</param> /// <param name="groupByMetadata">The KPI GroupByMetadata.</param> /// <param name="participantProfilesMetadata">The participant /// profiles.</param> /// <param name="provisioningState">Provisioning state. Possible values /// include: 'Provisioning', 'Succeeded', 'Expiring', 'Deleting', /// 'HumanIntervention', 'Failed'</param> /// <param name="thresHolds">The KPI thresholds.</param> /// <param name="aliases">The aliases.</param> /// <param name="extracts">The KPI extracts.</param> public KpiDefinition(EntityTypes entityType, string entityTypeName, CalculationWindowTypes calculationWindow, KpiFunctions function, string expression, string tenantId = default(string), string kpiName = default(string), IDictionary<string, string> displayName = default(IDictionary<string, string>), IDictionary<string, string> description = default(IDictionary<string, string>), string calculationWindowFieldName = default(string), string unit = default(string), string filter = default(string), IList<string> groupBy = default(IList<string>), IList<KpiGroupByMetadata> groupByMetadata = default(IList<KpiGroupByMetadata>), IList<KpiParticipantProfilesMetadata> participantProfilesMetadata = default(IList<KpiParticipantProfilesMetadata>), string provisioningState = default(string), KpiThresholds thresHolds = default(KpiThresholds), IList<KpiAlias> aliases = default(IList<KpiAlias>), IList<KpiExtract> extracts = default(IList<KpiExtract>)) { EntityType = entityType; EntityTypeName = entityTypeName; TenantId = tenantId; KpiName = kpiName; DisplayName = displayName; Description = description; CalculationWindow = calculationWindow; CalculationWindowFieldName = calculationWindowFieldName; Function = function; Expression = expression; Unit = unit; Filter = filter; GroupBy = groupBy; GroupByMetadata = groupByMetadata; ParticipantProfilesMetadata = participantProfilesMetadata; ProvisioningState = provisioningState; ThresHolds = thresHolds; Aliases = aliases; Extracts = extracts; } /// <summary> /// Gets or sets the mapping entity type. Possible values include: /// 'None', 'Profile', 'Interaction', 'Relationship' /// </summary> [JsonProperty(PropertyName = "entityType")] public EntityTypes EntityType { get; set; } /// <summary> /// Gets or sets the mapping entity name. /// </summary> [JsonProperty(PropertyName = "entityTypeName")] public string EntityTypeName { get; set; } /// <summary> /// Gets the hub name. /// </summary> [JsonProperty(PropertyName = "tenantId")] public string TenantId { get; protected set; } /// <summary> /// Gets the KPI name. /// </summary> [JsonProperty(PropertyName = "kpiName")] public string KpiName { get; protected set; } /// <summary> /// Gets or sets localized display name for the KPI. /// </summary> [JsonProperty(PropertyName = "displayName")] public IDictionary<string, string> DisplayName { get; set; } /// <summary> /// Gets or sets localized description for the KPI. /// </summary> [JsonProperty(PropertyName = "description")] public IDictionary<string, string> Description { get; set; } /// <summary> /// Gets or sets the calculation window. Possible values include: /// 'Lifetime', 'Hour', 'Day', 'Week', 'Month' /// </summary> [JsonProperty(PropertyName = "calculationWindow")] public CalculationWindowTypes CalculationWindow { get; set; } /// <summary> /// Gets or sets name of calculation window field. /// </summary> [JsonProperty(PropertyName = "calculationWindowFieldName")] public string CalculationWindowFieldName { get; set; } /// <summary> /// Gets or sets the computation function for the KPI. Possible values /// include: 'Sum', 'Avg', 'Min', 'Max', 'Last', 'Count', 'None', /// 'CountDistinct' /// </summary> [JsonProperty(PropertyName = "function")] public KpiFunctions Function { get; set; } /// <summary> /// Gets or sets the computation expression for the KPI. /// </summary> [JsonProperty(PropertyName = "expression")] public string Expression { get; set; } /// <summary> /// Gets or sets the unit of measurement for the KPI. /// </summary> [JsonProperty(PropertyName = "unit")] public string Unit { get; set; } /// <summary> /// Gets or sets the filter expression for the KPI. /// </summary> [JsonProperty(PropertyName = "filter")] public string Filter { get; set; } /// <summary> /// Gets or sets the group by properties for the KPI. /// </summary> [JsonProperty(PropertyName = "groupBy")] public IList<string> GroupBy { get; set; } /// <summary> /// Gets the KPI GroupByMetadata. /// </summary> [JsonProperty(PropertyName = "groupByMetadata")] public IList<KpiGroupByMetadata> GroupByMetadata { get; protected set; } /// <summary> /// Gets the participant profiles. /// </summary> [JsonProperty(PropertyName = "participantProfilesMetadata")] public IList<KpiParticipantProfilesMetadata> ParticipantProfilesMetadata { get; protected set; } /// <summary> /// Gets provisioning state. Possible values include: 'Provisioning', /// 'Succeeded', 'Expiring', 'Deleting', 'HumanIntervention', 'Failed' /// </summary> [JsonProperty(PropertyName = "provisioningState")] public string ProvisioningState { get; protected set; } /// <summary> /// Gets or sets the KPI thresholds. /// </summary> [JsonProperty(PropertyName = "thresHolds")] public KpiThresholds ThresHolds { get; set; } /// <summary> /// Gets or sets the aliases. /// </summary> [JsonProperty(PropertyName = "aliases")] public IList<KpiAlias> Aliases { get; set; } /// <summary> /// Gets or sets the KPI extracts. /// </summary> [JsonProperty(PropertyName = "extracts")] public IList<KpiExtract> Extracts { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (EntityTypeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "EntityTypeName"); } if (Expression == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Expression"); } if (ParticipantProfilesMetadata != null) { foreach (var element in ParticipantProfilesMetadata) { if (element != null) { element.Validate(); } } } if (ThresHolds != null) { ThresHolds.Validate(); } if (Aliases != null) { foreach (var element1 in Aliases) { if (element1 != null) { element1.Validate(); } } } if (Extracts != null) { foreach (var element2 in Extracts) { if (element2 != null) { element2.Validate(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableSortedSetTest : ImmutableSetTest { private enum Operation { Add, Union, Remove, Except, Last, } protected override bool IncludesGetHashCodeDerivative { get { return false; } } [Fact] public void RandomOperationsTest() { int operationCount = this.RandomOperationsCount; var expected = new SortedSet<int>(); var actual = ImmutableSortedSet<int>.Empty; int seed = unchecked((int)DateTime.Now.Ticks); Debug.WriteLine("Using random seed {0}", seed); var random = new Random(seed); for (int iOp = 0; iOp < operationCount; iOp++) { switch ((Operation)random.Next((int)Operation.Last)) { case Operation.Add: int value = random.Next(); Debug.WriteLine("Adding \"{0}\" to the set.", value); expected.Add(value); actual = actual.Add(value); break; case Operation.Union: int inputLength = random.Next(100); int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray(); Debug.WriteLine("Adding {0} elements to the set.", inputLength); expected.UnionWith(values); actual = actual.Union(values); break; case Operation.Remove: if (expected.Count > 0) { int position = random.Next(expected.Count); int element = expected.Skip(position).First(); Debug.WriteLine("Removing element \"{0}\" from the set.", element); Assert.True(expected.Remove(element)); actual = actual.Remove(element); } break; case Operation.Except: var elements = expected.Where(el => random.Next(2) == 0).ToArray(); Debug.WriteLine("Removing {0} elements from the set.", elements.Length); expected.ExceptWith(elements); actual = actual.Except(elements); break; } Assert.Equal<int>(expected.ToList(), actual.ToList()); } } [Fact] public void EmptyTest() { this.EmptyTestHelper(Empty<int>(), 5, null); this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase); } [Fact] public void CustomSort() { this.CustomSortTestHelper( ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal), true, new[] { "apple", "APPLE" }, new[] { "APPLE", "apple" }); this.CustomSortTestHelper( ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase), true, new[] { "apple", "APPLE" }, new[] { "apple" }); } [Fact] public void ChangeSortComparer() { var ordinalSet = ImmutableSortedSet<string>.Empty .WithComparer(StringComparer.Ordinal) .Add("apple") .Add("APPLE"); Assert.Equal(2, ordinalSet.Count); // claimed count Assert.False(ordinalSet.Contains("aPpLe")); var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, ignoreCaseSet.Count); Assert.True(ignoreCaseSet.Contains("aPpLe")); } [Fact] public void ToUnorderedTest() { var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet(); Assert.True(result.Contains(3)); } [Fact] public void ToImmutableSortedSetFromArrayTest() { var set = new[] { 1, 2, 2 }.ToImmutableSortedSet(); Assert.Same(Comparer<int>.Default, set.KeyComparer); Assert.Equal(2, set.Count); } [Theory] [InlineData(new int[] { }, new int[] { })] [InlineData(new int[] { 1 }, new int[] { 1 })] [InlineData(new int[] { 1, 1 }, new int[] { 1 })] [InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })] [InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })] [InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })] [InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })] public void ToImmutableSortedSetFromEnumerableTest(int[] input, int[] expectedOutput) { IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces var set = enumerableInput.ToImmutableSortedSet(); Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray()); } [Theory] [InlineData(new int[] { }, new int[] { 1 })] [InlineData(new int[] { 1 }, new int[] { 1 })] [InlineData(new int[] { 1, 1 }, new int[] { 1 })] [InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })] [InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })] [InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })] [InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })] [InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })] public void UnionWithEnumerableTest(int[] input, int[] expectedOutput) { IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces var set = ImmutableSortedSet.Create(1).Union(enumerableInput); Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray()); } [Fact] public void IndexOfTest() { var set = ImmutableSortedSet<int>.Empty; Assert.Equal(~0, set.IndexOf(5)); set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100 Assert.Equal(0, set.IndexOf(10)); Assert.Equal(1, set.IndexOf(20)); Assert.Equal(4, set.IndexOf(50)); Assert.Equal(8, set.IndexOf(90)); Assert.Equal(9, set.IndexOf(100)); Assert.Equal(~0, set.IndexOf(5)); Assert.Equal(~1, set.IndexOf(15)); Assert.Equal(~2, set.IndexOf(25)); Assert.Equal(~5, set.IndexOf(55)); Assert.Equal(~9, set.IndexOf(95)); Assert.Equal(~10, set.IndexOf(105)); } [Fact] public void IndexGetTest() { var set = ImmutableSortedSet<int>.Empty .Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100 int i = 0; foreach (var item in set) { AssertAreSame(item, set[i++]); } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => set[-1]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => set[set.Count]); } [Fact] public void ReverseTest() { var range = Enumerable.Range(1, 10); var set = ImmutableSortedSet<int>.Empty.Union(range); var expected = range.Reverse().ToList(); var actual = set.Reverse().ToList(); Assert.Equal<int>(expected, actual); } [Fact] public void MaxTest() { Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max); Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max); } [Fact] public void MinTest() { Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min); Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min); } [Fact] public void InitialBulkAdd() { Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count); Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count); } [Fact] public void ICollectionOfTMethods() { ICollection<string> set = ImmutableSortedSet.Create<string>(); Assert.Throws<NotSupportedException>(() => set.Add("a")); Assert.Throws<NotSupportedException>(() => set.Clear()); Assert.Throws<NotSupportedException>(() => set.Remove("a")); Assert.True(set.IsReadOnly); } [Fact] public void IListOfTMethods() { IList<string> set = ImmutableSortedSet.Create<string>("b"); Assert.Throws<NotSupportedException>(() => set.Insert(0, "a")); Assert.Throws<NotSupportedException>(() => set.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => set[0] = "a"); Assert.Equal("b", set[0]); Assert.True(set.IsReadOnly); } [Fact] public void UnionOptimizationsTest() { var set = ImmutableSortedSet.Create(1, 2, 3); var builder = set.ToBuilder(); Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder)); Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>())); var smallSet = ImmutableSortedSet.Create(1); var unionSet = smallSet.Union(set); Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique } [Fact] public void Create() { var comparer = StringComparer.OrdinalIgnoreCase; var set = ImmutableSortedSet.Create<string>(); Assert.Equal(0, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.Create<string>(comparer); Assert.Equal(0, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableSortedSet.Create("a"); Assert.Equal(1, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.Create(comparer, "a"); Assert.Equal(1, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableSortedSet.Create("a", "b"); Assert.Equal(2, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.Create(comparer, "a", "b"); Assert.Equal(2, set.Count); Assert.Same(comparer, set.KeyComparer); set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" }); Assert.Equal(2, set.Count); Assert.Same(Comparer<string>.Default, set.KeyComparer); set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" }); Assert.Equal(2, set.Count); Assert.Same(comparer, set.KeyComparer); } [Fact] public void IListMethods() { IList list = ImmutableSortedSet.Create("a", "b"); Assert.True(list.Contains("a")); Assert.Equal("a", list[0]); Assert.Equal("b", list[1]); Assert.Equal(0, list.IndexOf("a")); Assert.Equal(1, list.IndexOf("b")); Assert.Throws<NotSupportedException>(() => list.Add("b")); Assert.Throws<NotSupportedException>(() => list[3] = "c"); Assert.Throws<NotSupportedException>(() => list.Clear()); Assert.Throws<NotSupportedException>(() => list.Insert(0, "b")); Assert.Throws<NotSupportedException>(() => list.Remove("a")); Assert.Throws<NotSupportedException>(() => list.RemoveAt(0)); Assert.True(list.IsFixedSize); Assert.True(list.IsReadOnly); } [Fact] public void TryGetValueTest() { this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase)); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableSortedSet.Create<int>(); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.Create<int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.Create<string>("1", "2", "3")); object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedSet.Create<object>(), "_root"); DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode); } [Fact] public void SymmetricExceptWithComparerTests() { var set = ImmutableSortedSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase); var otherCollection = new[] {"A"}; var expectedSet = new SortedSet<string>(set, set.KeyComparer); expectedSet.SymmetricExceptWith(otherCollection); var actualSet = set.SymmetricExcept(otherCollection); CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList()); } protected override IImmutableSet<T> Empty<T>() { return ImmutableSortedSet<T>.Empty; } protected ImmutableSortedSet<T> EmptyTyped<T>() { return ImmutableSortedSet<T>.Empty; } protected override ISet<T> EmptyMutable<T>() { return new SortedSet<T>(); } internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set) { return ((ImmutableSortedSet<T>)set).Root; } /// <summary> /// Tests various aspects of a sorted set. /// </summary> /// <typeparam name="T">The type of element stored in the set.</typeparam> /// <param name="emptySet">The empty set.</param> /// <param name="value">A value that could be placed in the set.</param> /// <param name="comparer">The comparer used to obtain the empty set, if any.</param> private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer) { Assert.NotNull(emptySet); this.EmptyTestHelper(emptySet); Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer)); Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer); var reemptied = emptySet.Add(value).Clear(); Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer."); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\CheatManager.h:69 namespace UnrealEngine { [ManageType("ManageCheatManager")] public partial class ManageCheatManager : UCheatManager, IManageWrapper { public ManageCheatManager(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_BugItGo(IntPtr self, float x, float y, float z, float pitch, float yaw, float roll); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_ChangeSize(IntPtr self, float f); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DamageTarget(IntPtr self, float damageAmount); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DebugCapsuleSweep(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DebugCapsuleSweepCapture(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DebugCapsuleSweepClear(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DebugCapsuleSweepComplex(IntPtr self, bool bTraceComplex); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DebugCapsuleSweepPawn(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DebugCapsuleSweepSize(IntPtr self, float halfHeight, float radius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DestroyAllPawnsExceptTarget(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DestroyTarget(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DisableDebugCamera(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DumpChatState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DumpOnlineSessionState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DumpPartyState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_DumpVoiceMutingState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_EnableDebugCamera(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_FlushLog(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_Fly(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_FreezeFrame(IntPtr self, float delay); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_Ghost(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_God(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_InitCheatManager(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_InvertMouse(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_LogLoc(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PlayersOnly(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_ServerToggleAILogging(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_SetMouseSensitivityToDefault(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_Slomo(IntPtr self, float newTimeDilation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_Teleport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_TestCollisionDistance(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_ToggleAILogging(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_ToggleDebugCamera(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_ViewSelf(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_Walk(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCheatManager_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods public override void BugItGo(float x, float y, float z, float pitch, float yaw, float roll) => E__Supper__UCheatManager_BugItGo(this, x, y, z, pitch, yaw, roll); public override void ChangeSize(float f) => E__Supper__UCheatManager_ChangeSize(this, f); /// <summary> /// Damage the actor you're looking at (sourced from the player). /// </summary> public override void DamageTarget(float damageAmount) => E__Supper__UCheatManager_DamageTarget(this, damageAmount); public override void DebugCapsuleSweep() => E__Supper__UCheatManager_DebugCapsuleSweep(this); public override void DebugCapsuleSweepCapture() => E__Supper__UCheatManager_DebugCapsuleSweepCapture(this); public override void DebugCapsuleSweepClear() => E__Supper__UCheatManager_DebugCapsuleSweepClear(this); public override void DebugCapsuleSweepComplex(bool bTraceComplex) => E__Supper__UCheatManager_DebugCapsuleSweepComplex(this, bTraceComplex); public override void DebugCapsuleSweepPawn() => E__Supper__UCheatManager_DebugCapsuleSweepPawn(this); public override void DebugCapsuleSweepSize(float halfHeight, float radius) => E__Supper__UCheatManager_DebugCapsuleSweepSize(this, halfHeight, radius); public override void DestroyAllPawnsExceptTarget() => E__Supper__UCheatManager_DestroyAllPawnsExceptTarget(this); /// <summary> /// Destroy the actor you're looking at. /// </summary> public override void DestroyTarget() => E__Supper__UCheatManager_DestroyTarget(this); /// <summary> /// Switch controller from debug camera back to normal controller /// </summary> protected override void DisableDebugCamera() => E__Supper__UCheatManager_DisableDebugCamera(this); public override void DumpChatState() => E__Supper__UCheatManager_DumpChatState(this); public override void DumpOnlineSessionState() => E__Supper__UCheatManager_DumpOnlineSessionState(this); public override void DumpPartyState() => E__Supper__UCheatManager_DumpPartyState(this); public override void DumpVoiceMutingState() => E__Supper__UCheatManager_DumpVoiceMutingState(this); /// <summary> /// Switch controller to debug camera without locking gameplay and with locking local player controller input /// </summary> protected override void EnableDebugCamera() => E__Supper__UCheatManager_EnableDebugCamera(this); public override void FlushLog() => E__Supper__UCheatManager_FlushLog(this); /// <summary> /// Pawn can fly. /// </summary> public override void Fly() => E__Supper__UCheatManager_Fly(this); /// <summary> /// Pause the game for Delay seconds. /// </summary> public override void FreezeFrame(float delay) => E__Supper__UCheatManager_FreezeFrame(this, delay); /// <summary> /// Pawn no longer collides with the world, and can fly /// </summary> public override void Ghost() => E__Supper__UCheatManager_Ghost(this); /// <summary> /// Invulnerability cheat. /// </summary> public override void God() => E__Supper__UCheatManager_God(this); /// <summary> /// Called when CheatManager is created to allow any needed initialization. /// </summary> public override void InitCheatManager() => E__Supper__UCheatManager_InitCheatManager(this); public override void InvertMouse() => E__Supper__UCheatManager_InvertMouse(this); public override void LogLoc() => E__Supper__UCheatManager_LogLoc(this); /// <summary> /// Freeze everything in the level except for players. /// </summary> public override void PlayersOnly() => E__Supper__UCheatManager_PlayersOnly(this); public override void ServerToggleAILogging() => E__Supper__UCheatManager_ServerToggleAILogging(this); public override void SetMouseSensitivityToDefault() => E__Supper__UCheatManager_SetMouseSensitivityToDefault(this); /// <summary> /// Modify time dilation to change apparent speed of passage of time. e.g. "Slomo 0.1" makes everything move very slowly, while "Slomo 10" makes everything move very fast. /// </summary> public override void Slomo(float newTimeDilation) => E__Supper__UCheatManager_Slomo(this, newTimeDilation); public override void Teleport() => E__Supper__UCheatManager_Teleport(this); public override void TestCollisionDistance() => E__Supper__UCheatManager_TestCollisionDistance(this); public override void ToggleAILogging() => E__Supper__UCheatManager_ToggleAILogging(this); public override void ToggleDebugCamera() => E__Supper__UCheatManager_ToggleDebugCamera(this); public override void ViewSelf() => E__Supper__UCheatManager_ViewSelf(this); /// <summary> /// Return to walking movement mode from Fly or Ghost cheat. /// </summary> public override void Walk() => E__Supper__UCheatManager_Walk(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UCheatManager_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UCheatManager_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UCheatManager_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UCheatManager_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UCheatManager_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UCheatManager_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UCheatManager_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UCheatManager_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UCheatManager_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UCheatManager_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UCheatManager_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UCheatManager_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UCheatManager_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UCheatManager_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UCheatManager_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageCheatManager self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageCheatManager(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageCheatManager>(PtrDesc); } } }
// // Sample showing the core Element-based API to create a dialog // using System; using System.Linq; using MonoTouch.Dialog; using MonoTouch.UIKit; namespace Sample { public partial class AppDelegate { public void DemoElementApi () { var root = CreateRoot (); var dv = new DialogViewController (root, true); navigation.PushViewController (dv, true); } RootElement CreateRoot () { return new RootElement ("Settings") { new Section (){ new BooleanElement ("Airplane Mode", false), new RootElement ("Notifications", 0, 0) { new Section (null, "Turn off Notifications to disable Sounds\n" + "Alerts and Home Screen Badges for the\napplications below."){ new BooleanElement ("Notifications", false) } }}, new Section (){ CreateSoundSection (), new RootElement ("Brightness"){ new Section (){ new FloatElement (null, null, 0.5f), new BooleanElement ("Auto-brightness", false), } }, new RootElement ("Wallpaper"){ new Section (){ new ImageElement (null), new ImageElement (null), new ImageElement (null) } } }, new Section () { new EntryElement ("Login", "Your login name", null) { EnablesReturnKeyAutomatically = true, AlignEntryWithAllSections = true, }, new EntryElement ("Password", "Your password", null, true) { EnablesReturnKeyAutomatically = true, AlignEntryWithAllSections = true, }, new DateElement ("Select Date", DateTime.Now), new TimeElement ("Select Time", DateTime.Now), }, new Section () { new EntryElement ("Another Field", "Aligns with above fields", null) { AlignEntryWithAllSections = true, }, }, new Section () { CreateGeneralSection (), //new RootElement ("Mail, Contacts, Calendars"), //new RootElement ("Phone"), //new RootElement ("Safari"), //new RootElement ("Messages"), //new RootElement ("iPod"), //new RootElement ("Photos"), //new RootElement ("Store"), }, new Section () { new HtmlElement ("About", "http://monotouch.net"), new MultilineElement ("Remember to eat\nfruits and vegetables\nevery day") } }; } RootElement CreateSoundSection () { return new RootElement ("Sounds"){ new Section ("Silent") { new BooleanElement ("Vibrate", true), }, new Section ("Ring") { new BooleanElement ("Vibrate", true), new FloatElement (null, null, 0.8f), new RootElement ("Ringtone", new RadioGroup (0)){ new Section ("Custom"){ new RadioElement ("Circus Music"), new RadioElement ("True Blood"), }, new Section ("Standard"){ from n in "Marimba,Alarm,Ascending,Bark,Xylophone".Split (',') select (Element) new RadioElement (n) } }, new RootElement ("New Text Message", new RadioGroup (3)){ new Section (){ from n in "None,Tri-tone,Chime,Glass,Horn,Bell,Eletronic".Split (',') select (Element) new RadioElement (n) } }, new BooleanElement ("New Voice Mail", false), new BooleanElement ("New Mail", false), new BooleanElement ("Sent Mail", true), new BooleanElement ("Calendar Alerts", true), new BooleanElement ("Lock Sounds", true), new BooleanElement ("Keyboard Clicks", false) } }; } public RootElement CreateGeneralSection () { return new RootElement ("General") { new Section (){ new RootElement ("About"){ new Section ("My Phone") { new RootElement ("Network", new RadioGroup (null, 0)) { new Section (){ new RadioElement ("My First Network"), new RadioElement ("Second Network"), } }, new StringElement ("Songs", "23"), new StringElement ("Videos", "3"), new StringElement ("Photos", "24"), new StringElement ("Applications", "50"), new StringElement ("Capacity", "14.6GB"), new StringElement ("Available", "12.8GB"), new StringElement ("Version", "3.0 (FOOBAR)"), new StringElement ("Carrier", "My Carrier"), new StringElement ("Serial Number", "555-3434"), new StringElement ("Model", "The"), new StringElement ("Wi-Fi Address", "11:22:33:44:55:66"), new StringElement ("Bluetooth", "aa:bb:cc:dd:ee:ff:00"), }, new Section () { new HtmlElement ("Monologue", "http://www.go-mono.com/monologue"), } }, new RootElement ("Usage"){ new Section ("Time since last full charge"){ new StringElement ("Usage", "0 minutes"), new StringElement ("Standby", "0 minutes"), }, new Section ("Call time") { new StringElement ("Current Period", "4 days, 21 hours"), new StringElement ("Lifetime", "7 days, 20 hours") }, new Section ("Celullar Network Data"){ new StringElement ("Sent", "10 bytes"), new StringElement ("Received", "30 TB"), }, new Section (null, "Last Reset: 1/1/08 4:44pm"){ new StringElement ("Reset Statistics"){ Alignment = UITextAlignment.Center } } } }, new Section (){ new RootElement ("Network"){ new Section (null, "Using 3G loads data faster\nand burns the battery"){ new BooleanElement ("Enable 3G", true) }, new Section (null, "Turn this on if you are Donald Trump"){ new BooleanElement ("Data Roaming", false), }, new Section (){ new RootElement ("VPN", 0, 0){ new Section (){ new BooleanElement ("VPN", false), }, new Section ("Choose a configuration"){ new StringElement ("Add VPN Configuration") } } } }, new RootElement ("Bluetooth", 0, 0){ new Section (){ new BooleanElement ("Bluetooth", false) } }, new BooleanElement ("Location Services", true), }, new Section (){ new RootElement ("Auto-Lock", new RadioGroup (0)){ new Section (){ new RadioElement ("1 Minute"), new RadioElement ("2 Minutes"), new RadioElement ("3 Minutes"), new RadioElement ("4 Minutes"), new RadioElement ("5 Minutes"), new RadioElement ("Never"), } }, // Can be implemented with StringElement + Tapped, but makes sample larger // new StringElement ("Passcode lock"), new BooleanElement ("Restrictions", false), }, new Section () { new RootElement ("Home", new RadioGroup (2)){ new Section ("Double-click the Home Button for:"){ new RadioElement ("Home"), new RadioElement ("Search"), new RadioElement ("Phone favorites"), new RadioElement ("Camera"), new RadioElement ("iPod"), }, new Section (null, "When playing music, show iPod controls"){ new BooleanElement ("iPod Controls", true), } // Missing feature: sortable list of data // SearchResults }, new RootElement ("Date & Time"){ new Section (){ new BooleanElement ("24-Hour Time", false), }, new Section (){ new BooleanElement ("Set Automatically", false), // TimeZone: Can be implemented with string + tapped event // SetTime: Can be imeplemeneted with String + Tapped Event } }, new RootElement ("Keyboard"){ new Section (null, "Double tapping the space bar will\n" + "insert a period followed by a space"){ new BooleanElement ("Auto-Correction", true), new BooleanElement ("Auto-Capitalization", true), new BooleanElement ("Enable Caps Lock", false), new BooleanElement ("\".\" Shortcut", true), }, new Section (){ new RootElement ("International Keyboards", new Group ("kbd")){ new Section ("Using Checkboxes"){ new CheckboxElement ("English", true, "kbd"), new CheckboxElement ("Spanish", false, "kbd"), new CheckboxElement ("French", false, "kbd"), }, new Section ("Using BooleanElement"){ new BooleanElement ("Portuguese", true, "kbd"), new BooleanElement ("German", false, "kbd"), }, new Section ("Or mixing them"){ new BooleanElement ("Italian", true, "kbd"), new CheckboxElement ("Czech", true, "kbd"), } } } } } }; } } }
namespace Core.UnitTests { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Crest.Core; using FluentAssertions; using Xunit; public class LinkCollectionTests { private static readonly Uri ValidUri = new Uri("http://www.example.com/"); private readonly LinkCollection collection = new LinkCollection(); private static Link CreateLink(string relation, string path = "") { return new Link(relation, new Uri(ValidUri, path)); } public sealed class Add : LinkCollectionTests { [Fact] public void ShouldCheckForNullArguments() { this.collection.Invoking(x => x.Add(null)) .Should().Throw<ArgumentNullException>(); } [Fact] public void ShouldMaintinOrderForLinksWithTheSameRelation() { Link link1 = CreateLink("sameRelation", "insertedFirst"); Link link2 = CreateLink("sameRelation", "insertedAfter"); this.collection.Add(link1); this.collection.Add(link2); var links = new List<Link>(this.collection); links.Should().ContainInOrder(link1, link2); } } public sealed class AddRelationAndUri : LinkCollectionTests { [Fact] public void ShouldCheckForNullArguments() { this.collection.Invoking(x => x.Add(null, ValidUri)) .Should().Throw<ArgumentNullException>(); this.collection.Invoking(x => x.Add("self", null)) .Should().Throw<ArgumentNullException>(); } [Fact] public void ShouldAddANewLink() { this.collection.Add("relation", ValidUri); this.collection["relation"].Single().HRef.Should().Be(ValidUri); } } public sealed class Clear : LinkCollectionTests { [Fact] public void ShouldRemoveTheItems() { this.collection.Add(CreateLink("1")); this.collection.Add(CreateLink("2")); this.collection.Clear(); this.collection.Count.Should().Be(0); this.collection.Should().BeEmpty(); } } public sealed class Contains : LinkCollectionTests { [Fact] public void ShouldReturnFalseIfTheLinkDoesNotExist() { this.collection.Add(CreateLink("relation", "1")); bool result = this.collection.Contains(CreateLink("relation", "2")); result.Should().BeFalse(); } [Fact] public void ShouldReturnTrueIfTheLinkExists() { this.collection.Add(CreateLink("relation", "1")); bool result = this.collection.Contains(CreateLink("relation", "1")); result.Should().BeTrue(); } [Fact] public void ShouldReturnTrueIfTheRelationExists() { this.collection.Add(CreateLink("relation", "link")); bool result = ((ILookup<string, Link>)this.collection).Contains("relation"); result.Should().BeTrue(); } } public sealed class ContainsKey : LinkCollectionTests { [Fact] public void ShouldReturnFalseIfTheRelationDoesNotExist() { this.collection.Add(CreateLink("relation", "link")); bool result = this.collection.ContainsKey("link"); result.Should().BeFalse(); } [Fact] public void ShouldReturnTrueIfTheRelationExists() { this.collection.Add(CreateLink("relation", "link")); bool result = this.collection.ContainsKey("relation"); result.Should().BeTrue(); } } public sealed class CopyTo : LinkCollectionTests { [Fact] public void ShouldCheckForNegativeArrayIndexes() { Action action = () => this.collection.CopyTo(new Link[1], -1); action.Should().Throw<ArgumentOutOfRangeException>(); } [Fact] public void ShouldCheckForNullArguments() { Action action = () => this.collection.CopyTo(null, 0); action.Should().Throw<ArgumentNullException>(); } [Fact] public void ShouldCheckTheDestinationIsBigEnough() { this.collection.Add(CreateLink("1")); Action action = () => this.collection.CopyTo(new Link[1], 1); action.Should().Throw<ArgumentException>() .WithMessage("*long enough*"); } [Fact] public void ShouldCopyTheElements() { var destination = new Link[2]; Link link = CreateLink("1"); this.collection.Add(link); this.collection.CopyTo(destination, 1); destination.Should().HaveElementAt(0, null); destination.Should().HaveElementAt(1, link); } } public sealed class GetEnumerator : LinkCollectionTests { [Fact] public void ShouldReturnAllTheLinks() { this.collection.Add(CreateLink("1")); this.collection.Add(CreateLink("2")); IEnumerator<Link> result = this.collection.GetEnumerator(); result.MoveNext().Should().BeTrue(); result.MoveNext().Should().BeTrue(); result.MoveNext().Should().BeFalse(); } [Fact] public void ShouldReturnAllTheGroups() { this.collection.Add(CreateLink("rel1", "A")); this.collection.Add(CreateLink("rel2", "B")); this.collection.Add(CreateLink("rel1", "C")); IEnumerator<IGrouping<string, Link>> result = ((ILookup<string, Link>)this.collection).GetEnumerator(); result.MoveNext().Should().BeTrue(); result.Current.Key.Should().Be("rel1"); ((IReadOnlyCollection<Link>)result.Current).Count.Should().Be(2); result.MoveNext().Should().BeTrue(); result.Current.Key.Should().Be("rel2"); ((IReadOnlyCollection<Link>)result.Current).Count.Should().Be(1); result.MoveNext().Should().BeFalse(); } } public sealed class Index : LinkCollectionTests { [Fact] public void ShouldReturnAllTheLinksWithTheSameRelation() { this.collection.Add(CreateLink("rel1", "A")); this.collection.Add(CreateLink("rel2", "B")); this.collection.Add(CreateLink("rel1", "C")); IEnumerable<Link> result = this.collection["rel1"]; result.Select(l => l.HRef.PathAndQuery) .Should().BeEquivalentTo("/A", "/C"); } [Fact] public void ShouldReturnAnEmptyCollecitonIfTheKeyIsNotFound() { IEnumerable<Link> result = this.collection["unknown"]; result.Should().BeEmpty(); } } public sealed class IsReadOnly : LinkCollectionTests { [Fact] public void ShouldReturnFalse() { bool result = ((ICollection<Link>)this.collection).IsReadOnly; result.Should().BeFalse(); } } public sealed class NonGenericGetEnumerator : LinkCollectionTests { [Fact] public void ShouldReturnAllTheItems() { this.collection.Add(CreateLink("1")); this.collection.Add(CreateLink("2")); IEnumerator result = ((IEnumerable)this.collection).GetEnumerator(); result.MoveNext().Should().BeTrue(); result.MoveNext().Should().BeTrue(); result.MoveNext().Should().BeFalse(); } [Fact] public void ShouldReturnAllTheItemsInTheGroup() { this.collection.Add(CreateLink("a")); this.collection.Add(CreateLink("a")); IEnumerator result = ((IEnumerable)this.collection["a"]).GetEnumerator(); result.MoveNext().Should().BeTrue(); result.MoveNext().Should().BeTrue(); result.MoveNext().Should().BeFalse(); } } public sealed class Remove : LinkCollectionTests { [Fact] public void ShouldRemoveTheLink() { this.collection.Add(CreateLink("A", "1")); this.collection.Add(CreateLink("B", "2")); bool result = this.collection.Remove(CreateLink("A", "1")); result.Should().BeTrue(); ((IEnumerable<Link>)this.collection).Should().ContainSingle() .Which.Should().Be(CreateLink("B", "2")); } [Fact] public void ShouldReturnFalseIfTheLinkIsNotFound() { this.collection.Add(CreateLink("A", "1")); bool result = this.collection.Remove(CreateLink("B", "2")); result.Should().BeFalse(); } } } }
using System; using MonoTouch.CoreGraphics; using MonoTouch.ObjCRuntime; using MonoTouch.Foundation; using System.Drawing; using MonoTouch.UIKit; using System.Runtime.InteropServices; using MonoTouch.CoreAnimation; using System.Collections.Generic; using System.Collections.Specialized; namespace KS_PSPDFKitBindings { ////////////////////////////////////////////////////// //// PSPDFViewController.h // ////////////////////////////////////////////////////// public partial class PSPDFViewController { public PSPDFViewController () : this ((PSPDFDocument)null) { } } ////////////////////////////////////////// //// PSPDFKitGlobal.h // ////////////////////////////////////////// public partial class PSPDFKitGlobal { /// <summary> /// Helper to allow adjusting locale strings in PSPDFKit. /// <example> /// The following example replaces the English locale constants &quot;Outline&quot; with &quot;File Contents&quot; and the &quot;Bookmarks&quot; constant with &quot;Remember&quot; /// <code> /// Localize("en", new NameValueCollection /// { /// {"Outline", "File Content"}, /// {"Bookmarks", "Remember"} /// }); /// </code> /// </example> /// </summary> /// <param name="languageIdentifier">Language identifier.</param> /// <param name="constantValuePairs">Constant value pairs.</param> public static void Localize(string languageIdentifier, NameValueCollection constantValuePairs) { var localeDic = new NSMutableDictionary(); var customLanguageDic = new NSMutableDictionary(); foreach (var key in constantValuePairs.AllKeys) { string constantValue = constantValuePairs[key]; customLanguageDic.Add(new NSString(key), new NSString(constantValue)); } localeDic.Add(new NSString(languageIdentifier), customLanguageDic); // Set the dictionary in PSPDFKit. PSPDFKitGlobal.SetLocalizationDictionary(localeDic); } private static PSPDFLogLevel kPSPDFLogLevel; public static PSPDFLogLevel LogLevel { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFLogLevel"); kPSPDFLogLevel = (PSPDFLogLevel) Marshal.ReadInt32(ptr); return kPSPDFLogLevel; } set { kPSPDFLogLevel = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFLogLevel"); Marshal.WriteInt32(ptr, (int)kPSPDFLogLevel); } } private static PSPDFAnimate kPSPDFAnimateOption; public static PSPDFAnimate AnimateOption { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFAnimateOption"); kPSPDFAnimateOption = (PSPDFAnimate) Marshal.ReadInt32(ptr); return kPSPDFAnimateOption; } set { kPSPDFAnimateOption = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFAnimateOption"); Marshal.WriteInt32(ptr, (int)kPSPDFAnimateOption); } } private static bool kPSPDFLowMemoryMode; public static bool PSPDFLowMemoryMode { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFLowMemoryMode"); kPSPDFLowMemoryMode = Convert.ToBoolean(Marshal.ReadByte(ptr)); return kPSPDFLowMemoryMode; } set { kPSPDFLowMemoryMode = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFLowMemoryMode"); Marshal.WriteByte(ptr, Convert.ToByte(kPSPDFLowMemoryMode)); } } private static float kPSPDFAnimationDuration; public static float AnimationDuration { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); kPSPDFAnimationDuration = Dlfcn.GetFloat(RTLD_MAIN_ONLY, "kPSPDFAnimationDuration"); return kPSPDFAnimationDuration; } set { kPSPDFAnimationDuration = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFAnimationDuration"); unsafe { float m = kPSPDFAnimationDuration; Marshal.WriteIntPtr(ptr, *(IntPtr*)&m); } } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFFixNavigationBarForNavigationControllerAnimated")] private static extern void _PSPDFFixNavigationBarForNavigationControllerAnimated(IntPtr navController, byte animated); public static void PSPDFFixNavigationBarForNavigationControllerAnimated(UINavigationController navController, bool animated) { _PSPDFFixNavigationBarForNavigationControllerAnimated (navController.Handle, Convert.ToByte (animated)); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFShouldAnimate")] [return: MarshalAsAttribute(UnmanagedType.Bool)] private static extern bool _ShouldAnimate(); public static bool ShouldAnimate { get { return _ShouldAnimate(); } } private static float kPSPDFInitialAnnotationLoadDelay; public static float InitialAnnotationLoadDelay { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); kPSPDFInitialAnnotationLoadDelay = Dlfcn.GetFloat(RTLD_MAIN_ONLY, "kPSPDFInitialAnnotationLoadDelay"); return kPSPDFInitialAnnotationLoadDelay; } set { kPSPDFInitialAnnotationLoadDelay = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFInitialAnnotationLoadDelay"); unsafe { float m = kPSPDFInitialAnnotationLoadDelay; Marshal.WriteIntPtr(ptr, *(IntPtr*)&m); } } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFIsCrappyDevice")] [return: MarshalAsAttribute(UnmanagedType.Bool)] private static extern bool _IsCrappyDevice(); public static bool IsCrappyDevice { get { return _IsCrappyDevice(); } } private static string kPSPDFCacheClassName; public static string CacheClassName { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); kPSPDFCacheClassName = (string) Dlfcn.GetStringConstant (RTLD_MAIN_ONLY, "kPSPDFCacheClassName"); return kPSPDFCacheClassName; } set { kPSPDFCacheClassName = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFCacheClassName"); Marshal.WriteIntPtr(ptr, new NSString(kPSPDFCacheClassName).Handle); } } private static string kPSPDFIconGeneratorClassName; public static string IconGeneratorClassName { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); kPSPDFIconGeneratorClassName = (string) Dlfcn.GetStringConstant (RTLD_MAIN_ONLY, "kPSPDFIconGeneratorClassName"); return kPSPDFIconGeneratorClassName; } set { kPSPDFIconGeneratorClassName = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFIconGeneratorClassName"); Marshal.WriteIntPtr(ptr, new NSString(kPSPDFIconGeneratorClassName).Handle); } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFAppName")] private static extern IntPtr _AppName(); public static string AppName { get { IntPtr ptr = _AppName(); string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFVersionString")] private static extern IntPtr _VersionString(); public static string VersionString { get { IntPtr ptr = _VersionString(); string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFKitBundle")] private static extern IntPtr _PSPDFKitBundle(); public static NSBundle Bundle { get { IntPtr ptr = _PSPDFKitBundle(); NSBundle bundle = (NSBundle) Runtime.GetNSObject(ptr); return bundle; } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFLocalize")] private static extern IntPtr _Localize(IntPtr stringToken); public static string Localize (string stringToken) { var strToken = new NSString(stringToken); IntPtr ptr = _Localize(strToken.Handle); string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } [DllImportAttribute("__Internal", EntryPoint = "PSPDFSetLocalizationDictionary")] private static extern void _SetLocalizationDictionary(IntPtr localizationDict); public static void SetLocalizationDictionary (NSDictionary localizationDict) { _SetLocalizationDictionary(localizationDict.Handle); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFResolvePathNames")] private static extern IntPtr _ResolvePathNames(IntPtr path, IntPtr fallbackPath); public static string ResolvePathNames (string path, string fallbackPath) { if(string.IsNullOrEmpty(path)) throw new ArgumentNullException(path); var argPath = new NSString(path); IntPtr ptr; if (string.IsNullOrEmpty(fallbackPath)) ptr = _ResolvePathNames(argPath.Handle, IntPtr.Zero); else { var argfallbackPath = new NSString(fallbackPath); ptr = _ResolvePathNames(argPath.Handle, argfallbackPath.Handle); } string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } // This needs some extra work since NSMutableString is not bound in monotouch due to it is not needed well until now xD //extern BOOL PSPDFResolvePathNamesInMutableString(NSMutableString *mutableString, NSString *fallbackPath, NSString *(^resolveUnknownPathBlock)(NSString *unknownPath)); private static bool PSPDFResolvePathNamesEnableLegacyBehavior; public static bool ResolvePathNamesEnableLegacyBehavior { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "PSPDFResolvePathNamesEnableLegacyBehavior"); PSPDFResolvePathNamesEnableLegacyBehavior = Convert.ToBoolean(Marshal.ReadByte(ptr)); return PSPDFResolvePathNamesEnableLegacyBehavior; } set { PSPDFResolvePathNamesEnableLegacyBehavior = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "PSPDFResolvePathNamesEnableLegacyBehavior"); Marshal.WriteByte(ptr, Convert.ToByte(PSPDFResolvePathNamesEnableLegacyBehavior)); } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFStripPDFFileType")] private static extern IntPtr _StripPDFFileType(IntPtr pdfFileName); public static string StripPDFFileType(string pdfFileName) { if (string.IsNullOrEmpty(pdfFileName)) return string.Empty; IntPtr ptr = _StripPDFFileType( new NSString(pdfFileName).Handle ); string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } [DllImportAttribute("__Internal", EntryPoint = "PSPDFGetViewInsideView")] private static extern IntPtr _GetViewInsideView(IntPtr view, IntPtr classNamePrefix); public static UIView GetViewInsideView(UIView view, string classNamePrefix) { if (string.IsNullOrEmpty(classNamePrefix)) throw new ArgumentException("Agument classNamePrefix cannot be null or Empty"); if(view == null) throw new ArgumentNullException("view"); IntPtr ptr = _GetViewInsideView(view.Handle, new NSString(classNamePrefix).Handle ); UIView val = (UIView) Runtime.GetNSObject(ptr); return val; } [DllImportAttribute("__Internal", EntryPoint = "PSPDFSimulatorAnimationDragCoefficient")] private static extern IntPtr _SimulatorAnimationDragCoefficient(); public static float SimulatorAnimationDragCoefficient { get { IntPtr intPtr = _SimulatorAnimationDragCoefficient(); unsafe { float* ptr = (float*)((void*)intPtr); return *ptr; } } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFFadeTransition")] private static extern IntPtr _FadeTransition(); public static CATransition FadeTransition { get { IntPtr intPtr = _SimulatorAnimationDragCoefficient(); CATransition t = (CATransition) Runtime.GetNSObject(intPtr); return t; } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFFadeTransitionWithDuration")] private static extern IntPtr _FadeTransitionWithDuration(IntPtr duration); public static CATransition FadeTransitionWithDuration(float duration) { unsafe { float m = duration; IntPtr intPtr = _FadeTransitionWithDuration(*(IntPtr*)&m); CATransition t = (CATransition) Runtime.GetNSObject(intPtr); return t; } } [DllImportAttribute("__Internal", EntryPoint = "PSDPFActionSheetStyleForBarButtonStyle")] private static extern int _ActionSheetStyleForBarButtonStyle(int barStyle, byte translucent); public static UIActionSheetStyle ActionSheetStyleForBarButtonStyle(UIBarStyle barStyle, bool translucent) { return (UIActionSheetStyle) _ActionSheetStyleForBarButtonStyle((int) barStyle, Convert.ToByte(translucent)); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFToolbarHeightForOrientation")] private static extern IntPtr _ToolbarHeightForOrientation(int orientation); public static float ToolbarHeightForOrientation(UIInterfaceOrientation orientation) { IntPtr intPtr = _ToolbarHeightForOrientation((int)orientation); unsafe { float* ptr = (float*)((void*)intPtr); return *ptr; } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFToolbarHeight")] private static extern IntPtr _ToolbarHeight(byte isSmall); public static float ToolbarHeight(bool isSmall) { IntPtr intPtr = _ToolbarHeight(Convert.ToByte(isSmall)); unsafe { float* ptr = (float*)((void*)intPtr); return *ptr; } } [DllImportAttribute("__Internal", EntryPoint = "psrangef")] private static extern IntPtr _psrangef(IntPtr minRange, IntPtr value, IntPtr maxRange); public static float PSRangeF(float minRange, float value, float maxRange) { unsafe { float _minRange = minRange; float _value = value; float _maxRange = maxRange; IntPtr pointer = _psrangef(*(IntPtr*)&_minRange, *(IntPtr*)&_value, *(IntPtr*)&_maxRange); float* ptr = (float*)((void*)pointer); return *ptr; } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFTrimString")] private static extern IntPtr _TrimString(IntPtr theString); public static string TrimString(string theString) { if (string.IsNullOrEmpty(theString)) return string.Empty; IntPtr ptr = _TrimString( new NSString(theString).Handle ); string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } [DllImportAttribute("__Internal", EntryPoint = "PSPDFIsControllerClassInPopoverAndVisible")] private static extern IntPtr _IsControllerClassInPopoverAndVisible(IntPtr popoverController, IntPtr controllerClass); public static bool IsControllerClassInPopoverAndVisible(UIPopoverController popoverController, Class controllerClass) { IntPtr ptr = _IsControllerClassInPopoverAndVisible(popoverController.Handle, controllerClass.Handle); return Convert.ToBoolean(Marshal.ReadByte(ptr)); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFIndexSetFromArray")] private static extern IntPtr _IndexSetFromArray(IntPtr array); public static NSIndexSet IndexSetFromArray(NSNumber [] array) { List<NSObject> obj = new List<NSObject>(); foreach (var item in array) obj.Add(item); NSArray arr = NSArray.FromNSObjects(obj.ToArray()); return new NSIndexSet(_IndexSetFromArray(arr.Handle)); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFCacheKeyboard")] private static extern void _CacheKeyboard(); public static void CacheKeyboard() { _CacheKeyboard(); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFIsRotationLocked")] [return: MarshalAsAttribute(UnmanagedType.Bool)] private static extern bool _IsRotationLocked(); [Since(6,0)] public static bool IsRotationLocked { get { return _IsRotationLocked(); } } [DllImportAttribute("__Internal", EntryPoint = "PSPDFLockRotation")] private static extern void _LockRotation(); [Since(6,0)] public static void LockRotation() { _LockRotation(); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFUnlockRotation")] private static extern void _UnlockRotation(); [Since(6,0)] public static void UnlockRotation() { _UnlockRotation(); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFTempFileURLWithPathExtension")] private static extern IntPtr PSPDFTempFileURLWithPathExtension(IntPtr prefix, IntPtr pathExtension); public static NSUrl TempFileURLWithPathExtension(string prefix, string pathExtension) { NSString pref = new NSString(prefix); NSString path = new NSString(pathExtension); NSUrl url = new NSUrl(PSPDFTempFileURLWithPathExtension(pref.Handle, path.Handle)); return url; } } ////////////////////////////////////////// //// PSPDFGlobalLock.h // ////////////////////////////////////////// public partial class PSPDFGlobalLock : NSObject { } ////////////////////////////////////// //// PSPDFGlyph.h // ////////////////////////////////////// public partial class PSPDFGlyph : NSObject { [DllImportAttribute("__Internal", EntryPoint = "PSPDFRectsFromGlyphs")] private static extern RectangleF [] _RectsFromGlyphs(IntPtr glyphs, CGAffineTransform t, RectangleF boundingBox); public static RectangleF [] RectsFromGlyphs(PSPDFGlyph [] glyphs, CGAffineTransform t, RectangleF boundingBox) { var objs = new List<NSObject>(); foreach (var glyph in glyphs) objs.Add(glyph); NSArray arry = NSArray.FromNSObjects(objs.ToArray()); return _RectsFromGlyphs(arry.Handle, t, boundingBox); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFBoundingBoxFromGlyphs")] private static extern RectangleF _BoundingBoxFromGlyphs(IntPtr glyphs, CGAffineTransform t); public static RectangleF BoundingBoxFromGlyphs(PSPDFGlyph [] glyphs, CGAffineTransform t) { var objs = new List<NSObject>(); foreach (var glyph in glyphs) objs.Add(glyph); NSArray arry = NSArray.FromNSObjects(objs.ToArray()); return _BoundingBoxFromGlyphs(arry.Handle, t); } [DllImportAttribute("__Internal", EntryPoint = "PSPDFReduceGlyphsToColumn")] private static extern IntPtr _ReduceGlyphsToColumn(IntPtr glyphs); public static NSArray ReduceGlyphsToColumn(PSPDFGlyph [] glyphs) { var objs = new List<NSObject>(); foreach (var glyph in glyphs) objs.Add(glyph); NSArray arry = NSArray.FromNSObjects(objs.ToArray()); return new NSArray(_ReduceGlyphsToColumn(arry.Handle)); } } ////////////////////////////////////////// //// PSPDFAnnotation.h // ////////////////////////////////////////// public partial class PSPDFAnnotation : PSPDFModel { [DllImportAttribute("__Internal", EntryPoint = "PSPDFTypeStringFromAnnotationType")] private static extern IntPtr _StringFromAnnotationType(PSPDFAnnotationType annotationType); public static string StringFromAnnotationType(PSPDFAnnotationType annotationType) { IntPtr ptr = _StringFromAnnotationType(annotationType); string val = (string) (NSString) Runtime.GetNSObject(ptr); return val; } } ////////////////////////////////////////// //// PSPDFTextParser.h // ////////////////////////////////////////// public partial class PSPDFTextParser : NSObject { public PSPDFTextParser (CGPDFPage pageRef, uint page, PSPDFDocument document, NSMutableDictionary fontCache, bool hideGlyphsOutsidePageRect, CGPDFBox PDFBox) : this(pageRef.Handle, page, document, fontCache, hideGlyphsOutsidePageRect, PDFBox) { } public PSPDFTextParser (CGPDFStream stream) : this (stream.Handle, true) { } } ////////////////////////////////////////////// //// PSPDFInkAnnotation.h // ////////////////////////////////////////////// public partial class PSPDFInkAnnotation : PSPDFAnnotation { // [DllImportAttribute("__Internal", EntryPoint = "PSPDFBezierPathGetPoints")] // private static extern IntPtr _PSPDFBezierPathGetPoints(IntPtr path); // // public static NSArray PSPDFBezierPathGetPoints(UIBezierPath path) // { // return new NSArray(_PSPDFBezierPathGetPoints(path.Handle)); // } // // [DllImportAttribute("__Internal", EntryPoint = "PSPDFBoundingBoxFromLines")] // private static extern RectangleF _BoundingBoxFromLines(IntPtr lines, float lineWidth); // // public static RectangleF BoundingBoxFromLines(NSArray lines, float lineWidth) // { // return _BoundingBoxFromLines(lines.Handle, lineWidth); // } // // [DllImportAttribute("__Internal", EntryPoint = "PSPDFConvertViewLinesToPDFLines")] // private static extern IntPtr _ConvertViewLinesToPDFLines(IntPtr lines, RectangleF cropBox, uint rotation, RectangleF bounds); // // public static NSArray ConvertViewLinesToPDFLines(NSArray lines, RectangleF cropBox, uint rotation, RectangleF bounds) // { // return new NSArray(_ConvertViewLinesToPDFLines(lines.Handle, cropBox, rotation, bounds)); // } // // [DllImportAttribute("__Internal", EntryPoint = "PSPDFConvertPDFLinesToViewLines")] // private static extern IntPtr _ConvertPDFLinesToViewLines(IntPtr lines, RectangleF cropBox, uint rotation, RectangleF bounds); // // public static NSArray ConvertPDFLinesToViewLines(NSArray lines, RectangleF cropBox, uint rotation, RectangleF bounds) // { // return new NSArray(_ConvertPDFLinesToViewLines(lines.Handle, cropBox, rotation, bounds)); // } } ////////////////////////////////////////////////// //// PSPDFHighlightAnnotation.h // ////////////////////////////////////////////////// public partial class PSPDFHighlightAnnotation : PSPDFAnnotation { } ////////////////////////////// //// PSPDFDocument.h // ////////////////////////////// public partial class PSPDFDocument : NSObject { public static PSPDFDocument PDFDocumentWithDataProvider (CGDataProvider dataProvider) { return DocumentWithDataProvider_(dataProvider.Handle); } public PSPDFDocument InitWithDataProvider (CGDataProvider dataProvider) { return InitWithDataProvider_(dataProvider.Handle); } public virtual PSPDFPageInfo PageInfoForPage (uint page, CGPDFPage pageRef) { return PageInfoForPage_ (page, pageRef.Handle); } // public void RenderPage (uint page, CGContext /*CGContextRef*/ context, SizeF fullSize, RectangleF clipRect, PSPDFAnnotation [] annotations, NSDictionary options) // { // RenderPage_ (page, context.Handle, fullSize, clipRect, annotations, options); // } public CGDataProvider DataProvider { get { IntPtr ptr = this.DataProvider_; return new CGDataProvider(ptr); } } } ////////////////////////////////////////////// //// PSPDFDocumentProvider.h // ////////////////////////////////////////////// public partial class PSPDFDocumentProvider : NSObject { public PSPDFDocumentProvider (CGDataProvider dataProvider, PSPDFDocument document) : this (dataProvider.Handle, document) { } public CGPDFDocument RequestDocumentRefWithOwner (NSObject owner) { return new CGPDFDocument(RequestDocumentRefWithOwner_ (owner)); } public void ReleaseDocumentRef (CGPDFDocument documentRef, NSObject owner) { ReleaseDocumentRef_ (documentRef.Handle, owner); } public void ReleasePageRef (CGPDFPage pageRef) { ReleasePageRef_ (pageRef.Handle); } public CGPDFPage RequestPageRefForPageNumber (uint page, out NSError error) { IntPtr ptr = RequestPageRefForPageNumber_ (page, out error); return new CGPDFPage(ptr); } public CGPDFPage RequestPageRefForPageNumber (uint page) { IntPtr ptr = RequestPageRefForPageNumber_ (page); return new CGPDFPage(ptr); } public CGDataProvider DataProvider { get { IntPtr ptr = this.DataProvider_; return new CGDataProvider(ptr); } } PSPDFPageInfo PageInfoForPage (uint page, CGPDFPage pageRef) { return PageInfoForPage_ (page, pageRef.Handle); } } ////////////////////////////////////////////// //// PSPDFDocumentProvider.h // ////////////////////////////////////////////// public partial class PSPDFOutlineParser : NSObject { // public static NSDictionary ResolveDestNames (NSSet destNames, CGPDFDocument document) // { // return ResolveDestNames_ (destNames, document.Handle); // } } ////////////////////////////////////////////// //// PSPDFAnnotationToolbar.h // ////////////////////////////////////////////// public partial class PSPDFAnnotationToolbar { public unsafe virtual void HideToolbar (bool animated, PSPDFAnnotationToolbarCompletionDel completionBlock) { if (completionBlock == null) { MonoTouch.ObjCRuntime.Messaging.void_objc_msgSend_bool_IntPtr (this.Handle, Selector.GetHandle ("hideToolbarAnimated:completion:"), animated, IntPtr.Zero ); return; } /* BlockLiteral *block_ptr_completionBlock; BlockLiteral block_completionBlock; block_completionBlock = new BlockLiteral (); block_ptr_completionBlock = &block_completionBlock; block_completionBlock.SetupBlock (static_InnerPSPDFAnnotationToolbarCompletionDel, completionBlock); MonoTouch.ObjCRuntime.Messaging.void_objc_msgSend_bool_IntPtr (this.Handle, Selector.GetHandle ("hideToolbarAnimated:completion:"), animated, (IntPtr) block_ptr_completionBlock); block_ptr_completionBlock->CleanupBlock (); */ } } ////////////////////////////////////////////// //// PSPDFAnnotationParser.h // ////////////////////////////////////////////// public partial class PSPDFAnnotationParser : NSObject { // public PSPDFAnnotation [] AnnotationsForPage (uint page, PSPDFAnnotationType type, CGPDFPage /*CGPDFPageRef*/ pageRef) // { // return AnnotationsForPage_ (page, type, pageRef.Handle); // } } ////////////////////////////////////////////// //// PSPDFNoteAnnotation.h // ////////////////////////////////////////////// public partial class PSPDFNoteAnnotation : PSPDFAnnotation { private static SizeF kPSPDFNoteAnnotationViewFixedSize; public static SizeF PSPDFNoteAnnotationViewFixedSize { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); kPSPDFNoteAnnotationViewFixedSize = Dlfcn.GetSizeF(RTLD_MAIN_ONLY, "kPSPDFNoteAnnotationViewFixedSize"); return kPSPDFNoteAnnotationViewFixedSize; } set { kPSPDFNoteAnnotationViewFixedSize = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym(RTLD_MAIN_ONLY, "kPSPDFNoteAnnotationViewFixedSize"); Marshal.StructureToPtr((object) kPSPDFNoteAnnotationViewFixedSize, ptr, true); } } } ////////////////////////////////////// //// PSPDFCache.h // ////////////////////////////////////// public partial class PSPDFCache : NSObject { } ////////////////////////////////////////////////// //// PSPDFWebViewController.h // ////////////////////////////////////////////////// public partial class PSPDFWebViewController : PSPDFBaseViewController { private static bool PSPDFHonorBlackAndTranslucentSettingsOnWebViewController; public static bool HonorBlackAndTranslucentSettingsOnWebViewController { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "PSPDFHonorBlackAndTranslucentSettingsOnWebViewController"); PSPDFHonorBlackAndTranslucentSettingsOnWebViewController = Convert.ToBoolean(Marshal.ReadByte(ptr)); return PSPDFHonorBlackAndTranslucentSettingsOnWebViewController; } set { PSPDFHonorBlackAndTranslucentSettingsOnWebViewController = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "PSPDFHonorBlackAndTranslucentSettingsOnWebViewController"); Marshal.WriteByte(ptr, Convert.ToByte(PSPDFHonorBlackAndTranslucentSettingsOnWebViewController)); } } } ////////////////////////////////////////////////// //// PSPDFSearchViewController.h // ////////////////////////////////////////////////// public partial class PSPDFSearchViewController : UITableViewController { private static uint kPSPDFMinimumSearchLength; public static uint MinimumSearchLength { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFMinimumSearchLength"); kPSPDFMinimumSearchLength = (uint)Marshal.PtrToStructure(ptr, typeof(uint)); return kPSPDFMinimumSearchLength; } set { kPSPDFMinimumSearchLength = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFMinimumSearchLength"); byte [] data = BitConverter.GetBytes(kPSPDFMinimumSearchLength); Marshal.Copy(data, 0, ptr, data.Length); } } } ////////////////////////////////////////////////////// //// PSPDFAESCryptoDataProvider.h // ////////////////////////////////////////////////////// public partial class PSPDFAESCryptoDataProvider : NSObject { public CGDataProvider DataProvider { get { IntPtr ptr = this.DataProvider_; return new CGDataProvider(ptr); } } public bool isAESCryptoDataProvider (CGDataProvider dataProvider) { return IsAESCryptoDataProvider_ (dataProvider.Handle); } } ////////////////////////////////////////////////////// //// PSPDFFileAnnotationProvider.h // ////////////////////////////////////////////////////// public partial class PSPDFFileAnnotationProvider : NSObject { public virtual PSPDFAnnotation [] AnnotationsForPage (uint page, CGPDFPage pageRef) { return AnnotationsForPage_ (page, pageRef.Handle); } public virtual PSPDFAnnotation [] ParseAnnotationsForPage (uint page, CGPDFPage pageRef) { return ParseAnnotationsForPage_ (page, pageRef.Handle); } public bool TryLoadAnnotationsFromFileWithError (out NSError error) { unsafe { IntPtr val; IntPtr val_addr = (IntPtr) ((IntPtr *) &val); bool ret = _TryLoadAnnotationsFromFileWithError (val_addr); error = (NSError) Runtime.GetNSObject (val); return ret; } } } ////////////////////////////////////////////////// //// PSPDFOpenInBarButtonItem.h // ////////////////////////////////////////////////// public partial class PSPDFOpenInBarButtonItem : PSPDFBarButtonItem { private static bool kPSPDFCheckIfCompatibleAppsAreInstalled; public static bool CheckIfCompatibleAppsAreInstalled { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFCheckIfCompatibleAppsAreInstalled"); kPSPDFCheckIfCompatibleAppsAreInstalled = Convert.ToBoolean(Marshal.ReadByte(ptr)); return kPSPDFCheckIfCompatibleAppsAreInstalled; } set { kPSPDFCheckIfCompatibleAppsAreInstalled = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFCheckIfCompatibleAppsAreInstalled"); Marshal.WriteByte(ptr, Convert.ToByte(kPSPDFCheckIfCompatibleAppsAreInstalled)); } } } ////////////////////////////////////// //// PSPDFMenuItem.h // ////////////////////////////////////// public partial class PSPDFMenuItem : UIMenuItem { private static bool kPSPDFAllowImagesForMenuItems; public static bool AllowImagesForMenuItems { get { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFAllowImagesForMenuItems"); kPSPDFAllowImagesForMenuItems = Convert.ToBoolean(Marshal.ReadByte(ptr)); return kPSPDFAllowImagesForMenuItems; } set { kPSPDFAllowImagesForMenuItems = value; IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "kPSPDFAllowImagesForMenuItems"); Marshal.WriteByte(ptr, Convert.ToByte(kPSPDFAllowImagesForMenuItems)); } } } ////////////////////////////////////////////////////// //// PSPDFOutlineViewController.h // ////////////////////////////////////////////////////// public partial class PSPDFOutlineViewController : PSPDFStatefulTableViewController { public PSPDFOutlineViewController (PSPDFViewController controller) : this (controller.Document, controller.Handle) { } } ////////////////////////////////////////// //// UIImage+PSPDFKitAdditions // ////////////////////////////////////////// public partial class UIImageExtension : UIImage { public static UIImageExtension FromUIImage (UIImage img) { return (UIImageExtension) img; } } public static class UIImageExtensionExMethods { /// <summary> /// Converts from UIImageExtension to UIImage /// </summary> /// <returns> /// Returns UIImage from UIImageExtension. /// </returns> /// <param name='imgExt'> /// The UIImageExtension to conver to UIImage. /// </param> public static UIImage ToUIImage (this UIImageExtension imgExt) { return (UIImage) imgExt; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using AutoyaFramework; using AutoyaFramework.Settings.Auth; using Miyamasu; using UnityEngine; /** tests for Autoya Authenticated HTTP. Autoya strongly handle these server-related errors which comes from game-server. these test codes are depends on online env + "https://httpbin.org". */ public class AuthenticatedHTTPImplementationTests : MiyamasuTestRunner { private void DeleteAllData(string path) { if (Directory.Exists(path)) { Directory.Delete(path, true); } } [MSetup] public IEnumerator Setup() { Autoya.ResetAllForceSetting(); var dataPath = Application.persistentDataPath; var fwPath = Path.Combine(dataPath, AuthSettings.AUTH_STORED_FRAMEWORK_DOMAIN); DeleteAllData(fwPath); Autoya.TestEntryPoint(dataPath); while (!Autoya.Auth_IsAuthenticated()) { yield return false; } var authenticated = false; Autoya.Auth_SetOnAuthenticated( () => { authenticated = true; } ); Autoya.Auth_SetOnBootAuthFailed( (code, reason) => { Debug.LogError("code:" + code + " reason:" + reason); } ); yield return WaitUntil( () => authenticated, () => { throw new TimeoutException("failed to auth."); } ); True(Autoya.Auth_IsAuthenticated(), "not logged in."); } [MTeardown] public IEnumerator Teardown() { Autoya.ResetAllForceSetting(); Autoya.Shutdown(); while (GameObject.Find("AutoyaMainthreadDispatcher") != null) { yield return null; } } [MTest] public IEnumerator AutoyaHTTPGet() { var result = string.Empty; Autoya.Http_Get( "https://httpbin.org/get", (conId, resultData) => { result = "done!:" + resultData; }, (conId, code, reason, autoyaStatus) => { True(false, "failed. code:" + code + " reason:" + reason); } ); yield return WaitUntil( () => !string.IsNullOrEmpty(result), () => { throw new TimeoutException("timeout."); } ); } [MTest] public IEnumerator AutoyaHTTPGetWithAdditionalHeader() { var result = string.Empty; Autoya.Http_Get( "https://httpbin.org/headers", (conId, resultData) => { result = resultData; }, (conId, code, reason, autoyaStatus) => { True(false, "failed. code:" + code + " reason:" + reason); }, new Dictionary<string, string>{ {"Hello", "World"} } ); yield return WaitUntil( () => (result.Contains("Hello") && result.Contains("World")), () => { throw new TimeoutException("timeout."); } ); } [MTest] public IEnumerator AutoyaHTTPGetFailWith404() { var resultCode = 0; Autoya.Http_Get( "https://httpbin.org/status/404", (conId, resultData) => { True(false, "unexpected succeeded. resultData:" + resultData); }, (conId, code, reason, autoyaStatus) => { resultCode = code; } ); yield return WaitUntil( () => (resultCode != 0), () => { throw new TimeoutException("timeout."); } ); // result should be have reason, True(resultCode == 404, "code unmatched. resultCode:" + resultCode); } [MTest] public IEnumerator AutoyaHTTPGetFailWithUnauth() { Autoya.forceSetHttpCodeAsUnauthorized = true; var unauthorized = false; /* dummy server returns 401 forcibly. */ Autoya.Http_Get( "https://httpbin.org/status/401", (conId, resultData) => { Fail("never succeed."); }, (conId, code, reason, autoyaStatus) => { unauthorized = autoyaStatus.isAuthFailed; Autoya.forceSetHttpCodeAsUnauthorized = false; } ); yield return WaitUntil( () => unauthorized, () => { throw new TimeoutException("timeout."); } ); // token refresh feature is already running. wait end. yield return WaitUntil( () => Autoya.Auth_IsAuthenticated(), () => { throw new TimeoutException("failed to refresh token."); } ); } [MTest] public IEnumerator AutoyaHTTPGetFailWithTimeout() { var failedCode = -1; var timeoutError = string.Empty; /* fake server should be response in 1msec. server responses 1 sec later. it is impossible. */ Autoya.Http_Get( "https://httpbin.org/delay/1", (conId, resultData) => { True(false, "got success result."); }, (conId, code, reason, autoyaStatus) => { failedCode = code; timeoutError = reason; }, null, 0.0001 ); yield return WaitUntil( () => { return !string.IsNullOrEmpty(timeoutError); }, () => { throw new TimeoutException("timeout."); } ); True(failedCode == BackyardSettings.HTTP_TIMEOUT_CODE, "unmatch. failedCode:" + failedCode + " message:" + timeoutError); } [MTest] public IEnumerator AutoyaHTTPPost() { var result = string.Empty; Autoya.Http_Post( "https://httpbin.org/post", "data", (conId, resultData) => { result = "done!:" + resultData; }, (conId, code, reason, autoyaStatus) => { // do nothing. } ); yield return WaitUntil( () => !string.IsNullOrEmpty(result), () => { throw new TimeoutException("timeout."); } ); } /* target test site does not support show post request. hmmm,,, */ // [MTest] public IEnumerator AutoyaHTTPPostWithAdditionalHeader () { // var result = string.Empty; // Autoya.Http_Post( // "https://httpbin.org/headers", // "data", // (conId, resultData) => { // TestLogger.Log("resultData:" + resultData); // result = resultData; // }, // (conId, code, reason) => { // TestLogger.Log("fmmmm,,,,, AutoyaHTTPPostWithAdditionalHeader failed conId:" + conId + " reason:" + reason); // // do nothing. // }, // new Dictionary<string, string>{ // {"Hello", "World"} // } // ); // var wait = yield return WaitUntil( // () => (result.Contains("Hello") && result.Contains("World")), // 5 // ); // if (!wait) return false; // return true; // } [MTest] public IEnumerator AutoyaHTTPPostFailWith404() { var resultCode = 0; Autoya.Http_Post( "https://httpbin.org/status/404", "data", (conId, resultData) => { // do nothing. }, (conId, code, reason, autoyaStatus) => { resultCode = code; } ); yield return WaitUntil( () => (resultCode == 404), () => { throw new TimeoutException("failed to detect 404."); } ); // result should be have reason, True(resultCode == 404, "code unmatched. resultCode:" + resultCode); } [MTest] public IEnumerator AutoyaHTTPPostFailWithUnauth() { Autoya.forceSetHttpCodeAsUnauthorized = true; var unauthorized = false; /* dummy server returns 401 forcibly. */ Autoya.Http_Post( "https://httpbin.org/status/401", "dummy_data", (conId, resultData) => { Fail(); }, (conId, code, reason, autoyaStatus) => { unauthorized = autoyaStatus.isAuthFailed; Autoya.forceSetHttpCodeAsUnauthorized = false; } ); yield return WaitUntil( () => unauthorized, () => { throw new TimeoutException("timeout."); }, 10 ); // token refresh feature is already running. wait end. yield return WaitUntil( () => Autoya.Auth_IsAuthenticated(), () => { throw new TimeoutException("failed to refresh token."); }, 20 ); } [MTest] public IEnumerator AutoyaHTTPPostFailWithTimeout() { var timeoutError = string.Empty; /* fake server should be response 1msec */ Autoya.Http_Post( "https://httpbin.org/delay/1", "data", (conId, resultData) => { True(false, "got success result."); }, (conId, code, reason, autoyaStatus) => { True(code == BackyardSettings.HTTP_TIMEOUT_CODE, "not match. code:" + code + " reason:" + reason); timeoutError = reason; }, null, 0.0001// 1ms ); yield return WaitUntil( () => { return !string.IsNullOrEmpty(timeoutError); }, () => { throw new TimeoutException("timeout."); } ); } }
// 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 BinaryShiftTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckByteShiftTest(bool useInterpreter) { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyByteShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckSByteShiftTest(bool useInterpreter) { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifySByteShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortShiftTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyUShortShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortShiftTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyShortShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntShiftTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyUIntShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntShiftTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyIntShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongShiftTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyULongShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongShiftTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyLongShift(array[i], useInterpreter); } } #endregion #region Test verifiers private static int[] s_shifts = new[] { int.MinValue, -1, 0, 1, 2, 31, 32, 63, 64, int.MaxValue }; private static void VerifyByteShift(byte a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyByteShift(a, b, true, useInterpreter); VerifyByteShift(a, b, false, useInterpreter); } } private static void VerifyByteShift(byte a, int b, bool left, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(int))) ); Func<byte> f = e.Compile(useInterpreter); Assert.Equal((byte)(left ? a << b : a >> b), f()); } private static void VerifySByteShift(sbyte a, bool useInterpreter) { foreach (var b in s_shifts) { VerifySByteShift(a, b, true, useInterpreter); VerifySByteShift(a, b, false, useInterpreter); } } private static void VerifySByteShift(sbyte a, int b, bool left, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(int))) ); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal((sbyte)(left ? a << b : a >> b), f()); } private static void VerifyUShortShift(ushort a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyUShortShift(a, b, true, useInterpreter); VerifyUShortShift(a, b, false, useInterpreter); } } private static void VerifyUShortShift(ushort a, int b, bool left, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(int))) ); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal((ushort)(left ? a << b : a >> b), f()); } private static void VerifyShortShift(short a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyShortShift(a, b, true, useInterpreter); VerifyShortShift(a, b, false, useInterpreter); } } private static void VerifyShortShift(short a, int b, bool left, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(int))) ); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(left ? a << b : a >> b), f()); } private static void VerifyUIntShift(uint a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyUIntShift(a, b, true, useInterpreter); VerifyUIntShift(a, b, false, useInterpreter); } } private static void VerifyUIntShift(uint a, int b, bool left, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(int))) ); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyIntShift(int a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyIntShift(a, b, true, useInterpreter); VerifyIntShift(a, b, false, useInterpreter); } } private static void VerifyIntShift(int a, int b, bool left, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))) ); Func<int> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyULongShift(ulong a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyULongShift(a, b, true, useInterpreter); VerifyULongShift(a, b, false, useInterpreter); } } private static void VerifyULongShift(ulong a, int b, bool left, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(int))) ); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyLongShift(long a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyLongShift(a, b, true, useInterpreter); VerifyLongShift(a, b, false, useInterpreter); } } private static void VerifyLongShift(long a, int b, bool left, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(int))) ); Func<long> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } #endregion [Fact] public static void CannotReduceLeft() { Expression exp = Expression.LeftShift(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void CannotReduceRight() { Expression exp = Expression.RightShift(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void LeftThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.LeftShift(null, Expression.Constant(""))); } [Fact] public static void LeftThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.LeftShift(Expression.Constant(""), null)); } [Fact] public static void RightThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.RightShift(null, Expression.Constant(""))); } [Fact] public static void RightThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.RightShift(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void LeftThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.LeftShift(value, Expression.Constant(1))); } [Fact] public static void LeftThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.LeftShift(Expression.Constant(1), value)); } [Fact] public static void RightThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.RightShift(value, Expression.Constant(1))); } [Fact] public static void RightThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.RightShift(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { var e1 = Expression.LeftShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a << b)", e1.ToString()); var e2 = Expression.RightShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a >> b)", e2.ToString()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using RunTests.Cache; using Newtonsoft.Json.Linq; using RestSharp; using System.Collections.Immutable; using Newtonsoft.Json; using System.Reflection; using System.Diagnostics; namespace RunTests { internal sealed partial class Program { internal const int ExitSuccess = 0; internal const int ExitFailure = 1; private const long MaxTotalDumpSizeInMegabytes = 4096; internal static int Main(string[] args) { Logger.Log("RunTest command line"); Logger.Log(string.Join(" ", args)); var options = Options.Parse(args); if (options == null) { Options.PrintUsage(); return ExitFailure; } // Setup cancellation for ctrl-c key presses var cts = new CancellationTokenSource(); Console.CancelKeyPress += delegate { cts.Cancel(); }; var result = Run(options, cts.Token).GetAwaiter().GetResult(); CheckTotalDumpFilesSize(); return result; } private static async Task<int> Run(Options options, CancellationToken cancellationToken) { if (options.Timeout == null) { return await RunCore(options, cancellationToken); } var timeoutTask = Task.Delay(options.Timeout.Value); var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var runTask = RunCore(options, cts.Token); if (cancellationToken.IsCancellationRequested) { return ExitFailure; } var finishedTask = await Task.WhenAny(timeoutTask, runTask); if (finishedTask == timeoutTask) { await HandleTimeout(options, cancellationToken); cts.Cancel(); try { // Need to await here to ensure that all of the child processes are properly // killed before we exit. await runTask; } catch { // Cancellation exceptions expected here. } return ExitFailure; } return await runTask; } private static async Task<int> RunCore(Options options, CancellationToken cancellationToken) { if (!CheckAssemblyList(options)) { return ExitFailure; } var testExecutor = CreateTestExecutor(options); var testRunner = new TestRunner(options, testExecutor); var start = DateTime.Now; var assemblyInfoList = GetAssemblyList(options); ConsoleUtil.WriteLine($"Data Storage: {testExecutor.DataStorage.Name}"); ConsoleUtil.WriteLine($"Proc dump location: {options.ProcDumpDirectory}"); ConsoleUtil.WriteLine($"Running {options.Assemblies.Count()} test assemblies in {assemblyInfoList.Count} partitions"); var result = await testRunner.RunAllAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true); var elapsed = DateTime.Now - start; ConsoleUtil.WriteLine($"Test execution time: {elapsed}"); LogProcessResultDetails(result.ProcessResults); WriteLogFile(options); DisplayResults(options.Display, result.TestResults); if (CanUseWebStorage() && options.UseCachedResults) { await SendRunStats(options, testExecutor.DataStorage, elapsed, result, assemblyInfoList.Count, cancellationToken).ConfigureAwait(true); } if (!result.Succeeded) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Test failures encountered"); return ExitFailure; } ConsoleUtil.WriteLine($"All tests passed"); return ExitSuccess; } private static void LogProcessResultDetails(ImmutableArray<ProcessResult> processResults) { Logger.Log("### Begin logging executed process details"); foreach (var processResult in processResults) { var process = processResult.Process; var startInfo = process.StartInfo; Logger.Log($"### Begin {process.Id}"); Logger.Log($"### {startInfo.FileName} {startInfo.Arguments}"); Logger.Log($"### Exit code {process.ExitCode}"); Logger.Log("### Standard Output"); foreach (var line in processResult.OutputLines) { Logger.Log(line); } Logger.Log("### Standard Error"); foreach (var line in processResult.ErrorLines) { Logger.Log(line); } Logger.Log($"### End {process.Id}"); } Logger.Log("End logging executed process details"); } private static void WriteLogFile(Options options) { var logFilePath = Path.Combine(options.LogsDirectory, "runtests.log"); try { using (var writer = new StreamWriter(logFilePath, append: false)) { Logger.WriteTo(writer); } } catch (Exception ex) { ConsoleUtil.WriteLine($"Error writing log file {logFilePath}"); ConsoleUtil.WriteLine(ex.ToString()); } Logger.Clear(); } /// <summary> /// Invoked when a timeout occurs and we need to dump all of the test processes and shut down /// the runnner. /// </summary> private static async Task HandleTimeout(Options options, CancellationToken cancellationToken) { async Task DumpProcess(Process targetProcess, string procDumpExeFilePath, string dumpFilePath) { var name = targetProcess.ProcessName; // Our space for saving dump files is limited. Skip dumping for processes that won't contribute // to bug investigations. if (name == "procdump" || name == "conhost") { return; } ConsoleUtil.Write($"Dumping {name} {targetProcess.Id} to {dumpFilePath} ... "); try { var args = $"-accepteula -ma {targetProcess.Id} {dumpFilePath}"; var processInfo = ProcessRunner.CreateProcess(procDumpExeFilePath, args, cancellationToken: cancellationToken); var processOutput = await processInfo.Result; // The exit code for procdump doesn't obey standard windows rules. It will return non-zero // for succesful cases (possibly returning the count of dumps that were written). Best // backup is to test for the dump file being present. if (File.Exists(dumpFilePath)) { ConsoleUtil.WriteLine("succeeded"); } else { ConsoleUtil.WriteLine($"FAILED with {processOutput.ExitCode}"); ConsoleUtil.WriteLine($"{procDumpExeFilePath} {args}"); ConsoleUtil.WriteLine(string.Join(Environment.NewLine, processOutput.OutputLines)); } } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { ConsoleUtil.WriteLine("FAILED"); ConsoleUtil.WriteLine(ex.Message); Logger.Log("Failed to dump process", ex); } } ConsoleUtil.WriteLine("Roslyn Error: test timeout exceeded, dumping remaining processes"); var procDumpInfo = GetProcDumpInfo(options); if (procDumpInfo != null) { var dumpDir = procDumpInfo.Value.DumpDirectory; var counter = 0; foreach (var proc in ProcessUtil.GetProcessTree(Process.GetCurrentProcess()).OrderBy(x => x.ProcessName)) { var dumpFilePath = Path.Combine(dumpDir, $"{proc.ProcessName}-{counter}.dmp"); await DumpProcess(proc, procDumpInfo.Value.ProcDumpFilePath, dumpFilePath); counter++; } } else { ConsoleUtil.WriteLine("Could not locate procdump"); } WriteLogFile(options); } private static ProcDumpInfo? GetProcDumpInfo(Options options) { if (!string.IsNullOrEmpty(options.ProcDumpDirectory)) { return new ProcDumpInfo(Path.Combine(options.ProcDumpDirectory, "procdump.exe"), options.LogsDirectory); } return null; } /// <summary> /// Quick sanity check to look over the set of assemblies to make sure they are valid and something was /// specified. /// </summary> private static bool CheckAssemblyList(Options options) { var anyMissing = false; foreach (var assemblyPath in options.Assemblies) { if (!File.Exists(assemblyPath)) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"The file '{assemblyPath}' does not exist, is an invalid file name, or you do not have sufficient permissions to read the specified file."); anyMissing = true; } } if (anyMissing) { return false; } if (options.Assemblies.Count == 0) { ConsoleUtil.WriteLine("No test assemblies specified."); return false; } return true; } private static List<AssemblyInfo> GetAssemblyList(Options options) { var scheduler = new AssemblyScheduler(options); var list = new List<AssemblyInfo>(); foreach (var assemblyPath in options.Assemblies.OrderByDescending(x => new FileInfo(x).Length)) { var name = Path.GetFileName(assemblyPath); // As a starting point we will just schedule the items we know to be a performance // bottleneck. Can adjust as we get real data. if (name == "Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.dll" || name == "Microsoft.CodeAnalysis.EditorFeatures.UnitTests.dll" || name == "Roslyn.Services.Editor.UnitTests2.dll" || name == "Microsoft.VisualStudio.LanguageServices.UnitTests.dll" || name == "Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.dll" || name == "Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.dll") { list.AddRange(scheduler.Schedule(assemblyPath)); } else { list.Add(scheduler.CreateAssemblyInfo(assemblyPath)); } } return list; } private static void DisplayResults(Display display, ImmutableArray<TestResult> testResults) { foreach (var cur in testResults) { var open = false; switch (display) { case Display.All: open = true; break; case Display.None: open = false; break; case Display.Succeeded: open = cur.Succeeded; break; case Display.Failed: open = !cur.Succeeded; break; } if (open) { ProcessRunner.OpenFile(cur.ResultsFilePath); } } } private static bool CanUseWebStorage() { // The web caching layer is still being worked on. For now want to limit it to Roslyn developers // and Jenkins runs by default until we work on this a bit more. Anyone reading this who wants // to try it out should feel free to opt into this. return StringComparer.OrdinalIgnoreCase.Equals("REDMOND", Environment.UserDomainName) || Constants.IsJenkinsRun; } private static ITestExecutor CreateTestExecutor(Options options) { var testExecutionOptions = new TestExecutionOptions( xunitPath: options.XunitPath, procDumpInfo: GetProcDumpInfo(options), logsDirectory: options.LogsDirectory, trait: options.Trait, noTrait: options.NoTrait, useHtml: options.UseHtml, test64: options.Test64, testVsi: options.TestVsi); var processTestExecutor = new ProcessTestExecutor(testExecutionOptions); if (!options.UseCachedResults) { return processTestExecutor; } // The web caching layer is still being worked on. For now want to limit it to Roslyn developers // and Jenkins runs by default until we work on this a bit more. Anyone reading this who wants // to try it out should feel free to opt into this. IDataStorage dataStorage = new LocalDataStorage(); if (CanUseWebStorage()) { dataStorage = new WebDataStorage(); } return new CachingTestExecutor(testExecutionOptions, processTestExecutor, dataStorage); } /// <summary> /// Order the assembly list so that the largest assemblies come first. This /// is not ideal as the largest assembly does not necessarily take the most time. /// </summary> /// <param name="list"></param> private static IOrderedEnumerable<string> OrderAssemblyList(IEnumerable<string> list) { return list.OrderByDescending((assemblyName) => new FileInfo(assemblyName).Length); } private static async Task SendRunStats(Options options, IDataStorage dataStorage, TimeSpan elapsed, RunAllResult result, int partitionCount, CancellationToken cancellationToken) { var testRunData = new TestRunData() { Cache = dataStorage.Name, ElapsedSeconds = (int)elapsed.TotalSeconds, JenkinsUrl = Constants.JenkinsUrl, IsJenkins = Constants.IsJenkinsRun, Is32Bit = !options.Test64, AssemblyCount = options.Assemblies.Count, ChunkCount = partitionCount, CacheCount = result.CacheCount, Succeeded = result.Succeeded, HasErrors = Logger.HasErrors }; var request = new RestRequest("api/testData/run", Method.POST); request.RequestFormat = DataFormat.Json; request.AddParameter("text/json", JsonConvert.SerializeObject(testRunData), ParameterType.RequestBody); try { var client = new RestClient(Constants.DashboardUriString); var response = await client.ExecuteTaskAsync(request); if (response.StatusCode != System.Net.HttpStatusCode.NoContent) { Logger.Log($"Unable to send results: {response.ErrorMessage}"); } } catch { Logger.Log("Unable to send results"); } } /// <summary> /// Checks the total size of dump file and removes files exceeding a limit. /// </summary> private static void CheckTotalDumpFilesSize() { var directory = Directory.GetCurrentDirectory(); var dumpFiles = Directory.EnumerateFiles(directory, "*.dmp", SearchOption.AllDirectories).ToArray(); long currentTotalSize = 0; foreach (var dumpFile in dumpFiles) { long fileSizeInMegabytes = (new FileInfo(dumpFile).Length / 1024) / 1024; currentTotalSize += fileSizeInMegabytes; if (currentTotalSize > MaxTotalDumpSizeInMegabytes) { File.Delete(dumpFile); } } } } }
// 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.Collections.ObjectModel; using Xunit; namespace System.Collections.ObjectModel.Tests { /// <summary> /// Since <see cref="Collection{T}"/> is just a wrapper base class around an <see cref="IList{T}"/>, /// we just verify that the underlying list is what we expect, validate that the calls which /// we expect are forwarded to the underlying list, and verify that the exceptions we expect /// are thrown. /// </summary> public class CollectionTests : CollectionTestBase { private static readonly Collection<int> s_empty = new Collection<int>(); [Fact] public static void Ctor_Empty() { Collection<int> collection = new Collection<int>(); Assert.Empty(collection); } [Fact] public static void Ctor_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => new Collection<int>(null)); } [Fact] public static void Ctor_IList() { var collection = new TestCollection<int>(s_intArray); Assert.Same(s_intArray, collection.GetItems()); Assert.Equal(s_intArray.Length, collection.Count); } [Fact] public static void GetItems_CastableToList() { // // Although MSDN only documents that Collection<T>.Items returns an IList<T>, // apps have made it through the Windows Store that successfully cast the return value // of Items to List<T>. // // Thus, we must grumble and continue to honor this behavior. // TestCollection<int> c = new TestCollection<int>(); IList<int> il = c.GetItems(); // Avoid using the List<T> type so that we don't have to depend on the System.Collections contract Type type = il.GetType(); Assert.Equal(1, type.GenericTypeArguments.Length); Assert.Equal(typeof(int), type.GenericTypeArguments[0]); Assert.Equal("System.Collections.Generic.List`1", string.Format("{0}.{1}", type.Namespace, type.Name)); } [Fact] public static void Item_Get_Set() { var collection = new ModifiableCollection<int>(s_intArray); for (int i = 0; i < s_intArray.Length; i++) { collection[i] = i; Assert.Equal(i, collection[i]); } } [Fact] public static void Item_Get_Set_InvalidIndex_ThrowsArgumentOutOfRangeException() { var collection = new ModifiableCollection<int>(s_intArray); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[-1]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[s_intArray.Length]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => s_empty[0]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[-1] = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[s_intArray.Length] = 0); } [Fact] public static void Item_Set_InvalidType_ThrowsArgumentException() { var collection = new Collection<int>(new Collection<int>(s_intArray)); AssertExtensions.Throws<ArgumentException>("value", () => ((IList)collection)[1] = "Two"); } [Fact] public static void IsReadOnly_ReturnsTrue() { var collection = new Collection<int>(s_intArray); Assert.True(((IList)collection).IsReadOnly); Assert.True(((IList<int>)collection).IsReadOnly); } [Fact] public static void Insert_ZeroIndex() { const int itemsToInsert = 5; var collection = new ModifiableCollection<int>(); for (int i = itemsToInsert - 1; i >= 0; i--) { collection.Insert(0, i); } for (int i = 0; i < itemsToInsert; i++) { Assert.Equal(i, collection[i]); } } [Fact] public static void Insert_MiddleIndex() { const int insertIndex = 3; const int itemsToInsert = 5; var collection = new ModifiableCollection<int>(s_intArray); for (int i = 0; i < itemsToInsert; i++) { collection.Insert(insertIndex + i, i); } // Verify from the beginning of the collection up to insertIndex for (int i = 0; i < insertIndex; i++) { Assert.Equal(s_intArray[i], collection[i]); } // Verify itemsToInsert items starting from insertIndex for (int i = 0; i < itemsToInsert; i++) { Assert.Equal(i, collection[insertIndex + i]); } // Verify the rest of the items in the collection for (int i = insertIndex; i < s_intArray.Length; i++) { Assert.Equal(s_intArray[i], collection[itemsToInsert + i]); } } [Fact] public static void Insert_EndIndex() { const int itemsToInsert = 5; var collection = new ModifiableCollection<int>(s_intArray); for (int i = 0; i < itemsToInsert; i++) { collection.Insert(collection.Count, i); } for (int i = 0; i < itemsToInsert; i++) { Assert.Equal(i, collection[s_intArray.Length + i]); } } [Fact] public static void Insert_InvalidIndex_ThrowsArgumentOutOfRangeException() { var collection = new ModifiableCollection<int>(s_intArray); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Insert(-1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Insert(s_intArray.Length + 1, 0)); } [Fact] public static void Clear() { var collection = new ModifiableCollection<int>(s_intArray); collection.Clear(); Assert.Equal(0, collection.Count); } [Fact] public static void Contains() { var collection = new Collection<int>(s_intArray); for (int i = 0; i < s_intArray.Length; i++) { Assert.True(collection.Contains(s_intArray[i])); } for (int i = 0; i < s_excludedFromIntArray.Length; i++) { Assert.False(collection.Contains(s_excludedFromIntArray[i])); } } [Fact] public static void CopyTo() { var collection = new Collection<int>(s_intArray); const int targetIndex = 3; int[] intArray = new int[s_intArray.Length + targetIndex]; Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentException>(null, () => ((ICollection)collection).CopyTo(new int[s_intArray.Length, s_intArray.Length], 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(intArray, -1)); AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(intArray, s_intArray.Length - 1)); collection.CopyTo(intArray, targetIndex); for (int i = targetIndex; i < intArray.Length; i++) { Assert.Equal(collection[i - targetIndex], intArray[i]); } object[] objectArray = new object[s_intArray.Length + targetIndex]; ((ICollection)collection).CopyTo(intArray, targetIndex); for (int i = targetIndex; i < intArray.Length; i++) { Assert.Equal(collection[i - targetIndex], intArray[i]); } } [Fact] public static void IndexOf() { var collection = new Collection<int>(s_intArray); for (int i = 0; i < s_intArray.Length; i++) { int item = s_intArray[i]; Assert.Equal(Array.IndexOf(s_intArray, item), collection.IndexOf(item)); } for (int i = 0; i < s_excludedFromIntArray.Length; i++) { Assert.Equal(-1, collection.IndexOf(s_excludedFromIntArray[i])); } } private static readonly int[] s_intSequence = new int[] { 0, 1, 2, 3, 4, 5 }; [Fact] public static void RemoveAt() { VerifyRemoveAt(0, 1, new[] { 1, 2, 3, 4, 5 }); VerifyRemoveAt(3, 2, new[] { 0, 1, 2, 5 }); VerifyRemoveAt(4, 1, new[] { 0, 1, 2, 3, 5 }); VerifyRemoveAt(5, 1, new[] { 0, 1, 2, 3, 4 }); VerifyRemoveAt(0, 6, s_empty); } private static void VerifyRemoveAt(int index, int count, IEnumerable<int> expected) { var collection = new ModifiableCollection<int>(s_intSequence); for (int i = 0; i < count; i++) { collection.RemoveAt(index); } Assert.Equal(expected, collection); } [Fact] public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { var collection = new ModifiableCollection<int>(s_intSequence); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveAt(s_intArray.Length)); } [Fact] public static void MembersForwardedToUnderlyingIList() { var expectedApiCalls = IListApi.Count | IListApi.IsReadOnly | IListApi.IndexerGet | IListApi.IndexerSet | IListApi.Insert | IListApi.Clear | IListApi.Contains | IListApi.CopyTo | IListApi.GetEnumeratorGeneric | IListApi.IndexOf | IListApi.RemoveAt | IListApi.GetEnumerator; var list = new CallTrackingIList<int>(expectedApiCalls); var collection = new Collection<int>(list); int count = collection.Count; bool readOnly = ((IList)collection).IsReadOnly; int x = collection[0]; collection[0] = 22; collection.Add(x); collection.Clear(); collection.Contains(x); collection.CopyTo(s_intArray, 0); collection.GetEnumerator(); collection.IndexOf(x); collection.Insert(0, x); collection.Remove(x); collection.RemoveAt(0); ((IEnumerable)collection).GetEnumerator(); list.AssertAllMembersCalled(); } [Fact] public void ReadOnly_ModifyingCollection_ThrowsNotSupportedException() { var collection = new Collection<int>(s_intArray); Assert.Throws<NotSupportedException>(() => collection[0] = 0); Assert.Throws<NotSupportedException>(() => collection.Add(0)); Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Throws<NotSupportedException>(() => collection.Insert(0, 0)); Assert.Throws<NotSupportedException>(() => collection.Remove(0)); Assert.Throws<NotSupportedException>(() => collection.RemoveAt(0)); } [Fact] public void IList_Add_ValidItemButThrowsInvalidCastExceptionFromOverride_ThrowsInvalidCastException() { var collection = new ObservableCollection<int>(); collection.CollectionChanged += delegate { throw new InvalidCastException(); }; Assert.Throws<InvalidCastException>(() => ((IList)collection).Add(1)); } [Fact] public void IList_Insert_ValidItemButThrowsInvalidCastExceptionFromOverride_ThrowsInvalidCastException() { var collection = new ObservableCollection<int>(); collection.CollectionChanged += delegate { throw new InvalidCastException(); }; Assert.Throws<InvalidCastException>(() => ((IList)collection).Insert(0, 1)); } [Fact] public void IList_Item_Set_ValidItemButThrowsInvalidCastExceptionFromOverride_ThrowsInvalidCastException() { var collection = new ObservableCollection<int>() { 1 }; collection.CollectionChanged += delegate { throw new InvalidCastException(); }; Assert.Throws<InvalidCastException>(() => ((IList)collection)[0] = 2); } private class TestCollection<T> : Collection<T> { public TestCollection() { } public TestCollection(IList<T> items) : base(items) { } public IList<T> GetItems() => Items; } private class ModifiableCollection<T> : Collection<T> { public ModifiableCollection() { } public ModifiableCollection(IList<T> items) { foreach (var item in items) { Items.Add(item); } } } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Semmle.Extraction.CSharp.Populators; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Semmle.Extraction.CSharp.Entities { internal class NamedType : Type<INamedTypeSymbol> { private NamedType(Context cx, INamedTypeSymbol init, bool constructUnderlyingTupleType) : base(cx, init) { typeArgumentsLazy = new Lazy<Type[]>(() => Symbol.TypeArguments.Select(t => Create(cx, t)).ToArray()); this.constructUnderlyingTupleType = constructUnderlyingTupleType; } public static NamedType Create(Context cx, INamedTypeSymbol type) => NamedTypeFactory.Instance.CreateEntityFromSymbol(cx, type); /// <summary> /// Creates a named type entity from a tuple type. Unlike `Create`, this /// will create an entity for the underlying `System.ValueTuple` struct. /// For example, `(int, string)` will result in an entity for /// `System.ValueTuple<int, string>`. /// </summary> public static NamedType CreateNamedTypeFromTupleType(Context cx, INamedTypeSymbol type) => UnderlyingTupleTypeFactory.Instance.CreateEntity(cx, (new SymbolEqualityWrapper(type), typeof(TupleType)), type); public override bool NeedsPopulation => base.NeedsPopulation || Symbol.TypeKind == TypeKind.Error; public override void Populate(TextWriter trapFile) { if (Symbol.TypeKind == TypeKind.Error) { UnknownType.Create(Context); // make sure this exists so we can use it in `TypeRef::getReferencedType` Context.Extractor.MissingType(Symbol.ToString()!, Context.FromSource); return; } if (UsesTypeRef) trapFile.typeref_type((NamedTypeRef)TypeRef, this); if (Symbol.IsGenericType) { if (Symbol.IsBoundNullable()) { // An instance of Nullable<T> trapFile.nullable_underlying_type(this, TypeArguments[0].TypeRef); } else if (Symbol.IsReallyUnbound()) { for (var i = 0; i < Symbol.TypeParameters.Length; ++i) { TypeParameter.Create(Context, Symbol.TypeParameters[i]); var param = Symbol.TypeParameters[i]; var typeParameter = TypeParameter.Create(Context, param); trapFile.type_parameters(typeParameter, i, this); } } else { var unbound = constructUnderlyingTupleType ? CreateNamedTypeFromTupleType(Context, Symbol.ConstructedFrom) : Type.Create(Context, Symbol.ConstructedFrom); trapFile.constructed_generic(this, unbound.TypeRef); for (var i = 0; i < TypeArguments.Length; ++i) { trapFile.type_arguments(TypeArguments[i].TypeRef, i, this); } } } PopulateType(trapFile, constructUnderlyingTupleType); if (Symbol.EnumUnderlyingType is not null) { trapFile.enum_underlying_type(this, Type.Create(Context, Symbol.EnumUnderlyingType).TypeRef); } // Class location if (!Symbol.IsGenericType || Symbol.IsReallyUnbound()) { foreach (var l in Locations) trapFile.type_location(this, l); } if (Symbol.IsAnonymousType) { trapFile.anonymous_types(this); } } private readonly Lazy<Type[]> typeArgumentsLazy; private readonly bool constructUnderlyingTupleType; public Type[] TypeArguments => typeArgumentsLazy.Value; public override IEnumerable<Type> TypeMentions => TypeArguments; public override IEnumerable<Extraction.Entities.Location> Locations { get { foreach (var l in GetLocations(Symbol)) yield return Context.CreateLocation(l); if (!Context.Extractor.Mode.HasFlag(ExtractorMode.Standalone) && Symbol.DeclaringSyntaxReferences.Any()) yield return Assembly.CreateOutputAssembly(Context); } } private static IEnumerable<Microsoft.CodeAnalysis.Location> GetLocations(INamedTypeSymbol type) { return type.Locations .Where(l => l.IsInMetadata) .Concat(type.DeclaringSyntaxReferences .Select(loc => loc.GetSyntax()) .OfType<CSharpSyntaxNode>() .Select(l => l.FixedLocation()) ); } public override Microsoft.CodeAnalysis.Location? ReportingLocation => GetLocations(Symbol).FirstOrDefault(); private bool IsAnonymousType() => Symbol.IsAnonymousType || Symbol.Name.Contains("__AnonymousType"); public override void WriteId(EscapingTextWriter trapFile) { if (IsAnonymousType()) { trapFile.Write('*'); } else { Symbol.BuildTypeId(Context, trapFile, Symbol, constructUnderlyingTupleType); trapFile.Write(";type"); } } public sealed override void WriteQuotedId(EscapingTextWriter trapFile) { if (IsAnonymousType()) trapFile.Write('*'); else base.WriteQuotedId(trapFile); } private class NamedTypeFactory : CachedEntityFactory<INamedTypeSymbol, NamedType> { public static NamedTypeFactory Instance { get; } = new NamedTypeFactory(); public override NamedType Create(Context cx, INamedTypeSymbol init) => new NamedType(cx, init, false); } private class UnderlyingTupleTypeFactory : CachedEntityFactory<INamedTypeSymbol, NamedType> { public static UnderlyingTupleTypeFactory Instance { get; } = new UnderlyingTupleTypeFactory(); public override NamedType Create(Context cx, INamedTypeSymbol init) => new NamedType(cx, init, true); } // Do not create typerefs of constructed generics as they are always in the current trap file. // Create typerefs for constructed error types in case they are fully defined elsewhere. // We cannot use `!this.NeedsPopulation` because this would not be stable as it would depend on // the assembly that was being extracted at the time. private bool UsesTypeRef => Symbol.TypeKind == TypeKind.Error || SymbolEqualityComparer.Default.Equals(Symbol.OriginalDefinition, Symbol); public override Type TypeRef => UsesTypeRef ? (Type)NamedTypeRef.Create(Context, Symbol) : this; } internal class NamedTypeRef : Type<INamedTypeSymbol> { private readonly Type referencedType; public NamedTypeRef(Context cx, INamedTypeSymbol symbol) : base(cx, symbol) { referencedType = Type.Create(cx, symbol); } public static NamedTypeRef Create(Context cx, INamedTypeSymbol type) => // We need to use a different cache key than `type` to avoid mixing up // `NamedType`s and `NamedTypeRef`s NamedTypeRefFactory.Instance.CreateEntity(cx, (typeof(NamedTypeRef), new SymbolEqualityWrapper(type)), type); private class NamedTypeRefFactory : CachedEntityFactory<INamedTypeSymbol, NamedTypeRef> { public static NamedTypeRefFactory Instance { get; } = new NamedTypeRefFactory(); public override NamedTypeRef Create(Context cx, INamedTypeSymbol init) => new NamedTypeRef(cx, init); } public override bool NeedsPopulation => true; public override void WriteId(EscapingTextWriter trapFile) { trapFile.WriteSubId(referencedType); trapFile.Write(";typeRef"); } public override void Populate(TextWriter trapFile) { trapFile.typerefs(this, Symbol.Name); } } }
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Piranha.Data; using Piranha.Services; namespace Piranha.Repositories { public class ContentRepository : IContentRepository { private readonly IDb _db; private readonly IContentService<Content, ContentField, Models.GenericContent> _service; /// <summary> /// Default constructor. /// </summary> /// <param name="db">The current db connection</param> /// <param name="factory">The content service factory</param> public ContentRepository(IDb db, IContentServiceFactory factory) { _db = db; _service = factory.CreateContentService(); } /// <summary> /// Gets all of the available content for the optional /// group id. /// </summary> /// <param name="groupId">The optional group id</param> /// <returns>The available content</returns> public async Task<IEnumerable<Guid>> GetAll(string groupId = null) { var query = _db.Content .AsNoTracking(); if (!string.IsNullOrEmpty(groupId)) { query = query .Where(c => c.Type.Group == groupId); } return await query .OrderBy(c => c.Title) .ThenBy(c => c.LastModified) .Select(c => c.Id) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// Gets the content model with the specified id. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="id">The unique id</param> /// <param name="languageId">The selected language id</param> /// <returns>The content model</returns> public async Task<T> GetById<T>(Guid id, Guid languageId) where T : Models.GenericContent { var content = await GetQuery() .FirstOrDefaultAsync(c => c.Id == id) .ConfigureAwait(false); if (content != null) { return await _service.TransformAsync<T>(content, App.ContentTypes.GetById(content.TypeId), ProcessAsync, languageId) .ConfigureAwait(false); } return null; } /// <summary> /// Gets all available categories for the specified group. /// </summary> /// <param name="groupId">The group id</param> /// <returns>The available categories</returns> public Task<IEnumerable<Models.Taxonomy>> GetAllCategories(string groupId) { return GetAllTaxonomies(groupId, TaxonomyType.Category); } /// <summary> /// Gets all available tags for the specified groupd. /// </summary> /// <param name="groupId">The group id</param> /// <returns>The available tags</returns> public Task<IEnumerable<Models.Taxonomy>> GetAllTags(string groupId) { return GetAllTaxonomies(groupId, TaxonomyType.Tag); } /// <summary> /// Gets the current translation status for the content model /// with the given id. /// </summary> /// <param name="contentId">The unique content id</param> /// <returns>The translation status</returns> public async Task<Models.TranslationStatus> GetTranslationStatusById(Guid contentId) { var allLanguages = await _db.Languages .OrderBy(l => l.Title) .ToListAsync() .ConfigureAwait(false); var defaultLang = allLanguages .FirstOrDefault(l => l.IsDefault); var languages = allLanguages .Where(l => !l.IsDefault) .ToList(); var translations = await _db.ContentTranslations .Where(t => t.ContentId == contentId) .ToListAsync() .ConfigureAwait(false); return GetTranslationStatus(contentId, defaultLang, languages, translations); } /// <summary> /// Gets the translation summary for the content group with /// the given id. /// </summary> /// <param name="groupId">The group id</param> /// <returns>The translation summary</returns> public async Task<Models.TranslationSummary> GetTranslationStatusByGroup(string groupId) { var result = new Models.TranslationSummary { GroupId = groupId, }; var allLanguages = await _db.Languages .OrderBy(l => l.Title) .ToListAsync() .ConfigureAwait(false); var defaultLang = allLanguages .FirstOrDefault(l => l.IsDefault); var languages = allLanguages .Where(l => !l.IsDefault) .ToList(); var translations = await _db.ContentTranslations .Where(t => t.Content.Type.Group == groupId) .OrderBy(t => t.ContentId) .ToListAsync() .ConfigureAwait(false); var contentIds = translations .Select(t => t.ContentId) .Distinct() .ToList(); // Get the translation status for each of the // content models. foreach (var contentId in contentIds) { var status = GetTranslationStatus(contentId, defaultLang, languages, translations.Where(t => t.ContentId == contentId)); if (status != null) { // Summarize content status status.UpToDateCount = status.Translations.Count(t => t.IsUpToDate); status.TotalCount = status.Translations.Count; status.IsUpToDate = status.UpToDateCount == status.TotalCount; result.Content.Add(status); } } // Summarize result.UpToDateCount = result.Content.Sum(c => c.UpToDateCount); result.TotalCount = result.Content.Sum(c => c.TotalCount); result.IsUpToDate = result.UpToDateCount == result.TotalCount; return result; } /// <summary> /// Saves the given content model /// </summary> /// <param name="model">The content model</param> /// <param name="languageId">The selected language id</param> public async Task Save<T>(T model, Guid languageId) where T : Models.GenericContent { var type = App.ContentTypes.GetById(model.TypeId); var lastModified = DateTime.MinValue; if (type != null) { // Ensure category if (type.UseCategory) { if (model is Models.ICategorizedContent categorized) { var category = await _db.Taxonomies .FirstOrDefaultAsync(c => c.Id == categorized.Category.Id) .ConfigureAwait(false); if (category == null) { if (!string.IsNullOrWhiteSpace(categorized.Category.Slug)) { category = await _db.Taxonomies .FirstOrDefaultAsync(c => c.GroupId == type.Group && c.Slug == categorized.Category.Slug && c.Type == TaxonomyType.Category) .ConfigureAwait(false); } if (category == null && !string.IsNullOrWhiteSpace(categorized.Category.Title)) { category = await _db.Taxonomies .FirstOrDefaultAsync(c => c.GroupId == type.Group && c.Title == categorized.Category.Title && c.Type == TaxonomyType.Category) .ConfigureAwait(false); } if (category == null) { category = new Taxonomy { Id = categorized.Category.Id != Guid.Empty ? categorized.Category.Id : Guid.NewGuid(), GroupId = type.Group, Type = TaxonomyType.Category, Title = categorized.Category.Title, Slug = Utils.GenerateSlug(categorized.Category.Title), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Taxonomies.AddAsync(category).ConfigureAwait(false); } categorized.Category.Id = category.Id; categorized.Category.Title = category.Title; categorized.Category.Slug = category.Slug; } } } // Ensure tags if (type.UseTags) { if (model is Models.ITaggedContent tagged) { foreach (var t in tagged.Tags) { var tag = await _db.Taxonomies .FirstOrDefaultAsync(tg => tg.Id == t.Id) .ConfigureAwait(false); if (tag == null) { if (!string.IsNullOrWhiteSpace(t.Slug)) { tag = await _db.Taxonomies .FirstOrDefaultAsync(tg => tg.GroupId == type.Group && tg.Slug == t.Slug && tg.Type == TaxonomyType.Tag) .ConfigureAwait(false); } if (tag == null && !string.IsNullOrWhiteSpace(t.Title)) { tag = await _db.Taxonomies .FirstOrDefaultAsync(tg => tg.GroupId == type.Group && tg.Title == t.Title && tg.Type == TaxonomyType.Tag) .ConfigureAwait(false); } if (tag == null) { tag = new Taxonomy { Id = t.Id != Guid.Empty ? t.Id : Guid.NewGuid(), GroupId = type.Group, Type = TaxonomyType.Tag, Title = t.Title, Slug = Utils.GenerateSlug(t.Title), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Taxonomies.AddAsync(tag).ConfigureAwait(false); } t.Id = tag.Id; } t.Title = tag.Title; t.Slug = tag.Slug; } } } var content = await _db.Content .Include(c => c.Translations) .Include(c => c.Blocks).ThenInclude(b => b.Fields).ThenInclude(f => f.Translations) .Include(c => c.Fields).ThenInclude(f => f.Translations) .Include(c => c.Category) .Include(c => c.Tags).ThenInclude(t => t.Taxonomy) .AsSplitQuery() .FirstOrDefaultAsync(p => p.Id == model.Id) .ConfigureAwait(false); // If not, create new content if (content == null) { content = new Content { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), Created = DateTime.Now, LastModified = DateTime.Now }; model.Id = content.Id; await _db.Content.AddAsync(content).ConfigureAwait(false); } else { content.LastModified = DateTime.Now; } content = _service.Transform<T>(model, type, content, languageId); // Process fields foreach (var field in content.Fields) { // Ensure foreign key for new fields if (field.ContentId == Guid.Empty) { field.ContentId = content.Id; await _db.ContentFields.AddAsync(field).ConfigureAwait(false); } } if (type.UseTags) { if (model is Models.ITaggedContent taggedModel) { // Remove tags var removedTags = new List<ContentTaxonomy>(); foreach (var tag in content.Tags) { if (!taggedModel.Tags.Any(t => t.Id == tag.TaxonomyId)) { removedTags.Add(tag); } } foreach (var removed in removedTags) { content.Tags.Remove(removed); } // Add tags foreach (var tag in taggedModel.Tags) { if (!content.Tags.Any(t => t.ContentId == content.Id && t.TaxonomyId == tag.Id)) { var contentTaxonomy = new ContentTaxonomy { ContentId = content.Id, TaxonomyId = tag.Id }; content.Tags.Add(contentTaxonomy); } } } } // Transform blocks if (model is Models.IBlockContent blockModel) { var blockModels = blockModel.Blocks; if (blockModels != null) { var blocks = _service.TransformContentBlocks(blockModels, languageId); var current = blocks.Select(b => b.Id).ToArray(); // Delete removed blocks var removed = content.Blocks .Where(b => !current.Contains(b.Id) && b.ParentId == null) .ToList(); var removedItems = content.Blocks .Where(b => !current.Contains(b.Id) && b.ParentId != null) // && removed.Select(p => p.Id).ToList().Contains(b.ParentId.Value)) .ToList(); _db.ContentBlocks.RemoveRange(removed); _db.ContentBlocks.RemoveRange(removedItems); // Map the new block for (var n = 0; n < blocks.Count; n++) { var block = content.Blocks.FirstOrDefault(b => b.Id == blocks[n].Id); if (block == null) { block = new ContentBlock { Id = blocks[n].Id != Guid.Empty ? blocks[n].Id : Guid.NewGuid() }; await _db.ContentBlocks.AddAsync(block).ConfigureAwait(false); } block.ParentId = blocks[n].ParentId; block.SortOrder = n; block.CLRType = blocks[n].CLRType; var currentFields = blocks[n].Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); _db.ContentBlockFields.RemoveRange(removedFields); foreach (var newField in blocks[n].Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new ContentBlockField { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; await _db.ContentBlockFields.AddAsync(field).ConfigureAwait(false); block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; foreach (var newTranslation in newField.Translations) { var translation = field.Translations.FirstOrDefault(t => t.LanguageId == newTranslation.LanguageId); if (translation == null) { translation = new ContentBlockFieldTranslation { FieldId = field.Id, LanguageId = languageId }; await _db.ContentBlockFieldTranslations.AddAsync(translation).ConfigureAwait(false); field.Translations.Add(translation); } translation.Value = newTranslation.Value; } } content.Blocks.Add(block); } } } await _db.SaveChangesAsync().ConfigureAwait(false); /* * TODO * await DeleteUnusedCategories(model.BlogId).ConfigureAwait(false); await DeleteUnusedTags(model.BlogId).ConfigureAwait(false); */ } } /// <summary> /// Deletes the content model with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task Delete(Guid id) { var model = await _db.Content .Include(c => c.Translations) .Include(c => c.Fields).ThenInclude(f => f.Translations) .AsSplitQuery() .FirstOrDefaultAsync(p => p.Id == id) .ConfigureAwait(false); if (model != null) { _db.Content.Remove(model); await _db.SaveChangesAsync().ConfigureAwait(false); /* * TODO * await DeleteUnusedCategories(model.BlogId).ConfigureAwait(false); await DeleteUnusedTags(model.BlogId).ConfigureAwait(false); */ } } private async Task<IEnumerable<Models.Taxonomy>> GetAllTaxonomies(string groupId, TaxonomyType type) { var result = new List<Models.Taxonomy>(); var taxonomies = await _db.Taxonomies .AsNoTracking() .Where(t => t.GroupId == groupId && t.Type == type) .OrderBy(t => t.Title) .ToListAsync() .ConfigureAwait(false); foreach (var taxonomy in taxonomies) { result.Add(new Models.Taxonomy { Id = taxonomy.Id, Title = taxonomy.Title, Slug = taxonomy.Slug, Type = taxonomy.Type == TaxonomyType.Category ? Models.TaxonomyType.Category : Models.TaxonomyType.Tag }); } return result; } private Models.TranslationStatus GetTranslationStatus( Guid contentId, Language defaultLanguage, IEnumerable<Language> languages, IEnumerable<ContentTranslation> translations) { var defaultTranslation = translations .FirstOrDefault(t => t.LanguageId == defaultLanguage.Id); if (defaultTranslation != null) { // Create the result object var result = new Models.TranslationStatus { ContentId = contentId, Translations = languages .Where(l => !l.IsDefault) .Select(l => new Models.TranslationStatus.TranslationStatusItem { LanguageId = l.Id, LanguageTitle = l.Title }).OrderBy(l => l.LanguageTitle).ToList() }; // Examine the available translations foreach (var translation in translations.Where(t => t.LanguageId != defaultLanguage.Id)) { if (translation.LastModified >= defaultTranslation.LastModified) { result.Translations .FirstOrDefault(t => t.LanguageId == translation.LanguageId) .IsUpToDate = true; } } // Summarize result.TotalCount = result.Translations.Count; result.UpToDateCount = result.Translations.Count(t => t.IsUpToDate); result.IsUpToDate = result.UpToDateCount == result.TotalCount; return result; } // The content model wasn't available in the default language // which means we can't decide if the translations are up to date. return null; } /// <summary> /// Gets the base query for content. /// </summary> /// <returns>The queryable</returns> private IQueryable<Content> GetQuery() { return (IQueryable<Content>)_db.Content .AsNoTracking() .Include(c => c.Category) .Include(c => c.Translations) .Include(c => c.Blocks).ThenInclude(b => b.Fields).ThenInclude(f => f.Translations) .Include(c => c.Fields).ThenInclude(f => f.Translations) .Include(c => c.Tags).ThenInclude(t => t.Taxonomy) .AsSplitQuery() .AsQueryable(); } /// <summary> /// Performs additional processing and loads related models. /// </summary> /// <param name="content">The source content</param> /// <param name="model">The target model</param> private Task ProcessAsync<T>(Data.Content content, T model) where T : Models.GenericContent { return Task.Run(() => { // Map category if (content.Category != null && model is Models.ICategorizedContent categorizedModel) { categorizedModel.Category = new Models.Taxonomy { Id = content.Category.Id, Title = content.Category.Title, Slug = content.Category.Slug }; } // Map tags if (model is Models.ITaggedContent taggedContent) { foreach (var tag in content.Tags) { taggedContent.Tags.Add(new Models.Taxonomy { Id = tag.Taxonomy.Id, Title = tag.Taxonomy.Title, Slug = tag.Taxonomy.Slug }); } } // Map Blocks if (!(model is Models.IContentInfo) && model is Models.IBlockContent blockModel) { blockModel.Blocks = _service.TransformBlocks(content.Blocks.OrderBy(b => b.SortOrder), content.SelectedLanguageId); } }); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Reflection; using System.Globalization; using NUnit.Common; using NUnit.Options; using NUnit.Framework; namespace NUnitLite.Tests { using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.TestUtilities; [TestFixture] public class CommandLineTests { #region Argument PreProcessor Tests [TestCase("--arg", "--arg")] [TestCase("--ArG", "--ArG")] [TestCase("--arg1 --arg2", "--arg1", "--arg2")] [TestCase("--arg1 data --arg2", "--arg1", "data", "--arg2")] [TestCase("")] [TestCase(" ")] [TestCase("\"--arg 1\" --arg2", "--arg 1", "--arg2")] [TestCase("--arg1 \"--arg 2\"", "--arg1", "--arg 2")] [TestCase("\"--arg 1\" \"--arg 2\"", "--arg 1", "--arg 2")] [TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4")] [TestCase("--arg1 \"--arg 2\" arg3 \"arg 4\"", "--arg1", "--arg 2", "arg3", "arg 4")] [TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\" \"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4", "--arg 1", "--arg 2", "arg3", "arg 4")] [TestCase("\"--arg\"", "--arg")] [TestCase("\"--arg 1\"", "--arg 1")] [TestCase("\"--arg abc\"", "--arg abc")] [TestCase("\"--arg abc\"", "--arg abc")] [TestCase("\" --arg abc \"", " --arg abc ")] [TestCase("\"--arg=abc\"", "--arg=abc")] [TestCase("\"--arg=aBc\"", "--arg=aBc")] [TestCase("\"--arg = abc\"", "--arg = abc")] [TestCase("\"--arg=abc,xyz\"", "--arg=abc,xyz")] [TestCase("\"--arg=abc, xyz\"", "--arg=abc, xyz")] [TestCase("\"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz\"", "@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz")] public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs) { var actualArgs = CommandLineOptions.GetArgs(cmdline); Assert.AreEqual(expectedArgs, actualArgs); } [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1\r\n--filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 data", "--arg1", "--filearg1", "data", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes\"", "--arg1", "--filearg1", "data in quotes", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with 'single' quotes\"", "--arg1", "--filearg1", "data in quotes with 'single' quotes", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with /slashes/\"", "--arg1", "--filearg1", "data in quotes with /slashes/", "--arg2")] [TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:", "--arg1", "--arg2")] // Blank lines [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n\n\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n \n\t\t\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n\r\n\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n \r\n\t\t\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2\r\n\n--filearg3 --filearg4", "--arg1", "--filearg1", "--filearg2", "--filearg3", "--filearg4", "--arg2")] // Comments [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\nThis is NOT treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "This", "is", "NOT", "treated", "as", "a", "COMMENT", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n#This is treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] // Nested files [TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3 @file3.txt,file3.txt:--filearg4", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3", "--filearg4")] // Where clauses [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test==somelongname", "testfile.dll", "--where", "test==somelongname", "--arg2")] // NOTE: The next is not valid. Where clause is spread over several args and therefore won't parse. Quotes are required. [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test == somelongname", "testfile.dll", "--where", "test", "==", "somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where \"test == somelongname\"", "testfile.dll", "--where", "test == somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname\"", "testfile.dll", "--where", "test == somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname or test == /another long name/ or cat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname or\ntest == /another long name/ or\ncat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname ||\ntest == /another long name/ ||\ncat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname || test == /another long name/ || cat == SomeCategory", "--arg2")] public void GetArgsFromFiles(string commandLine, string files, params string[] expectedArgs) { var filespecs = files.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var testFiles = new TestFile[filespecs.Length]; for (int ix = 0; ix < filespecs.Length; ++ix) { var filespec = filespecs[ix]; var split = filespec.IndexOf( ':' ); if (split < 0) throw new Exception("Invalid test data"); var fileName = filespec.Substring(0, split); var fileContent = filespec.Substring(split + 1); testFiles[ix] = new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, fileName), fileContent, true); } var options = new NUnitLiteOptions(); string[] expandedArgs; try { expandedArgs = options.PreParse(CommandLineOptions.GetArgs(commandLine)).ToArray(); } finally { foreach (var tf in testFiles) tf.Dispose(); } Assert.AreEqual(expectedArgs, expandedArgs); Assert.Zero(options.ErrorMessages.Count); } [TestCase("--arg1 @file1.txt --arg2", "The file \"file1.txt\" was not found.")] [TestCase("--arg1 @ --arg2", "You must include a file name after @.")] public void GetArgsFromFiles_FailureTests(string args, string errorMessage) { var options = new NUnitLiteOptions(); options.PreParse(CommandLineOptions.GetArgs(args)); Assert.That(options.ErrorMessages, Is.EqualTo(new object[] { errorMessage })); } //[Test] public void GetArgsFromFiles_NestingOverflow() { var options = new NUnitLiteOptions(); var args = new[] { "--arg1", "@file1.txt", "--arg2" }; var expectedErrors = new string[] { "@ nesting exceeds maximum depth of 3." }; using (new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "file1.txt"), "@file1.txt", true)) { var expandedArgs = options.PreParse(args); Assert.AreEqual(args, expandedArgs); Assert.AreEqual(expectedErrors, options.ErrorMessages); } } #endregion #region General Tests [Test] public void NoInputFiles() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.Null(options.InputFile); } [TestCase("ShowHelp", "help|h")] [TestCase("ShowVersion", "version|V")] [TestCase("StopOnError", "stoponerror")] [TestCase("WaitBeforeExit", "wait")] [TestCase("NoHeader", "noheader|noh")] [TestCase("TeamCity", "teamcity")] public void CanRecognizeBooleanOptions(string propertyName, string pattern) { Console.WriteLine("Testing " + propertyName); string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName); NUnitLiteOptions options; foreach (string option in prototypes) { if (option.Length == 1) { options = new NUnitLiteOptions("-" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option); } else { options = new NUnitLiteOptions("--" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option); } options = new NUnitLiteOptions("/" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option); } } [TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])] [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "Before", "After", "All" }, new string[] { "JUNK" })] [TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])] [TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])] [TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })] public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string option in prototypes) { foreach (string value in goodValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } foreach (string value in badValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue); } } } [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })] public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues) { PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string canonicalValue in canonicalValues) { string lowercaseValue = canonicalValue.ToLowerInvariant(); string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } } [TestCase("DefaultTimeout", "timeout")] [TestCase("RandomSeed", "seed")] [TestCase("NumberOfTestWorkers", "workers")] public void CanRecognizeIntOptions(string propertyName, string pattern) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(int), property.PropertyType); foreach (string option in prototypes) { var options = new NUnitLiteOptions("--" + option + ":42"); Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text"); } } [TestCase("TestList", "--test=Some.Name.Space.TestFixture", "Some.Name.Space.TestFixture")] [TestCase("TestList", "--test=A.B.C,E.F.G", "A.B.C", "E.F.G")] [TestCase("TestList", "--test=A.B.C|--test=E.F.G", "A.B.C", "E.F.G")] [TestCase("PreFilters", "--prefilter=Some.Name.Space.TestFixture", "Some.Name.Space.TestFixture")] [TestCase("PreFilters", "--prefilter=A.B.C,E.F.G", "A.B.C", "E.F.G")] [TestCase("PreFilters", "--prefilter=A.B.C|--prefilter=E.F.G", "A.B.C", "E.F.G")] public void CanRecognizeTestSelectionOptions(string propertyName, string args, params string[] expected) { var property = GetPropertyInfo(propertyName); Assert.That(property.PropertyType, Is.EqualTo(typeof(IList<string>))); var options = new NUnitLiteOptions(args.Split(new char[] { '|' })); var list = (IList<string>)property.GetValue(options, null); Assert.That(list, Is.EqualTo(expected)); } // [TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))] // public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType) // { // string[] prototypes = pattern.Split('|'); // PropertyInfo property = GetPropertyInfo(propertyName); // Assert.IsNotNull(property, "Property {0} not found", propertyName); // Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName); // Assert.AreEqual(enumType, property.PropertyType); // foreach (string option in prototypes) // { // foreach (string name in Enum.GetNames(enumType)) // { // { // ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name); // Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name); // } // } // } // } [TestCase("--where")] [TestCase("--output")] [TestCase("--err")] [TestCase("--work")] [TestCase("--trace")] [TestCase("--test")] [TestCase("--prefilter")] [TestCase("--timeout")] public void MissingValuesAreReported(string option) { var options = new NUnitLiteOptions(option + "="); Assert.False(options.Validate(), "Missing value should not be valid"); Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]); } [Test] public void AssemblyIsInvalidByDefault() { var options = new NUnitLiteOptions("nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll")); } [Test] public void MultipleAssembliesAreInvalidByDefault() { var options = new NUnitLiteOptions("nunit.tests.dll", "another.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll")); Assert.That(options.ErrorMessages[1], Contains.Substring("Invalid entry: another.dll")); } [Test] public void AssemblyIsValidIfAllowed() { var options = new NUnitLiteOptions(true, "nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); } [Test] public void MultipleAssembliesAreInvalidEvenIfOneIsAllowed() { var options = new NUnitLiteOptions(true, "nunit.tests.dll", "another.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: another.dll")); } [Test] public void InvalidOption() { var options = new NUnitLiteOptions("-asembly:nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -asembly:nunit.tests.dll", options.ErrorMessages[0]); } [Test] public void InvalidCommandLineParms() { var options = new NUnitLiteOptions("-garbage:TestFixture", "-assembly:Tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]); Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]); } #endregion #region Timeout Option [Test] public void TimeoutIsMinusOneIfNoOptionIsProvided() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } [Test] public void TimeoutThrowsExceptionIfOptionHasNoValue() { Assert.Throws<OptionException>(() => new NUnitLiteOptions("-timeout")); } [Test] public void TimeoutParsesIntValueCorrectly() { var options = new NUnitLiteOptions("-timeout:5000"); Assert.True(options.Validate()); Assert.AreEqual(5000, options.DefaultTimeout); } [Test] public void TimeoutCausesErrorIfValueIsNotInteger() { var options = new NUnitLiteOptions("-timeout:abc"); Assert.False(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #endregion #region EngineResult Option [Test] public void FileNameWithoutResultOptionLooksLikeParameter() { var options = new NUnitLiteOptions(true, "results.xml"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); //Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: results.xml")); Assert.AreEqual("results.xml", options.InputFile); } [Test] public void ResultOptionWithFilePath() { var options = new NUnitLiteOptions("-result:results.xml"); Assert.True(options.Validate()); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void ResultOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("-result:results.xml;format=nunit2"); Assert.True(options.Validate()); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit2", spec.Format); } [Test] public void ResultOptionWithoutFileNameIsInvalid() { var options = new NUnitLiteOptions("-result:"); Assert.False(options.Validate(), "Should not be valid"); Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected"); } [Test] public void ResultOptionMayBeRepeated() { var options = new NUnitLiteOptions("-result:results.xml", "-result:nunit2results.xml;format=nunit2"); Assert.True(options.Validate(), "Should be valid"); var specs = options.ResultOutputSpecifications; Assert.That(specs, Has.Count.EqualTo(2)); var spec1 = specs[0]; Assert.AreEqual("results.xml", spec1.OutputPath); Assert.AreEqual("nunit3", spec1.Format); var spec2 = specs[1]; Assert.AreEqual("nunit2results.xml", spec2.OutputPath); Assert.AreEqual("nunit2", spec2.Format); } [Test] public void DefaultResultSpecification() { var options = new NUnitLiteOptions(); Assert.AreEqual(1, options.ResultOutputSpecifications.Count); var spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("TestResult.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void NoResultSuppressesDefaultResultSpecification() { var options = new NUnitLiteOptions("-noresult"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void NoResultSuppressesAllResultSpecifications() { var options = new NUnitLiteOptions("-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test, SetCulture("en-US")] public void InvalidResultSpecRecordsError() { var options = new NUnitLiteOptions("test.dll", "-result:userspecifed.xml;format=nunit2;format=nunit3"); Assert.That(options.ResultOutputSpecifications, Has.Exactly(1).Items .And.Exactly(1).Property(nameof(OutputSpecification.OutputPath)).EqualTo("TestResult.xml")); Assert.That(options.ErrorMessages, Has.Exactly(1).Contains("invalid output spec").IgnoreCase); } #endregion #region Explore Option [Test] public void ExploreOptionWithoutPath() { var options = new NUnitLiteOptions("-explore"); Assert.True(options.Validate()); Assert.True(options.Explore); } [Test] public void ExploreOptionWithFilePath() { var options = new NUnitLiteOptions("-explore:results.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void ExploreOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("-explore:results.xml;format=cases"); Assert.True(options.Validate()); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("cases", spec.Format); } [Test] public void ExploreOptionWithFilePathUsingEqualSign() { var options = new NUnitLiteOptions("-explore=C:/nunit/tests/bin/Debug/console-test.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath); } [TestCase(true, null, true)] [TestCase(false, null, false)] [TestCase(true, false, true)] [TestCase(false, false, false)] [TestCase(true, true, true)] [TestCase(false, true, true)] public void ShouldSetTeamCityFlagAccordingToArgsAndDefaults(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity) { // Given List<string> args = new List<string> { "tests.dll" }; if (hasTeamcityInCmd) { args.Add("--teamcity"); } CommandLineOptions options; if (defaultTeamcity.HasValue) { options = new NUnitLiteOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray()); } else { options = new NUnitLiteOptions(args.ToArray()); } // When var actualTeamCity = options.TeamCity; // Then Assert.AreEqual(actualTeamCity, expectedTeamCity); } #endregion #region Test Parameters [Test] public void SingleTestParameter() { var options = new NUnitLiteOptions("--params=X=5"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { {"X", "5" } })); } [Test] public void TwoTestParametersInOneOption() { var options = new NUnitLiteOptions("--params:X=5;Y=7"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } })); } [Test] public void TwoTestParametersInSeparateOptions() { var options = new NUnitLiteOptions("-p:X=5", "-p:Y=7"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } })); } [Test] public void ThreeTestParametersInTwoOptions() { var options = new NUnitLiteOptions("--params:X=5;Y=7", "-p:Z=3"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" }, { "Z", "3" } })); } [Test] public void ParameterWithoutEqualSignIsInvalid() { var options = new NUnitLiteOptions("--params=X5"); Assert.That(options.ErrorMessages.Count, Is.EqualTo(1)); } [Test] public void DisplayTestParameters() { if (TestContext.Parameters.Count == 0) { Console.WriteLine("No Test Parameters were passed"); return; } Console.WriteLine("Test Parameters---"); foreach (var name in TestContext.Parameters.Names) Console.WriteLine(" Name: {0} Value: {1}", name, TestContext.Parameters[name]); } #endregion #region Helper Methods //private static FieldInfo GetFieldInfo(string fieldName) //{ // FieldInfo field = typeof(NUnitLiteOptions).GetField(fieldName); // Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName); // return field; //} private static PropertyInfo GetPropertyInfo(string propertyName) { PropertyInfo property = typeof(NUnitLiteOptions).GetProperty(propertyName); Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName); return property; } #endregion internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider { public DefaultOptionsProviderStub(bool teamCity) { TeamCity = teamCity; } public bool TeamCity { get; } } } }
using System; using System.Windows; using System.Windows.Input; using System.IO; using System.Reflection; namespace tvToolbox { /// <summary> /// This utility class supports the embedding of DLLs in an EXE that uses them. /// This approach allows for a primary EXE to serve as its own setup program. /// /// This functionality can also be used to package any other files with /// the primary EXE (eg. DLLs, configuration files as well as other EXEs /// and their support files). /// </summary> internal class tvFetchResource { private tvFetchResource(){} /// <summary> /// Fetches an embedded resource from the currently executing assembly. It is /// written to disk to the same folder that contains the assembly. The namespace /// of the first class found in the assembly is used by default. If this fails, /// try including the namespace as the first argument. /// </summary> /// <param name="asResourceName">The name of the embedded resource to fetch.</param> internal static void ToDisk(string asResourceName) { btArray(null, asResourceName, true, null); } /// <summary> /// Fetches an embedded resource from the currently executing assembly. The namespace /// of the first class found in the assembly is used by default. If this fails, /// try including the namespace as the first argument. /// /// The resource is written to disk at asPathFile. /// </summary> /// <param name="asResourceName">The name of the embedded resource to fetch.</param> /// <param name="asPathFile"> /// The location where the embedded resource is written to disk. If this parameter is null, /// the given resource name with the location of the currently running EXE is used instead. /// </param> internal static void ToDisk(string asResourceName, string asPathFile) { btArray(null, asResourceName, true, asPathFile); } /// <summary> /// Fetches an embedded resource from the currently executing assembly. /// /// The resource is written to disk at asPathFile. /// </summary> /// <param name="asNamespace">The namespace of the embedded resource to fetch.</param> /// <param name="asResourceName">The name of the embedded resource to fetch.</param> /// <param name="asPathFile"> /// The location where the embedded resource is written to disk. If this parameter is null, /// the given resource name with the location of the currently running EXE is used instead. /// </param> internal static void ToDisk(string asNamespace, string asResourceName, string asPathFile) { btArray(asNamespace, asResourceName, true, asPathFile); } /// <summary> /// Fetches a byte array (ie. an embedded resource) from the currently executing assembly. /// The namespace of the first class found in the assembly is used by default. If this fails, /// try including the namespace as the first argument. /// /// The byte array is written to disk at asPathFile. /// /// If the file already exists on disk (ie. asPathFile), a byte array is returned from the file. /// </summary> /// <param name="asResourceName">The name of the embedded resource to fetch.</param> /// <param name="asPathFile"> /// The location where the embedded resource is written to disk. If this parameter is null, /// the given resource name with the location of the currently running EXE is used instead. /// </param> /// <returns> /// A byte array that contains the resource fetched from the assembly. /// </returns> internal static byte[] btArrayToDisk(string asResourceName, string asPathFile) { return btArrayToDisk(null, asResourceName, asPathFile); } /// <summary> /// Fetches a byte array (ie. an embedded resource) from the currently executing assembly. /// /// The byte array is written to disk at asPathFile. /// /// If the file already exists on disk (ie. asPathFile), a byte array is returned from the file. /// </summary> /// <param name="asNamespace">The namespace of the embedded resource to fetch.</param> /// <param name="asResourceName">The name of the embedded resource to fetch.</param> /// <param name="asPathFile"> /// The location where the embedded resource is written to disk. If this parameter is null, /// the given resource name with the location of the currently running EXE is used instead. /// </param> /// <returns> /// A byte array that contains the resource fetched from the assembly. /// </returns> internal static byte[] btArrayToDisk(string asNamespace, string asResourceName, string asPathFile) { byte[] lbtArray = btArray(asNamespace, asResourceName, true, asPathFile); if ( null == lbtArray ) { FileStream loFileStream = null; try { loFileStream = new FileStream(asPathFile, FileMode.Open, FileAccess.Read); lbtArray = new Byte[loFileStream.Length]; loFileStream.Read(lbtArray, 0, (int)loFileStream.Length); } finally { if ( null != loFileStream ) loFileStream.Close(); } } return lbtArray; } /// <summary> /// Fetches a byte array (ie. an embedded resource) from the currently executing assembly. /// /// If abFetchToDisk is true, the byte array is written to disk at asPathFile. /// null is returned if the resource file already exists on disk. /// /// If abFetchToDisk is false, the contents of asResourceName is returned from the executing /// assembly without regard to what may already be on disk. /// </summary> /// <param name="asNamespace">The namespace of the embedded resource to fetch.</param> /// <param name="asResourceName">The name of the embedded resource to fetch.</param> /// <param name="abFetchToDisk">Fetch to disk if this boolean is true.</param> /// <param name="asPathFile"> /// The location where the embedded resource is written to disk. If this parameter is null, /// the given resource name with the location of the currently running EXE is used instead. /// </param> /// <returns> /// A byte array that contains the resource fetched from the assembly. /// </returns> internal static byte[] btArray(string asNamespace, string asResourceName, bool abFetchToDisk, string asPathFile) { if ( null == asPathFile ) asPathFile = Path.Combine(Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location), asResourceName); if ( File.Exists(asPathFile) && abFetchToDisk ) return null; Stream loStream = null; FileStream loFileStream = null; Byte[] lbtArray = null; try { string lsResourceName = ( null != asNamespace && "" != asNamespace ? asNamespace + "." + asResourceName : Assembly.GetExecutingAssembly().GetName().Name + "." + asResourceName ); loStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(lsResourceName); if ( null == loStream ) { tvFetchResource.ErrorMessage(null, String.Format( "The embedded resource ({0}) could not be found in the running assembly ({1})." + Environment.NewLine + Environment.NewLine + "Try specifying the namespace as the first argument." , asResourceName, Assembly.GetExecutingAssembly().FullName)); } else { lbtArray = new Byte[loStream.Length]; loStream.Read(lbtArray, 0, (int)loStream.Length); if ( abFetchToDisk ) { loFileStream = new FileStream(asPathFile, FileMode.OpenOrCreate); loFileStream.Write(lbtArray, 0, (int)loStream.Length); } } } finally { if ( null != loStream) loStream.Close(); if ( null != loFileStream ) loFileStream.Close(); } return lbtArray; } internal static void ErrorMessage(Window aoWindow, string asMessage) { Type lttvMessageBox = Type.GetType("tvMessageBox"); if ( null != lttvMessageBox ) { object loErrMsg = Activator.CreateInstance(lttvMessageBox); lttvMessageBox.InvokeMember("ShowError", BindingFlags.InvokeMethod, null, loErrMsg , new object[]{aoWindow, asMessage, System.Windows.Forms.Application.ProductName}); } } internal static void NetworkSecurityStartupErrorMessage() { ErrorMessage(null, "Network Security Exception: apparently you can't run this from the network." + Environment.NewLine + Environment.NewLine + "Try copying the software to a local PC before running it."); } internal static void ModelessMessageBox(tvProfile aoProfile, string asNamespace, string asTitle, string asMessage) { String lcsMsgBoxExeName = "MessageBox.exe"; System.Diagnostics.Process[] loProcessArray = System.Diagnostics.Process.GetProcessesByName( System.IO.Path.GetFileNameWithoutExtension(lcsMsgBoxExeName)); if ( loProcessArray.Length < aoProfile.iValue("-ModelessMessageBoxMaxCount", 3) ) { string lsMsgExePathFile = Path.Combine( Path.GetDirectoryName(aoProfile.sExePathFile), lcsMsgBoxExeName); tvFetchResource.ToDisk(asNamespace, lcsMsgBoxExeName, lsMsgExePathFile); if ( File.Exists(lsMsgExePathFile) ) System.Diagnostics.Process.Start(lsMsgExePathFile, String.Format( "-Title=\"{0}: {1}\" -Message=\"{2}\"" , asNamespace.Replace("\"", "'") , asTitle.Replace("\"", "'") , asMessage.Replace("\"", "'") )); } } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Rendering.PostProcessing; namespace UnityEditor.Rendering.PostProcessing { public sealed class EffectListEditor { public PostProcessProfile asset { get; private set; } Editor m_BaseEditor; SerializedObject m_SerializedObject; SerializedProperty m_SettingsProperty; Dictionary<Type, Type> m_EditorTypes; // SettingsType => EditorType List<PostProcessEffectBaseEditor> m_Editors; public EffectListEditor(Editor editor) { Assert.IsNotNull(editor); m_BaseEditor = editor; } public void Init(PostProcessProfile asset, SerializedObject serializedObject) { Assert.IsNotNull(asset); Assert.IsNotNull(serializedObject); this.asset = asset; m_SerializedObject = serializedObject; m_SettingsProperty = serializedObject.FindProperty("settings"); Assert.IsNotNull(m_SettingsProperty); m_EditorTypes = new Dictionary<Type, Type>(); m_Editors = new List<PostProcessEffectBaseEditor>(); // Gets the list of all available postfx editors var editorTypes = RuntimeUtilities.GetAllAssemblyTypes() .Where( t => t.IsSubclassOf(typeof(PostProcessEffectBaseEditor)) && t.IsDefined(typeof(PostProcessEditorAttribute), false) && !t.IsAbstract ); // Map them to their corresponding settings type foreach (var editorType in editorTypes) { var attribute = editorType.GetAttribute<PostProcessEditorAttribute>(); m_EditorTypes.Add(attribute.settingsType, editorType); } // Create editors for existing settings for (int i = 0; i < this.asset.settings.Count; i++) CreateEditor(this.asset.settings[i], m_SettingsProperty.GetArrayElementAtIndex(i)); // Keep track of undo/redo to redraw the inspector when that happens Undo.undoRedoPerformed += OnUndoRedoPerformed; } void OnUndoRedoPerformed() { asset.isDirty = true; // Dumb hack to make sure the serialized object is up to date on undo (else there'll be // a state mismatch when this class is used in a GameObject inspector). m_SerializedObject.Update(); m_SerializedObject.ApplyModifiedProperties(); // Seems like there's an issue with the inspector not repainting after some undo events // This will take care of that m_BaseEditor.Repaint(); } void CreateEditor(PostProcessEffectSettings settings, SerializedProperty property, int index = -1) { var settingsType = settings.GetType(); Type editorType; if (!m_EditorTypes.TryGetValue(settingsType, out editorType)) editorType = typeof(DefaultPostProcessEffectEditor); var editor = (PostProcessEffectBaseEditor)Activator.CreateInstance(editorType); editor.Init(settings, m_BaseEditor); editor.baseProperty = property.Copy(); if (index < 0) m_Editors.Add(editor); else m_Editors[index] = editor; } // Clears & recreate all editors - mainly used when the volume has been modified outside of // the editor (user scripts, inspector reset etc). void RefreshEditors() { // Disable all editors first foreach (var editor in m_Editors) editor.OnDisable(); // Remove them m_Editors.Clear(); // Recreate editors for existing settings, if any for (int i = 0; i < asset.settings.Count; i++) CreateEditor(asset.settings[i], m_SettingsProperty.GetArrayElementAtIndex(i)); } public void Clear() { if (m_Editors == null) return; // Hasn't been inited yet foreach (var editor in m_Editors) editor.OnDisable(); m_Editors.Clear(); m_EditorTypes.Clear(); Undo.undoRedoPerformed -= OnUndoRedoPerformed; } public void OnGUI() { if (asset == null) return; if (asset.isDirty) { RefreshEditors(); asset.isDirty = false; } bool isEditable = !VersionControl.Provider.isActive || AssetDatabase.IsOpenForEdit(asset, StatusQueryOptions.UseCachedIfPossible); using (new EditorGUI.DisabledScope(!isEditable)) { EditorGUILayout.LabelField(EditorUtilities.GetContent("Overrides"), EditorStyles.boldLabel); // Override list for (int i = 0; i < m_Editors.Count; i++) { var editor = m_Editors[i]; string title = editor.GetDisplayTitle(); int id = i; // Needed for closure capture below EditorUtilities.DrawSplitter(); bool displayContent = EditorUtilities.DrawHeader( title, editor.baseProperty, editor.activeProperty, editor.target, () => ResetEffectOverride(editor.target.GetType(), id), () => RemoveEffectOverride(id) ); if (displayContent) { using (new EditorGUI.DisabledScope(!editor.activeProperty.boolValue)) editor.OnInternalInspectorGUI(); } } if (m_Editors.Count > 0) { EditorUtilities.DrawSplitter(); EditorGUILayout.Space(); } else { EditorGUILayout.HelpBox("No override set on this volume.", MessageType.Info); } if (GUILayout.Button("Add effect...", EditorStyles.miniButton)) { var menu = new GenericMenu(); var typeMap = PostProcessManager.instance.settingsTypes; foreach (var kvp in typeMap) { var type = kvp.Key; var title = EditorUtilities.GetContent(kvp.Value.menuItem); bool exists = asset.HasSettings(type); if (!exists) menu.AddItem(title, false, () => AddEffectOverride(type)); else menu.AddDisabledItem(title); } menu.ShowAsContext(); } EditorGUILayout.Space(); } } void AddEffectOverride(Type type) { m_SerializedObject.Update(); var effect = CreateNewEffect(type); Undo.RegisterCreatedObjectUndo(effect, "Add Effect Override"); // Store this new effect as a subasset so we can reference it safely afterwards. Only when its not an instantiated profile if (EditorUtility.IsPersistent(asset)) AssetDatabase.AddObjectToAsset(effect, asset); // Grow the list first, then add - that's how serialized lists work in Unity m_SettingsProperty.arraySize++; var effectProp = m_SettingsProperty.GetArrayElementAtIndex(m_SettingsProperty.arraySize - 1); effectProp.objectReferenceValue = effect; // Create & store the internal editor object for this effect CreateEditor(effect, effectProp); m_SerializedObject.ApplyModifiedProperties(); // Force save / refresh. Important to do this last because SaveAssets can cause effect to become null! if (EditorUtility.IsPersistent(asset)) { EditorUtility.SetDirty(asset); AssetDatabase.SaveAssets(); } } void RemoveEffectOverride(int id) { // Huh. Hack to keep foldout state on the next element... bool nextFoldoutState = false; if (id < m_Editors.Count - 1) nextFoldoutState = m_Editors[id + 1].baseProperty.isExpanded; // Remove from the cached editors list m_Editors[id].OnDisable(); m_Editors.RemoveAt(id); m_SerializedObject.Update(); var property = m_SettingsProperty.GetArrayElementAtIndex(id); var effect = property.objectReferenceValue; // Unassign it (should be null already but serialization does funky things property.objectReferenceValue = null; // ...and remove the array index itself from the list m_SettingsProperty.DeleteArrayElementAtIndex(id); // Finally refresh editor reference to the serialized settings list for (int i = 0; i < m_Editors.Count; i++) m_Editors[i].baseProperty = m_SettingsProperty.GetArrayElementAtIndex(i).Copy(); if (id < m_Editors.Count) m_Editors[id].baseProperty.isExpanded = nextFoldoutState; m_SerializedObject.ApplyModifiedProperties(); // Destroy the setting object after ApplyModifiedProperties(). If we do it before, redo // actions will be in the wrong order and the reference to the setting object in the // list will be lost. Undo.DestroyObjectImmediate(effect); // Force save / refresh EditorUtility.SetDirty(asset); AssetDatabase.SaveAssets(); } // Reset is done by deleting and removing the object from the list and adding a new one in // the place as it was before void ResetEffectOverride(Type type, int id) { // Remove from the cached editors list m_Editors[id].OnDisable(); m_Editors[id] = null; m_SerializedObject.Update(); var property = m_SettingsProperty.GetArrayElementAtIndex(id); var prevSettings = property.objectReferenceValue; // Unassign it but down remove it from the array to keep the index available property.objectReferenceValue = null; // Create a new object var newEffect = CreateNewEffect(type); Undo.RegisterCreatedObjectUndo(newEffect, "Reset Effect Override"); // Store this new effect as a subasset so we can reference it safely afterwards AssetDatabase.AddObjectToAsset(newEffect, asset); // Put it in the reserved space property.objectReferenceValue = newEffect; // Create & store the internal editor object for this effect CreateEditor(newEffect, property, id); m_SerializedObject.ApplyModifiedProperties(); // Same as RemoveEffectOverride, destroy at the end so it's recreated first on Undo to // make sure the GUID exists before undoing the list state Undo.DestroyObjectImmediate(prevSettings); // Force save / refresh EditorUtility.SetDirty(asset); AssetDatabase.SaveAssets(); } PostProcessEffectSettings CreateNewEffect(Type type) { var effect = (PostProcessEffectSettings)ScriptableObject.CreateInstance(type); effect.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; effect.name = type.Name; effect.enabled.value = true; return effect; } } }
using System; using System.Data; namespace VirtualObjects.Queries.Mapping { class OffsetedReader : IDataReader { private readonly int _offset; private readonly IDataReader _reader; public OffsetedReader(IDataReader reader, int offset) { _offset = offset; _reader = reader; } #region IDataReader Members public void Close() { _reader.Close(); } public int Depth { get { return _reader.Depth; } } public DataTable GetSchemaTable() { return _reader.GetSchemaTable(); } public bool IsClosed { get { return _reader.IsClosed; } } public bool NextResult() { return _reader.NextResult(); } public bool Read() { return _reader.Read(); } public int RecordsAffected { get { return _reader.RecordsAffected; } } #endregion #region IDisposable Members public void Dispose() { _reader.Dispose(); } #endregion #region IDataRecord Members public int FieldCount { get { return _reader.FieldCount; } } public bool GetBoolean(int i) { return _reader.GetBoolean(i + _offset); } public byte GetByte(int i) { return _reader.GetByte(i + _offset); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { return _reader.GetBytes(i, fieldOffset, buffer, bufferoffset, length); } public char GetChar(int i) { return _reader.GetChar(i + _offset); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { return _reader.GetChars(i, fieldoffset, buffer, bufferoffset, length); } public IDataReader GetData(int i) { return _reader.GetData(i + _offset); } public string GetDataTypeName(int i) { return _reader.GetDataTypeName(i + _offset); } public DateTime GetDateTime(int i) { return _reader.GetDateTime(i + _offset); } public decimal GetDecimal(int i) { return _reader.GetDecimal(i + _offset); } public double GetDouble(int i) { return _reader.GetDouble(i + _offset); } public Type GetFieldType(int i) { return _reader.GetFieldType(i + _offset); } public float GetFloat(int i) { return _reader.GetFloat(i + _offset); } public Guid GetGuid(int i) { return _reader.GetGuid(i + _offset); } public short GetInt16(int i) { return _reader.GetInt16(i + _offset); } public int GetInt32(int i) { return _reader.GetInt32(i + _offset); } public long GetInt64(int i) { return _reader.GetInt64(i + _offset); } public string GetName(int i) { return _reader.GetName(i + _offset); } public int GetOrdinal(string name) { return _reader.GetOrdinal(name); } public string GetString(int i) { return _reader.GetString(i + _offset); } public object GetValue(int i) { return _reader.GetValue(i + _offset); } public int GetValues(object[] values) { var length = FieldCount - _offset; _reader.GetValues(values); if ( _offset > 0 ) { for ( int i = 0; i < length; i++ ) { values[i] = values[_offset + i]; } } return length; } public bool IsDBNull(int i) { return _reader.IsDBNull(i + _offset); } public object this[string name] { get { return _reader[name]; } } public object this[int i] { get { return _reader[i + _offset]; } } #endregion } }
using System; using System.Collections.Generic; using MySql.Data.MySqlClient; using ProjectStableLibrary; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; namespace ConsoleTools { public class Capstone { const int Full = 9; public static void run() { using(var dbCon = new MySqlConnection(Program.GetConStr())) { dbCon.Open(); A(dbCon); } } static void A(MySqlConnection dbCon) { var pres_grade = new Dictionary<uint, uint>(); var data = new Dictionary<uint, Dictionary<string, uint>>(); var pres = new List<uint>(); var presC = new Dictionary<uint, uint>(); var presBlock = new Dictionary<uint, uint>(); string q; q = "SELECT `viewer_id`, `grade_id` FROM `viewers`;"; using(var cmd = new MySqlCommand(q, dbCon)) { using(var r = cmd.ExecuteReader()) { uint viewer_id; while(r.Read()) { viewer_id = r.GetUInt32("viewer_id"); data.Add(viewer_id, new Dictionary<string, uint>()); pres_grade.Add(viewer_id, r.GetUInt32("grade_id")); } } } Console.WriteLine($"Viewer count: {data.Count}"); q = "SELECT `viewer_id`,`date`, `block_id`, `presentation_id` FROM `registrations`;"; using(var cmd = new MySqlCommand(q, dbCon)) { using(var r = cmd.ExecuteReader()) { while(r.Read()) { data[r.GetUInt32("viewer_id")].Add(r.GetUInt32("date") + "_" + r.GetUInt32("block_id"), r.GetUInt32("presentation_id")); } } } int regCount = data.Sum(thus => thus.Value.Count); int expected = data.Count * Full; int partial = data.Where(thus => thus.Value.Count < Full).Count(); Console.WriteLine($"Registration Count: {regCount} Expected: {expected} ({((double)regCount/expected)} %) Partial Count: {partial}"); q = "SELECT `presentation_id`, `block_id` FROM `presentations`;"; using(var cmd = new MySqlCommand(q, dbCon)) { using(var r = cmd.ExecuteReader()) { uint pres_id; while(r.Read()) { pres_id = r.GetUInt32("presentation_id"); pres.Add(pres_id); presBlock.Add(pres_id, r.GetUInt32("block_id")); } } } Console.WriteLine("done"); foreach(var p in pres) { presC.Add(p, Convert.ToUInt32(GetCount(dbCon, p))); } var toAdd = new List<Entry>(); var toRemove = new List<Entry>(); List<uint> toSkip = new List<uint>() { 132,39,32,96,74,99 }; foreach(var g in pres_grade.OrderByDescending(thus => thus.Value)) { if(data[g.Key].Count < Full) { //missing pres for(uint x = 1; x <= 8; x++) { if(!data[g.Key].ContainsKey("20180531" + "_" + x)) { var pres_in_block = presBlock.Where(thus => thus.Value == x); var pres_by_count = presC.Where(thus => pres_in_block.Any(t => thus.Key == t.Key) && thus.Value < 37).OrderBy(thus => thus.Value); Console.WriteLine($"Block {x} Possible: " + string.Join(", ", pres_by_count.Select( thus => thus.Key +"C"+thus.Value))); try { uint p_to_add = pres_by_count.First().Key; if (toSkip.Contains(p_to_add)) { throw new Exception(); } /* if(p_to_add == 39 || p_to_add == 132) { presC[39]++; presC[132]++; toAdd.Add(new Entry() { date = 20180601, block_id = 2, viewer_id = g.Key, presentation_id = 132 }); toAdd.Add(new Entry() { date = 20180601, block_id = 1, viewer_id = g.Key, presentation_id = 39 }); if(!data[g.Key].ContainsKey(7)) data[g.Key].Add(7, 77); else { presC[data[g.Key][7]]--; toRemove.Add(new Entry() { date = 20170601, block_id = 7, viewer_id = g.Key, presentation_id = data[g.Key][7] }); data[g.Key][7] = 77; } if(!data[g.Key].ContainsKey(8)) data[g.Key].Add(8, 78); else { presC[data[g.Key][8]]--; toRemove.Add(new Entry() { date = 20170601, block_id = 8, viewer_id = g.Key, presentation_id = data[g.Key][8] }); data[g.Key][8] = 78; } continue; } if(p_to_add == 50 || p_to_add == 91) { presC[50]++; presC[91]++; toAdd.Add(new Entry() { date = 20170601, block_id = 2, viewer_id = g.Key, presentation_id = 50 }); toAdd.Add(new Entry() { date = 20170601, block_id = 1, viewer_id = g.Key, presentation_id = 91 }); if(!data[g.Key].ContainsKey(1)) data[g.Key].Add(1, 91); else { presC[data[g.Key][1]]--; toRemove.Add(new Entry() { date = 20170601, block_id = 1, viewer_id = g.Key, presentation_id = data[g.Key][1] }); data[g.Key][1] = 91; } if(!data[g.Key].ContainsKey(2)) data[g.Key].Add(2, 50); else { presC[data[g.Key][2]]--; toRemove.Add(new Entry() { date = 20170601, block_id = 2, viewer_id = g.Key, presentation_id = data[g.Key][2] }); data[g.Key][2] = 50; } continue; } */ //increas count presC[p_to_add]++; toAdd.Add(new Entry() { date = 20170601, block_id = x, viewer_id = g.Key, presentation_id = p_to_add }); } catch { Console.WriteLine($"Warn! Empty!! block_id: {x}"); } } } } } Console.WriteLine("Partial Reg: " + string.Join(", ", data.Where(thus => thus.Value.Count < 8).Select(thus => thus.Key))); //final foreach(var s in presC.OrderBy(thus => thus.Value).Select(thus => thus.Key +" " + thus.Value)) { Console.WriteLine(s); } string sqlD = ""; foreach(var d in toRemove) { sqlD += $" DELETE from registrations where date = {d.date} and block_id = {d.block_id} and viewer_id = {d.viewer_id};"; } Console.WriteLine("PAUSE"); Console.ReadLine(); string sql = "INSERT INTO `registrations` VALUES "; sql += string.Join(", ", toAdd.Select( thus => $"({thus.date},{thus.block_id},{thus.viewer_id},{thus.presentation_id})")); sql += ";"; Console.WriteLine(sqlD); Console.WriteLine($"Registration Count: {regCount} Expected: {expected} ({((double)regCount/expected)} %) Partial Count: {partial} Final {regCount + toAdd.Count}"); long r_count; long a_count; using(var cmd = new MySqlCommand(sql, dbCon)) { a_count = cmd.ExecuteNonQuery(); } Console.WriteLine($"Affected rows {a_count}"); } static long GetCount(MySqlConnection dbCon, uint p_id) { string q = "SELECT COUNT(`presentation_id`) FROM `registrations` WHERE `presentation_id` = @p_id;"; using(var cmd = new MySqlCommand(q, dbCon)) { cmd.Prepare(); cmd.Parameters.AddWithValue("@p_id", p_id); return (long) cmd.ExecuteScalar(); } } } struct Entry { public uint date { get; set; } public uint block_id { get; set; } public uint viewer_id { get; set; } public uint presentation_id { get; set; } } }
using Lucene.Net.Codecs; using Lucene.Net.Codecs.Asserting; using Lucene.Net.Codecs.Bloom; using Lucene.Net.Codecs.DiskDV; using Lucene.Net.Codecs.Lucene41; using Lucene.Net.Codecs.Lucene41Ords; using Lucene.Net.Codecs.Lucene45; using Lucene.Net.Codecs.Lucene46; using Lucene.Net.Codecs.Memory; using Lucene.Net.Codecs.MockIntBlock; using Lucene.Net.Codecs.MockRandom; using Lucene.Net.Codecs.MockSep; using Lucene.Net.Codecs.NestedPulsing; using Lucene.Net.Codecs.Pulsing; using Lucene.Net.Codecs.SimpleText; using Lucene.Net.Diagnostics; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Concurrent; using System.Collections.Generic; using JCG = J2N.Collections.Generic; using Console = Lucene.Net.Util.SystemConsole; using J2N.Collections.Generic.Extensions; 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. */ /// <summary> /// <see cref="Codec"/> that assigns per-field random <see cref="Codecs.PostingsFormat"/>s. /// <para/> /// The same field/format assignment will happen regardless of order, /// a hash is computed up front that determines the mapping. /// This means fields can be put into things like <see cref="HashSet{T}"/>s and added to /// documents in different orders and the test will still be deterministic /// and reproducable. /// </summary> [ExcludeCodecFromScan] // LUCENENET specific - we don't want this codec to replace Lucene46Codec during testing - some of these codecs are read-only public class RandomCodec : Lucene46Codec { /// <summary> /// Shuffled list of postings formats to use for new mappings </summary> private IList<PostingsFormat> formats = new List<PostingsFormat>(); /// <summary> /// Shuffled list of docvalues formats to use for new mappings </summary> private IList<DocValuesFormat> dvFormats = new List<DocValuesFormat>(); /// <summary> /// unique set of format names this codec knows about </summary> public ISet<string> FormatNames { get; set; } = new JCG.HashSet<string>(); /// <summary> /// unique set of docvalues format names this codec knows about </summary> public ISet<string> DvFormatNames { get; set; } = new JCG.HashSet<string>(); /// <summary> /// memorized field->postingsformat mappings </summary> // note: we have to sync this map even though its just for debugging/toString, // otherwise DWPT's .toString() calls that iterate over the map can // cause concurrentmodificationexception if indexwriter's infostream is on private readonly IDictionary<string, PostingsFormat> previousMappings = new ConcurrentDictionary<string, PostingsFormat>(StringComparer.Ordinal); private IDictionary<string, DocValuesFormat> previousDVMappings = new ConcurrentDictionary<string, DocValuesFormat>(StringComparer.Ordinal); private readonly int perFieldSeed; public override PostingsFormat GetPostingsFormatForField(string name) { if (!previousMappings.TryGetValue(name, out PostingsFormat codec) || codec == null) { codec = formats[Math.Abs(perFieldSeed ^ name.GetHashCode()) % formats.Count]; if (codec is SimpleTextPostingsFormat && perFieldSeed % 5 != 0) { // make simpletext rarer, choose again codec = formats[Math.Abs(perFieldSeed ^ name.ToUpperInvariant().GetHashCode()) % formats.Count]; } previousMappings[name] = codec; // Safety: if (Debugging.AssertsEnabled) Debugging.Assert(previousMappings.Count < 10000, "test went insane"); } //if (LuceneTestCase.VERBOSE) //{ Console.WriteLine("RandomCodec.GetPostingsFormatForField(\"" + name + "\") returned '" + codec.Name + "' with underlying type '" + codec.GetType().ToString() + "'."); //} return codec; } public override DocValuesFormat GetDocValuesFormatForField(string name) { if (!previousDVMappings.TryGetValue(name, out DocValuesFormat codec) || codec == null) { codec = dvFormats[Math.Abs(perFieldSeed ^ name.GetHashCode()) % dvFormats.Count]; if (codec is SimpleTextDocValuesFormat && perFieldSeed % 5 != 0) { // make simpletext rarer, choose again codec = dvFormats[Math.Abs(perFieldSeed ^ name.ToUpperInvariant().GetHashCode()) % dvFormats.Count]; } previousDVMappings[name] = codec; // Safety: if (Debugging.AssertsEnabled) Debugging.Assert(previousDVMappings.Count < 10000, "test went insane"); } //if (LuceneTestCase.VERBOSE) //{ Console.WriteLine("RandomCodec.GetDocValuesFormatForField(\"" + name + "\") returned '" + codec.Name + "' with underlying type '" + codec.GetType().ToString() + "'."); //} return codec; } public RandomCodec(Random random, ISet<string> avoidCodecs) { this.perFieldSeed = random.Next(); // TODO: make it possible to specify min/max iterms per // block via CL: int minItemsPerBlock = TestUtil.NextInt32(random, 2, 100); int maxItemsPerBlock = 2 * (Math.Max(2, minItemsPerBlock - 1)) + random.Next(100); int lowFreqCutoff = TestUtil.NextInt32(random, 2, 100); Add(avoidCodecs, new Lucene41PostingsFormat(minItemsPerBlock, maxItemsPerBlock), new FSTPostingsFormat(), new FSTOrdPostingsFormat(), new FSTPulsing41PostingsFormat(1 + random.Next(20)), new FSTOrdPulsing41PostingsFormat(1 + random.Next(20)), new DirectPostingsFormat(LuceneTestCase.Rarely(random) ? 1 : (LuceneTestCase.Rarely(random) ? int.MaxValue : maxItemsPerBlock), LuceneTestCase.Rarely(random) ? 1 : (LuceneTestCase.Rarely(random) ? int.MaxValue : lowFreqCutoff)), new Pulsing41PostingsFormat(1 + random.Next(20), minItemsPerBlock, maxItemsPerBlock), // add pulsing again with (usually) different parameters new Pulsing41PostingsFormat(1 + random.Next(20), minItemsPerBlock, maxItemsPerBlock), //TODO as a PostingsFormat which wraps others, we should allow TestBloomFilteredLucene41Postings to be constructed //with a choice of concrete PostingsFormats. Maybe useful to have a generic means of marking and dealing //with such "wrapper" classes? new TestBloomFilteredLucene41Postings(), new MockSepPostingsFormat(), new MockFixedInt32BlockPostingsFormat(TestUtil.NextInt32(random, 1, 2000)), new MockVariableInt32BlockPostingsFormat(TestUtil.NextInt32(random, 1, 127)), new MockRandomPostingsFormat(random), new NestedPulsingPostingsFormat(), new Lucene41WithOrds(), new SimpleTextPostingsFormat(), new AssertingPostingsFormat(), new MemoryPostingsFormat(true, random.nextFloat()), new MemoryPostingsFormat(false, random.nextFloat()) ); AddDocValues(avoidCodecs, new Lucene45DocValuesFormat(), new DiskDocValuesFormat(), new MemoryDocValuesFormat(), new SimpleTextDocValuesFormat(), new AssertingDocValuesFormat()); formats.Shuffle(random); dvFormats.Shuffle(random); // Avoid too many open files: if (formats.Count > 4) { formats = formats.SubList(0, 4); } if (dvFormats.Count > 4) { dvFormats = dvFormats.SubList(0, 4); } } public RandomCodec(Random random) : this(random, Collections.EmptySet<string>()) { } private void Add(ISet<string> avoidCodecs, params PostingsFormat[] postings) { foreach (PostingsFormat p in postings) { if (!avoidCodecs.Contains(p.Name)) { formats.Add(p); FormatNames.Add(p.Name); } } } private void AddDocValues(ISet<string> avoidCodecs, params DocValuesFormat[] docvalues) { foreach (DocValuesFormat d in docvalues) { if (!avoidCodecs.Contains(d.Name)) { dvFormats.Add(d); DvFormatNames.Add(d.Name); } } } public override string ToString() { // LUCENENET NOTE: using StringFormatter on dictionaries to print out their contents return string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}: {1}, docValues:{2}", base.ToString(), previousMappings, previousDVMappings); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing.Printing; using System.Linq; using DevExpress.XtraPrinting; using DevExpress.XtraReports.UI; using EIDSS.Reports.BaseControls; using EIDSS.Reports.BaseControls.Report; using EIDSS.Reports.Parameterized.Human.AJ.DataSets; using bv.common.Core; using bv.model.BLToolkit; using eidss.model.Reports.AZ; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { public sealed partial class VetLabReport : BaseReport { private const string TestNamePrefix = "strTestName_"; private const string TestCountPrefix = "intTest_"; private const string TempPrefix = "TEMP_"; private bool m_IsFirstRow = true; private bool m_IsPrintGroup = true; private int m_DiagnosisCounter; public VetLabReport() { InitializeComponent(); } public void SetParameters(DbManagerProxy manager, VetLabSurrogateModel model) { SetLanguage(manager, model.Language); ReportRebinder rebinder = ReportRebinder.GetDateRebinder(model.Language, this); DateTimeLabel.Text = rebinder.ToDateTimeString(DateTime.Now); PeriodCell.Text = model.Header; OrganizationCell.Text = model.OrganizationEnteredByName; if (string.IsNullOrEmpty(model.OrganizationEnteredByName)) { OrganizationPrefixCell.Text = string.Empty; } locationCell.Text = LocationHelper.GetLocation(model.Language, baseDataSet1.sprepGetBaseParameters[0].CountryName, model.RegionId, model.RegionName, model.RayonId, model.RayonName); m_DiagnosisCounter = 1; Action<SqlConnection> action = (connection => { m_DataAdapter.Connection = connection; m_DataAdapter.Transaction = (SqlTransaction)manager.Transaction; m_DataAdapter.CommandTimeout = CommandTimeout; m_DataSet.EnforceConstraints = false; m_DataAdapter.Fill(m_DataSet.spRepVetLabReportAZ, model.Language, model.StartDate.ToString("s"), model.EndDate.ToString("s"), model.RegionId, model.RayonId, model.OrganizationEnteredById); }); FillDataTableWithArchive(action, BeforeMergeWithArchive, (SqlConnection) manager.Connection, m_DataSet.spRepVetLabReportAZ, model.UseArchive, new[] {"strDiagnosisSpeciesKey", "strOIECode"}); m_DataSet.spRepVetLabReportAZ.DefaultView.Sort = "DiagniosisOrder, strDiagnosisName, SpeciesOrder, strSpecies"; IEnumerable<DataColumn> columns = m_DataSet.spRepVetLabReportAZ.Columns.Cast<DataColumn>(); int testCount = columns.Count(c => c.ColumnName.Contains(TestCountPrefix)); AddCells(testCount - 1); } private void BeforeMergeWithArchive(DataTable sourceData, DataTable archiveData) { RemoveTestColumnsIfEmpty(sourceData); RemoveTestColumnsIfEmpty(archiveData); List<string> sourceCaptions = SetTestNameCaptions(sourceData); List<string> archiveCaptions = SetTestNameCaptions(archiveData); MergeCaptions(sourceCaptions, archiveCaptions); AddMissingColumns(sourceData, sourceCaptions); AddMissingColumns(archiveData, sourceCaptions); RemoveEmptyRowsIfRealDataExists(archiveData, sourceData); } internal static void RemoveTestColumnsIfEmpty(DataTable data) { if (data.Rows.Count == 0) { List<DataColumn> testColumns = data.Columns .Cast<DataColumn>() .Where(c => c.ColumnName.Contains(TestNamePrefix) || c.ColumnName.Contains(TestCountPrefix)) .ToList(); foreach (DataColumn column in testColumns) { data.Columns.Remove(column); } } } internal static List<string> SetTestNameCaptions(DataTable data) { var result = new List<string>(); if (data.Rows.Count > 0) { IEnumerable<DataColumn> testColumns = data.Columns .Cast<DataColumn>() .Where(c => c.ColumnName.Contains(TestNamePrefix)); foreach (DataColumn column in testColumns) { column.ReadOnly = false; object firstValue = data.Rows[0][column]; if (!Utils.IsEmpty(firstValue)) { column.Caption = firstValue.ToString(); if (result.Contains(column.Caption)) { throw new ApplicationException(string.Format("Duplicate test name {0}", column.Caption)); } result.Add(column.Caption); } } } return result; } private static void MergeCaptions(List<string> sourceCaptions, IEnumerable<string> archiveCaptions) { foreach (string caption in archiveCaptions) { if (!sourceCaptions.Contains(caption)) { sourceCaptions.Add(caption); } } sourceCaptions.Sort(); } internal static void AddMissingColumns(DataTable data, List<string> sourceCaptions) { var columnList = new List<DataColumn>(); for (int i = 0; i < sourceCaptions.Count; i++) { string caption = sourceCaptions[i]; DataColumn testNameColumn = data.Columns .Cast<DataColumn>() .FirstOrDefault(c => c.Caption == caption); string tempTestColumnName = TempPrefix + TestNamePrefix + (i + 1).ToString(); string tempCountColumnName = TempPrefix + TestCountPrefix + (i + 1).ToString(); DataColumn testCountColumn; if (testNameColumn != null) { string oldCountColumnName = testNameColumn.ColumnName.Replace(TestNamePrefix, TestCountPrefix); testCountColumn = data.Columns[oldCountColumnName]; testNameColumn.ColumnName = tempTestColumnName; testCountColumn.ColumnName = tempCountColumnName; } else { testNameColumn = data.Columns.Add(tempTestColumnName, typeof (String)); testNameColumn.Caption = caption; testCountColumn = data.Columns.Add(tempCountColumnName, typeof (Int32)); foreach (DataRow row in data.Rows) { row[testNameColumn] = caption; } } columnList.Add(testNameColumn); columnList.Add(testCountColumn); } for (int i = columnList.Count - 1; i >= 0; i--) { DataColumn column = columnList[i]; column.ColumnName = column.ColumnName.Replace(TempPrefix, string.Empty); column.SetOrdinal(data.Columns.Count - columnList.Count + i); } } private void RemoveEmptyRowsIfRealDataExists(DataTable archiveData, DataTable sourceData) { var archiveRow = archiveData.Rows.Cast<VetLabReportDataSet.spRepVetLabReportAZRow>().FirstOrDefault(r => r.strDiagnosisSpeciesKey == "1_1"); var sourceRow = sourceData.Rows.Cast<VetLabReportDataSet.spRepVetLabReportAZRow>().FirstOrDefault(r => r.strDiagnosisSpeciesKey == "1_1"); if (archiveRow == null && sourceRow != null) { sourceData.Rows.Remove(sourceRow); } if (archiveRow != null && sourceRow == null) { archiveData.Rows.Remove(archiveRow); } } private void AddCells(int testCount) { if (testCount <= 0) { return; } try { ((ISupportInitialize) (DetailsDataTable)).BeginInit(); ((ISupportInitialize) (HeaderDataTable)).BeginInit(); var resources = new ComponentResourceManager(typeof (VetLabReport)); float cellWidth = TestCountCell_1.WidthF * (float) Math.Pow(14.0 / 15, testCount - 1) / 2; TestCountCell_1.WidthF = cellWidth; TestCountCell_1.DataBindings.Clear(); TestCountCell_1.DataBindings.Add(CreateTestCountBinding(testCount + 1)); TestNameHeaderCell_1.WidthF = cellWidth; TestNameHeaderCell_1.DataBindings.Clear(); TestNameHeaderCell_1.DataBindings.Add(CreateTestNameBinding(testCount + 1)); TestsConductedHeaderCell.WidthF = cellWidth * (testCount + 1); for (int i = 0; i < testCount; i++) { int columnIndex = i + 1; var testCountCell = new XRTableCell(); DetailsDataRow.InsertCell(testCountCell, DetailsDataRow.Cells.Count - 2); resources.ApplyResources(testCountCell, TestCountCell_1.Name); testCountCell.WidthF = cellWidth; testCountCell.DataBindings.Add(CreateTestCountBinding(columnIndex)); var testNameCell = new XRTableCell(); HeaderDataRow2.InsertCell(testNameCell, HeaderDataRow2.Cells.Count - 2); resources.ApplyResources(testCountCell, TestCountCell_1.Name); testNameCell.WidthF = cellWidth; testNameCell.Angle = 90; testNameCell.DataBindings.Add(CreateTestNameBinding(columnIndex)); } } finally { ((ISupportInitialize) (HeaderDataTable)).EndInit(); ((ISupportInitialize) (DetailsDataTable)).EndInit(); } } private static XRBinding CreateTestCountBinding(int columnIndex) { return new XRBinding("Text", null, "spRepVetLabReportAZ." + TestCountPrefix + columnIndex); } private static XRBinding CreateTestNameBinding(int columnIndex) { return new XRBinding("Text", null, "spRepVetLabReportAZ." + TestNamePrefix + columnIndex); } private void GroupFooterDiagnosis_BeforePrint(object sender, PrintEventArgs e) { m_IsPrintGroup = true; m_DiagnosisCounter++; RowNumberCell.Text = m_DiagnosisCounter.ToString(); } private void RowNumberCell_BeforePrint(object sender, PrintEventArgs e) { AjustGroupBorders(RowNumberCell, m_IsPrintGroup); AjustGroupBorders(DiseaseCell, m_IsPrintGroup); AjustGroupBorders(OIECell, m_IsPrintGroup); m_IsPrintGroup = false; AjustNonGroupBorders(SpeciesCell); } private void AjustNonGroupBorders(XRTableCell firstNonGroupCell) { if (!m_IsFirstRow) { XRTableCellCollection cells = firstNonGroupCell.Row.Cells; for (int i = cells.IndexOf(firstNonGroupCell); i < cells.Count; i++) { cells[i].Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right; } } m_IsFirstRow = false; } private void AjustGroupBorders(XRTableCell cell, bool isPrinted) { if (!isPrinted) { cell.Text = string.Empty; cell.Borders = BorderSide.Left | BorderSide.Right; } else { cell.Borders = m_DiagnosisCounter > 1 ? BorderSide.Left | BorderSide.Top | BorderSide.Right : BorderSide.Left | BorderSide.Right; } } } }
// 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.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Transactions.Distributed; namespace System.Transactions { public class TransactionEventArgs : EventArgs { internal Transaction _transaction; public Transaction Transaction => _transaction; } public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e); public enum IsolationLevel { Serializable = 0, RepeatableRead = 1, ReadCommitted = 2, ReadUncommitted = 3, Snapshot = 4, Chaos = 5, Unspecified = 6, } public enum TransactionStatus { Active = 0, Committed = 1, Aborted = 2, InDoubt = 3 } public enum DependentCloneOption { BlockCommitUntilComplete = 0, RollbackIfNotComplete = 1, } [Flags] public enum EnlistmentOptions { None = 0x0, EnlistDuringPrepareRequired = 0x1, } // When we serialize a Transaction, we specify the type DistributedTransaction, so a Transaction never // actually gets deserialized. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")] [Serializable] public class Transaction : IDisposable, ISerializable { // UseServiceDomain // // Property tells parts of system.transactions if it should use a // service domain for current. [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static bool UseServiceDomainForCurrent() => false; // InteropMode // // This property figures out the current interop mode based on the // top of the transaction scope stack as well as the default mode // from config. internal static EnterpriseServicesInteropOption InteropMode(TransactionScope currentScope) { if (currentScope != null) { return currentScope.InteropMode; } return EnterpriseServicesInteropOption.None; } internal static Transaction FastGetTransaction(TransactionScope currentScope, ContextData contextData, out Transaction contextTransaction) { Transaction current = null; contextTransaction = null; contextTransaction = contextData.CurrentTransaction; switch (InteropMode(currentScope)) { case EnterpriseServicesInteropOption.None: current = contextTransaction; // If there is a transaction in the execution context or if there is a current transaction scope // then honer the transaction context. if (current == null && currentScope == null) { // Otherwise check for an external current. if (TransactionManager.s_currentDelegateSet) { current = TransactionManager.s_currentDelegate(); } else { current = EnterpriseServices.GetContextTransaction(contextData); } } break; case EnterpriseServicesInteropOption.Full: current = EnterpriseServices.GetContextTransaction(contextData); break; case EnterpriseServicesInteropOption.Automatic: if (EnterpriseServices.UseServiceDomainForCurrent()) { current = EnterpriseServices.GetContextTransaction(contextData); } else { current = contextData.CurrentTransaction; } break; } return current; } // GetCurrentTransactionAndScope // // Returns both the current transaction and scope. This is implemented for optimizations // in TransactionScope because it is required to get both of them in several cases. internal static void GetCurrentTransactionAndScope( TxLookup defaultLookup, out Transaction current, out TransactionScope currentScope, out Transaction contextTransaction) { current = null; currentScope = null; contextTransaction = null; ContextData contextData = ContextData.LookupContextData(defaultLookup); if (contextData != null) { currentScope = contextData.CurrentScope; current = FastGetTransaction(currentScope, contextData, out contextTransaction); } } public static Transaction Current { get { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.get_Current"); } Transaction current = null; TransactionScope currentScope = null; Transaction contextValue = null; GetCurrentTransactionAndScope(TxLookup.Default, out current, out currentScope, out contextValue); if (currentScope != null) { if (currentScope.ScopeComplete) { throw new InvalidOperationException(SR.TransactionScopeComplete); } } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.get_Current"); } return current; } set { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.set_Current"); } // Bring your own Transaction(BYOT) is supported only for legacy scenarios. // This transaction won't be flown across thread continuations. if (InteropMode(ContextData.TLSCurrentData.CurrentScope) != EnterpriseServicesInteropOption.None) { if (etwLog.IsEnabled()) { etwLog.InvalidOperation("Transaction", "Transaction.set_Current"); } throw new InvalidOperationException(SR.CannotSetCurrent); } // Support only legacy scenarios using TLS. ContextData.TLSCurrentData.CurrentTransaction = value; // Clear CallContext data. CallContextCurrentData.ClearCurrentData(null, false); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.set_Current"); } } } // Storage for the transaction isolation level internal IsolationLevel _isoLevel; // Storage for the consistent flag internal bool _complete = false; // Record an identifier for this clone internal int _cloneId; // Storage for a disposed flag internal const int _disposedTrueValue = 1; internal int _disposed = 0; internal bool Disposed { get { return _disposed == Transaction._disposedTrueValue; } } internal Guid DistributedTxId { get { Guid returnValue = Guid.Empty; if (_internalTransaction != null) { returnValue = _internalTransaction.DistributedTxId; } return returnValue; } } // Internal synchronization object for transactions. It is not safe to lock on the // transaction object because it is public and users of the object may lock it for // other purposes. internal InternalTransaction _internalTransaction; // The TransactionTraceIdentifier for the transaction instance. internal TransactionTraceIdentifier _traceIdentifier; // Not used by anyone private Transaction() { } // Create a transaction with the given settings // internal Transaction(IsolationLevel isoLevel, InternalTransaction internalTransaction) { TransactionManager.ValidateIsolationLevel(isoLevel); _isoLevel = isoLevel; // Never create a transaction with an IsolationLevel of Unspecified. if (IsolationLevel.Unspecified == _isoLevel) { _isoLevel = TransactionManager.DefaultIsolationLevel; } if (internalTransaction != null) { _internalTransaction = internalTransaction; _cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount); } else { // Null is passed from the constructor of a CommittableTransaction. That // constructor will fill in the traceIdentifier because it has allocated the // internal transaction. } } internal Transaction(DistributedTransaction distributedTransaction) { _isoLevel = distributedTransaction.IsolationLevel; _internalTransaction = new InternalTransaction(this, distributedTransaction); _cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount); } internal Transaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior) { TransactionManager.ValidateIsolationLevel(isoLevel); if (superior == null) { throw new ArgumentNullException(nameof(superior)); } _isoLevel = isoLevel; // Never create a transaction with an IsolationLevel of Unspecified. if (IsolationLevel.Unspecified == _isoLevel) { _isoLevel = TransactionManager.DefaultIsolationLevel; } _internalTransaction = new InternalTransaction(this, superior); // ISimpleTransactionSuperior is defined to also promote to MSDTC. _internalTransaction.SetPromoterTypeToMSDTC(); _cloneId = 1; } #region System.Object Overrides // Don't use the identifier for the hash code. // public override int GetHashCode() { return _internalTransaction.TransactionHash; } // Don't allow equals to get the identifier // public override bool Equals(object obj) { Transaction transaction = obj as Transaction; // If we can't cast the object as a Transaction, it must not be equal // to this, which is a Transaction. if (null == transaction) { return false; } // Check the internal transaction object for equality. return _internalTransaction.TransactionHash == transaction._internalTransaction.TransactionHash; } public static bool operator ==(Transaction x, Transaction y) { if (((object)x) != null) { return x.Equals(y); } return ((object)y) == null; } public static bool operator !=(Transaction x, Transaction y) { if (((object)x) != null) { return !x.Equals(y); } return ((object)y) != null; } #endregion public TransactionInformation TransactionInformation { get { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } TransactionInformation txInfo = _internalTransaction._transactionInformation; if (txInfo == null) { // A race would only result in an extra allocation txInfo = new TransactionInformation(_internalTransaction); _internalTransaction._transactionInformation = txInfo; } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return txInfo; } } // Return the Isolation Level for the given transaction // public IsolationLevel IsolationLevel { get { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return _isoLevel; } } /// <summary> /// Gets the PromoterType value for the transaction. /// </summary> /// <value> /// If the transaction has not yet been promoted and does not yet have a promotable single phase enlistment, /// this property value will be Guid.Empty. /// /// If the transaction has been promoted or has a promotable single phase enlistment, this will return the /// promoter type specified by the transaction promoter. /// /// If the transaction is, or will be, promoted to MSDTC, the value will be TransactionInterop.PromoterTypeDtc. /// </value> public Guid PromoterType { get { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { return _internalTransaction._promoterType; } } } /// <summary> /// Gets the PromotedToken for the transaction. /// /// If the transaction has not already been promoted, retrieving this value will cause promotion. Before retrieving the /// PromotedToken, the Transaction.PromoterType value should be checked to see if it is a promoter type (Guid) that the /// caller understands. If the caller does not recognize the PromoterType value, retreiving the PromotedToken doesn't /// have much value because the caller doesn't know how to utilize it. But if the PromoterType is recognized, the /// caller should know how to utilize the PromotedToken to communicate with the promoting distributed transaction /// coordinator to enlist on the distributed transaction. /// /// If the value of a transaction's PromoterType is TransactionInterop.PromoterTypeDtc, then that transaction's /// PromotedToken will be an MSDTC-based TransmitterPropagationToken. /// </summary> /// <returns> /// The byte[] that can be used to enlist with the distributed transaction coordinator used to promote the transaction. /// The format of the byte[] depends upon the value of Transaction.PromoterType. /// </returns> public byte[] GetPromotedToken() { // We need to ask the current transaction state for the PromotedToken because depending on the state // we may need to induce a promotion. TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } // We always make a copy of the promotedToken stored in the internal transaction. byte[] internalPromotedToken; lock (_internalTransaction) { internalPromotedToken = _internalTransaction.State.PromotedToken(_internalTransaction); } byte[] toReturn = new byte[internalPromotedToken.Length]; Array.Copy(internalPromotedToken, toReturn, toReturn.Length); return toReturn; } public Enlistment EnlistDurable( Guid resourceManagerIdentifier, IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (enlistmentNotification == null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction, resourceManagerIdentifier, enlistmentNotification, enlistmentOptions, this); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return enlistment; } } // Forward request to the state machine to take the appropriate action. // public Enlistment EnlistDurable( Guid resourceManagerIdentifier, ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (singlePhaseNotification == null) { throw new ArgumentNullException(nameof(singlePhaseNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction, resourceManagerIdentifier, singlePhaseNotification, enlistmentOptions, this); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return enlistment; } } public void Rollback() { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); etwLog.TransactionRollback(this, "Transaction"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { Debug.Assert(_internalTransaction.State != null); _internalTransaction.State.Rollback(_internalTransaction, null); } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } } public void Rollback(Exception e) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); etwLog.TransactionRollback(this, "Transaction"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { Debug.Assert(_internalTransaction.State != null); _internalTransaction.State.Rollback(_internalTransaction, e); } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } } // Forward request to the state machine to take the appropriate action. // public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (enlistmentNotification == null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction, enlistmentNotification, enlistmentOptions, this); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return enlistment; } } // Forward request to the state machine to take the appropriate action. // public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (singlePhaseNotification == null) { throw new ArgumentNullException(nameof(singlePhaseNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction, singlePhaseNotification, enlistmentOptions, this); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return enlistment; } } // Create a clone of the transaction that forwards requests to this object. // public Transaction Clone() { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } Transaction clone = InternalClone(); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return clone; } internal Transaction InternalClone() { Transaction clone = new Transaction(_isoLevel, _internalTransaction); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionCloneCreate(clone, "Transaction"); } return clone; } // Create a dependent clone of the transaction that forwards requests to this object. // public DependentTransaction DependentClone( DependentCloneOption cloneOption ) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (cloneOption != DependentCloneOption.BlockCommitUntilComplete && cloneOption != DependentCloneOption.RollbackIfNotComplete) { throw new ArgumentOutOfRangeException(nameof(cloneOption)); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } DependentTransaction clone = new DependentTransaction( _isoLevel, _internalTransaction, cloneOption == DependentCloneOption.BlockCommitUntilComplete); if (etwLog.IsEnabled()) { etwLog.TransactionCloneCreate(clone, "DependentTransaction"); etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return clone; } internal TransactionTraceIdentifier TransactionTraceId { get { if (_traceIdentifier == TransactionTraceIdentifier.Empty) { lock (_internalTransaction) { if (_traceIdentifier == TransactionTraceIdentifier.Empty) { TransactionTraceIdentifier temp = new TransactionTraceIdentifier( _internalTransaction.TransactionTraceId.TransactionIdentifier, _cloneId); Interlocked.MemoryBarrier(); _traceIdentifier = temp; } } } return _traceIdentifier; } } // Forward request to the state machine to take the appropriate action. // public event TransactionCompletedEventHandler TransactionCompleted { add { if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { // Register for completion with the inner transaction _internalTransaction.State.AddOutcomeRegistrant(_internalTransaction, value); } } remove { lock (_internalTransaction) { _internalTransaction._transactionCompletedDelegate = (TransactionCompletedEventHandler) System.Delegate.Remove(_internalTransaction._transactionCompletedDelegate, value); } } } public void Dispose() { InternalDispose(); } // Handle Transaction Disposal. // internal virtual void InternalDispose() { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Interlocked.Exchange(ref _disposed, Transaction._disposedTrueValue) == Transaction._disposedTrueValue) { return; } // Attempt to clean up the internal transaction long remainingITx = Interlocked.Decrement(ref _internalTransaction._cloneCount); if (remainingITx == 0) { _internalTransaction.Dispose(); } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } } // Ask the state machine for serialization info. // void ISerializable.GetObjectData( SerializationInfo serializationInfo, StreamingContext context) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (serializationInfo == null) { throw new ArgumentNullException(nameof(serializationInfo)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { _internalTransaction.State.GetObjectData(_internalTransaction, serializationInfo, context); } if (etwLog.IsEnabled()) { etwLog.TransactionSerialized(this, "Transaction"); etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } } /// <summary> /// Create a promotable single phase enlistment that promotes to MSDTC. /// </summary> /// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param> /// <returns> /// True if the enlistment is successful. /// /// False if the transaction already has a durable enlistment or promotable single phase enlistment or /// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other /// means, such as Transaction.EnlistDurable or retreive the MSDTC export cookie or propagation token to enlist with MSDTC. /// </returns> // We apparently didn't spell Promotable like FXCop thinks it should be spelled. public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification) { return EnlistPromotableSinglePhase(promotableSinglePhaseNotification, TransactionInterop.PromoterTypeDtc); } /// <summary> /// Create a promotable single phase enlistment that promotes to a distributed transaction manager other than MSDTC. /// </summary> /// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param> /// <param name="promoterType"> /// The promoter type Guid that identifies the format of the byte[] that is returned by the ITransactionPromoter.Promote /// call that is implemented by the IPromotableSinglePhaseNotificationObject, and thus the promoter of the transaction. /// </param> /// <returns> /// True if the enlistment is successful. /// /// False if the transaction already has a durable enlistment or promotable single phase enlistment or /// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other /// means. /// /// If the Transaction.PromoterType matches the promoter type supported by the caller, then the /// Transaction.PromotedToken can be retrieved and used to enlist directly with the identified distributed transaction manager. /// /// How the enlistment is created with the distributed transaction manager identified by the Transaction.PromoterType /// is defined by that distributed transaction manager. /// </returns> public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (promotableSinglePhaseNotification == null) { throw new ArgumentNullException(nameof(promotableSinglePhaseNotification)); } if (promoterType == Guid.Empty) { throw new ArgumentException(SR.PromoterTypeInvalid, nameof(promoterType)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } bool succeeded = false; lock (_internalTransaction) { succeeded = _internalTransaction.State.EnlistPromotableSinglePhase(_internalTransaction, promotableSinglePhaseNotification, this, promoterType); } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return succeeded; } public Enlistment PromoteAndEnlistDurable(Guid resourceManagerIdentifier, IPromotableSinglePhaseNotification promotableNotification, ISinglePhaseNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (promotableNotification == null) { throw new ArgumentNullException(nameof(promotableNotification)); } if (enlistmentNotification == null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.PromoteAndEnlistDurable(_internalTransaction, resourceManagerIdentifier, promotableNotification, enlistmentNotification, enlistmentOptions, this); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, this); } return enlistment; } } public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification, Guid distributedTransactionIdentifier) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (promotableNotification == null) { throw new ArgumentNullException(nameof(promotableNotification)); } if (distributedTransactionIdentifier == Guid.Empty) { throw new ArgumentException(null, nameof(distributedTransactionIdentifier)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } lock (_internalTransaction) { _internalTransaction.State.SetDistributedTransactionId(_internalTransaction, promotableNotification, distributedTransactionIdentifier); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } return; } } internal DistributedTransaction Promote() { lock (_internalTransaction) { // This method is only called when we expect to be promoting to MSDTC. _internalTransaction.ThrowIfPromoterTypeIsNotMSDTC(); _internalTransaction.State.Promote(_internalTransaction); return _internalTransaction.PromotedTransaction; } } } // // The following code & data is related to management of Transaction.Current // internal enum DefaultComContextState { Unknown = 0, Unavailable = -1, Available = 1 } // // The TxLookup enum is used internally to detect where the ambient context needs to be stored or looked up. // Default - Used internally when looking up Transaction.Current. // DefaultCallContext - Used when TransactionScope with async flow option is enabled. Internally we will use CallContext to store the ambient transaction. // Default TLS - Used for legacy/syncronous TransactionScope. Internally we will use TLS to store the ambient transaction. // internal enum TxLookup { Default, DefaultCallContext, DefaultTLS, } // // CallContextCurrentData holds the ambient transaction and uses CallContext and ConditionalWeakTable to track the ambient transaction. // For async flow scenarios, we should not allow flowing of transaction across app domains. To prevent transaction from flowing across // AppDomain/Remoting boundaries, we are using ConditionalWeakTable to hold the actual ambient transaction and store only a object reference // in CallContext. When TransactionScope is used to invoke a call across AppDomain/Remoting boundaries, only the object reference will be sent // across and not the actaul ambient transaction which is stashed away in the ConditionalWeakTable. // internal static class CallContextCurrentData { private static AsyncLocal<ContextKey> s_currentTransaction = new AsyncLocal<ContextKey>(); // ConditionalWeakTable is used to automatically remove the entries that are no longer referenced. This will help prevent leaks in async nested TransactionScope // usage and when child nested scopes are not syncronized properly. private static readonly ConditionalWeakTable<ContextKey, ContextData> s_contextDataTable = new ConditionalWeakTable<ContextKey, ContextData>(); // // Set CallContext data with the given contextKey. // return the ContextData if already present in contextDataTable, otherwise return the default value. // public static ContextData CreateOrGetCurrentData(ContextKey contextKey) { s_currentTransaction.Value = contextKey; return s_contextDataTable.GetValue(contextKey, (env) => new ContextData(true)); } public static void ClearCurrentData(ContextKey contextKey, bool removeContextData) { // Get the current ambient CallContext. ContextKey key = s_currentTransaction.Value; if (contextKey != null || key != null) { // removeContextData flag is used for perf optimization to avoid removing from the table in certain nested TransactionScope usage. if (removeContextData) { // if context key is passed in remove that from the contextDataTable, otherwise remove the default context key. s_contextDataTable.Remove(contextKey ?? key); } if (key != null) { s_currentTransaction.Value = null; } } } public static bool TryGetCurrentData(out ContextData currentData) { currentData = null; ContextKey contextKey = s_currentTransaction.Value; if (contextKey == null) { return false; } else { return s_contextDataTable.TryGetValue(contextKey, out currentData); } } } // // MarshalByRefObject is needed for cross AppDomain scenarios where just using object will end up with a different reference when call is made across serialization boundary. // internal class ContextKey // : MarshalByRefObject { } internal class ContextData { internal TransactionScope CurrentScope; internal Transaction CurrentTransaction; internal DefaultComContextState DefaultComContextState; internal WeakReference WeakDefaultComContext; internal bool _asyncFlow; [ThreadStatic] private static ContextData s_staticData; internal ContextData(bool asyncFlow) { _asyncFlow = asyncFlow; } internal static ContextData TLSCurrentData { get { ContextData data = s_staticData; if (data == null) { data = new ContextData(false); s_staticData = data; } return data; } set { if (value == null && s_staticData != null) { // set each property to null to retain one TLS ContextData copy. s_staticData.CurrentScope = null; s_staticData.CurrentTransaction = null; s_staticData.DefaultComContextState = DefaultComContextState.Unknown; s_staticData.WeakDefaultComContext = null; } else { s_staticData = value; } } } internal static ContextData LookupContextData(TxLookup defaultLookup) { ContextData currentData = null; if (CallContextCurrentData.TryGetCurrentData(out currentData)) { if (currentData.CurrentScope == null && currentData.CurrentTransaction == null && defaultLookup != TxLookup.DefaultCallContext) { // Clear Call Context Data CallContextCurrentData.ClearCurrentData(null, true); return TLSCurrentData; } return currentData; } else { return TLSCurrentData; } } } }
// 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.ServiceModel.Channels { using System; using System.ServiceModel.Description; using Microsoft.Xml; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Net.Security; using System.Text; public sealed class AsymmetricSecurityBindingElement : SecurityBindingElement, IPolicyExportExtension { internal const bool defaultAllowSerializedSigningTokenOnReply = false; private bool _allowSerializedSigningTokenOnReply; private SecurityTokenParameters _initiatorTokenParameters; private MessageProtectionOrder _messageProtectionOrder; private SecurityTokenParameters _recipientTokenParameters; private bool _requireSignatureConfirmation; private bool _isCertificateSignatureBinding; private AsymmetricSecurityBindingElement(AsymmetricSecurityBindingElement elementToBeCloned) : base(elementToBeCloned) { if (elementToBeCloned._initiatorTokenParameters != null) _initiatorTokenParameters = (SecurityTokenParameters)elementToBeCloned._initiatorTokenParameters.Clone(); _messageProtectionOrder = elementToBeCloned._messageProtectionOrder; if (elementToBeCloned._recipientTokenParameters != null) _recipientTokenParameters = (SecurityTokenParameters)elementToBeCloned._recipientTokenParameters.Clone(); _requireSignatureConfirmation = elementToBeCloned._requireSignatureConfirmation; _allowSerializedSigningTokenOnReply = elementToBeCloned._allowSerializedSigningTokenOnReply; _isCertificateSignatureBinding = elementToBeCloned._isCertificateSignatureBinding; } public AsymmetricSecurityBindingElement() : this(null, null) { // empty } public AsymmetricSecurityBindingElement(SecurityTokenParameters recipientTokenParameters) : this(recipientTokenParameters, null) { // empty } public AsymmetricSecurityBindingElement(SecurityTokenParameters recipientTokenParameters, SecurityTokenParameters initiatorTokenParameters) : this(recipientTokenParameters, initiatorTokenParameters, AsymmetricSecurityBindingElement.defaultAllowSerializedSigningTokenOnReply) { // empty } internal AsymmetricSecurityBindingElement( SecurityTokenParameters recipientTokenParameters, SecurityTokenParameters initiatorTokenParameters, bool allowSerializedSigningTokenOnReply) : base() { _messageProtectionOrder = SecurityBindingElement.defaultMessageProtectionOrder; _requireSignatureConfirmation = SecurityBindingElement.defaultRequireSignatureConfirmation; _initiatorTokenParameters = initiatorTokenParameters; _recipientTokenParameters = recipientTokenParameters; _allowSerializedSigningTokenOnReply = allowSerializedSigningTokenOnReply; _isCertificateSignatureBinding = false; } public bool AllowSerializedSigningTokenOnReply { get { return _allowSerializedSigningTokenOnReply; } set { _allowSerializedSigningTokenOnReply = value; } } public SecurityTokenParameters InitiatorTokenParameters { get { return _initiatorTokenParameters; } set { _initiatorTokenParameters = value; } } public MessageProtectionOrder MessageProtectionOrder { get { return _messageProtectionOrder; } set { if (!MessageProtectionOrderHelper.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); _messageProtectionOrder = value; } } public SecurityTokenParameters RecipientTokenParameters { get { return _recipientTokenParameters; } set { _recipientTokenParameters = value; } } public bool RequireSignatureConfirmation { get { return _requireSignatureConfirmation; } set { _requireSignatureConfirmation = value; } } internal override ISecurityCapabilities GetIndividualISecurityCapabilities() { ProtectionLevel requestProtectionLevel = ProtectionLevel.EncryptAndSign; ProtectionLevel responseProtectionLevel = ProtectionLevel.EncryptAndSign; bool supportsServerAuthentication = false; if (IsCertificateSignatureBinding) { requestProtectionLevel = ProtectionLevel.Sign; responseProtectionLevel = ProtectionLevel.None; } else if (RecipientTokenParameters != null) { supportsServerAuthentication = RecipientTokenParameters.SupportsServerAuthentication; } bool supportsClientAuthentication; bool supportsClientWindowsIdentity; GetSupportingTokensCapabilities(out supportsClientAuthentication, out supportsClientWindowsIdentity); if (InitiatorTokenParameters != null) { supportsClientAuthentication = supportsClientAuthentication || InitiatorTokenParameters.SupportsClientAuthentication; supportsClientWindowsIdentity = supportsClientWindowsIdentity || InitiatorTokenParameters.SupportsClientWindowsIdentity; } return new SecurityCapabilities(supportsClientAuthentication, supportsServerAuthentication, supportsClientWindowsIdentity, requestProtectionLevel, responseProtectionLevel); } internal override bool SupportsDuplex { get { return !_isCertificateSignatureBinding; } } internal override bool SupportsRequestReply { get { return !_isCertificateSignatureBinding; } } internal bool IsCertificateSignatureBinding { get { return _isCertificateSignatureBinding; } set { _isCertificateSignatureBinding = value; } } public override void SetKeyDerivation(bool requireDerivedKeys) { base.SetKeyDerivation(requireDerivedKeys); if (_initiatorTokenParameters != null) _initiatorTokenParameters.RequireDerivedKeys = requireDerivedKeys; if (_recipientTokenParameters != null) _recipientTokenParameters.RequireDerivedKeys = requireDerivedKeys; } internal override bool IsSetKeyDerivation(bool requireDerivedKeys) { if (!base.IsSetKeyDerivation(requireDerivedKeys)) return false; if (_initiatorTokenParameters != null && _initiatorTokenParameters.RequireDerivedKeys != requireDerivedKeys) return false; if (_recipientTokenParameters != null && _recipientTokenParameters.RequireDerivedKeys != requireDerivedKeys) return false; return true; } private bool HasProtectionRequirements(ScopedMessagePartSpecification scopedParts) { foreach (string action in scopedParts.Actions) { MessagePartSpecification parts; if (scopedParts.TryGetParts(action, out parts)) { if (!parts.IsEmpty()) { return true; } } } return false; } protected override IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(BindingContext context) { throw new NotImplementedException(); } public override T GetProperty<T>(BindingContext context) { throw new NotImplementedException(); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine(base.ToString()); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "MessageProtectionOrder: {0}", _messageProtectionOrder.ToString())); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "RequireSignatureConfirmation: {0}", _requireSignatureConfirmation.ToString())); sb.Append("InitiatorTokenParameters: "); if (_initiatorTokenParameters != null) sb.AppendLine(_initiatorTokenParameters.ToString().Trim().Replace("\n", "\n ")); else sb.AppendLine("null"); sb.Append("RecipientTokenParameters: "); if (_recipientTokenParameters != null) sb.AppendLine(_recipientTokenParameters.ToString().Trim().Replace("\n", "\n ")); else sb.AppendLine("null"); return sb.ToString().Trim(); } public override BindingElement Clone() { return new AsymmetricSecurityBindingElement(this); } void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using bfstats.web.Areas.HelpPage.ModelDescriptions; using bfstats.web.Areas.HelpPage.Models; namespace bfstats.web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//------------------------------------------------------------------------------ // <copyright file="ParsedAttributeCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Web.Util; /// <devdoc> /// Contains parsed attributes organized by filter. /// The IDictionary implementation uses the combination of all filters using filter:attrName as the attribute names /// </devdoc> internal sealed class ParsedAttributeCollection : IDictionary { private IDictionary _filterTable; private IDictionary _allFiltersDictionary; private IDictionary<String, Pair> _attributeValuePositionInfo; internal ParsedAttributeCollection() { _filterTable = new ListDictionary(StringComparer.OrdinalIgnoreCase); } /// <devdoc> /// Returns the combination of all filters using filter:attrName as the attribute names /// </devdoc> private IDictionary AllFiltersDictionary { get { if (_allFiltersDictionary == null) { _allFiltersDictionary = new ListDictionary(StringComparer.OrdinalIgnoreCase); foreach (FilteredAttributeDictionary fac in _filterTable.Values) { foreach (DictionaryEntry entry in fac) { Debug.Assert(entry.Key != null); _allFiltersDictionary[Util.CreateFilteredName(fac.Filter, entry.Key.ToString())] = entry.Value; } } } return _allFiltersDictionary; } } /// <devdoc> /// Adds a filtered attribute /// </devdoc> public void AddFilteredAttribute(string filter, string name, string value) { if (String.IsNullOrEmpty(name)) { throw ExceptionUtil.ParameterNullOrEmpty("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (filter == null) { filter = String.Empty; } if (_allFiltersDictionary != null) { _allFiltersDictionary.Add(Util.CreateFilteredName(filter, name), value); } FilteredAttributeDictionary filteredAttributes = (FilteredAttributeDictionary)_filterTable[filter]; if (filteredAttributes == null) { filteredAttributes = new FilteredAttributeDictionary(this, filter); _filterTable[filter] = filteredAttributes; } filteredAttributes.Data.Add(name, value); } /// <summary> /// This adds an entry for the attribute name and the starting column of attribute value within the text. /// This information is later used for generating line pragmas for intellisense to work. /// </summary> /// <param name="name">Name of the attribute.</param> /// <param name="line">The line number where the attribute value expression is present.</param> /// <param name="column">The column value where the attribute value expression begins. Note that this is actually after the attribute name itself.</param> public void AddAttributeValuePositionInformation(string name, int line, int column) { Debug.Assert(!String.IsNullOrEmpty(name)); Pair pair = new Pair(line, column); AttributeValuePositionsDictionary[name] = pair; } public IDictionary<String, Pair> AttributeValuePositionsDictionary { get { if (_attributeValuePositionInfo == null) { _attributeValuePositionInfo = new Dictionary<String, Pair>(StringComparer.OrdinalIgnoreCase); } return _attributeValuePositionInfo; } } /// <devdoc> /// Clears all attributes from the specified filter /// </devdoc> public void ClearFilter(string filter) { if (filter == null) { filter = String.Empty; } if (_allFiltersDictionary != null) { ArrayList removeList = new ArrayList(); foreach (string key in _allFiltersDictionary.Keys) { string attrName; string currentFilter = Util.ParsePropertyDeviceFilter(key, out attrName); if (StringUtil.EqualsIgnoreCase(currentFilter, filter)) { removeList.Add(key); } } foreach (string key in removeList) { _allFiltersDictionary.Remove(key); } } _filterTable.Remove(filter); } /// <devdoc> /// Gets the collection of FilteredAttributeDictionaries used by this collection. /// </devdoc> public ICollection GetFilteredAttributeDictionaries() { return _filterTable.Values; } /// <devdoc> /// Removes the specified attribute from the specified filter. /// </devdoc> public void RemoveFilteredAttribute(string filter, string name) { if (String.IsNullOrEmpty(name)) { throw ExceptionUtil.ParameterNullOrEmpty("name"); } if (filter == null) { filter = String.Empty; } if (_allFiltersDictionary != null) { _allFiltersDictionary.Remove(Util.CreateFilteredName(filter, name)); } FilteredAttributeDictionary filteredAttributes = (FilteredAttributeDictionary)_filterTable[filter]; if (filteredAttributes != null) { filteredAttributes.Data.Remove(name); } } /// <devdoc> /// Replaces the specified attribute's value from the specified filter. /// </devdoc> public void ReplaceFilteredAttribute(string filter, string name, string value) { if (String.IsNullOrEmpty(name)) { throw ExceptionUtil.ParameterNullOrEmpty("name"); } if (filter == null) { filter = String.Empty; } if (_allFiltersDictionary != null) { _allFiltersDictionary[Util.CreateFilteredName(filter, name)] = value; } FilteredAttributeDictionary filteredAttributes = (FilteredAttributeDictionary)_filterTable[filter]; if (filteredAttributes == null) { filteredAttributes = new FilteredAttributeDictionary(this, filter); _filterTable[filter] = filteredAttributes; } filteredAttributes.Data[name] = value; } #region IDictionary implementation /// <internalonly/> bool IDictionary.IsFixedSize { get { return false; } } /// <internalonly/> bool IDictionary.IsReadOnly { get { return false; } } /// <internalonly/> object IDictionary.this[object key] { get { return AllFiltersDictionary[key]; } set { if (key == null) { throw new ArgumentNullException("key"); } string attrName; string filter = Util.ParsePropertyDeviceFilter(key.ToString(), out attrName); ReplaceFilteredAttribute(filter, attrName, value.ToString()); } } /// <internalonly/> ICollection IDictionary.Keys { get { return AllFiltersDictionary.Keys; } } /// <internalonly/> ICollection IDictionary.Values { get { return AllFiltersDictionary.Values; } } /// <internalonly/> void IDictionary.Add(object key, object value) { if (key == null) { throw new ArgumentNullException("key"); } if (value == null) { value = String.Empty; } string attrName; string filter = Util.ParsePropertyDeviceFilter(key.ToString(), out attrName); AddFilteredAttribute(filter, attrName, value.ToString()); } /// <internalonly/> bool IDictionary.Contains(object key) { return AllFiltersDictionary.Contains(key); } /// <internalonly/> void IDictionary.Clear() { AllFiltersDictionary.Clear(); _filterTable.Clear(); } /// <internalonly/> IDictionaryEnumerator IDictionary.GetEnumerator() { return AllFiltersDictionary.GetEnumerator(); } /// <internalonly/> void IDictionary.Remove(object key) { if (key == null) { throw new ArgumentNullException("key"); } string attrName; string filter = Util.ParsePropertyDeviceFilter(key.ToString(), out attrName); RemoveFilteredAttribute(filter, attrName); } #endregion IDictionary implementation #region ICollection implementation /// <internalonly/> int ICollection.Count { get { return AllFiltersDictionary.Count; } } /// <internalonly/> bool ICollection.IsSynchronized { get { return ((ICollection)AllFiltersDictionary).IsSynchronized; } } /// <internalonly/> object ICollection.SyncRoot { get { return AllFiltersDictionary.SyncRoot; } } /// <internalonly/> void ICollection.CopyTo(Array array, int index) { AllFiltersDictionary.CopyTo(array, index); } /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return AllFiltersDictionary.GetEnumerator(); } #endregion ICollection implementation } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using NUnit.Common; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnitLite.Runner { public class TextUI { private ExtendedTextWriter _outWriter; #if !SILVERLIGHT private ConsoleOptions _options; #endif #region Constructors #if SILVERLIGHT public TextUI(ExtendedTextWriter writer) { _outWriter = writer; } #else public TextUI(ConsoleOptions options) : this(null, options) { } public TextUI(ExtendedTextWriter writer, ConsoleOptions options) { _options = options; _outWriter = writer ?? new ColorConsoleWriter(!options.NoColor); } #endif #endregion #region Public Methods #region DisplayHeader /// <summary> /// Writes the header. /// </summary> public void DisplayHeader() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly); Version version = assemblyName.Version; string copyright = "Copyright (C) 2015, Charlie Poole"; string build = ""; object[] attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attrs.Length > 0) { var copyrightAttr = (AssemblyCopyrightAttribute)attrs[0]; copyright = copyrightAttr.Copyright; } attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false); if (attrs.Length > 0) { var configAttr = (AssemblyConfigurationAttribute)attrs[0]; build = string.Format("({0})", configAttr.Configuration); } WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build)); WriteSubHeader(copyright); SkipLine(); } #endregion #region DisplayTestFiles public void DisplayTestFiles(string[] testFiles) { WriteSectionHeader("Test Files"); foreach (string testFile in testFiles) WriteLine(ColorStyle.Default, " " + testFile); SkipLine(); } #endregion #region DisplayHelp #if !SILVERLIGHT public void DisplayHelp() { // TODO: The NETCF code is just a placeholder. Figure out how to do it correctly. WriteHeader("Usage: NUNITLITE [assembly] [options]"); SkipLine(); WriteHelpLine("Runs a set of NUnitLite tests from the console."); SkipLine(); WriteSectionHeader("Assembly:"); WriteHelpLine(" An alternate assembly from which to execute tests. Normally, the tests"); WriteHelpLine(" contained in the executable test assembly itself are run. An alternate"); WriteHelpLine(" assembly is specified using the assembly name, without any path or."); WriteHelpLine(" extension. It must be in the same in the same directory as the executable"); WriteHelpLine(" or on the probing path."); SkipLine(); WriteSectionHeader("Options:"); using (var sw = new StringWriter()) { _options.WriteOptionDescriptions(sw); _outWriter.Write(ColorStyle.Help, sw.ToString()); } WriteSectionHeader("Notes:"); WriteHelpLine(" * File names may be listed by themselves, with a relative path or "); WriteHelpLine(" using an absolute path. Any relative path is based on the current "); WriteHelpLine(" directory or on the Documents folder if running on a under the "); WriteHelpLine(" compact framework."); SkipLine(); if (System.IO.Path.DirectorySeparatorChar != '/') { WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired"); SkipLine(); } WriteHelpLine(" * Options that take values may use an equal sign or a colon"); WriteHelpLine(" to separate the option from its value."); SkipLine(); WriteHelpLine(" * Several options that specify processing of XML output take"); WriteHelpLine(" an output specification as a value. A SPEC may take one of"); WriteHelpLine(" the following forms:"); WriteHelpLine(" --OPTION:filename"); WriteHelpLine(" --OPTION:filename;format=formatname"); WriteHelpLine(" --OPTION:filename;transform=xsltfile"); SkipLine(); WriteHelpLine(" The --result option may use any of the following formats:"); WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0"); WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit"); SkipLine(); WriteHelpLine(" The --explore option may use any of the following formats:"); WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0"); WriteHelpLine(" cases - a text file listing the full names of all test cases."); WriteHelpLine(" If --explore is used without any specification following, a list of"); WriteHelpLine(" test cases is output to the console."); SkipLine(); } #endif #endregion #region DisplayRequestedOptions #if !SILVERLIGHT public void DisplayRequestedOptions() { WriteSectionHeader("Options"); if (_options.DefaultTimeout >= 0) WriteLabelLine(" Default timeout: ", _options.DefaultTimeout); WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? NUnit.Env.DefaultWorkDirectory); WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off"); if (_options.TeamCity) _outWriter.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages"); SkipLine(); if (_options.TestList.Count > 0) { WriteSectionHeader("Selected test(s) -"); foreach (string testName in _options.TestList) _outWriter.WriteLine(ColorStyle.Value, " " + testName); SkipLine(); } if (!string.IsNullOrEmpty(_options.Include)) { WriteLabelLine("Included categories: ", _options.Include); SkipLine(); } if (!string.IsNullOrEmpty(_options.Exclude)) { WriteLabelLine("Excluded categories: ", _options.Exclude); SkipLine(); } } #endif #endregion #region DisplayRuntimeEnvironment /// <summary> /// Displays info about the runtime environment. /// </summary> public void DisplayRuntimeEnvironment() { WriteSectionHeader("Runtime Environment"); WriteLabelLine(" OS Version: ", Environment.OSVersion); WriteLabelLine(" CLR Version: ", Environment.Version); SkipLine(); } #endregion #region TestFinished private bool _testCreatedOutput = false; public void TestFinished(ITestResult result) { bool isSuite = result.Test.IsSuite; var labels = "ON"; #if !SILVERLIGHT if (_options.DisplayTestLabels != null) labels = _options.DisplayTestLabels.ToUpper(CultureInfo.InvariantCulture); #endif if (!isSuite && labels == "ALL" || !isSuite && labels == "ON" && result.Output.Length > 0) { _outWriter.WriteLine(ColorStyle.SectionHeader, "=> " + result.Test.Name); _testCreatedOutput = true; } if (result.Output.Length > 0) { _outWriter.Write(ColorStyle.Output, result.Output); _testCreatedOutput = true; if (!result.Output.EndsWith("\n")) SkipLine(); } } #endregion #region WaitForUser #if !SILVERLIGHT public void WaitForUser(string message) { // Ignore if we are not using the console if (_outWriter is ColorConsoleWriter) { _outWriter.WriteLine(ColorStyle.Label, message); Console.ReadLine(); } } #endif #endregion #region Test Result Reports #region DisplaySummaryReport public void DisplaySummaryReport(ResultSummary summary) { var status = summary.ResultState.Status; var overallResult = status.ToString(); if (overallResult == "Skipped") overallResult = "Warning"; ColorStyle overallStyle = status == TestStatus.Passed ? ColorStyle.Pass : status == TestStatus.Failed ? ColorStyle.Failure : status == TestStatus.Skipped ? ColorStyle.Warning : ColorStyle.Output; if (_testCreatedOutput) SkipLine(); WriteSectionHeader("Test Run Summary"); WriteLabelLine(" Overall result: ", overallResult, overallStyle); WriteSummaryCount(" Tests run: ", summary.RunCount); WriteSummaryCount(", Passed: ", summary.PassCount); WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error); WriteSummaryCount(", Failures: ", summary.FailureCount, ColorStyle.Failure); WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount); _outWriter.WriteLine(); WriteSummaryCount(" Not run: ", summary.NotRunCount); WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error); WriteSummaryCount(", Ignored: ", summary.IgnoreCount, ColorStyle.Warning); WriteSummaryCount(", Explicit: ", summary.ExplicitCount); WriteSummaryCount(", Skipped: ", summary.SkipCount); _outWriter.WriteLine(); WriteLabelLine(" Start time: ", summary.StartTime.ToString("u")); WriteLabelLine(" End time: ", summary.EndTime.ToString("u")); WriteLabelLine(" Duration: ", summary.Duration.ToString("0.000") + " seconds"); SkipLine(); } private void WriteSummaryCount(string label, int count) { _outWriter.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture)); } private void WriteSummaryCount(string label, int count, ColorStyle color) { _outWriter.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value); } #endregion #region DisplayErrorsAndFailuresReport public void DisplayErrorsAndFailuresReport(ITestResult result) { _reportIndex = 0; WriteSectionHeader("Errors and Failures"); DisplayErrorsAndFailures(result); SkipLine(); #if !SILVERLIGHT if (_options.StopOnError) { WriteLine(ColorStyle.Failure, "Execution terminated after first error"); SkipLine(); } #endif } #endregion #region DisplayNotRunReport public void DisplayNotRunReport(ITestResult result) { _reportIndex = 0; WriteSectionHeader("Tests Not Run"); DisplayNotRunResults(result); SkipLine(); } #endregion #region DisplayFullReport #if FULL // Not currently used, but may be reactivated /// <summary> /// Prints a full report of all results /// </summary> public void DisplayFullReport(ITestResult result) { WriteLine(ColorStyle.SectionHeader, "All Test Results -"); SkipLine(); DisplayAllResults(result, " "); SkipLine(); } #endif #endregion #endregion #region DisplayWarning public void DisplayWarning(string text) { WriteLine(ColorStyle.Warning, text); } #endregion #region DisplayError public void DisplayError(string text) { WriteLine(ColorStyle.Error, text); } #endregion #region DisplayErrors public void DisplayErrors(IList<string> messages) { foreach (string message in messages) DisplayError(message); } #endregion #endregion #region Helper Methods private void DisplayErrorsAndFailures(ITestResult result) { if (result.Test.IsSuite) { if (result.ResultState.Status == TestStatus.Failed) { var suite = result.Test as TestSuite; var site = result.ResultState.Site; if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown) DisplayTestResult(result); if (site == FailureSite.SetUp) return; } foreach (ITestResult childResult in result.Children) DisplayErrorsAndFailures(childResult); } else if (result.ResultState.Status == TestStatus.Failed) DisplayTestResult(result); } private void DisplayNotRunResults(ITestResult result) { if (result.HasChildren) foreach (ITestResult childResult in result.Children) DisplayNotRunResults(childResult); else if (result.ResultState.Status == TestStatus.Skipped) DisplayTestResult(result); } private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' }; private int _reportIndex; private void DisplayTestResult(ITestResult result) { string status = result.ResultState.Label; if (string.IsNullOrEmpty(status)) status = result.ResultState.Status.ToString(); if (status == "Failed" || status == "Error") { var site = result.ResultState.Site.ToString(); if (site == "SetUp" || site == "TearDown") status = site + " " + status; } ColorStyle style = ColorStyle.Output; switch (result.ResultState.Status) { case TestStatus.Failed: style = ColorStyle.Failure; break; case TestStatus.Skipped: style = status == "Ignored" ? ColorStyle.Warning : ColorStyle.Output; break; case TestStatus.Passed: style = ColorStyle.Pass; break; } SkipLine(); WriteLine( style, string.Format("{0}) {1} : {2}", ++_reportIndex, status, result.FullName)); if (!string.IsNullOrEmpty(result.Message)) WriteLine(style, result.Message.TrimEnd(TRIM_CHARS)); if (!string.IsNullOrEmpty(result.StackTrace)) WriteLine(style, result.StackTrace.TrimEnd(TRIM_CHARS)); } #if FULL private void DisplayAllResults(ITestResult result, string indent) { string status = null; ColorStyle style = ColorStyle.Output; switch (result.ResultState.Status) { case TestStatus.Failed: status = "FAIL"; style = ColorStyle.Failure; break; case TestStatus.Skipped: if (result.ResultState.Label == "Ignored") { status = "IGN "; style = ColorStyle.Warning; } else { status = "SKIP"; style = ColorStyle.Output; } break; case TestStatus.Inconclusive: status = "INC "; style = ColorStyle.Output; break; case TestStatus.Passed: status = "OK "; style = ColorStyle.Pass; break; } WriteLine(style, status + indent + result.Name); if (result.HasChildren) foreach (ITestResult childResult in result.Children) PrintAllResults(childResult, indent + " "); } #endif private void WriteLine(ColorStyle style, string text) { _outWriter.WriteLine(style, text); } private void WriteHeader(string text) { WriteLine(ColorStyle.Header, text); } private void WriteSubHeader(string text) { WriteLine(ColorStyle.SubHeader, text); } private void WriteSectionHeader(string text) { WriteLine(ColorStyle.SectionHeader, text); } private void WriteHelpLine(string text) { WriteLine(ColorStyle.Help, text); } private void WriteLabel(string label, object option) { _outWriter.WriteLabel(label, option); } private void WriteLabelLine(string label, object option) { _outWriter.WriteLabelLine(label, option); } private void WriteLabelLine(string label, object option, ColorStyle valueStyle) { _outWriter.WriteLabelLine(label, option, valueStyle); } private void SkipLine() { _outWriter.WriteLine(); } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/11/2009 4:28:29 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Xml.Serialization; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// PictureSymbol /// </summary> public class PictureSymbol : OutlinedSymbol, IPictureSymbol { #region Private Variables private bool _disposed; private Image _image; private string _imageFilename; private float _opacity; private Image _original; // Non-transparent version #endregion #region Constructors /// <summary> /// Creates a new instance of PictureSymbol /// </summary> public PictureSymbol() { base.SymbolType = SymbolType.Picture; _opacity = 1F; } /// <summary> /// Creates a new instance of a PictureSymbol from the specified image /// </summary> /// <param name="image">The image to use when creating the symbol</param> public PictureSymbol(Image image) { base.SymbolType = SymbolType.Picture; _opacity = 1F; Image = image; } /// <summary> /// Creates a new instance of a PictureSymbol from the specified image. /// The larger dimension from the image will be adjusted to fit the size, /// while the smaller dimension will be kept proportional. /// </summary> /// <param name="image">The image to use for this symbol</param> /// <param name="size">The double size to use for the larger of the two dimensions of the image.</param> public PictureSymbol(Image image, double size) { base.SymbolType = SymbolType.Picture; _opacity = 1F; Image = image; if (image == null) return; double scale; if (image.Width > image.Height) { scale = size / image.Width; } else { scale = size / image.Height; } Size = new Size2D(scale * image.Width, scale * image.Height); } /// <summary> /// Creates a new instance of a PictureSymbol from the specified icon /// </summary> /// <param name="icon">The icon to use when creating this symbol</param> public PictureSymbol(Icon icon) { base.SymbolType = SymbolType.Picture; _opacity = 1F; _original = icon.ToBitmap(); _image = MakeTransparent(_original, _opacity); } /// <summary> /// Creates a new PictureSymbol given an existing imageData object. /// </summary> /// <param name="imageData">The imageData object to use.</param> public PictureSymbol(IImageData imageData) { base.SymbolType = SymbolType.Picture; _opacity = 1F; _image = imageData.GetBitmap(); _original = _image; _imageFilename = imageData.Filename; } #endregion #region Methods /// <inheritdoc /> public override void SetColor(Color color) { Bitmap bm = new Bitmap(_image.Width, _image.Height); Graphics g = Graphics.FromImage(bm); float r = (color.R / 255f) / 2; float gr = (color.G / 255f) / 2; float b = (color.B / 255f) / 2; ColorMatrix cm = new ColorMatrix(new[] { new[]{r, gr, b, 0, 0}, new[]{r, gr, b, 0, 0}, new[]{r, gr, b, 0, 0}, new float[]{0, 0, 0, 1, 0, 0}, new float[]{0, 0, 0, 0, 1, 0}, new float[]{0, 0, 0, 0, 0, 1}}); ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm); g.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height), 0, 0, _image.Width, _image.Height, GraphicsUnit.Pixel, ia); g.Dispose(); _image = bm; } /// <summary> /// Disposes the current images /// </summary> public void Dispose() { OnDisposing(); _disposed = true; } #endregion #region Properties /// <summary> /// This is set to true when the dispose method is called. /// This will be set to false again if the image is set after that. /// </summary> public bool IsDisposed { get { return _disposed; } set { _disposed = value; } } /// <summary> /// Gets or sets the image in 'base64' string format. /// This can be used if the image file name is not set. /// </summary> [Serialize("ImageBase64String")] public string ImageBase64String { get { if (String.IsNullOrEmpty(ImageFilename)) { return ConvertImageToBase64(Image); } return String.Empty; } set { if (!String.IsNullOrEmpty(value)) { if (_original != null) _original.Dispose(); _original = null; if (_image != null) _image.Dispose(); _image = null; this.Image = ConvertBase64ToImage(value); if (_opacity < 1) { _image = MakeTransparent(_original, _opacity); } } } } /// <summary> /// Gets or sets the image to use when the PictureMode is set to Image /// </summary> [XmlIgnore] public Image Image { get { return _image; } set { if (_original != null && _original != value) { _original.Dispose(); _original = null; } if (_image != null && _image != _original && _image != value) { _image.Dispose(); _image = null; } _original = value; _image = MakeTransparent(value, _opacity); if (_original != null) _disposed = false; } } /// <summary> /// Gets or sets the string image fileName to use /// </summary> [Serialize("ImageFilename")] public string ImageFilename { get { return _imageFilename; } set { _imageFilename = value; if (_original != null) _original.Dispose(); _original = null; if (_image != null) _image.Dispose(); _image = null; if (_imageFilename == null) return; if (File.Exists(_imageFilename) == false) return; if (Path.GetExtension(_imageFilename) == ".ico") { _original = new Icon(_imageFilename).ToBitmap(); } else { _original = Image.FromFile(_imageFilename); } _image = MakeTransparent(_original, _opacity); } } /// <summary> /// Gets or sets the opacity for this image. Setting this will automatically change the image in memory. /// </summary> [Serialize("Opacity")] public float Opacity { get { return _opacity; } set { _opacity = value; if (_image != null && _image != _original) _image.Dispose(); _image = MakeTransparent(_original, _opacity); } } private string ConvertImageToBase64(Image image) { if (image == null) return String.Empty; using (MemoryStream ms = new MemoryStream()) { // Convert Image to byte[] image.Save(ms, ImageFormat.Png); byte[] imageBytes = ms.ToArray(); // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); return base64String; } } private Image ConvertBase64ToImage(string base64String) { // Convert Base64 String to byte[] byte[] imageBytes = Convert.FromBase64String(base64String); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); // Convert byte[] to Image ms.Write(imageBytes, 0, imageBytes.Length); Image image = Image.FromStream(ms, true); return image; } #endregion #region Protected Methods /// <summary> /// This helps the copy process by preparing the internal variables AFTER memberwiseclone has created this /// /// </summary> /// <param name="copy"></param> protected override void OnCopy(Descriptor copy) { // Setting the image property has a built in check to dispose the older reference. // After a MemberwiseClone, however, this older reference is still in use in the original PictureSymbol. // We must, therefore, set the private variables to null before doing the cloning. PictureSymbol duplicate = copy as PictureSymbol; if (duplicate != null) { duplicate._image = null; duplicate._original = null; } base.OnCopy(copy); if (duplicate != null) { duplicate._image = _image.Copy(); duplicate._original = _original.Copy(); } } /// <summary> /// OnDraw /// </summary> /// <param name="g">Graphics object</param> /// <param name="scaleSize">The double scale Size</param> protected override void OnDraw(Graphics g, double scaleSize) { float dx = (float)(scaleSize * Size.Width / 2); float dy = (float)(scaleSize * Size.Height / 2); GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(new RectangleF(-dx, -dy, dx * 2, dy * 2)); if (_image != null) { g.DrawImage(_image, new RectangleF(-dx, -dy, dx * 2, dy * 2)); } base.OnDrawOutline(g, scaleSize, gp); gp.Dispose(); } /// <summary> /// We can randomize the opacity /// </summary> /// <param name="generator"></param> protected override void OnRandomize(Random generator) { base.OnRandomize(generator); Opacity = generator.NextFloat(); } /// <summary> /// Overrideable functions for handling the basic disposal of image classes in this object. /// </summary> protected virtual void OnDisposing() { _image.Dispose(); _original.Dispose(); } #endregion private static Image MakeTransparent(Image image, float opacity) { if (image == null) return null; if (opacity == 1F) return image.Clone() as Image; Bitmap bmp = new Bitmap(image.Width, image.Height); Graphics g = Graphics.FromImage(bmp); float[][] ptsArray ={ new float[] {1, 0, 0, 0, 0}, // R new float[] {0, 1, 0, 0, 0}, // G new float[] {0, 0, 1, 0, 0}, // B new[] {0, 0, 0, opacity, 0}, // A new float[] {0, 0, 0, 0, 1}}; ColorMatrix clrMatrix = new ColorMatrix(ptsArray); ImageAttributes att = new ImageAttributes(); att.SetColorMatrix(clrMatrix); g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, att); g.Dispose(); return bmp; } } }
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdGroupBidModifierServiceClient"/> instances.</summary> public sealed partial class AdGroupBidModifierServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupBidModifierServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupBidModifierServiceSettings"/>.</returns> public static AdGroupBidModifierServiceSettings GetDefault() => new AdGroupBidModifierServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupBidModifierServiceSettings"/> object with default settings. /// </summary> public AdGroupBidModifierServiceSettings() { } private AdGroupBidModifierServiceSettings(AdGroupBidModifierServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdGroupBidModifierSettings = existing.GetAdGroupBidModifierSettings; MutateAdGroupBidModifiersSettings = existing.MutateAdGroupBidModifiersSettings; OnCopy(existing); } partial void OnCopy(AdGroupBidModifierServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupBidModifierServiceClient.GetAdGroupBidModifier</c> and /// <c>AdGroupBidModifierServiceClient.GetAdGroupBidModifierAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAdGroupBidModifierSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupBidModifierServiceClient.MutateAdGroupBidModifiers</c> and /// <c>AdGroupBidModifierServiceClient.MutateAdGroupBidModifiersAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupBidModifiersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupBidModifierServiceSettings"/> object.</returns> public AdGroupBidModifierServiceSettings Clone() => new AdGroupBidModifierServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupBidModifierServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupBidModifierServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupBidModifierServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupBidModifierServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupBidModifierServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupBidModifierServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupBidModifierServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupBidModifierServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupBidModifierServiceClient Build() { AdGroupBidModifierServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupBidModifierServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupBidModifierServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupBidModifierServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupBidModifierServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupBidModifierServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupBidModifierServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupBidModifierServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupBidModifierServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupBidModifierServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupBidModifierService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group bid modifiers. /// </remarks> public abstract partial class AdGroupBidModifierServiceClient { /// <summary> /// The default endpoint for the AdGroupBidModifierService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupBidModifierService scopes.</summary> /// <remarks> /// The default AdGroupBidModifierService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupBidModifierServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupBidModifierServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupBidModifierServiceClient"/>.</returns> public static stt::Task<AdGroupBidModifierServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupBidModifierServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupBidModifierServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupBidModifierServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupBidModifierServiceClient"/>.</returns> public static AdGroupBidModifierServiceClient Create() => new AdGroupBidModifierServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupBidModifierServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupBidModifierServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupBidModifierServiceClient"/>.</returns> internal static AdGroupBidModifierServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupBidModifierServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupBidModifierService.AdGroupBidModifierServiceClient grpcClient = new AdGroupBidModifierService.AdGroupBidModifierServiceClient(callInvoker); return new AdGroupBidModifierServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupBidModifierService client</summary> public virtual AdGroupBidModifierService.AdGroupBidModifierServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupBidModifier GetAdGroupBidModifier(GetAdGroupBidModifierRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(GetAdGroupBidModifierRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(GetAdGroupBidModifierRequest request, st::CancellationToken cancellationToken) => GetAdGroupBidModifierAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group bid modifier to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupBidModifier GetAdGroupBidModifier(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupBidModifier(new GetAdGroupBidModifierRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group bid modifier to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupBidModifierAsync(new GetAdGroupBidModifierRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group bid modifier to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdGroupBidModifierAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group bid modifier to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupBidModifier GetAdGroupBidModifier(gagvr::AdGroupBidModifierName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupBidModifier(new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group bid modifier to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(gagvr::AdGroupBidModifierName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupBidModifierAsync(new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group bid modifier to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(gagvr::AdGroupBidModifierName resourceName, st::CancellationToken cancellationToken) => GetAdGroupBidModifierAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupBidModifiersResponse MutateAdGroupBidModifiers(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(MutateAdGroupBidModifiersRequest request, st::CancellationToken cancellationToken) => MutateAdGroupBidModifiersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group bid modifiers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group bid modifiers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupBidModifiersResponse MutateAdGroupBidModifiers(string customerId, scg::IEnumerable<AdGroupBidModifierOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupBidModifiers(new MutateAdGroupBidModifiersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group bid modifiers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group bid modifiers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(string customerId, scg::IEnumerable<AdGroupBidModifierOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupBidModifiersAsync(new MutateAdGroupBidModifiersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group bid modifiers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group bid modifiers. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(string customerId, scg::IEnumerable<AdGroupBidModifierOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupBidModifiersAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupBidModifierService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group bid modifiers. /// </remarks> public sealed partial class AdGroupBidModifierServiceClientImpl : AdGroupBidModifierServiceClient { private readonly gaxgrpc::ApiCall<GetAdGroupBidModifierRequest, gagvr::AdGroupBidModifier> _callGetAdGroupBidModifier; private readonly gaxgrpc::ApiCall<MutateAdGroupBidModifiersRequest, MutateAdGroupBidModifiersResponse> _callMutateAdGroupBidModifiers; /// <summary> /// Constructs a client wrapper for the AdGroupBidModifierService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupBidModifierServiceSettings"/> used within this client. /// </param> public AdGroupBidModifierServiceClientImpl(AdGroupBidModifierService.AdGroupBidModifierServiceClient grpcClient, AdGroupBidModifierServiceSettings settings) { GrpcClient = grpcClient; AdGroupBidModifierServiceSettings effectiveSettings = settings ?? AdGroupBidModifierServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdGroupBidModifier = clientHelper.BuildApiCall<GetAdGroupBidModifierRequest, gagvr::AdGroupBidModifier>(grpcClient.GetAdGroupBidModifierAsync, grpcClient.GetAdGroupBidModifier, effectiveSettings.GetAdGroupBidModifierSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdGroupBidModifier); Modify_GetAdGroupBidModifierApiCall(ref _callGetAdGroupBidModifier); _callMutateAdGroupBidModifiers = clientHelper.BuildApiCall<MutateAdGroupBidModifiersRequest, MutateAdGroupBidModifiersResponse>(grpcClient.MutateAdGroupBidModifiersAsync, grpcClient.MutateAdGroupBidModifiers, effectiveSettings.MutateAdGroupBidModifiersSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupBidModifiers); Modify_MutateAdGroupBidModifiersApiCall(ref _callMutateAdGroupBidModifiers); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetAdGroupBidModifierApiCall(ref gaxgrpc::ApiCall<GetAdGroupBidModifierRequest, gagvr::AdGroupBidModifier> call); partial void Modify_MutateAdGroupBidModifiersApiCall(ref gaxgrpc::ApiCall<MutateAdGroupBidModifiersRequest, MutateAdGroupBidModifiersResponse> call); partial void OnConstruction(AdGroupBidModifierService.AdGroupBidModifierServiceClient grpcClient, AdGroupBidModifierServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupBidModifierService client</summary> public override AdGroupBidModifierService.AdGroupBidModifierServiceClient GrpcClient { get; } partial void Modify_GetAdGroupBidModifierRequest(ref GetAdGroupBidModifierRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAdGroupBidModifiersRequest(ref MutateAdGroupBidModifiersRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdGroupBidModifier GetAdGroupBidModifier(GetAdGroupBidModifierRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupBidModifierRequest(ref request, ref callSettings); return _callGetAdGroupBidModifier.Sync(request, callSettings); } /// <summary> /// Returns the requested ad group bid modifier in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdGroupBidModifier> GetAdGroupBidModifierAsync(GetAdGroupBidModifierRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupBidModifierRequest(ref request, ref callSettings); return _callGetAdGroupBidModifier.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdGroupBidModifiersResponse MutateAdGroupBidModifiers(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupBidModifiersRequest(ref request, ref callSettings); return _callMutateAdGroupBidModifiers.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupBidModifiersRequest(ref request, ref callSettings); return _callMutateAdGroupBidModifiers.Async(request, callSettings); } } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using DebuggerCommonApi; using LldbApi; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; namespace DebuggerGrpcServer.Tests { [TestFixture] [Timeout(5000)] class RemoteFrameTests { const ulong TEST_PC = 0x123456789abcdef0; const ulong FUNCTION_ADDRESS_MIN = 10; const ulong FUNCTION_ADDRESS_MAX = 20; const ulong SYMBOL_ADDRESS_MIN = 30; const ulong SYMBOL_ADDRESS_MAX = 40; const string NAME = "DebugStackFrameTests"; const string ARG1_TYPE_NAME = "type_name_1"; const string ARG1_NAME = "name_1"; const string ARG1_VALUE = "value_1"; const string ARG2_TYPE_NAME = "type_name_2"; const string ARG2_NAME = "name_2"; const string ARG2_VALUE = "value_2"; const string ARG_THIS_VALUE = "value_this"; const string ARG_THIS_NAME = "this"; RemoteFrame stackFrame; SbFrame mockDebuggerStackFrame; SbTarget mockTarget; SbFrame CreateMockStackFrame() { mockDebuggerStackFrame = Substitute.For<SbFrame>(); mockDebuggerStackFrame.GetPC().Returns(TEST_PC); mockDebuggerStackFrame.GetThread().GetProcess().GetTarget().Returns(mockTarget); mockDebuggerStackFrame.GetFunction().GetStartAddress().GetLoadAddress(mockTarget) .Returns(FUNCTION_ADDRESS_MIN); mockDebuggerStackFrame.GetFunction().GetEndAddress().GetLoadAddress(mockTarget) .Returns(FUNCTION_ADDRESS_MAX); mockDebuggerStackFrame.GetSymbol().GetStartAddress().GetLoadAddress(mockTarget) .Returns(SYMBOL_ADDRESS_MIN); mockDebuggerStackFrame.GetSymbol().GetEndAddress().GetLoadAddress(mockTarget) .Returns(SYMBOL_ADDRESS_MAX); mockDebuggerStackFrame.GetFunctionName().Returns(NAME); return mockDebuggerStackFrame; } [SetUp] public void SetUp() { mockTarget = Substitute.For<SbTarget>(); mockDebuggerStackFrame = CreateMockStackFrame(); var mockArgument1 = Substitute.For<SbValue>(); mockArgument1.GetValue().Returns(ARG1_VALUE); var mockArgument2 = Substitute.For<SbValue>(); mockArgument2.GetValue().Returns(ARG2_VALUE); var functionArguments = new List<SbValue>(); functionArguments.Add(mockArgument1); functionArguments.Add(mockArgument2); mockDebuggerStackFrame.GetVariables(true, false, false, false).Returns( functionArguments); mockDebuggerStackFrame.GetFunction().GetArgumentName(0).Returns(ARG1_NAME); mockDebuggerStackFrame.GetFunction().GetArgumentName(1).Returns(ARG2_NAME); var mockArgTypeList = Substitute.For<SbTypeList>(); mockArgTypeList.GetSize().Returns(2u); mockArgTypeList.GetTypeAtIndex(0u).GetName().Returns(ARG1_TYPE_NAME); mockArgTypeList.GetTypeAtIndex(1u).GetName().Returns(ARG2_TYPE_NAME); var mockFunctionType = Substitute.For<SbType>(); mockFunctionType.GetFunctionArgumentTypes().Returns(mockArgTypeList); mockDebuggerStackFrame.GetFunction().GetType().Returns(mockFunctionType); var optionsFactory = Substitute.For<ILldbExpressionOptionsFactory>(); var valueFactory = new RemoteValueImpl.Factory(optionsFactory); stackFrame = new RemoteFrameImpl.Factory(valueFactory, optionsFactory) .Create(mockDebuggerStackFrame); } [Test] public void GetPhysicalStackRangePrioritizesFunctionAddressRange() { var result = stackFrame.GetPhysicalStackRange(); Assert.NotNull(result); Assert.AreEqual(FUNCTION_ADDRESS_MIN, result.addressMin); Assert.AreEqual(FUNCTION_ADDRESS_MAX, result.addressMax); } [Test] public void GetPhysicalStackRangeChecksSymbolAddressRange() { mockDebuggerStackFrame.GetFunction().GetEndAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetFunction().GetStartAddress().Returns((SbAddress)null); var result = stackFrame.GetPhysicalStackRange(); Assert.NotNull(result); Assert.AreEqual(SYMBOL_ADDRESS_MIN, result.addressMin); Assert.AreEqual(SYMBOL_ADDRESS_MAX, result.addressMax); } [Test] public void GetPhysicalStackRangeDefaultsToPC() { mockDebuggerStackFrame.GetFunction().GetStartAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetFunction().GetEndAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetSymbol().GetStartAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetSymbol().GetEndAddress().Returns((SbAddress)null); var result = stackFrame.GetPhysicalStackRange(); Assert.NotNull(result); Assert.AreEqual(TEST_PC, result.addressMin); Assert.AreEqual(TEST_PC, result.addressMax); } [Test] public void GetPhysicalStackRangeFail() { mockDebuggerStackFrame.GetFunction().GetStartAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetFunction().GetEndAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetSymbol().GetStartAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetSymbol().GetEndAddress().Returns((SbAddress)null); mockDebuggerStackFrame.GetPC().Returns(ulong.MaxValue); var result = stackFrame.GetPhysicalStackRange(); Assert.Null(result); } [Test] public void GetPhysicalStackRangeFailWithNullTarget() { mockDebuggerStackFrame.GetThread().GetProcess().GetTarget().Returns((SbTarget)null); mockDebuggerStackFrame.GetPC().Returns(ulong.MaxValue); var result = stackFrame.GetPhysicalStackRange(); Assert.Null(result); } [Test] public void GetInfoEmpty() { var info = stackFrame.GetInfo(0); Assert.AreEqual((FrameInfoFlags)0, info.ValidFields); } [Test] public void GetInfoFunction() { var fields = FrameInfoFlags.FIF_FUNCNAME; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(NAME, info.FuncName); } [Test] public void GetInfoFunctionModule() { const string moduleName = "module name"; var module = Substitute.For<SbModule>(); module.GetPlatformFileSpec().GetFilename().Returns(moduleName); mockDebuggerStackFrame.GetModule().Returns(module); var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_MODULE; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(moduleName + "!" + NAME, info.FuncName); } [Test] public void GetInfoModuleName() { const string moduleName = "module_name"; var module = Substitute.For<SbModule>(); module.GetPlatformFileSpec().GetFilename().Returns(moduleName); mockDebuggerStackFrame.GetModule().Returns(module); FrameInfo<SbModule> info = stackFrame.GetInfo(FrameInfoFlags.FIF_MODULE); Assert.That(info.ValidFields & FrameInfoFlags.FIF_MODULE, Is.EqualTo(FrameInfoFlags.FIF_MODULE)); Assert.That(info.ModuleName, Is.EqualTo(moduleName)); } [Test] public void GetInfoFunctionLine() { uint lineNum = 17; var lineEntry = Substitute.For<SbLineEntry>(); lineEntry.GetLine().Returns(lineNum); mockDebuggerStackFrame.GetLineEntry().Returns(lineEntry); var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_LINES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(NAME + " Line " + lineNum, info.FuncName); } [Test] public void GetInfoFunctionGlobalScopeResolution([Values("::", "::::")] string prefix) { var name = prefix + NAME; mockDebuggerStackFrame.GetFunctionName().Returns(name); var fields = FrameInfoFlags.FIF_FUNCNAME; var info = stackFrame.GetInfo(fields); Assert.IsTrue(info.ValidFields.HasFlag(FrameInfoFlags.FIF_FUNCNAME)); Assert.AreEqual(NAME, info.FuncName); } [Test] public void GetInfoLeadingAnonymousNamespace() { var name = "(anonymous namespace)::f"; mockDebuggerStackFrame.GetFunctionName().Returns(name); var fields = FrameInfoFlags.FIF_FUNCNAME; var info = stackFrame.GetInfo(fields); Assert.That(info.ValidFields.HasFlag(FrameInfoFlags.FIF_FUNCNAME), Is.True); Assert.That(info.FuncName, Is.EqualTo("`anonymous namespace'::f")); } [Test] public void GetInfoInnerAnonymousNamespace() { var name = "a::(anonymous namespace)::f"; mockDebuggerStackFrame.GetFunctionName().Returns(name); var fields = FrameInfoFlags.FIF_FUNCNAME; var info = stackFrame.GetInfo(fields); Assert.That(info.ValidFields.HasFlag(FrameInfoFlags.FIF_FUNCNAME), Is.True); Assert.That(info.FuncName, Is.EqualTo("a::`anonymous namespace'::f")); } [Test] public void GetInfoFunctionNameStripNameParams() { var name = "T<void(*)(int)>::m(a, void (*func)(), b)"; mockDebuggerStackFrame.GetFunctionName().Returns(name); var fields = FrameInfoFlags.FIF_FUNCNAME; var info = stackFrame.GetInfo(fields); Assert.That(info.ValidFields.HasFlag(FrameInfoFlags.FIF_FUNCNAME), Is.True); Assert.That(info.FuncName, Is.EqualTo("T<void(*)(int)>::m")); } [Test] public void GetInfoFunctionNameStripNameEmptyParams() { var name = "f()"; mockDebuggerStackFrame.GetFunctionName().Returns(name); var fields = FrameInfoFlags.FIF_FUNCNAME; var info = stackFrame.GetInfo(fields); Assert.That(info.ValidFields.HasFlag(FrameInfoFlags.FIF_FUNCNAME), Is.True); Assert.That(info.FuncName, Is.EqualTo("f")); } [Test] public void GetInfoTypes() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(string.Format("{0}({1}, {2})", NAME, ARG1_TYPE_NAME, ARG2_TYPE_NAME), info.FuncName); } [Test] public void GetInfoTypesAndNames() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual( string.Format("{0}({1} {2}, {3} {4})", NAME, ARG1_TYPE_NAME, ARG1_NAME, ARG2_TYPE_NAME, ARG2_NAME), info.FuncName); } [Test] public void GetInfoTypesAndValues() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual( string.Format("{0}({1} = {2}, {3} = {4})", NAME, ARG1_TYPE_NAME, ARG1_VALUE, ARG2_TYPE_NAME, ARG2_VALUE), info.FuncName); } [Test] public void GetInfoTypesAndNamesAndValues() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual( string.Format("{0}({1} {2} = {3}, {4} {5} = {6})", NAME, ARG1_TYPE_NAME, ARG1_NAME, ARG1_VALUE, ARG2_TYPE_NAME, ARG2_NAME, ARG2_VALUE), info.FuncName); } [Test] public void GetInfoNames() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(string.Format("{0}({1}, {2})", NAME, ARG1_NAME, ARG2_NAME), info.FuncName); } [Test] public void GetInfoNamesAndValues() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual( string.Format("{0}({1} = {2}, {3} = {4})", NAME, ARG1_NAME, ARG1_VALUE, ARG2_NAME, ARG2_VALUE), info.FuncName); } [Test] public void GetInfoValues() { var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(string.Format("{0}({1}, {2})", NAME, ARG1_VALUE, ARG2_VALUE), info.FuncName); } [Test] public void GetInfoNamesAndValuesStripFunctionNameParams() { var name = $"{NAME}({ARG1_TYPE_NAME}, {ARG2_TYPE_NAME})"; mockDebuggerStackFrame.GetFunctionName().Returns(name); var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(string.Format("{0}({1} = {2}, {3} = {4})", NAME, ARG1_NAME, ARG1_VALUE, ARG2_NAME, ARG2_VALUE), info.FuncName); } RemoteFrame CreateMethodStackFrame() { var mockDebuggerMethodStackFrame = CreateMockStackFrame(); var mockArgument0 = Substitute.For<SbValue>(); mockArgument0.GetValue().Returns(ARG_THIS_VALUE); var mockArgument1 = Substitute.For<SbValue>(); mockArgument1.GetValue().Returns(ARG1_VALUE); var mockArgument2 = Substitute.For<SbValue>(); mockArgument2.GetValue().Returns(ARG2_VALUE); var functionArguments = new List<SbValue>(); functionArguments.Add(mockArgument0); functionArguments.Add(mockArgument1); functionArguments.Add(mockArgument2); mockDebuggerMethodStackFrame.GetVariables(true, false, false, false).Returns( functionArguments); mockDebuggerMethodStackFrame.GetFunction().GetArgumentName(0).Returns(ARG_THIS_NAME); mockDebuggerMethodStackFrame.GetFunction().GetArgumentName(1).Returns(ARG1_NAME); mockDebuggerMethodStackFrame.GetFunction().GetArgumentName(2).Returns(ARG2_NAME); var mockArgTypeList = Substitute.For<SbTypeList>(); mockArgTypeList.GetSize().Returns(2u); mockArgTypeList.GetTypeAtIndex(0u).GetName().Returns(ARG1_TYPE_NAME); mockArgTypeList.GetTypeAtIndex(1u).GetName().Returns(ARG2_TYPE_NAME); var mockFunctionType = Substitute.For<SbType>(); mockFunctionType.GetFunctionArgumentTypes().Returns(mockArgTypeList); mockDebuggerMethodStackFrame.GetFunction().GetType().Returns(mockFunctionType); var optionsFactory = Substitute.For<ILldbExpressionOptionsFactory>(); return new RemoteFrameImpl.Factory( new RemoteValueImpl.Factory(optionsFactory), optionsFactory) .Create(mockDebuggerMethodStackFrame); } [Test] public void GetInfoTypesForMethod() { RemoteFrame methodStackFrame = CreateMethodStackFrame(); var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES; var info = methodStackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual(string.Format("{0}({1}, {2})", NAME, ARG1_TYPE_NAME, ARG2_TYPE_NAME), info.FuncName); } [Test] public void GetInfoTypesAndNamesAndValuesForMethod() { RemoteFrame methodStackFrame = CreateMethodStackFrame(); var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = methodStackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual( string.Format("{0}({1} {2} = {3}, {4} {5} = {6})", NAME, ARG1_TYPE_NAME, ARG1_NAME, ARG1_VALUE, ARG2_TYPE_NAME, ARG2_NAME, ARG2_VALUE), info.FuncName); } [Test] public void GetInfoTypesAndNamesWithMissingValues() { mockDebuggerStackFrame.GetVariables(true, false, false, false).Returns( new List<SbValue>()); var fields = FrameInfoFlags.FIF_FUNCNAME | FrameInfoFlags.FIF_FUNCNAME_ARGS | FrameInfoFlags.FIF_FUNCNAME_ARGS_TYPES | FrameInfoFlags.FIF_FUNCNAME_ARGS_NAMES | FrameInfoFlags.FIF_FUNCNAME_ARGS_VALUES; var info = stackFrame.GetInfo(fields); Assert.AreEqual(FrameInfoFlags.FIF_FUNCNAME, info.ValidFields & FrameInfoFlags.FIF_FUNCNAME); Assert.AreEqual( string.Format("{0}({1} {2}, {3} {4})", NAME, ARG1_TYPE_NAME, ARG1_NAME, ARG2_TYPE_NAME, ARG2_NAME), info.FuncName); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A hotel. /// </summary> public class Hotel_Core : TypeCore, ILodgingBusiness { public Hotel_Core() { this._TypeId = 132; this._Id = "Hotel"; this._Schema_Org_Url = "http://schema.org/Hotel"; string label = ""; GetLabel(out label, "Hotel", typeof(Hotel_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,157}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{157}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JCG = J2N.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. */ /// <summary> /// Collection of <see cref="Index.FieldInfo"/>s (accessible by number or by name). /// <para/> /// @lucene.experimental /// </summary> public class FieldInfos : IEnumerable<FieldInfo> { private readonly bool hasFreq; private readonly bool hasProx; private readonly bool hasPayloads; private readonly bool hasOffsets; private readonly bool hasVectors; private readonly bool hasNorms; private readonly bool hasDocValues; private readonly IDictionary<int, FieldInfo> byNumber = new JCG.SortedDictionary<int, FieldInfo>(); private readonly IDictionary<string, FieldInfo> byName = new JCG.Dictionary<string, FieldInfo>(); private readonly ICollection<FieldInfo> values; // for an unmodifiable iterator /// <summary> /// Constructs a new <see cref="FieldInfos"/> from an array of <see cref="Index.FieldInfo"/> objects /// </summary> public FieldInfos(FieldInfo[] infos) { bool hasVectors = false; bool hasProx = false; bool hasPayloads = false; bool hasOffsets = false; bool hasFreq = false; bool hasNorms = false; bool hasDocValues = false; foreach (FieldInfo info in infos) { if (info.Number < 0) { throw new ArgumentException("illegal field number: " + info.Number + " for field " + info.Name); } FieldInfo previous; if (byNumber.TryGetValue(info.Number, out previous)) { throw new ArgumentException("duplicate field numbers: " + previous.Name + " and " + info.Name + " have: " + info.Number); } byNumber[info.Number] = info; if (byName.TryGetValue(info.Name, out previous)) { throw new ArgumentException("duplicate field names: " + previous.Number + " and " + info.Number + " have: " + info.Name); } byName[info.Name] = info; hasVectors |= info.HasVectors; hasProx |= info.IsIndexed && info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; hasFreq |= info.IsIndexed && info.IndexOptions != IndexOptions.DOCS_ONLY; hasOffsets |= info.IsIndexed && info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; hasNorms |= info.HasNorms; hasDocValues |= info.HasDocValues; hasPayloads |= info.HasPayloads; } this.hasVectors = hasVectors; this.hasProx = hasProx; this.hasPayloads = hasPayloads; this.hasOffsets = hasOffsets; this.hasFreq = hasFreq; this.hasNorms = hasNorms; this.hasDocValues = hasDocValues; this.values = byNumber.Values; } /// <summary> /// Returns <c>true</c> if any fields have freqs </summary> public virtual bool HasFreq => hasFreq; /// <summary> /// Returns <c>true</c> if any fields have positions </summary> public virtual bool HasProx => hasProx; /// <summary> /// Returns <c>true</c> if any fields have payloads </summary> public virtual bool HasPayloads => hasPayloads; /// <summary> /// Returns <c>true</c> if any fields have offsets </summary> public virtual bool HasOffsets => hasOffsets; /// <summary> /// Returns <c>true</c> if any fields have vectors </summary> public virtual bool HasVectors => hasVectors; /// <summary> /// Returns <c>true</c> if any fields have norms </summary> public virtual bool HasNorms => hasNorms; /// <summary> /// Returns <c>true</c> if any fields have <see cref="DocValues"/> </summary> public virtual bool HasDocValues => hasDocValues; /// <summary> /// Returns the number of fields. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public virtual int Count { get { Debug.Assert(byNumber.Count == byName.Count); return byNumber.Count; } } /// <summary> /// Returns an iterator over all the fieldinfo objects present, /// ordered by ascending field number /// </summary> // TODO: what happens if in fact a different order is used? public virtual IEnumerator<FieldInfo> GetEnumerator() { return values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Return the <see cref="Index.FieldInfo"/> object referenced by the <paramref name="fieldName"/> </summary> /// <returns> the <see cref="Index.FieldInfo"/> object or <c>null</c> when the given <paramref name="fieldName"/> /// doesn't exist. </returns> public virtual FieldInfo FieldInfo(string fieldName) { FieldInfo ret; byName.TryGetValue(fieldName, out ret); return ret; } /// <summary> /// Return the <see cref="Index.FieldInfo"/> object referenced by the <paramref name="fieldNumber"/>. </summary> /// <param name="fieldNumber"> field's number. </param> /// <returns> the <see cref="Index.FieldInfo"/> object or null when the given <paramref name="fieldNumber"/> /// doesn't exist. </returns> /// <exception cref="ArgumentException"> if <paramref name="fieldNumber"/> is negative </exception> public virtual FieldInfo FieldInfo(int fieldNumber) { if (fieldNumber < 0) { throw new ArgumentException("Illegal field number: " + fieldNumber); } Index.FieldInfo ret; byNumber.TryGetValue(fieldNumber, out ret); return ret; } internal sealed class FieldNumbers { private readonly IDictionary<int?, string> numberToName; private readonly IDictionary<string, int?> nameToNumber; // We use this to enforce that a given field never // changes DV type, even across segments / IndexWriter // sessions: private readonly IDictionary<string, DocValuesType> docValuesType; // TODO: we should similarly catch an attempt to turn // norms back on after they were already ommitted; today // we silently discard the norm but this is badly trappy private int lowestUnassignedFieldNumber = -1; internal FieldNumbers() { this.nameToNumber = new Dictionary<string, int?>(); this.numberToName = new Dictionary<int?, string>(); this.docValuesType = new Dictionary<string, DocValuesType>(); } /// <summary> /// Returns the global field number for the given field name. If the name /// does not exist yet it tries to add it with the given preferred field /// number assigned if possible otherwise the first unassigned field number /// is used as the field number. /// </summary> internal int AddOrGet(string fieldName, int preferredFieldNumber, DocValuesType dvType) { lock (this) { if (dvType != DocValuesType.NONE) { DocValuesType currentDVType; docValuesType.TryGetValue(fieldName, out currentDVType); if (currentDVType == DocValuesType.NONE) // default value in .NET (value type 0) { docValuesType[fieldName] = dvType; } else if (currentDVType != DocValuesType.NONE && currentDVType != dvType) { throw new ArgumentException("cannot change DocValues type from " + currentDVType + " to " + dvType + " for field \"" + fieldName + "\""); } } int? fieldNumber; nameToNumber.TryGetValue(fieldName, out fieldNumber); if (fieldNumber == null) { int? preferredBoxed = preferredFieldNumber; if (preferredFieldNumber != -1 && !numberToName.ContainsKey(preferredBoxed)) { // cool - we can use this number globally fieldNumber = preferredBoxed; } else { // find a new FieldNumber while (numberToName.ContainsKey(++lowestUnassignedFieldNumber)) { // might not be up to date - lets do the work once needed } fieldNumber = lowestUnassignedFieldNumber; } numberToName[fieldNumber] = fieldName; nameToNumber[fieldName] = fieldNumber; } return (int)fieldNumber; } } // used by assert internal bool ContainsConsistent(int? number, string name, DocValuesType dvType) { lock (this) { string numberToNameStr; int? nameToNumberVal; DocValuesType docValuesType_E; numberToName.TryGetValue(number, out numberToNameStr); nameToNumber.TryGetValue(name, out nameToNumberVal); docValuesType.TryGetValue(name, out docValuesType_E); return name.Equals(numberToNameStr, StringComparison.Ordinal) && number.Equals(nameToNumber[name]) && (dvType == DocValuesType.NONE || docValuesType_E == DocValuesType.NONE || dvType == docValuesType_E); } } /// <summary> /// Returns <c>true</c> if the <paramref name="fieldName"/> exists in the map and is of the /// same <paramref name="dvType"/>. /// </summary> internal bool Contains(string fieldName, DocValuesType dvType) { lock (this) { // used by IndexWriter.updateNumericDocValue if (!nameToNumber.ContainsKey(fieldName)) { return false; } else { // only return true if the field has the same dvType as the requested one DocValuesType dvCand; docValuesType.TryGetValue(fieldName, out dvCand); return dvType == dvCand; } } } internal void Clear() { lock (this) { numberToName.Clear(); nameToNumber.Clear(); docValuesType.Clear(); } } internal void SetDocValuesType(int number, string name, DocValuesType dvType) { lock (this) { Debug.Assert(ContainsConsistent(number, name, dvType)); docValuesType[name] = dvType; } } } internal sealed class Builder { private readonly Dictionary<string, FieldInfo> byName = new Dictionary<string, FieldInfo>(); private readonly FieldNumbers globalFieldNumbers; internal Builder() : this(new FieldNumbers()) { } /// <summary> /// Creates a new instance with the given <see cref="FieldNumbers"/>. /// </summary> internal Builder(FieldNumbers globalFieldNumbers) { Debug.Assert(globalFieldNumbers != null); this.globalFieldNumbers = globalFieldNumbers; } public void Add(FieldInfos other) { foreach (FieldInfo fieldInfo in other) { Add(fieldInfo); } } /// <summary> /// NOTE: this method does not carry over termVector /// booleans nor docValuesType; the indexer chain /// (TermVectorsConsumerPerField, DocFieldProcessor) must /// set these fields when they succeed in consuming /// the document /// </summary> public FieldInfo AddOrUpdate(string name, IIndexableFieldType fieldType) { // TODO: really, indexer shouldn't even call this // method (it's only called from DocFieldProcessor); // rather, each component in the chain should update // what it "owns". EG fieldType.indexOptions() should // be updated by maybe FreqProxTermsWriterPerField: return AddOrUpdateInternal(name, -1, fieldType.IsIndexed, false, fieldType.OmitNorms, false, fieldType.IndexOptions, fieldType.DocValueType, DocValuesType.NONE); } private FieldInfo AddOrUpdateInternal(string name, int preferredFieldNumber, bool isIndexed, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions, DocValuesType docValues, DocValuesType normType) { FieldInfo fi = FieldInfo(name); if (fi == null) { // this field wasn't yet added to this in-RAM // segment's FieldInfo, so now we get a global // number for this field. If the field was seen // before then we'll get the same name and number, // else we'll allocate a new one: int fieldNumber = globalFieldNumbers.AddOrGet(name, preferredFieldNumber, docValues); fi = new FieldInfo(name, isIndexed, fieldNumber, storeTermVector, omitNorms, storePayloads, indexOptions, docValues, normType, null); Debug.Assert(!byName.ContainsKey(fi.Name)); Debug.Assert(globalFieldNumbers.ContainsConsistent(fi.Number, fi.Name, fi.DocValuesType)); byName[fi.Name] = fi; } else { fi.Update(isIndexed, storeTermVector, omitNorms, storePayloads, indexOptions); if (docValues != DocValuesType.NONE) { // only pay the synchronization cost if fi does not already have a DVType bool updateGlobal = !fi.HasDocValues; fi.DocValuesType = docValues; // this will also perform the consistency check. if (updateGlobal) { // must also update docValuesType map so it's // aware of this field's DocValueType globalFieldNumbers.SetDocValuesType(fi.Number, name, docValues); } } if (!fi.OmitsNorms && normType != DocValuesType.NONE) { fi.NormType = normType; } } return fi; } public FieldInfo Add(FieldInfo fi) { // IMPORTANT - reuse the field number if possible for consistent field numbers across segments return AddOrUpdateInternal(fi.Name, fi.Number, fi.IsIndexed, fi.HasVectors, fi.OmitsNorms, fi.HasPayloads, fi.IndexOptions, fi.DocValuesType, fi.NormType); } public FieldInfo FieldInfo(string fieldName) { FieldInfo ret; byName.TryGetValue(fieldName, out ret); return ret; } public FieldInfos Finish() { return new FieldInfos(byName.Values.ToArray()); } } } }
/** * 7/8/2013 */ #define PRO using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.IO; namespace ProGrids { [InitializeOnLoad] public static class pg_Initializer { /** * When opening Unity, remember whether or not ProGrids was open when Unity was shut down last. * Only check within 10 seconds of opening Unity because otherwise Init will be called multiple * times due to _instance not being set (OnAfterDeserialize is called after static constructors). */ static pg_Initializer() { if( EditorApplication.timeSinceStartup < 10f && EditorPrefs.GetBool(pg_Constant.ProGridsIsEnabled) ) pg_Editor.InitProGrids(); } } public class pg_Editor : ScriptableObject, ISerializationCallbackReceiver { #region MEMBERS string ProGrids_Icons_Path = "Assets/ProCore/ProGrids/GUI/ProGridsToggles"; public static pg_Editor instance { get { if(_instance == null) { pg_Editor[] editor = Resources.FindObjectsOfTypeAll<pg_Editor>(); if(editor != null && editor.Length > 0) { _instance = editor[0]; for(int i = 1; i < editor.Length; i++) { GameObject.DestroyImmediate(editor[i]); } } } return _instance; } set { _instance = value; } } private static pg_Editor _instance; Color oldColor; private bool useAxisConstraints = false; private bool snapEnabled = true; private SnapUnit snapUnit = SnapUnit.Meter; #if PRO private float snapValue = 1f; // the actual snap value, taking into account unit size private float t_snapValue = 1f; // what the user sees #else private float snapValue = .25f; private float t_snapValue = .25f; #endif private bool drawGrid = true; private bool drawAngles = false; public float angleValue = 45f; private bool gridRepaint = true; public bool predictiveGrid = true; private bool _snapAsGroup = true; public bool snapAsGroup { get { return EditorPrefs.HasKey(pg_Constant.SnapAsGroup) ? EditorPrefs.GetBool(pg_Constant.SnapAsGroup) : true; } set { _snapAsGroup = value; EditorPrefs.SetBool(pg_Constant.SnapAsGroup, _snapAsGroup); } } public bool fullGrid { get; private set; } private bool _scaleSnapEnabled = false; public bool ScaleSnapEnabled { get { return EditorPrefs.HasKey(pg_Constant.SnapScale) ? EditorPrefs.GetBool(pg_Constant.SnapScale) : false; } set { _scaleSnapEnabled = value; EditorPrefs.SetBool(pg_Constant.SnapScale, _scaleSnapEnabled); } } bool lockGrid = false; private Axis renderPlane = Axis.Y; #if PG_DEBUG private GameObject _pivotGo; public GameObject pivotGo { get { if(_pivotGo == null) { GameObject find = GameObject.Find("PG_PIVOT_CUBE"); if(find == null) { _pivotGo = GameObject.CreatePrimitive(PrimitiveType.Cube); _pivotGo.name = "PG_PIVOT_CUBE"; } else _pivotGo = find; } return _pivotGo; } set { _pivotGo = value; } } #endif #endregion #region CONSTANT const int VERSION = 20; const bool RESET_PREFS_REQ = true; #if PRO const int WINDOW_HEIGHT = 240; #else const int WINDOW_HEIGHT = 260; #endif const int MAX_LINES = 150; // the maximum amount of lines to display on screen in either direction public static float alphaBump; // Every tenth line gets an alpha bump by this amount const int BUTTON_SIZE = 46; private Texture2D icon_extendoClose, icon_extendoOpen; [SerializeField] private pg_ToggleContent gc_SnapToGrid = new pg_ToggleContent("Snap", "", "Snaps all selected objects to grid."); [SerializeField] private pg_ToggleContent gc_GridEnabled = new pg_ToggleContent("Hide", "Show", "Toggles drawing of guide lines on or off. Note that object snapping is not affected by this setting."); [SerializeField] private pg_ToggleContent gc_SnapEnabled = new pg_ToggleContent("On", "Off", "Toggles snapping on or off."); [SerializeField] private pg_ToggleContent gc_LockGrid = new pg_ToggleContent("Lock", "Unlck", "Lock the perspective grid center in place."); [SerializeField] private pg_ToggleContent gc_AngleEnabled = new pg_ToggleContent("> On", "> Off", "If on, ProGrids will draw angled line guides. Angle is settable in degrees."); [SerializeField] private pg_ToggleContent gc_RenderPlaneX = new pg_ToggleContent("X", "X", "Renders a grid on the X plane."); [SerializeField] private pg_ToggleContent gc_RenderPlaneY = new pg_ToggleContent("Y", "Y", "Renders a grid on the Y plane."); [SerializeField] private pg_ToggleContent gc_RenderPlaneZ = new pg_ToggleContent("Z", "Z", "Renders a grid on the Z plane."); [SerializeField] private pg_ToggleContent gc_RenderPerspectiveGrid = new pg_ToggleContent("Full", "Plane", "Renders a 3d grid in perspective mode."); [SerializeField] private GUIContent gc_ExtendMenu = new GUIContent("", "Show or hide the scene view menu."); [SerializeField] private GUIContent gc_SnapIncrement = new GUIContent("", "Set the snap increment."); #endregion #region PREFERENCES /** Settings **/ public Color gridColorX, gridColorY, gridColorZ; public Color gridColorX_primary, gridColorY_primary, gridColorZ_primary; // private bool lockOrthographic; public void LoadPreferences() { if( (EditorPrefs.HasKey(pg_Constant.PGVersion) ? EditorPrefs.GetInt(pg_Constant.PGVersion) : 0) < VERSION ) { EditorPrefs.SetInt(pg_Constant.PGVersion, VERSION); if(RESET_PREFS_REQ) { pg_Preferences.ResetPrefs(); // Debug.Log("Resetting Prefs"); } } if(EditorPrefs.HasKey(pg_Constant.SnapEnabled)) { snapEnabled = EditorPrefs.GetBool(pg_Constant.SnapEnabled); } SetSnapValue( EditorPrefs.HasKey(pg_Constant.GridUnit) ? (SnapUnit)EditorPrefs.GetInt(pg_Constant.GridUnit) : SnapUnit.Meter, EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1, EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100 ); if(EditorPrefs.HasKey(pg_Constant.UseAxisConstraints)) useAxisConstraints = EditorPrefs.GetBool(pg_Constant.UseAxisConstraints); lockGrid = EditorPrefs.GetBool(pg_Constant.LockGrid); if(lockGrid) { if(EditorPrefs.HasKey(pg_Constant.LockedGridPivot)) { string piv = EditorPrefs.GetString(pg_Constant.LockedGridPivot); string[] pivsplit = piv.Replace("(", "").Replace(")", "").Split(','); float x, y, z; if( !float.TryParse(pivsplit[0], out x) ) goto NoParseForYou; if( !float.TryParse(pivsplit[1], out y) ) goto NoParseForYou; if( !float.TryParse(pivsplit[2], out z) ) goto NoParseForYou; pivot.x = x; pivot.y = y; pivot.z = z; NoParseForYou: ; // appease the compiler } } fullGrid = EditorPrefs.GetBool(pg_Constant.PerspGrid); renderPlane = EditorPrefs.HasKey(pg_Constant.GridAxis) ? (Axis)EditorPrefs.GetInt(pg_Constant.GridAxis) : Axis.Y; alphaBump = (EditorPrefs.HasKey("pg_alphaBump")) ? EditorPrefs.GetFloat("pg_alphaBump") : pg_Preferences.ALPHA_BUMP; gridColorX = (EditorPrefs.HasKey("gridColorX")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorX")) : pg_Preferences.GRID_COLOR_X; gridColorX_primary = new Color(gridColorX.r, gridColorX.g, gridColorX.b, gridColorX.a + alphaBump); gridColorY = (EditorPrefs.HasKey("gridColorY")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorY")) : pg_Preferences.GRID_COLOR_Y; gridColorY_primary = new Color(gridColorY.r, gridColorY.g, gridColorY.b, gridColorY.a + alphaBump); gridColorZ = (EditorPrefs.HasKey("gridColorZ")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorZ")) : pg_Preferences.GRID_COLOR_Z; gridColorZ_primary = new Color(gridColorZ.r, gridColorZ.g, gridColorZ.b, gridColorZ.a + alphaBump); drawGrid = (EditorPrefs.HasKey("showgrid")) ? EditorPrefs.GetBool("showgrid") : pg_Preferences.SHOW_GRID; predictiveGrid = EditorPrefs.HasKey(pg_Constant.PredictiveGrid) ? EditorPrefs.GetBool(pg_Constant.PredictiveGrid) : true; _snapAsGroup = snapAsGroup; _scaleSnapEnabled = ScaleSnapEnabled; } private GUISkin sixBySevenSkin; #endregion #region MENU [MenuItem("Tools/ProGrids/About", false, 0)] public static void MenuAboutProGrids() { pg_AboutWindow.Init("Assets/ProCore/ProGrids/About/pc_AboutEntry_ProGrids.txt", true); } [MenuItem("Tools/ProGrids/ProGrids Window", false, 15)] public static void InitProGrids() { if( instance == null ) { EditorPrefs.SetBool(pg_Constant.ProGridsIsEnabled, true); instance = ScriptableObject.CreateInstance<pg_Editor>(); instance.hideFlags = HideFlags.DontSave; EditorApplication.delayCall += instance.Initialize; } else { CloseProGrids(); } SceneView.RepaintAll(); } [MenuItem("Tools/ProGrids/Close ProGrids", true, 200)] public static bool VerifyCloseProGrids() { return instance != null || Resources.FindObjectsOfTypeAll<pg_Editor>().Length > 0; } [MenuItem("Tools/ProGrids/Close ProGrids")] public static void CloseProGrids() { foreach(pg_Editor editor in Resources.FindObjectsOfTypeAll<pg_Editor>()) editor.Close(); } [MenuItem("Tools/ProGrids/Cycle SceneView Projection", false, 101)] public static void CyclePerspective() { if(instance == null) return; SceneView scnvw = SceneView.lastActiveSceneView; if(scnvw == null) return; int nextOrtho = EditorPrefs.GetInt(pg_Constant.LastOrthoToggledRotation); switch(nextOrtho) { case 0: scnvw.orthographic = true; scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.zero)); nextOrtho++; break; case 1: scnvw.orthographic = true; scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.up * -90f)); nextOrtho++; break; case 2: scnvw.orthographic = true; scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.right * 90f)); nextOrtho++; break; case 3: scnvw.orthographic = false; scnvw.LookAt(scnvw.pivot, new Quaternion(-0.1f, 0.9f, -0.2f, -0.4f) ); nextOrtho = 0; break; } EditorPrefs.SetInt(pg_Constant.LastOrthoToggledRotation, nextOrtho); } [MenuItem("Tools/ProGrids/Cycle SceneView Projection", true, 101)] [MenuItem("Tools/ProGrids/Increase Grid Size", true, 203)] [MenuItem("Tools/ProGrids/Decrease Grid Size", true, 202)] public static bool VerifyGridSizeAdjustment() { return instance != null; } [MenuItem("Tools/ProGrids/Decrease Grid Size", false, 202)] public static void DecreaseGridSize() { if(instance == null) return; int multiplier = EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100; float val = EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1f; multiplier /= 2; instance.SetSnapValue(instance.snapUnit, val, multiplier); SceneView.RepaintAll(); } [MenuItem("Tools/ProGrids/Increase Grid Size", false, 203)] public static void IncreaseGridSize() { if(instance == null) return; int multiplier = EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100; float val = EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1f; multiplier *= 2; instance.SetSnapValue(instance.snapUnit, val, multiplier); SceneView.RepaintAll(); } [MenuItem("Tools/ProGrids/Nudge Perspective Backward", true, 304)] [MenuItem("Tools/ProGrids/Nudge Perspective Forward", true, 305)] [MenuItem("Tools/ProGrids/Reset Perspective Nudge", true, 306)] public static bool VerifyMenuNudgePerspective() { return instance != null && !instance.fullGrid && !instance.ortho && instance.lockGrid; } [MenuItem("Tools/ProGrids/Nudge Perspective Backward", false, 304)] public static void MenuNudgePerspectiveBackward() { if(!instance.lockGrid) return; instance.offset -= instance.snapValue; SceneView.RepaintAll(); } [MenuItem("Tools/ProGrids/Nudge Perspective Forward", false, 305)] public static void MenuNudgePerspectiveForward() { if(!instance.lockGrid) return; instance.offset += instance.snapValue; SceneView.RepaintAll(); } [MenuItem("Tools/ProGrids/Reset Perspective Nudge", false, 306)] public static void MenuNudgePerspectiveReset() { if(!instance.lockGrid) return; instance.offset = 0; SceneView.RepaintAll(); } #endregion #region INITIALIZATION / SERIALIZATION public void OnBeforeSerialize() {} public void OnAfterDeserialize() { instance = this; SceneView.onSceneGUIDelegate += OnSceneGUI; EditorApplication.update += Update; EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged; LoadPreferences(); } public void Initialize() { SceneView.onSceneGUIDelegate += OnSceneGUI; EditorApplication.update += Update; EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged; LoadGUIResources(); LoadPreferences(); instance = this; pg_GridRenderer.Init(); SetMenuIsExtended(false); lastTime = Time.realtimeSinceStartup; ToggleMenuVisibility(); gridRepaint = true; RepaintSceneView(); } void OnDestroy() { this.Close(true); } public void Close() { EditorPrefs.SetBool(pg_Constant.ProGridsIsEnabled, false); GameObject.DestroyImmediate(this); } public void Close(bool isBeingDestroyed) { pg_GridRenderer.Destroy(); SceneView.onSceneGUIDelegate -= OnSceneGUI; EditorApplication.update -= Update; EditorApplication.hierarchyWindowChanged -= HierarchyWindowChanged; instance = null; foreach(System.Action<bool> listener in toolbarEventSubscribers) listener(false); SceneView.RepaintAll(); } private void LoadGUIResources() { gc_GridEnabled.image_on = LoadIcon("ProGrids2_GUI_Vis_On.png"); gc_GridEnabled.image_off = LoadIcon("ProGrids2_GUI_Vis_Off.png"); gc_SnapEnabled.image_on = LoadIcon("ProGrids2_GUI_Snap_On.png"); gc_SnapEnabled.image_off = LoadIcon("ProGrids2_GUI_Snap_Off.png"); gc_SnapToGrid.image_on = LoadIcon("ProGrids2_GUI_PushToGrid_Normal.png"); gc_LockGrid.image_on = LoadIcon("ProGrids2_GUI_PGrid_Lock_On.png"); gc_LockGrid.image_off = LoadIcon("ProGrids2_GUI_PGrid_Lock_Off.png"); gc_AngleEnabled.image_on = LoadIcon("ProGrids2_GUI_AngleVis_On.png"); gc_AngleEnabled.image_off = LoadIcon("ProGrids2_GUI_AngleVis_Off.png"); gc_RenderPlaneX.image_on = LoadIcon("ProGrids2_GUI_PGrid_X_On.png"); gc_RenderPlaneX.image_off = LoadIcon("ProGrids2_GUI_PGrid_X_Off.png"); gc_RenderPlaneY.image_on = LoadIcon("ProGrids2_GUI_PGrid_Y_On.png"); gc_RenderPlaneY.image_off = LoadIcon("ProGrids2_GUI_PGrid_Y_Off.png"); gc_RenderPlaneZ.image_on = LoadIcon("ProGrids2_GUI_PGrid_Z_On.png"); gc_RenderPlaneZ.image_off = LoadIcon("ProGrids2_GUI_PGrid_Z_Off.png"); gc_RenderPerspectiveGrid.image_on = LoadIcon("ProGrids2_GUI_PGrid_3D_On.png"); gc_RenderPerspectiveGrid.image_off = LoadIcon("ProGrids2_GUI_PGrid_3D_Off.png"); icon_extendoOpen = LoadIcon("ProGrids2_MenuExtendo_Open.png"); icon_extendoClose = LoadIcon("ProGrids2_MenuExtendo_Close.png"); } private Texture2D LoadIcon(string iconName) { string iconPath = ProGrids_Icons_Path + "/" + iconName; if(!File.Exists(iconPath)) { string[] path = Directory.GetFiles("Assets", iconName, SearchOption.AllDirectories); if(path.Length > 0) { ProGrids_Icons_Path = Path.GetDirectoryName(path[0]); iconPath = path[0]; } else { Debug.LogError("ProGrids failed to locate menu image: " + iconName + ".\nThis can happen if the GUI folder is moved or deleted. Deleting and re-importing ProGrids will fix this error."); return (Texture2D) null; } } return LoadAssetAtPath<Texture2D>(iconPath); } T LoadAssetAtPath<T>(string path) where T : UnityEngine.Object { return (T) AssetDatabase.LoadAssetAtPath(path, typeof(T)); } #endregion #region INTERFACE GUIStyle gridButtonStyle = new GUIStyle(); GUIStyle extendoStyle = new GUIStyle(); GUIStyle gridButtonStyleBlank = new GUIStyle(); GUIStyle backgroundStyle = new GUIStyle(); bool guiInitialized = false; public float GetSnapIncrement() { return t_snapValue; } public void SetSnapIncrement(float inc) { SetSnapValue(snapUnit, Mathf.Max(inc, .001f), 100); } void RepaintSceneView() { SceneView.RepaintAll(); } int MENU_HIDDEN { get { return menuIsOrtho ? -192 : -173; } } const int MENU_EXTENDED = 8; const int PAD = 3; Rect r = new Rect(8, MENU_EXTENDED, 42, 16); Rect backgroundRect = new Rect(00,0,0,0); Rect extendoButtonRect = new Rect(0,0,0,0); bool menuOpen = true; float menuStart = MENU_EXTENDED; const float MENU_SPEED = 500f; float deltaTime = 0f; float lastTime = 0f; const float FADE_SPEED = 2.5f; float backgroundFade = 1f; bool mouseOverMenu = false; Color menuBackgroundColor = new Color(0f, 0f, 0f, .5f); Color extendoNormalColor = new Color(.9f, .9f, .9f, .7f); Color extendoHoverColor = new Color(0f, 1f, .4f, 1f); bool extendoButtonHovering = false; bool menuIsOrtho = false; void Update() { deltaTime = Time.realtimeSinceStartup - lastTime; lastTime = Time.realtimeSinceStartup; if( menuOpen && menuStart < MENU_EXTENDED || !menuOpen && menuStart > MENU_HIDDEN ) { menuStart += deltaTime * MENU_SPEED * (menuOpen ? 1f : -1f); menuStart = Mathf.Clamp(menuStart, MENU_HIDDEN, MENU_EXTENDED); RepaintSceneView(); } float a = menuBackgroundColor.a; backgroundFade = (mouseOverMenu || !menuOpen) ? FADE_SPEED : -FADE_SPEED; menuBackgroundColor.a = Mathf.Clamp(menuBackgroundColor.a + backgroundFade * deltaTime, 0f, .5f); extendoNormalColor.a = menuBackgroundColor.a; extendoHoverColor.a = (menuBackgroundColor.a / .5f); if( !Mathf.Approximately(menuBackgroundColor.a,a) ) RepaintSceneView(); } void DrawSceneGUI() { // GUILayout.BeginArea(new Rect(300, 200, 400, 600)); // off = EditorGUILayout.RectField("Rect", off); // extendoHoverColor = EditorGUI.ColorField(new Rect(200, 40, 200, 18), "howver", extendoHoverColor); // GUILayout.EndArea(); GUI.backgroundColor = menuBackgroundColor; backgroundRect.x = r.x - 4; backgroundRect.y = 0; backgroundRect.width = r.width + 8; backgroundRect.height = r.y + r.height + PAD; GUI.Box(backgroundRect, "", backgroundStyle); // when hit testing mouse for showing the background, add some leeway backgroundRect.width += 32f; backgroundRect.height += 32f; GUI.backgroundColor = Color.white; if( !guiInitialized ) { extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen; extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen; guiInitialized = true; backgroundStyle.normal.background = EditorGUIUtility.whiteTexture; Texture2D icon_button_normal = LoadIcon("ProGrids2_Button_Normal.png"); Texture2D icon_button_hover = LoadIcon("ProGrids2_Button_Hover.png"); if(icon_button_normal == null) { gridButtonStyleBlank = new GUIStyle("button"); } else { gridButtonStyleBlank.normal.background = icon_button_normal; gridButtonStyleBlank.hover.background = icon_button_hover; gridButtonStyleBlank.normal.textColor = icon_button_normal != null ? Color.white : Color.black; gridButtonStyleBlank.hover.textColor = new Color(.7f, .7f, .7f, 1f); } gridButtonStyleBlank.padding = new RectOffset(1,2,1,2); gridButtonStyleBlank.alignment = TextAnchor.MiddleCenter; } r.y = menuStart; gc_SnapIncrement.text = t_snapValue.ToString(); if( GUI.Button(r, gc_SnapIncrement, gridButtonStyleBlank) ) { #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX // On Mac ShowAsDropdown and ShowAuxWindow both throw stack pop exceptions when initialized. pg_ParameterWindow options = EditorWindow.GetWindow<pg_ParameterWindow>(true, "ProGrids Settings", true); Rect screenRect = SceneView.lastActiveSceneView.position; options.editor = this; options.position = new Rect(screenRect.x + r.x + r.width + PAD, screenRect.y + r.y + 24, 256, 162); #else pg_ParameterWindow options = ScriptableObject.CreateInstance<pg_ParameterWindow>(); Rect screenRect = SceneView.lastActiveSceneView.position; options.editor = this; options.ShowAsDropDown(new Rect(screenRect.x + r.x + r.width + PAD, screenRect.y + r.y + 24, 0, 0), new Vector2(256, 162)); #endif } r.y += r.height + PAD; // Draw grid if(pg_ToggleContent.ToggleButton(r, gc_GridEnabled, drawGrid, gridButtonStyle, EditorStyles.miniButton)) SetGridEnabled(!drawGrid); r.y += r.height + PAD; // Snap enabled if(pg_ToggleContent.ToggleButton(r, gc_SnapEnabled, snapEnabled, gridButtonStyle, EditorStyles.miniButton)) SetSnapEnabled(!snapEnabled); r.y += r.height + PAD; // Push to grid if(pg_ToggleContent.ToggleButton(r, gc_SnapToGrid, true, gridButtonStyle, EditorStyles.miniButton)) SnapToGrid(Selection.transforms); r.y += r.height + PAD; // Lock grid if(pg_ToggleContent.ToggleButton(r, gc_LockGrid, lockGrid, gridButtonStyle, EditorStyles.miniButton)) { lockGrid = !lockGrid; EditorPrefs.SetBool(pg_Constant.LockGrid, lockGrid); EditorPrefs.SetString(pg_Constant.LockedGridPivot, pivot.ToString()); // if we've modified the nudge value, reset the pivot here if(!lockGrid) offset = 0f; gridRepaint = true; RepaintSceneView(); } if(menuIsOrtho) { r.y += r.height + PAD; if(pg_ToggleContent.ToggleButton(r, gc_AngleEnabled, drawAngles, gridButtonStyle, EditorStyles.miniButton)) SetDrawAngles(!drawAngles); } /** * Perspective Toggles */ r.y += r.height + PAD + 4; if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneX, (renderPlane & Axis.X) == Axis.X && !fullGrid, gridButtonStyle, EditorStyles.miniButton)) SetRenderPlane(Axis.X); r.y += r.height + PAD; if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneY, (renderPlane & Axis.Y) == Axis.Y && !fullGrid, gridButtonStyle, EditorStyles.miniButton)) SetRenderPlane(Axis.Y); r.y += r.height + PAD; if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneZ, (renderPlane & Axis.Z) == Axis.Z && !fullGrid, gridButtonStyle, EditorStyles.miniButton)) SetRenderPlane(Axis.Z); r.y += r.height + PAD; if(pg_ToggleContent.ToggleButton(r, gc_RenderPerspectiveGrid, fullGrid, gridButtonStyle, EditorStyles.miniButton)) { fullGrid = !fullGrid; gridRepaint = true; EditorPrefs.SetBool(pg_Constant.PerspGrid, fullGrid); RepaintSceneView(); } r.y += r.height + PAD; extendoButtonRect.x = r.x; extendoButtonRect.y = r.y; extendoButtonRect.width = r.width; extendoButtonRect.height = r.height; GUI.backgroundColor = extendoButtonHovering ? extendoHoverColor : extendoNormalColor; gc_ExtendMenu.text = icon_extendoOpen == null ? (menuOpen ? "Close" : "Open") : ""; if(GUI.Button(r, gc_ExtendMenu, icon_extendoOpen ? extendoStyle : gridButtonStyleBlank)) { ToggleMenuVisibility(); extendoButtonHovering = false; } GUI.backgroundColor = Color.white; } void ToggleMenuVisibility() { menuOpen = !menuOpen; extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen; extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen; foreach(System.Action<bool> listener in toolbarEventSubscribers) listener(menuOpen); RepaintSceneView(); } // skip color fading and stuff void SetMenuIsExtended(bool isExtended) { menuOpen = isExtended; menuIsOrtho = ortho; menuStart = menuOpen ? MENU_EXTENDED : MENU_HIDDEN; menuBackgroundColor.a = 0f; extendoNormalColor.a = menuBackgroundColor.a; extendoHoverColor.a = (menuBackgroundColor.a / .5f); extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen; extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen; foreach(System.Action<bool> listener in toolbarEventSubscribers) listener(menuOpen); } private void OpenProGridsPopup() { if( EditorUtility.DisplayDialog( "Upgrade to ProGrids", // Title "Enables all kinds of super-cool features, like different snap values, more units of measurement, and angles.", // Message "Upgrade", // Okay "Cancel" // Cancel )) // #if UNITY_4 // AssetStore.OpenURL(pg_Constant.ProGridsUpgradeURL); // #else Application.OpenURL(pg_Constant.ProGridsUpgradeURL); // #endif } #endregion #region ONSCENEGUI private Transform lastTransform; const string AXIS_CONSTRAINT_KEY = "s"; const string TEMP_DISABLE_KEY = "d"; private bool toggleAxisConstraint = false; private bool toggleTempSnap = false; private Vector3 lastPosition = Vector3.zero; // private Vector3 lastRotation = Vector3.zero; private Vector3 lastScale = Vector3.one; private Vector3 pivot = Vector3.zero, lastPivot = Vector3.zero; private Vector3 camDir = Vector3.zero, prevCamDir = Vector3.zero; private float lastDistance = 0f; ///< Distance from camera to pivot at the last time the grid mesh was updated. public float offset = 0f; private bool firstMove = true; #if PROFILE_TIMES pb_Profiler profiler = new pb_Profiler(); #endif public bool ortho { get; private set; } private bool prevOrtho = false; float planeGridDrawDistance = 0f; public void OnSceneGUI(SceneView scnview) { bool isCurrentView = scnview == SceneView.lastActiveSceneView; if( isCurrentView ) { Handles.BeginGUI(); DrawSceneGUI(); Handles.EndGUI(); } // don't snap stuff in play mode if(EditorApplication.isPlayingOrWillChangePlaymode) return; Event e = Event.current; // repaint scene gui if mouse is near controls if( isCurrentView && e.type == EventType.MouseMove ) { bool tmp = extendoButtonHovering; extendoButtonHovering = extendoButtonRect.Contains(e.mousePosition); if( extendoButtonHovering != tmp ) RepaintSceneView(); mouseOverMenu = backgroundRect.Contains(e.mousePosition); } if (e.Equals(Event.KeyboardEvent(AXIS_CONSTRAINT_KEY))) { toggleAxisConstraint = true; } if (e.Equals(Event.KeyboardEvent(TEMP_DISABLE_KEY))) { toggleTempSnap = true; } if(e.type == EventType.KeyUp) { toggleAxisConstraint = false; toggleTempSnap = false; bool used = true; switch(e.keyCode) { case KeyCode.Equals: IncreaseGridSize(); break; case KeyCode.Minus: DecreaseGridSize(); break; case KeyCode.LeftBracket: if(VerifyMenuNudgePerspective()) MenuNudgePerspectiveBackward(); break; case KeyCode.RightBracket: if(VerifyMenuNudgePerspective()) MenuNudgePerspectiveForward(); break; case KeyCode.Alpha0: if(VerifyMenuNudgePerspective()) MenuNudgePerspectiveReset(); break; case KeyCode.Backslash: CyclePerspective(); break; default: used = false; break; } if(used) e.Use(); } Camera cam = Camera.current; if(cam == null) return; ortho = cam.orthographic && IsRounded(scnview.rotation.eulerAngles.normalized); camDir = pg_Util.CeilFloor( pivot - cam.transform.position ); if(ortho && !prevOrtho || ortho != menuIsOrtho) OnSceneBecameOrtho(isCurrentView); if(!ortho && prevOrtho) OnSceneBecamePersp(isCurrentView); prevOrtho = ortho; float camDistance = Vector3.Distance(cam.transform.position, lastPivot); // distance from camera to pivot if(fullGrid) { pivot = lockGrid || Selection.activeTransform == null ? pivot : Selection.activeTransform.position; } else { Vector3 sceneViewPlanePivot = pivot; Ray ray = new Ray(cam.transform.position, cam.transform.forward); Plane plane = new Plane(Vector3.up, pivot); float dist; // the only time a locked grid should ever move is if it's pivot is out // of the camera's frustum. if( (lockGrid && !cam.InFrustum(pivot)) || !lockGrid || scnview != SceneView.lastActiveSceneView) { if(plane.Raycast(ray, out dist)) sceneViewPlanePivot = ray.GetPoint( Mathf.Min(dist, planeGridDrawDistance/2f) ); else sceneViewPlanePivot = ray.GetPoint( Mathf.Min(cam.farClipPlane/2f, planeGridDrawDistance/2f) ); } if(lockGrid) { pivot = pg_Enum.InverseAxisMask(sceneViewPlanePivot, renderPlane) + pg_Enum.AxisMask(pivot, renderPlane); } else { pivot = Selection.activeTransform == null ? pivot : Selection.activeTransform.position; if( Selection.activeTransform == null || !cam.InFrustum(pivot) ) { pivot = pg_Enum.InverseAxisMask(sceneViewPlanePivot, renderPlane) + pg_Enum.AxisMask(Selection.activeTransform == null ? pivot : Selection.activeTransform.position, renderPlane); } } } #if PG_DEBUG pivotGo.transform.position = pivot; #endif if(drawGrid) { if(ortho) { // ortho don't care about pivots DrawGridOrthographic(cam); } else { #if PROFILE_TIMES profiler.LogStart("DrawGridPerspective"); #endif if( gridRepaint || pivot != lastPivot || Mathf.Abs(camDistance - lastDistance) > lastDistance/2 || camDir != prevCamDir) { prevCamDir = camDir; gridRepaint = false; lastPivot = pivot; lastDistance = camDistance; if(fullGrid) { // if perspective and 3d, use pivot like normal pg_GridRenderer.DrawGridPerspective( cam, pivot, snapValue, new Color[3] { gridColorX, gridColorY, gridColorZ }, alphaBump ); } else { if( (renderPlane & Axis.X) == Axis.X) planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.right*offset, Vector3.up, Vector3.forward, snapValue, gridColorX, alphaBump); if( (renderPlane & Axis.Y) == Axis.Y) planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.up*offset, Vector3.right, Vector3.forward, snapValue, gridColorY, alphaBump); if( (renderPlane & Axis.Z) == Axis.Z) planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.forward*offset, Vector3.up, Vector3.right, snapValue, gridColorZ, alphaBump); } } #if PROFILE_TIMES profiler.LogFinish("DrawGridPerspective"); #endif } } // Always keep track of the selection if(!Selection.transforms.Contains(lastTransform)) { if(Selection.activeTransform) { lastTransform = Selection.activeTransform; lastPosition = Selection.activeTransform.position; lastScale = Selection.activeTransform.localScale; } } if( e.type == EventType.MouseUp ) firstMove = true; if(!snapEnabled || GUIUtility.hotControl < 1) return; // Bugger.SetKey("Toggle Snap Off", toggleTempSnap); /** * Snapping (for all the junk in PG, this method is literally the only code that actually affects anything). */ if(Selection.activeTransform) { if( !FuzzyEquals(lastTransform.position, lastPosition) ) { Transform selected = lastTransform; if( !toggleTempSnap ) { Vector3 old = selected.position; Vector3 mask = old - lastPosition; bool constraintsOn = toggleAxisConstraint ? !useAxisConstraints : useAxisConstraints; if(constraintsOn) selected.position = pg_Util.SnapValue(old, mask, snapValue); else selected.position = pg_Util.SnapValue(old, snapValue); Vector3 offset = selected.position - old; if( predictiveGrid && firstMove && !fullGrid ) { firstMove = false; Axis dragAxis = pg_Util.CalcDragAxis(offset, scnview.camera); if(dragAxis != Axis.None && dragAxis != renderPlane) SetRenderPlane(dragAxis); } if(_snapAsGroup) { OffsetTransforms(Selection.transforms, selected, offset); } else { foreach(Transform t in Selection.transforms) t.position = constraintsOn ? pg_Util.SnapValue(t.position, mask, snapValue) : pg_Util.SnapValue(t.position, snapValue); } } lastPosition = selected.position; } if( !FuzzyEquals(lastTransform.localScale, lastScale) && _scaleSnapEnabled ) { if( !toggleTempSnap ) { Vector3 old = lastTransform.localScale; Vector3 mask = old - lastScale; if( predictiveGrid ) { Axis dragAxis = pg_Util.CalcDragAxis( Selection.activeTransform.TransformDirection(mask), scnview.camera); if(dragAxis != Axis.None && dragAxis != renderPlane) SetRenderPlane(dragAxis); } foreach(Transform t in Selection.transforms) t.localScale = pg_Util.SnapValue(t.localScale, mask, snapValue); lastScale = lastTransform.localScale; } } } } void OnSceneBecameOrtho(bool isCurrentView) { pg_GridRenderer.Destroy(); if(isCurrentView && ortho != menuIsOrtho) SetMenuIsExtended(menuOpen); } void OnSceneBecamePersp(bool isCurrentView) { if(isCurrentView && ortho != menuIsOrtho) SetMenuIsExtended(menuOpen); } #endregion #region GRAPHICS GameObject go; private void DrawGridOrthographic(Camera cam) { Axis camAxis = AxisWithVector(Camera.current.transform.TransformDirection(Vector3.forward).normalized); if(drawGrid) { switch(camAxis) { case Axis.X: case Axis.NegX: DrawGridOrthographic(cam, camAxis, gridColorX_primary, gridColorX); break; case Axis.Y: case Axis.NegY: DrawGridOrthographic(cam, camAxis, gridColorY_primary, gridColorY); break; case Axis.Z: case Axis.NegZ: DrawGridOrthographic(cam, camAxis, gridColorZ_primary, gridColorZ); break; } } } int PRIMARY_COLOR_INCREMENT = 10; Color previousColor; private void DrawGridOrthographic(Camera cam, Axis camAxis, Color primaryColor, Color secondaryColor) { previousColor = Handles.color; Handles.color = primaryColor; // !-- TODO: Update this stuff only when necessary. Currently it runs evvverrrryyy frame Vector3 bottomLeft = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(Vector2.zero), snapValue); Vector3 bottomRight = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, 0f)), snapValue); Vector3 topLeft = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(0f, cam.pixelHeight)), snapValue); Vector3 topRight = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, cam.pixelHeight)), snapValue); Vector3 axis = VectorWithAxis(camAxis); float width = Vector3.Distance(bottomLeft, bottomRight); float height = Vector3.Distance(bottomRight, topRight); // Shift lines to 10m forward of the camera bottomLeft += axis*10f; topRight += axis*10f; bottomRight += axis*10f; topLeft += axis*10f; /** * Draw Vertical Lines */ Vector3 cam_right = cam.transform.right; Vector3 cam_up = cam.transform.up; float _snapVal = snapValue; int segs = (int)Mathf.Ceil(width / _snapVal) + 2; float n = 2f; while(segs > MAX_LINES) { _snapVal = _snapVal*n; segs = (int)Mathf.Ceil(width / _snapVal ) + 2; n++; } /// Screen start and end Vector3 bl = cam_right.Sum() > 0 ? pg_Util.SnapToFloor(bottomLeft, cam_right, _snapVal*PRIMARY_COLOR_INCREMENT) : pg_Util.SnapToCeil(bottomLeft, cam_right, _snapVal*PRIMARY_COLOR_INCREMENT); Vector3 start = bl - cam_up * (height+_snapVal*2); Vector3 end = bl + cam_up * (height+_snapVal*2); segs += PRIMARY_COLOR_INCREMENT; /// The current line start and end Vector3 line_start = Vector3.zero; Vector3 line_end = Vector3.zero; for(int i = -1; i < segs; i++) { line_start = start + (i * (cam_right * _snapVal)); line_end = end + (i * (cam_right * _snapVal) ); Handles.color = i % PRIMARY_COLOR_INCREMENT == 0 ? primaryColor : secondaryColor; Handles.DrawLine( line_start, line_end ); } /** * Draw Horizontal Lines */ segs = (int)Mathf.Ceil(height / _snapVal) + 2; n = 2; while(segs > MAX_LINES) { _snapVal = _snapVal*n; segs = (int)Mathf.Ceil(height / _snapVal ) + 2; n++; } Vector3 tl = cam_up.Sum() > 0 ? pg_Util.SnapToCeil(topLeft, cam_up, _snapVal*PRIMARY_COLOR_INCREMENT) : pg_Util.SnapToFloor(topLeft, cam_up, _snapVal*PRIMARY_COLOR_INCREMENT); start = tl - cam_right * (width+_snapVal*2); end = tl + cam_right * (width+_snapVal*2); segs += (int)PRIMARY_COLOR_INCREMENT; for(int i = -1; i < segs; i++) { line_start = start + (i * (-cam_up * _snapVal)); line_end = end + (i * (-cam_up * _snapVal)); Handles.color = i % PRIMARY_COLOR_INCREMENT == 0 ? primaryColor : secondaryColor; Handles.DrawLine(line_start, line_end); } #if PRO if(drawAngles) { Vector3 cen = pg_Util.SnapValue(((topRight + bottomLeft) / 2f), snapValue); float half = (width > height) ? width : height; float opposite = Mathf.Tan( Mathf.Deg2Rad*angleValue ) * half; Vector3 up = cam.transform.up * opposite; Vector3 right = cam.transform.right * half; Vector3 bottomLeftAngle = cen - (up+right); Vector3 topRightAngle = cen + (up+right); Vector3 bottomRightAngle = cen + (right-up); Vector3 topLeftAngle = cen + (up-right); Handles.color = primaryColor; // y = 1x+1 Handles.DrawLine(bottomLeftAngle, topRightAngle); // y = -1x-1 Handles.DrawLine(topLeftAngle, bottomRightAngle); } #endif Handles.color = previousColor; } #endregion #region ENUM UTILITY public SnapUnit SnapUnitWithString(string str) { foreach(SnapUnit su in SnapUnit.GetValues(typeof(SnapUnit))) { if(su.ToString() == str) return su; } return (SnapUnit)0; } public Axis AxisWithVector(Vector3 val) { Vector3 v = new Vector3(Mathf.Abs(val.x), Mathf.Abs(val.y), Mathf.Abs(val.z)); if(v.x > v.y && v.x > v.z) { if(val.x > 0) return Axis.X; else return Axis.NegX; } else if(v.y > v.x && v.y > v.z) { if(val.y > 0) return Axis.Y; else return Axis.NegY; } else { if(val.z > 0) return Axis.Z; else return Axis.NegZ; } } public Vector3 VectorWithAxis(Axis axis) { switch(axis) { case Axis.X: return Vector3.right; case Axis.Y: return Vector3.up; case Axis.Z: return Vector3.forward; case Axis.NegX: return -Vector3.right; case Axis.NegY: return -Vector3.up; case Axis.NegZ: return -Vector3.forward; default: return Vector3.forward; } } public bool IsRounded(Vector3 v) { return ( Mathf.Approximately(v.x, 1f) || Mathf.Approximately(v.y, 1f) || Mathf.Approximately(v.z, 1f) ) || v == Vector3.zero; } public Vector3 RoundAxis(Vector3 v) { return VectorWithAxis(AxisWithVector(v)); } #endregion #region MOVING TRANSFORMS static bool FuzzyEquals(Vector3 lhs, Vector3 rhs) { return Mathf.Abs(lhs.x - rhs.x) < .001f && Mathf.Abs(lhs.y - rhs.y) < .001f && Mathf.Abs(lhs.z - rhs.z) < .001f; } public void OffsetTransforms(Transform[] trsfrms, Transform ignore, Vector3 offset) { foreach(Transform t in trsfrms) { if(t != ignore) t.position += offset; } } void HierarchyWindowChanged() { if( Selection.activeTransform != null) lastPosition = Selection.activeTransform.position; } #endregion #region SETTINGS public void SetSnapEnabled(bool enable) { EditorPrefs.SetBool(pg_Constant.SnapEnabled, enable); if(Selection.activeTransform) { lastTransform = Selection.activeTransform; lastPosition = Selection.activeTransform.position; } snapEnabled = enable; gridRepaint = true; RepaintSceneView(); } public void SetSnapValue(SnapUnit su, float val, int multiplier) { int clamp_multiplier = (int)(Mathf.Min(Mathf.Max(25, multiplier), 102400)); float value_multiplier = clamp_multiplier / 100f; /** * multiplier is a value modifies the snap val. 100 = no change, * 50 is half val, 200 is double val, etc. */ #if PRO snapValue = pg_Enum.SnapUnitValue(su) * val * value_multiplier; RepaintSceneView(); EditorPrefs.SetInt(pg_Constant.GridUnit, (int)su); EditorPrefs.SetFloat(pg_Constant.SnapValue, val); EditorPrefs.SetInt(pg_Constant.SnapMultiplier, clamp_multiplier); // update gui (only necessary when calling with editorpref values) t_snapValue = val * value_multiplier; snapUnit = su; switch(su) { case SnapUnit.Inch: PRIMARY_COLOR_INCREMENT = 12; // blasted imperial units break; case SnapUnit.Foot: PRIMARY_COLOR_INCREMENT = 3; break; default: PRIMARY_COLOR_INCREMENT = 10; break; } gridRepaint = true; #else Debug.LogWarning("Ye ought not be seein' this ye scurvy pirate."); #endif } public void SetRenderPlane(Axis axis) { offset = 0f; fullGrid = false; renderPlane = axis; EditorPrefs.SetBool(pg_Constant.PerspGrid, fullGrid); EditorPrefs.SetInt(pg_Constant.GridAxis, (int)renderPlane); gridRepaint = true; RepaintSceneView(); } public void SetGridEnabled(bool enable) { drawGrid = enable; if(!drawGrid) pg_GridRenderer.Destroy(); EditorPrefs.SetBool("showgrid", enable); gridRepaint = true; RepaintSceneView(); } public void SetDrawAngles(bool enable) { drawAngles = enable; gridRepaint = true; RepaintSceneView(); } private void SnapToGrid(Transform[] transforms) { Undo.RecordObjects(transforms as Object[], "Snap to Grid"); foreach(Transform t in transforms) t.position = pg_Util.SnapValue(t.position, snapValue); gridRepaint = true; PushToGrid(snapValue); } #endregion #region GLOBAL SETTING internal bool GetUseAxisConstraints() { return toggleAxisConstraint ? !useAxisConstraints : useAxisConstraints; } internal float GetSnapValue() { return snapValue; } internal bool GetSnapEnabled() { return (toggleTempSnap ? !snapEnabled : snapEnabled); } /** * Returns the value of useAxisConstraints, accounting for the shortcut key toggle. */ public static bool UseAxisConstraints() { return instance != null ? instance.GetUseAxisConstraints() : false; } /** * Return the current snap value. */ public static float SnapValue() { return instance != null ? instance.GetSnapValue() : 0f; } /** * Return true if snapping is enabled, false otherwise. */ public static bool SnapEnabled() { return instance == null ? false : instance.GetSnapEnabled(); } public static void AddPushToGridListener(System.Action<float> listener) { pushToGridListeners.Add(listener); } public static void RemovePushToGridListener(System.Action<float> listener) { pushToGridListeners.Remove(listener); } public static void AddToolbarEventSubscriber(System.Action<bool> listener) { toolbarEventSubscribers.Add(listener); } public static void RemoveToolbarEventSubscriber(System.Action<bool> listener) { toolbarEventSubscribers.Remove(listener); } public static bool SceneToolbarActive() { return instance != null; } [SerializeField] static List<System.Action<float>> pushToGridListeners = new List<System.Action<float>>(); [SerializeField] static List<System.Action<bool>> toolbarEventSubscribers = new List<System.Action<bool>>(); private void PushToGrid(float snapValue) { foreach(System.Action<float> listener in pushToGridListeners) listener(snapValue); } public static void OnHandleMove(Vector3 worldDirection) { if (instance != null) instance.OnHandleMove_Internal(worldDirection); } private void OnHandleMove_Internal(Vector3 worldDirection) { if( predictiveGrid && firstMove && !fullGrid ) { firstMove = false; Axis dragAxis = pg_Util.CalcDragAxis(worldDirection, SceneView.lastActiveSceneView.camera); if(dragAxis != Axis.None && dragAxis != renderPlane) SetRenderPlane(dragAxis); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Content.Server.Power.Components; using Content.Server.UserInterface; using Content.Shared.ActionBlocker; using Content.Shared.Arcade; using Content.Shared.Interaction; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Random; namespace Content.Server.Arcade.Components { [RegisterComponent] [ComponentReference(typeof(IActivate))] public sealed class BlockGameArcadeComponent : Component, IActivate { [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly IEntityManager _entityManager = default!; private bool Powered => _entityManager.TryGetComponent<ApcPowerReceiverComponent>(Owner, out var powerReceiverComponent) && powerReceiverComponent.Powered; private BoundUserInterface? UserInterface => Owner.GetUIOrNull(BlockGameUiKey.Key); private BlockGame? _game; private IPlayerSession? _player; private readonly List<IPlayerSession> _spectators = new(); [Obsolete("Component Messages are deprecated, use Entity Events instead.")] public override void HandleMessage(ComponentMessage message, IComponent? component) { #pragma warning disable 618 base.HandleMessage(message, component); #pragma warning restore 618 switch (message) { case PowerChangedMessage powerChanged: OnPowerStateChanged(powerChanged); break; } } void IActivate.Activate(ActivateEventArgs eventArgs) { if(!Powered || !IoCManager.Resolve<IEntityManager>().TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; UserInterface?.Toggle(actor.PlayerSession); if (UserInterface?.SessionHasOpen(actor.PlayerSession) == true) { RegisterPlayerSession(actor.PlayerSession); } } private void RegisterPlayerSession(IPlayerSession session) { if (_player == null) _player = session; else _spectators.Add(session); UpdatePlayerStatus(session); _game?.UpdateNewPlayerUI(session); } private void DeactivePlayer(IPlayerSession session) { if (_player != session) return; var temp = _player; _player = null; if (_spectators.Count != 0) { _player = _spectators[0]; _spectators.Remove(_player); UpdatePlayerStatus(_player); } _spectators.Add(temp); UpdatePlayerStatus(temp); } private void UnRegisterPlayerSession(IPlayerSession session) { if (_player == session) { DeactivePlayer(_player); } else { _spectators.Remove(session); UpdatePlayerStatus(session); } } private void UpdatePlayerStatus(IPlayerSession session) { UserInterface?.SendMessage(new BlockGameMessages.BlockGameUserStatusMessage(_player == session), session); } protected override void Initialize() { base.Initialize(); if (UserInterface != null) { UserInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage; UserInterface.OnClosed += UnRegisterPlayerSession; } _game = new BlockGame(this); } private void OnPowerStateChanged(PowerChangedMessage e) { if (e.Powered) return; UserInterface?.CloseAll(); _player = null; _spectators.Clear(); } private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage obj) { switch (obj.Message) { case BlockGameMessages.BlockGamePlayerActionMessage playerActionMessage: if (obj.Session != _player) break; if (playerActionMessage.PlayerAction == BlockGamePlayerAction.NewGame) { if(_game?.Started == true) _game = new BlockGame(this); _game?.StartGame(); } else { _game?.ProcessInput(playerActionMessage.PlayerAction); } break; } } public void DoGameTick(float frameTime) { _game?.GameTick(frameTime); } private sealed class BlockGame { //note: field is 10(0 -> 9) wide and 20(0 -> 19) high private readonly BlockGameArcadeComponent _component; private readonly List<BlockGameBlock> _field = new(); private BlockGamePiece _currentPiece; private BlockGamePiece _nextPiece { get => _internalNextPiece; set { _internalNextPiece = value; SendNextPieceUpdate(); } } private BlockGamePiece _internalNextPiece; private void SendNextPieceUpdate() { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(_nextPiece.BlocksForPreview(), BlockGameMessages.BlockGameVisualType.NextBlock)); } private void SendNextPieceUpdate(IPlayerSession session) { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(_nextPiece.BlocksForPreview(), BlockGameMessages.BlockGameVisualType.NextBlock), session); } private bool _holdBlock = false; private BlockGamePiece? _heldPiece { get => _internalHeldPiece; set { _internalHeldPiece = value; SendHoldPieceUpdate(); } } private BlockGamePiece? _internalHeldPiece = null; private void SendHoldPieceUpdate() { if(_heldPiece.HasValue) _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(_heldPiece.Value.BlocksForPreview(), BlockGameMessages.BlockGameVisualType.HoldBlock)); else _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(new BlockGameBlock[0], BlockGameMessages.BlockGameVisualType.HoldBlock)); } private void SendHoldPieceUpdate(IPlayerSession session) { if(_heldPiece.HasValue) _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(_heldPiece.Value.BlocksForPreview(), BlockGameMessages.BlockGameVisualType.HoldBlock), session); else _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(new BlockGameBlock[0], BlockGameMessages.BlockGameVisualType.HoldBlock), session); } private Vector2i _currentPiecePosition; private BlockGamePieceRotation _currentRotation; private float _softDropModifier = 0.1f; private float Speed => -0.03f * Level + 1 * (!_softDropPressed ? 1 : _softDropModifier); private const float _pressCheckSpeed = 0.08f; private bool _running; public bool Paused => !(_running && _started); private bool _started; public bool Started => _started; private bool _gameOver; private bool _leftPressed; private bool _rightPressed; private bool _softDropPressed; private int Points { get => _internalPoints; set { if (_internalPoints == value) return; _internalPoints = value; SendPointsUpdate(); } } private int _internalPoints; private BlockGameSystem.HighScorePlacement? _highScorePlacement = null; private void SendPointsUpdate() { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameScoreUpdateMessage(Points)); } private void SendPointsUpdate(IPlayerSession session) { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameScoreUpdateMessage(Points)); } public int Level { get => _level; set { _level = value; SendLevelUpdate(); } } private int _level = 0; private void SendLevelUpdate() { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameLevelUpdateMessage(Level)); } private void SendLevelUpdate(IPlayerSession session) { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameLevelUpdateMessage(Level)); } private int ClearedLines { get => _clearedLines; set { _clearedLines = value; if (_clearedLines < LevelRequirement) return; _clearedLines -= LevelRequirement; Level++; } } private int _clearedLines = 0; private int LevelRequirement => Math.Min(100, Math.Max(Level * 10 - 50, 10)); public BlockGame(BlockGameArcadeComponent component) { _component = component; _allBlockGamePieces = (BlockGamePieceType[]) Enum.GetValues(typeof(BlockGamePieceType)); _internalNextPiece = GetRandomBlockGamePiece(_component._random); InitializeNewBlock(); } private void SendHighscoreUpdate() { var entitySystem = EntitySystem.Get<BlockGameSystem>(); _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameHighScoreUpdateMessage(entitySystem.GetLocalHighscores(), entitySystem.GetGlobalHighscores())); } private void SendHighscoreUpdate(IPlayerSession session) { var entitySystem = EntitySystem.Get<BlockGameSystem>(); _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameHighScoreUpdateMessage(entitySystem.GetLocalHighscores(), entitySystem.GetGlobalHighscores()), session); } public void StartGame() { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameSetScreenMessage(BlockGameMessages.BlockGameScreen.Game)); FullUpdate(); _running = true; _started = true; } private void FullUpdate() { UpdateAllFieldUI(); SendHoldPieceUpdate(); SendNextPieceUpdate(); SendPointsUpdate(); SendHighscoreUpdate(); SendLevelUpdate(); } private void FullUpdate(IPlayerSession session) { UpdateFieldUI(session); SendPointsUpdate(session); SendNextPieceUpdate(session); SendHoldPieceUpdate(session); SendHighscoreUpdate(session); SendLevelUpdate(session); } public void GameTick(float frameTime) { if (!_running) return; InputTick(frameTime); FieldTick(frameTime); } private float _accumulatedLeftPressTime; private float _accumulatedRightPressTime; private void InputTick(float frameTime) { bool anythingChanged = false; if (_leftPressed) { _accumulatedLeftPressTime += frameTime; while (_accumulatedLeftPressTime >= _pressCheckSpeed) { if (_currentPiece.Positions(_currentPiecePosition.AddToX(-1), _currentRotation) .All(MoveCheck)) { _currentPiecePosition = _currentPiecePosition.AddToX(-1); anythingChanged = true; } _accumulatedLeftPressTime -= _pressCheckSpeed; } } if (_rightPressed) { _accumulatedRightPressTime += frameTime; while (_accumulatedRightPressTime >= _pressCheckSpeed) { if (_currentPiece.Positions(_currentPiecePosition.AddToX(1), _currentRotation) .All(MoveCheck)) { _currentPiecePosition = _currentPiecePosition.AddToX(1); anythingChanged = true; } _accumulatedRightPressTime -= _pressCheckSpeed; } } if(anythingChanged) UpdateAllFieldUI(); } private float _accumulatedFieldFrameTime; private void FieldTick(float frameTime) { _accumulatedFieldFrameTime += frameTime; var checkTime = Speed; while (_accumulatedFieldFrameTime >= checkTime) { if (_softDropPressed) AddPoints(1); InternalFieldTick(); _accumulatedFieldFrameTime -= checkTime; } } private void InternalFieldTick() { if (_currentPiece.Positions(_currentPiecePosition.AddToY(1), _currentRotation) .All(DropCheck)) { _currentPiecePosition = _currentPiecePosition.AddToY(1); } else { var blocks = _currentPiece.Blocks(_currentPiecePosition, _currentRotation); _field.AddRange(blocks); //check loose conditions if (IsGameOver) { InvokeGameover(); return; } InitializeNewBlock(); } CheckField(); UpdateAllFieldUI(); } private void CheckField() { int pointsToAdd = 0; int consecutiveLines = 0; int clearedLines = 0; for (int y = 0; y < 20; y++) { if (CheckLine(y)) { //line was cleared y--; consecutiveLines++; clearedLines++; } else if(consecutiveLines != 0) { var mod = consecutiveLines switch { 1 => 40, 2 => 100, 3 => 300, 4 => 1200, _ => 0 }; pointsToAdd += mod * (_level + 1); } } ClearedLines += clearedLines; AddPoints(pointsToAdd); } private bool CheckLine(int y) { for (var x = 0; x < 10; x++) { if (!_field.Any(b => b.Position.X == x && b.Position.Y == y)) return false; } //clear line _field.RemoveAll(b => b.Position.Y == y); //move everything down FillLine(y); return true; } private void AddPoints(int amount) { if (amount == 0) return; Points += amount; } private void FillLine(int y) { for (int c_y = y; c_y > 0; c_y--) { for (int j = 0; j < _field.Count; j++) { if(_field[j].Position.Y != c_y-1) continue; _field[j] = new BlockGameBlock(_field[j].Position.AddToY(1), _field[j].GameBlockColor); } } } private void InitializeNewBlock() { InitializeNewBlock(_nextPiece); _nextPiece = GetRandomBlockGamePiece(_component._random); _holdBlock = false; _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(_nextPiece.BlocksForPreview(), BlockGameMessages.BlockGameVisualType.NextBlock)); } private void InitializeNewBlock(BlockGamePiece piece) { _currentPiecePosition = new Vector2i(5,0); _currentRotation = BlockGamePieceRotation.North; _currentPiece = piece; UpdateAllFieldUI(); } private bool LowerBoundCheck(Vector2i position) => position.Y < 20; private bool BorderCheck(Vector2i position) => position.X >= 0 && position.X < 10; private bool ClearCheck(Vector2i position) => _field.All(block => !position.Equals(block.Position)); private bool DropCheck(Vector2i position) => LowerBoundCheck(position) && ClearCheck(position); private bool MoveCheck(Vector2i position) => BorderCheck(position) && ClearCheck(position); private bool RotateCheck(Vector2i position) => BorderCheck(position) && LowerBoundCheck(position) && ClearCheck(position); public void ProcessInput(BlockGamePlayerAction action) { if (_running) { switch (action) { case BlockGamePlayerAction.StartLeft: _leftPressed = true; break; case BlockGamePlayerAction.StartRight: _rightPressed = true; break; case BlockGamePlayerAction.Rotate: TrySetRotation(Next(_currentRotation, false)); break; case BlockGamePlayerAction.CounterRotate: TrySetRotation(Next(_currentRotation, true)); break; case BlockGamePlayerAction.SoftdropStart: _softDropPressed = true; if (_accumulatedFieldFrameTime > Speed) _accumulatedFieldFrameTime = Speed; //to prevent jumps break; case BlockGamePlayerAction.Harddrop: PerformHarddrop(); break; case BlockGamePlayerAction.Hold: HoldPiece(); break; } } switch (action) { case BlockGamePlayerAction.EndLeft: _leftPressed = false; break; case BlockGamePlayerAction.EndRight: _rightPressed = false; break; case BlockGamePlayerAction.SoftdropEnd: _softDropPressed = false; break; case BlockGamePlayerAction.Pause: _running = false; _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameSetScreenMessage(BlockGameMessages.BlockGameScreen.Pause, _started)); break; case BlockGamePlayerAction.Unpause: if (!_gameOver && _started) { _running = true; _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameSetScreenMessage(BlockGameMessages.BlockGameScreen.Game)); } break; case BlockGamePlayerAction.ShowHighscores: _running = false; _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameSetScreenMessage(BlockGameMessages.BlockGameScreen.Highscores, _started)); break; } } private void TrySetRotation(BlockGamePieceRotation rotation) { if(!_running) return; if (!_currentPiece.CanSpin) return; if (!_currentPiece.Positions(_currentPiecePosition, rotation) .All(RotateCheck)) { return; } _currentRotation = rotation; UpdateAllFieldUI(); } private void HoldPiece() { if (!_running) return; if (_holdBlock) return; var tempHeld = _heldPiece; _heldPiece = _currentPiece; _holdBlock = true; if (!tempHeld.HasValue) { InitializeNewBlock(); return; } InitializeNewBlock(tempHeld.Value); } private void PerformHarddrop() { int spacesDropped = 0; while (_currentPiece.Positions(_currentPiecePosition.AddToY(1), _currentRotation) .All(DropCheck)) { _currentPiecePosition = _currentPiecePosition.AddToY(1); spacesDropped++; } AddPoints(spacesDropped * 2); InternalFieldTick(); } public void UpdateAllFieldUI() { if (!_started) return; var computedField = ComputeField(); _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(computedField.ToArray(), BlockGameMessages.BlockGameVisualType.GameField)); } public void UpdateFieldUI(IPlayerSession session) { if (!_started) return; var computedField = ComputeField(); _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameVisualUpdateMessage(computedField.ToArray(), BlockGameMessages.BlockGameVisualType.GameField), session); } private bool IsGameOver => _field.Any(block => block.Position.Y == 0); private void InvokeGameover() { _running = false; _gameOver = true; if (_component._player?.AttachedEntity is {Valid: true} playerEntity) { var blockGameSystem = EntitySystem.Get<BlockGameSystem>(); _highScorePlacement = blockGameSystem.RegisterHighScore(IoCManager.Resolve<IEntityManager>().GetComponent<MetaDataComponent>(playerEntity).EntityName, Points); SendHighscoreUpdate(); } _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameGameOverScreenMessage(Points, _highScorePlacement?.LocalPlacement, _highScorePlacement?.GlobalPlacement)); } public void UpdateNewPlayerUI(IPlayerSession session) { if (_gameOver) { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameGameOverScreenMessage(Points, _highScorePlacement?.LocalPlacement, _highScorePlacement?.GlobalPlacement), session); } else { if (Paused) { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameSetScreenMessage(BlockGameMessages.BlockGameScreen.Pause, Started), session); } else { _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameSetScreenMessage(BlockGameMessages.BlockGameScreen.Game, Started), session); } } FullUpdate(session); } public List<BlockGameBlock> ComputeField() { var result = new List<BlockGameBlock>(); result.AddRange(_field); result.AddRange(_currentPiece.Blocks(_currentPiecePosition, _currentRotation)); var dropGhostPosition = _currentPiecePosition; while (_currentPiece.Positions(dropGhostPosition.AddToY(1), _currentRotation) .All(DropCheck)) { dropGhostPosition = dropGhostPosition.AddToY(1); } if (dropGhostPosition != _currentPiecePosition) { var blox = _currentPiece.Blocks(dropGhostPosition, _currentRotation); for (var i = 0; i < blox.Length; i++) { result.Add(new BlockGameBlock(blox[i].Position, BlockGameBlock.ToGhostBlockColor(blox[i].GameBlockColor))); } } return result; } private enum BlockGamePieceType { I, L, LInverted, S, SInverted, T, O } private enum BlockGamePieceRotation { North, East, South, West } private static BlockGamePieceRotation Next(BlockGamePieceRotation rotation, bool inverted) { return rotation switch { BlockGamePieceRotation.North => inverted ? BlockGamePieceRotation.West : BlockGamePieceRotation.East, BlockGamePieceRotation.East => inverted ? BlockGamePieceRotation.North : BlockGamePieceRotation.South, BlockGamePieceRotation.South => inverted ? BlockGamePieceRotation.East : BlockGamePieceRotation.West, BlockGamePieceRotation.West => inverted ? BlockGamePieceRotation.South : BlockGamePieceRotation.North, _ => throw new ArgumentOutOfRangeException(nameof(rotation), rotation, null) }; } private readonly BlockGamePieceType[] _allBlockGamePieces; private List<BlockGamePieceType> _blockGamePiecesBuffer = new(); private BlockGamePiece GetRandomBlockGamePiece(IRobustRandom random) { if (_blockGamePiecesBuffer.Count == 0) { _blockGamePiecesBuffer = _allBlockGamePieces.ToList(); } var chosenPiece = random.Pick(_blockGamePiecesBuffer); _blockGamePiecesBuffer.Remove(chosenPiece); return BlockGamePiece.GetPiece(chosenPiece); } private struct BlockGamePiece { public Vector2i[] Offsets; private BlockGameBlock.BlockGameBlockColor _gameBlockColor; public bool CanSpin; public Vector2i[] Positions(Vector2i center, BlockGamePieceRotation rotation) { return RotatedOffsets(rotation).Select(v => center + v).ToArray(); } private Vector2i[] RotatedOffsets(BlockGamePieceRotation rotation) { Vector2i[] rotatedOffsets = (Vector2i[])Offsets.Clone(); //until i find a better algo var amount = rotation switch { BlockGamePieceRotation.North => 0, BlockGamePieceRotation.East => 1, BlockGamePieceRotation.South => 2, BlockGamePieceRotation.West => 3, _ => 0 }; for (var i = 0; i < amount; i++) { for (var j = 0; j < rotatedOffsets.Length; j++) { rotatedOffsets[j] = rotatedOffsets[j].Rotate90DegreesAsOffset(); } } return rotatedOffsets; } public BlockGameBlock[] Blocks(Vector2i center, BlockGamePieceRotation rotation) { var positions = Positions(center, rotation); var result = new BlockGameBlock[positions.Length]; var i = 0; foreach (var position in positions) { result[i++] = position.ToBlockGameBlock(_gameBlockColor); } return result; } public BlockGameBlock[] BlocksForPreview() { var xOffset = 0; var yOffset = 0; foreach (var offset in Offsets) { if (offset.X < xOffset) xOffset = offset.X; if (offset.Y < yOffset) yOffset = offset.Y; } return Blocks(new Vector2i(-xOffset, -yOffset), BlockGamePieceRotation.North); } public static BlockGamePiece GetPiece(BlockGamePieceType type) { //switch statement, hardcoded offsets return type switch { BlockGamePieceType.I => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(0, 1), new Vector2i(0, 2), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.LightBlue, CanSpin = true }, BlockGamePieceType.L => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(0, 1), new Vector2i(1, 1), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Orange, CanSpin = true }, BlockGamePieceType.LInverted => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(-1, 1), new Vector2i(0, 1), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Blue, CanSpin = true }, BlockGamePieceType.S => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(1, -1), new Vector2i(-1, 0), new Vector2i(0, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Green, CanSpin = true }, BlockGamePieceType.SInverted => new BlockGamePiece { Offsets = new[] { new Vector2i(-1, -1), new Vector2i(0, -1), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Red, CanSpin = true }, BlockGamePieceType.T => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(-1, 0), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Purple, CanSpin = true }, BlockGamePieceType.O => new BlockGamePiece { Offsets = new[] { new Vector2i(0, -1), new Vector2i(1, -1), new Vector2i(0, 0), new Vector2i(1, 0), }, _gameBlockColor = BlockGameBlock.BlockGameBlockColor.Yellow, CanSpin = false }, _ => new BlockGamePiece {Offsets = new[] {new Vector2i(0, 0)}} }; } } } } }
// 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 OrInt16() { var test = new SimpleBinaryOpTest__OrInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.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(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } 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 SimpleBinaryOpTest__OrInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__OrInt16 testClass) { var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrInt16 testClass) { fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.Or( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__OrInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public SimpleBinaryOpTest__OrInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Or( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Or( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Or( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int16>* pClsVar1 = &_clsVar1) fixed (Vector256<Int16>* pClsVar2 = &_clsVar2) { var result = Avx2.Or( Avx.LoadVector256((Int16*)(pClsVar1)), Avx.LoadVector256((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__OrInt16(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__OrInt16(); fixed (Vector256<Int16>* pFld1 = &test._fld1) fixed (Vector256<Int16>* pFld2 = &test._fld2) { var result = Avx2.Or( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.Or( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Or( Avx.LoadVector256((Int16*)(&test._fld1)), Avx.LoadVector256((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(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(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] | right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] | right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Xml; using System.Xml.Xsl; using MLifter.DAL.DB; using MLifter.DAL.Security; using MLifter.DAL.Tools; using MLifter.DAL.XML; namespace MLifter.DAL.Interfaces { /// <summary> /// Save all Settings for MemoryLifter (GlobalSettings, LM AllowedSettings, UserSettings) /// </summary> /// <remarks>Documented by Dev11, 2008-08-08</remarks> public interface ISettings : ICopy, IParent, ISecurity { /// <summary> /// Interface that defines the available query directions for a dictionary. /// </summary> /// <remarks>Documented by Dev03, 2008-01-08</remarks> IQueryDirections QueryDirections { get; set; } /// <summary> /// Gets or sets the Learning modes (How MemoryLifter ask the questions) /// </summary> /// <value>The query types.</value> /// <remarks>Documented by Dev11, 2008-08-08</remarks> IQueryType QueryTypes { get; set; } // User settings /// <summary> /// Gets or sets the multiple choice options. /// </summary> /// <value>The multiple choice options.</value> /// <remarks>Documented by Dev03, 2008-01-08</remarks> IQueryMultipleChoiceOptions MultipleChoiceOptions { get; set; } /// <summary> /// Enumeration which defines the values for the 'Typing mistakes' options: /// AllCorrect - only promote when all correct, /// HalfCorrect - promote when more than 50% were typed correctly, /// NoneCorrect - always promote, /// Prompt - prompt /// </summary> /// <value>The grade typing.</value> /// <remarks>Documented by Dev11, 2008-08-08</remarks> IGradeTyping GradeTyping { get; set; } /// <summary> /// Enumeration which defines the values for the 'Synonyms' options: /// AllKnown - all synonyms need to be known, /// HalfKnown - half need to be known, /// OneKnown - one synonym needs to be known, /// FirstKnown - the card is promoted when the first synonym is known, /// Promp - prompt when not all were correct /// </summary> /// <value>The grade synonyms.</value> /// <remarks>Documented by Dev11, 2008-08-08</remarks> IGradeSynonyms GradeSynonyms { get; set; } /// <summary> /// Gets or sets the style. /// </summary> /// <value>The style.</value> /// <remarks>Documented by Dev05, 2008-08-19</remarks> ICardStyle Style { get; set; } /// <summary> /// Gets or sets the question stylesheet. /// </summary> /// <value>The question stylesheet.</value> /// <remarks>Documented by Dev05, 2008-08-19</remarks> [ValueCopy] CompiledTransform? QuestionStylesheet { get; set; } /// <summary> /// Gets or sets the answer stylesheet. /// </summary> /// <value>The answer stylesheet.</value> /// <remarks>Documented by Dev05, 2008-08-19</remarks> [ValueCopy] CompiledTransform? AnswerStylesheet { get; set; } /// <summary> /// Gets or sets a value indicating whether standard audio files should be played automatically. /// </summary> /// <value><c>true</c> if [autoplay audio]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? AutoplayAudio { get; set; } /// <summary> /// Gets or sets a value indicating whether [case sensitive]. /// </summary> /// <value><c>true</c> if [case sensitive]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? CaseSensitive { get; set; } /// <summary> /// Gets or sets a value indicating whether [Ignore Accent Chars]. /// </summary> /// <value><c>true</c> if [Ignore Accent Chars]; otherwise, <c>false</c>.</value> /// <remarks>Documented by 2013-11-12</remarks> [ValueCopy] bool? IgnoreAccentChars { get; set; } /// <summary> /// Gets or sets a value indicating whether user confirmation is required to confirm demote. /// </summary> /// <value><c>true</c> if [confirm demote]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? ConfirmDemote { get; set; } /// <summary> /// Gets or sets a value indicating whether commentary sounds are enabled. /// </summary> /// <value><c>true</c> if [enable commentary]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? EnableCommentary { get; set; } /// <summary> /// Gets or sets a value indicating whether [correct on the fly]. /// </summary> /// <value><c>true</c> if [correct on the fly]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? CorrectOnTheFly { get; set; } /// <summary> /// Gets or sets a value indicating whether the time should be enabled. /// </summary> /// <value><c>true</c> if [enable timer]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? EnableTimer { get; set; } /// <summary> /// Gets or sets a value indicating whether cards should be drawn randomly from pool. /// </summary> /// <value><c>true</c> if [random pool]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? RandomPool { get; set; } /// <summary> /// Gets or sets a value indicating whether self assessment mode is active. /// </summary> /// <value><c>true</c> if [self assessment]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? SelfAssessment { get; set; } /// <summary> /// Gets or sets a value indicating whether [show images]. /// </summary> /// <value><c>true</c> if [show images]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? ShowImages { get; set; } /// <summary> /// Gets or sets wether the pool emty message was shown. /// </summary> /// <value>The pool emty message shown.</value> /// <remarks>Documented by Dev05, 2008-08-18</remarks> [ValueCopy] bool? PoolEmptyMessageShown { get; set; } /// <summary> /// Gets or sets the use LM stylesheets. /// </summary> /// <value>The use LM stylesheets.</value> /// <remarks>Documented by Dev05, 2008-08-18</remarks> [ValueCopy] bool? UseLMStylesheets { get; set; } /// <summary> /// Gets or sets the the auto box size. /// </summary> /// <value>The size of the auto box.</value> /// <remarks>Documented by Dev05, 2008-08-19</remarks> [ValueCopy] bool? AutoBoxSize { get; set; } /// <summary> /// Gets or sets the strip chars. /// </summary> /// <value>The strip chars.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] string StripChars { get; set; } /// <summary> /// Gets or sets the question culture. /// </summary> /// <value>The question culture.</value> /// <remarks>Documented by Dev03, 2007-12-18</remarks> [ValueCopy] CultureInfo QuestionCulture { get; set; } /// <summary> /// Gets or sets the answer culture. /// </summary> /// <value>The answer culture.</value> /// <remarks>Documented by Dev03, 2007-12-18</remarks> [ValueCopy] CultureInfo AnswerCulture { get; set; } /// <summary> /// Gets or sets the question caption. /// </summary> /// <value>The question caption.</value> /// <remarks>Documented by Dev03, 2007-09-03</remarks> [ValueCopy] string QuestionCaption { get; set; } /// <summary> /// Gets or sets the answer caption. /// </summary> /// <value>The answer caption.</value> /// <remarks>Documented by Dev03, 2007-09-03</remarks> [ValueCopy] string AnswerCaption { get; set; } /// <summary> /// Gets or sets the commentary sounds. /// </summary> /// <value>The commentary sounds.</value> /// <remarks>Documented by Dev11, 2008-08-08</remarks> Dictionary<CommentarySoundIdentifier, IMedia> CommentarySounds { get; set; } /// <summary> /// Gets or sets the logo. /// </summary> /// <value>The logo.</value> /// <remarks>Documented by Dev03, 2008-01-11</remarks> IMedia Logo { get; set; } /// <summary> /// Gets or sets a value indicating whether [show statistics]. /// </summary> /// <value><c>true</c> if [show statistics]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? ShowStatistics { get; set; } /// <summary> /// Gets or sets a value indicating whether [skip correct answers]. /// </summary> /// <value><c>true</c> if [skip correct answers]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2007-09-04</remarks> [ValueCopy] bool? SkipCorrectAnswers { get; set; } /// <summary> /// Gets or sets the snooze options (MemoryLifter minimize after a few cards) /// </summary> /// <value>The snooze options.</value> /// <remarks>Documented by Dev11, 2008-08-08</remarks> ISnoozeOptions SnoozeOptions { get; set; } /// <summary> /// Gets or sets the selected learn chapters. /// </summary> /// <value>The selected learn chapters.</value> /// <remarks>Documented by Dev05, 2008-08-18</remarks> IList<int> SelectedLearnChapters { get; set; } } internal static class SettingsHelper { public static void Copy(ISettings source, ISettings target, CopyToProgress progressDelegate) { try { if (!(source is XmlAllowedSettings) && source.Style != null && target.Style == null) target.Style = target.Parent.GetParentDictionary().CreateCardStyle(); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } CopyBase.Copy(source, target, typeof(ISettings), progressDelegate); try { if (source is XmlChapterSettings || source is XmlCardSettings || source is XmlAllowedSettings || source.Logo == null) target.Logo = null; else target.Logo = GetNewMedia(source.Logo, target); } catch { } try { if (!(source is XmlChapterSettings || source is XmlCardSettings || source is XmlAllowedSettings)) { Dictionary<CommentarySoundIdentifier, IMedia> cSounds = new Dictionary<CommentarySoundIdentifier, IMedia>(); foreach (KeyValuePair<CommentarySoundIdentifier, IMedia> pair in source.CommentarySounds) cSounds.Add(pair.Key, GetNewMedia(pair.Value, target)); target.CommentarySounds = cSounds; } } catch { } } private static IMedia GetNewMedia(IMedia oldMedia, ISettings target) { return target is DbSettings ? (target.Parent.GetParentDictionary() as DbDictionary).CreateNewMediaObject(null, null, oldMedia.MediaType, oldMedia.Filename, oldMedia.Active.Value, oldMedia.Default.Value, oldMedia.Example.Value) : (target.Parent.GetParentDictionary() as XmlDictionary).CreateNewMediaObject(oldMedia.MediaType, oldMedia.Filename, oldMedia.Active.Value, oldMedia.Default.Value, oldMedia.Example.Value); } } /// <summary> /// Struct to hold a string/file trasnformer. /// </summary> /// <remarks>Documented by Dev05, 2009-02-09</remarks> public struct CompiledTransform { /// <summary> /// Path to a xsl-file. /// </summary> public string Filename; /// <summary> /// The complier-source. /// </summary> public string XslContent; /// <summary> /// Initializes a new instance of the <see cref="CompiledTransform"/> struct. /// </summary> /// <param name="filename">The filename.</param> /// <param name="content">The content.</param> /// <remarks>Documented by Dev05, 2009-02-09</remarks> public CompiledTransform(string filename, string content) { Filename = filename; XslContent = content; if (filename != null) { if (File.Exists(filename)) XslContent = File.ReadAllText(filename); } else if (content == null) throw new ArgumentNullException(); } } /// <summary> /// An identifier for a commentary sound. /// </summary> /// <remarks>Documented by Dev05, 2009-02-09</remarks> public struct CommentarySoundIdentifier { /// <summary> /// The Side. /// </summary> public Side Side; /// <summary> /// The type. /// </summary> public ECommentarySoundType Type; /// <summary> /// Creates the specified identifier. /// </summary> /// <param name="side">The side.</param> /// <param name="type">The type.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-02-09</remarks> public static CommentarySoundIdentifier Create(Side side, ECommentarySoundType type) { CommentarySoundIdentifier idf = new CommentarySoundIdentifier(); idf.Side = side; idf.Type = type; return idf; } } /// <summary> /// The types of commentary sounds. /// </summary> public enum ECommentarySoundType { /// <summary> /// See name... /// </summary> RightStandAlone = 0, /// <summary> /// See name... /// </summary> WrongStandAlone, /// <summary> /// See name... /// </summary> AlmostStandAlone, /// <summary> /// See name... /// </summary> Right, /// <summary> /// See name... /// </summary> Wrong, /// <summary> /// See name... /// </summary> Almost } }