context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ---------------------------------------------------------------------------------- // // FXMaker // Created by ismoon - 2012 - ismoonto@gmail.com // // ---------------------------------------------------------------------------------- using UnityEngine; using System.Collections; public class NcDuplicator : NcEffectBehaviour { // Attribute ------------------------------------------------------------------------ public float m_fDuplicateTime = 0.1f; public int m_nDuplicateCount = 3; public float m_fDuplicateLifeTime = 0; public Vector3 m_AddStartPos = Vector3.zero; public Vector3 m_AccumStartRot = Vector3.zero; public Vector3 m_RandomRange = Vector3.zero; protected int m_nCreateCount = 0; protected float m_fStartTime = 0; protected GameObject m_ClonObject; protected bool m_bInvoke = false; // Property ------------------------------------------------------------------------- #if UNITY_EDITOR public override string CheckProperty() { if (1 < gameObject.GetComponents(GetType()).Length) return "SCRIPT_WARRING_DUPLICATE"; // err check if (transform.parent != null && transform.parent.gameObject == FindRootEditorEffect()) return "SCRIPT_ERROR_ROOT"; return ""; // no error } #endif public override int GetAnimationState() { if ((enabled && IsActive(gameObject)) && (m_nDuplicateCount == 0 || m_nDuplicateCount != 0 && m_nCreateCount < m_nDuplicateCount)) return 1; return 0; } public GameObject GetCloneObject() { return m_ClonObject; } // Loop Function -------------------------------------------------------------------- void Awake() { m_nCreateCount = 0; m_fStartTime = -m_fDuplicateTime; m_ClonObject = null; m_bInvoke = false; if (enabled == false) return; // Debug.Log("Duration.Awake"); #if UNITY_EDITOR if (IsCreatingEditObject() == false) #endif if (transform.parent != null && (enabled && IsActive(gameObject) && GetComponent<NcDontActive>() == null)) InitCloneObject(); } protected override void OnDestroy() { // Debug.Log("OnDestroy"); if (m_ClonObject != null) Destroy(m_ClonObject); base.OnDestroy(); } void Start() { #if UNITY_EDITOR Debug.LogWarning("Waring!!! FXMaker - NcDuplicator.cs : This script is very slow. (Recommend : Not use)"); #endif // Debug.Log("Duration.Start"); if (m_bInvoke) { m_fStartTime = GetEngineTime(); CreateCloneObject(); InvokeRepeating("CreateCloneObject", m_fDuplicateTime, m_fDuplicateTime); } } void Update() { // Debug.Log("Duration.Update"); if (m_bInvoke) return; // Duration if (m_nDuplicateCount == 0 || m_nCreateCount < m_nDuplicateCount) { if (m_fStartTime + m_fDuplicateTime <= GetEngineTime()) { m_fStartTime = GetEngineTime(); CreateCloneObject(); } } } // Control Function ----------------------------------------------------------------- void InitCloneObject() { // Debug.Log("Duration.InitCloneObject"); if (m_ClonObject == null) { // clone ---------------- m_ClonObject = (GameObject)CreateGameObject(gameObject); // Cancel ActiveControl HideNcDelayActive(m_ClonObject); // Remove Dup NcDuplicator durCom = m_ClonObject.GetComponent<NcDuplicator>(); if (durCom != null) // DestroyImmediate(durCom); Destroy(durCom); // Remove NcDelayActive NcDelayActive delCom = m_ClonObject.GetComponent<NcDelayActive>(); if (delCom != null) // DestroyImmediate(delCom); Destroy(delCom); // this ---------------- // remove OtherComponent Component[] coms = transform.GetComponents<Component>(); for (int n = 0; n < coms.Length; n++) if ((coms[n] is Transform) == false && (coms[n] is NcDuplicator) == false) Destroy(coms[n]); // removeChild #if (!UNITY_3_5) RemoveAllChildObject(gameObject, false); #else // RemoveAllChildObject(gameObject, true); OnTrigger error - DestroyImmediate RemoveAllChildObject(gameObject, false); #endif } else return; } void CreateCloneObject() { if (m_ClonObject == null) return; GameObject createObj; if (transform.parent == null) createObj = (GameObject)CreateGameObject(gameObject); else createObj = (GameObject)CreateGameObject(transform.parent.gameObject, m_ClonObject); #if (!UNITY_3_5) SetActiveRecursively(createObj, true); #endif // m_fDuplicateLifeTime if (0 < m_fDuplicateLifeTime) { NcAutoDestruct ncAd = createObj.GetComponent<NcAutoDestruct>(); if (ncAd == null) ncAd = createObj.AddComponent<NcAutoDestruct>(); ncAd.m_fLifeTime = m_fDuplicateLifeTime; } // Random pos Vector3 newPos = createObj.transform.position; createObj.transform.position = new Vector3(Random.Range(-m_RandomRange.x, m_RandomRange.x)+newPos.x, Random.Range(-m_RandomRange.y, m_RandomRange.y)+newPos.y, Random.Range(-m_RandomRange.z, m_RandomRange.z)+newPos.z); // AddStartPos createObj.transform.position += m_AddStartPos; // m_AccumStartRot createObj.transform.localRotation *= Quaternion.Euler(m_AccumStartRot.x*m_nCreateCount, m_AccumStartRot.y*m_nCreateCount, m_AccumStartRot.z*m_nCreateCount); createObj.name += " " + m_nCreateCount; m_nCreateCount++; if (m_bInvoke) { if (m_nDuplicateCount <= m_nCreateCount) CancelInvoke("CreateCloneObject"); } } // Event Function ------------------------------------------------------------------- public override void OnUpdateEffectSpeed(float fSpeedRate, bool bRuntime) { m_fDuplicateTime /= fSpeedRate; m_fDuplicateLifeTime /= fSpeedRate; if (bRuntime && m_ClonObject != null) NsEffectManager.AdjustSpeedRuntime(m_ClonObject, fSpeedRate); } }
using System; using System.Net.Http; using System.Threading.Tasks; using System.Threading; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using ModernHttpClient.CoreFoundation; using ModernHttpClient.Foundation; #if UNIFIED using Foundation; using Security; #else using MonoTouch.Foundation; using MonoTouch.Security; using System.Globalization; #endif namespace ModernHttpClient { class InflightOperation { public HttpRequestMessage Request { get; set; } public TaskCompletionSource<HttpResponseMessage> FutureResponse { get; set; } public ProgressDelegate Progress { get; set; } public ByteArrayListStream ResponseBody { get; set; } public CancellationToken CancellationToken { get; set; } public bool IsCompleted { get; set; } } public class NativeMessageHandler : HttpClientHandler { readonly NSUrlSession session; readonly Dictionary<NSUrlSessionTask, InflightOperation> inflightRequests = new Dictionary<NSUrlSessionTask, InflightOperation>(); readonly Dictionary<HttpRequestMessage, ProgressDelegate> registeredProgressCallbacks = new Dictionary<HttpRequestMessage, ProgressDelegate>(); readonly Dictionary<string, string> headerSeparators = new Dictionary<string, string>(){ {"User-Agent", " "} }; readonly bool throwOnCaptiveNetwork; readonly bool customSSLVerification; public bool DisableCaching { get; set; } public NativeMessageHandler(): this(false, false) { } public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null, SslProtocol? minimumSSLProtocol = null) { var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration; // System.Net.ServicePointManager.SecurityProtocol provides a mechanism for specifying supported protocol types // for System.Net. Since iOS only provides an API for a minimum and maximum protocol we are not able to port // this configuration directly and instead use the specified minimum value when one is specified. if (minimumSSLProtocol.HasValue) { configuration.TLSMinimumSupportedProtocol = minimumSSLProtocol.Value; } session = NSUrlSession.FromConfiguration( NSUrlSessionConfiguration.DefaultSessionConfiguration, new DataTaskDelegate(this), null); this.throwOnCaptiveNetwork = throwOnCaptiveNetwork; this.customSSLVerification = customSSLVerification; this.DisableCaching = false; } string getHeaderSeparator(string name) { if (headerSeparators.ContainsKey(name)) { return headerSeparators[name]; } return ","; } public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback) { if (callback == null && registeredProgressCallbacks.ContainsKey(request)) { registeredProgressCallbacks.Remove(request); return; } registeredProgressCallbacks[request] = callback; } ProgressDelegate getAndRemoveCallbackFromRegister(HttpRequestMessage request) { ProgressDelegate emptyDelegate = delegate { }; lock (registeredProgressCallbacks) { if (!registeredProgressCallbacks.ContainsKey(request)) return emptyDelegate; var callback = registeredProgressCallbacks[request]; registeredProgressCallbacks.Remove(request); return callback; } } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>; var ms = new MemoryStream(); if (request.Content != null) { await request.Content.CopyToAsync(ms).ConfigureAwait(false); headers = headers.Union(request.Content.Headers).ToArray(); } var rq = new NSMutableUrlRequest() { AllowsCellularAccess = true, Body = NSData.FromArray(ms.ToArray()), CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData), Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => { acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value))); return acc; }), HttpMethod = request.Method.ToString().ToUpperInvariant(), Url = NSUrl.FromString(request.RequestUri.AbsoluteUri), }; var op = session.CreateDataTask(rq); cancellationToken.ThrowIfCancellationRequested(); var ret = new TaskCompletionSource<HttpResponseMessage>(); cancellationToken.Register(() => ret.TrySetCanceled()); lock (inflightRequests) { inflightRequests[op] = new InflightOperation() { FutureResponse = ret, Request = request, Progress = getAndRemoveCallbackFromRegister(request), ResponseBody = new ByteArrayListStream(), CancellationToken = cancellationToken, }; } op.Resume(); return await ret.Task.ConfigureAwait(false); } class DataTaskDelegate : NSUrlSessionDataDelegate { NativeMessageHandler This { get; set; } public DataTaskDelegate(NativeMessageHandler that) { this.This = that; } public override void DidReceiveResponse(NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler) { var data = getResponseForTask(dataTask); try { if (data.CancellationToken.IsCancellationRequested) { dataTask.Cancel(); } var resp = (NSHttpUrlResponse)response; var req = data.Request; if (This.throwOnCaptiveNetwork && req.RequestUri.Host != resp.Url.Host) { throw new CaptiveNetworkException(req.RequestUri, new Uri(resp.Url.ToString())); } var content = new CancellableStreamContent(data.ResponseBody, () => { if (!data.IsCompleted) { dataTask.Cancel(); } data.IsCompleted = true; data.ResponseBody.SetException(new OperationCanceledException()); }); content.Progress = data.Progress; // NB: The double cast is because of a Xamarin compiler bug int status = (int)resp.StatusCode; var ret = new HttpResponseMessage((HttpStatusCode)status) { Content = content, RequestMessage = data.Request, }; ret.RequestMessage.RequestUri = new Uri(resp.Url.AbsoluteString); foreach(var v in resp.AllHeaderFields) { // NB: Cocoa trolling us so hard by giving us back dummy // dictionary entries if (v.Key == null || v.Value == null) continue; ret.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString()); ret.Content.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString()); } data.FutureResponse.TrySetResult(ret); } catch (Exception ex) { data.FutureResponse.TrySetException(ex); } completionHandler(NSUrlSessionResponseDisposition.Allow); } public override void WillCacheResponse (NSUrlSession session, NSUrlSessionDataTask dataTask, NSCachedUrlResponse proposedResponse, Action<NSCachedUrlResponse> completionHandler) { completionHandler (This.DisableCaching ? null : proposedResponse); } public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error) { var data = getResponseForTask(task); data.IsCompleted = true; if (error != null) { var ex = createExceptionForNSError(error); // Pass the exception to the response data.FutureResponse.TrySetException(ex); data.ResponseBody.SetException(ex); return; } data.ResponseBody.Complete(); lock (This.inflightRequests) { This.inflightRequests.Remove(task); } } public override void DidReceiveData (NSUrlSession session, NSUrlSessionDataTask dataTask, NSData byteData) { var data = getResponseForTask(dataTask); var bytes = byteData.ToArray(); // NB: If we're cancelled, we still might have one more chunk // of data that attempts to be delivered if (data.IsCompleted) return; data.ResponseBody.AddByteArray(bytes); } InflightOperation getResponseForTask(NSUrlSessionTask task) { lock (This.inflightRequests) { return This.inflightRequests[task]; } } static readonly Regex cnRegex = new Regex(@"CN\s*=\s*([^,]*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline); public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) { NetworkCredential credentialsToUse; if (This.Credentials != null) { if (This.Credentials is NetworkCredential) { credentialsToUse = (NetworkCredential)This.Credentials; } else { var uri = this.getResponseForTask(task).Request.RequestUri; credentialsToUse = This.Credentials.GetCredential(uri, "NTLM"); } var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential); } return; } if (!This.customSSLVerification) { goto doDefault; } if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") { goto doDefault; } if (ServicePointManager.ServerCertificateValidationCallback == null) { goto doDefault; } // Convert Mono Certificates to .NET certificates and build cert // chain from root certificate var serverCertChain = challenge.ProtectionSpace.ServerSecTrust; var chain = new X509Chain(); X509Certificate2 root = null; var errors = SslPolicyErrors.None; if (serverCertChain == null || serverCertChain.Count == 0) { errors = SslPolicyErrors.RemoteCertificateNotAvailable; goto sslErrorVerify; } if (serverCertChain.Count == 1) { errors = SslPolicyErrors.RemoteCertificateChainErrors; goto sslErrorVerify; } var netCerts = Enumerable.Range(0, serverCertChain.Count) .Select(x => serverCertChain[x].ToX509Certificate2()) .ToArray(); for (int i = 1; i < netCerts.Length; i++) { chain.ChainPolicy.ExtraStore.Add(netCerts[i]); } root = netCerts[0]; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; if (!chain.Build(root)) { errors = SslPolicyErrors.RemoteCertificateChainErrors; goto sslErrorVerify; } var subject = root.Subject; var subjectCn = cnRegex.Match(subject).Groups[1].Value; if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) { errors = SslPolicyErrors.RemoteCertificateNameMismatch; goto sslErrorVerify; } sslErrorVerify: var hostname = task.CurrentRequest.Url.Host; bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors); if (result) { completionHandler( NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust)); } else { completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null); } return; doDefault: completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential); return; } public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler) { NSUrlRequest nextRequest = (This.AllowAutoRedirect ? newRequest : null); completionHandler(nextRequest); } static Exception createExceptionForNSError(NSError error) { var ret = default(Exception); var webExceptionStatus = WebExceptionStatus.UnknownError; var innerException = new NSErrorException(error); if (error.Domain == NSError.NSUrlErrorDomain) { // Convert the error code into an enumeration (this is future // proof, rather than just casting integer) NSUrlErrorExtended urlError; if (!Enum.TryParse<NSUrlErrorExtended>(error.Code.ToString(), out urlError)) urlError = NSUrlErrorExtended.Unknown; // Parse the enum into a web exception status or exception. Some // of these values don't necessarily translate completely to // what WebExceptionStatus supports, so made some best guesses // here. For your reading pleasure, compare these: // // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx switch (urlError) { case NSUrlErrorExtended.Cancelled: case NSUrlErrorExtended.UserCancelledAuthentication: // No more processing is required so just return. return new OperationCanceledException(error.LocalizedDescription, innerException); case NSUrlErrorExtended.BadURL: case NSUrlErrorExtended.UnsupportedURL: case NSUrlErrorExtended.CannotConnectToHost: case NSUrlErrorExtended.ResourceUnavailable: case NSUrlErrorExtended.NotConnectedToInternet: case NSUrlErrorExtended.UserAuthenticationRequired: case NSUrlErrorExtended.InternationalRoamingOff: case NSUrlErrorExtended.CallIsActive: case NSUrlErrorExtended.DataNotAllowed: webExceptionStatus = WebExceptionStatus.ConnectFailure; break; case NSUrlErrorExtended.TimedOut: webExceptionStatus = WebExceptionStatus.Timeout; break; case NSUrlErrorExtended.CannotFindHost: case NSUrlErrorExtended.DNSLookupFailed: webExceptionStatus = WebExceptionStatus.NameResolutionFailure; break; case NSUrlErrorExtended.DataLengthExceedsMaximum: webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded; break; case NSUrlErrorExtended.NetworkConnectionLost: webExceptionStatus = WebExceptionStatus.ConnectionClosed; break; case NSUrlErrorExtended.HTTPTooManyRedirects: case NSUrlErrorExtended.RedirectToNonExistentLocation: webExceptionStatus = WebExceptionStatus.ProtocolError; break; case NSUrlErrorExtended.RequestBodyStreamExhausted: webExceptionStatus = WebExceptionStatus.SendFailure; break; case NSUrlErrorExtended.BadServerResponse: case NSUrlErrorExtended.ZeroByteResource: case NSUrlErrorExtended.CannotDecodeRawData: case NSUrlErrorExtended.CannotDecodeContentData: case NSUrlErrorExtended.CannotParseResponse: case NSUrlErrorExtended.FileDoesNotExist: case NSUrlErrorExtended.FileIsDirectory: case NSUrlErrorExtended.NoPermissionsToReadFile: case NSUrlErrorExtended.CannotLoadFromNetwork: case NSUrlErrorExtended.CannotCreateFile: case NSUrlErrorExtended.CannotOpenFile: case NSUrlErrorExtended.CannotCloseFile: case NSUrlErrorExtended.CannotWriteToFile: case NSUrlErrorExtended.CannotRemoveFile: case NSUrlErrorExtended.CannotMoveFile: case NSUrlErrorExtended.DownloadDecodingFailedMidStream: case NSUrlErrorExtended.DownloadDecodingFailedToComplete: webExceptionStatus = WebExceptionStatus.ReceiveFailure; break; case NSUrlErrorExtended.SecureConnectionFailed: webExceptionStatus = WebExceptionStatus.SecureChannelFailure; break; case NSUrlErrorExtended.ServerCertificateHasBadDate: case NSUrlErrorExtended.ServerCertificateHasUnknownRoot: case NSUrlErrorExtended.ServerCertificateNotYetValid: case NSUrlErrorExtended.ServerCertificateUntrusted: case NSUrlErrorExtended.ClientCertificateRejected: case NSUrlErrorExtended.ClientCertificateRequired: webExceptionStatus = WebExceptionStatus.TrustFailure; break; } goto done; } if (error.Domain == CFNetworkError.ErrorDomain) { // Convert the error code into an enumeration (this is future // proof, rather than just casting integer) CFNetworkErrors networkError; if (!Enum.TryParse<CFNetworkErrors>(error.Code.ToString(), out networkError)) { networkError = CFNetworkErrors.CFHostErrorUnknown; } // Parse the enum into a web exception status or exception. Some // of these values don't necessarily translate completely to // what WebExceptionStatus supports, so made some best guesses // here. For your reading pleasure, compare these: // // Apple docs: https://developer.apple.com/library/ios/documentation/Networking/Reference/CFNetworkErrors/#//apple_ref/c/tdef/CFNetworkErrors // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx switch (networkError) { case CFNetworkErrors.CFURLErrorCancelled: case CFNetworkErrors.CFURLErrorUserCancelledAuthentication: case CFNetworkErrors.CFNetServiceErrorCancel: // No more processing is required so just return. return new OperationCanceledException(error.LocalizedDescription, innerException); case CFNetworkErrors.CFSOCKS5ErrorBadCredentials: case CFNetworkErrors.CFSOCKS5ErrorUnsupportedNegotiationMethod: case CFNetworkErrors.CFSOCKS5ErrorNoAcceptableMethod: case CFNetworkErrors.CFErrorHttpAuthenticationTypeUnsupported: case CFNetworkErrors.CFErrorHttpBadCredentials: case CFNetworkErrors.CFErrorHttpBadURL: case CFNetworkErrors.CFURLErrorBadURL: case CFNetworkErrors.CFURLErrorUnsupportedURL: case CFNetworkErrors.CFURLErrorCannotConnectToHost: case CFNetworkErrors.CFURLErrorResourceUnavailable: case CFNetworkErrors.CFURLErrorNotConnectedToInternet: case CFNetworkErrors.CFURLErrorUserAuthenticationRequired: case CFNetworkErrors.CFURLErrorInternationalRoamingOff: case CFNetworkErrors.CFURLErrorCallIsActive: case CFNetworkErrors.CFURLErrorDataNotAllowed: webExceptionStatus = WebExceptionStatus.ConnectFailure; break; case CFNetworkErrors.CFURLErrorTimedOut: case CFNetworkErrors.CFNetServiceErrorTimeout: webExceptionStatus = WebExceptionStatus.Timeout; break; case CFNetworkErrors.CFHostErrorHostNotFound: case CFNetworkErrors.CFURLErrorCannotFindHost: case CFNetworkErrors.CFURLErrorDNSLookupFailed: case CFNetworkErrors.CFNetServiceErrorDNSServiceFailure: webExceptionStatus = WebExceptionStatus.NameResolutionFailure; break; case CFNetworkErrors.CFURLErrorDataLengthExceedsMaximum: webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded; break; case CFNetworkErrors.CFErrorHttpConnectionLost: case CFNetworkErrors.CFURLErrorNetworkConnectionLost: webExceptionStatus = WebExceptionStatus.ConnectionClosed; break; case CFNetworkErrors.CFErrorHttpRedirectionLoopDetected: case CFNetworkErrors.CFURLErrorHTTPTooManyRedirects: case CFNetworkErrors.CFURLErrorRedirectToNonExistentLocation: webExceptionStatus = WebExceptionStatus.ProtocolError; break; case CFNetworkErrors.CFSOCKSErrorUnknownClientVersion: case CFNetworkErrors.CFSOCKSErrorUnsupportedServerVersion: case CFNetworkErrors.CFErrorHttpParseFailure: case CFNetworkErrors.CFURLErrorRequestBodyStreamExhausted: webExceptionStatus = WebExceptionStatus.SendFailure; break; case CFNetworkErrors.CFSOCKS4ErrorRequestFailed: case CFNetworkErrors.CFSOCKS4ErrorIdentdFailed: case CFNetworkErrors.CFSOCKS4ErrorIdConflict: case CFNetworkErrors.CFSOCKS4ErrorUnknownStatusCode: case CFNetworkErrors.CFSOCKS5ErrorBadState: case CFNetworkErrors.CFSOCKS5ErrorBadResponseAddr: case CFNetworkErrors.CFURLErrorBadServerResponse: case CFNetworkErrors.CFURLErrorZeroByteResource: case CFNetworkErrors.CFURLErrorCannotDecodeRawData: case CFNetworkErrors.CFURLErrorCannotDecodeContentData: case CFNetworkErrors.CFURLErrorCannotParseResponse: case CFNetworkErrors.CFURLErrorFileDoesNotExist: case CFNetworkErrors.CFURLErrorFileIsDirectory: case CFNetworkErrors.CFURLErrorNoPermissionsToReadFile: case CFNetworkErrors.CFURLErrorCannotLoadFromNetwork: case CFNetworkErrors.CFURLErrorCannotCreateFile: case CFNetworkErrors.CFURLErrorCannotOpenFile: case CFNetworkErrors.CFURLErrorCannotCloseFile: case CFNetworkErrors.CFURLErrorCannotWriteToFile: case CFNetworkErrors.CFURLErrorCannotRemoveFile: case CFNetworkErrors.CFURLErrorCannotMoveFile: case CFNetworkErrors.CFURLErrorDownloadDecodingFailedMidStream: case CFNetworkErrors.CFURLErrorDownloadDecodingFailedToComplete: case CFNetworkErrors.CFHTTPCookieCannotParseCookieFile: case CFNetworkErrors.CFNetServiceErrorUnknown: case CFNetworkErrors.CFNetServiceErrorCollision: case CFNetworkErrors.CFNetServiceErrorNotFound: case CFNetworkErrors.CFNetServiceErrorInProgress: case CFNetworkErrors.CFNetServiceErrorBadArgument: case CFNetworkErrors.CFNetServiceErrorInvalid: webExceptionStatus = WebExceptionStatus.ReceiveFailure; break; case CFNetworkErrors.CFURLErrorServerCertificateHasBadDate: case CFNetworkErrors.CFURLErrorServerCertificateUntrusted: case CFNetworkErrors.CFURLErrorServerCertificateHasUnknownRoot: case CFNetworkErrors.CFURLErrorServerCertificateNotYetValid: case CFNetworkErrors.CFURLErrorClientCertificateRejected: case CFNetworkErrors.CFURLErrorClientCertificateRequired: webExceptionStatus = WebExceptionStatus.TrustFailure; break; case CFNetworkErrors.CFURLErrorSecureConnectionFailed: webExceptionStatus = WebExceptionStatus.SecureChannelFailure; break; case CFNetworkErrors.CFErrorHttpProxyConnectionFailure: case CFNetworkErrors.CFErrorHttpBadProxyCredentials: case CFNetworkErrors.CFErrorPACFileError: case CFNetworkErrors.CFErrorPACFileAuth: case CFNetworkErrors.CFErrorHttpsProxyConnectionFailure: case CFNetworkErrors.CFStreamErrorHttpsProxyFailureUnexpectedResponseToConnectMethod: webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy; break; } goto done; } done: // Always create a WebException so that it can be handled by the client. ret = new WebException(error.LocalizedDescription, innerException, webExceptionStatus, response: null); return ret; } } } class ByteArrayListStream : Stream { Exception exception; IDisposable lockRelease; readonly AsyncLock readStreamLock; readonly List<byte[]> bytes = new List<byte[]>(); bool isCompleted; long maxLength = 0; long position = 0; int offsetInCurrentBuffer = 0; public ByteArrayListStream() { // Initially we have nothing to read so Reads should be parked readStreamLock = AsyncLock.CreateLocked(out lockRelease); } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void WriteByte(byte value) { throw new NotSupportedException(); } public override bool CanSeek { get { return false; } } public override bool CanTimeout { get { return false; } } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override long Position { get { return position; } set { throw new NotSupportedException(); } } public override long Length { get { return maxLength; } } public override int Read(byte[] buffer, int offset, int count) { return this.ReadAsync(buffer, offset, count).Result; } /* OMG THIS CODE IS COMPLICATED * * Here's the core idea. We want to create a ReadAsync function that * reads from our list of byte arrays **until it gets to the end of * our current list**. * * If we're not there yet, we keep returning data, serializing access * to the underlying position pointer (i.e. we definitely don't want * people concurrently moving position along). If we try to read past * the end, we return the section of data we could read and complete * it. * * Here's where the tricky part comes in. If we're not Completed (i.e. * the caller still wants to add more byte arrays in the future) and * we're at the end of the current stream, we want to *block* the read * (not blocking, but async blocking whatever you know what I mean), * until somebody adds another byte[] to chew through, or if someone * rewinds the position. * * If we *are* completed, we should return zero to simply complete the * read, signalling we're at the end of the stream */ public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { retry: int bytesRead = 0; int buffersToRemove = 0; if (isCompleted && position == maxLength) { return 0; } if (exception != null) throw exception; using (await readStreamLock.LockAsync().ConfigureAwait(false)) { lock (bytes) { foreach (var buf in bytes) { cancellationToken.ThrowIfCancellationRequested(); if (exception != null) throw exception; int toCopy = Math.Min(count, buf.Length - offsetInCurrentBuffer); Array.ConstrainedCopy(buf, offsetInCurrentBuffer, buffer, offset, toCopy); count -= toCopy; offset += toCopy; bytesRead += toCopy; offsetInCurrentBuffer += toCopy; if (offsetInCurrentBuffer >= buf.Length) { offsetInCurrentBuffer = 0; buffersToRemove++; } if (count <= 0) break; } // Remove buffers that we read in this operation bytes.RemoveRange(0, buffersToRemove); position += bytesRead; } } // If we're at the end of the stream and it's not done, prepare // the next read to park itself unless AddByteArray or Complete // posts if (position >= maxLength && !isCompleted) { lockRelease = await readStreamLock.LockAsync().ConfigureAwait(false); } if (bytesRead == 0 && !isCompleted) { // NB: There are certain race conditions where we somehow acquire // the lock yet are at the end of the stream, and we're not completed // yet. We should try again so that we can get stuck in the lock. goto retry; } if (cancellationToken.IsCancellationRequested) { Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); cancellationToken.ThrowIfCancellationRequested(); } if (exception != null) { Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); throw exception; } if (isCompleted && position < maxLength) { // NB: This solves a rare deadlock // // 1. ReadAsync called (waiting for lock release) // 2. AddByteArray called (release lock) // 3. AddByteArray called (release lock) // 4. Complete called (release lock the last time) // 5. ReadAsync called (lock released at this point, the method completed successfully) // 6. ReadAsync called (deadlock on LockAsync(), because the lock is block, and there is no way to release it) // // Current condition forces the lock to be released in the end of 5th point Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); } return bytesRead; } public void AddByteArray(byte[] arrayToAdd) { if (exception != null) throw exception; if (isCompleted) throw new InvalidOperationException("Can't add byte arrays once Complete() is called"); lock (bytes) { maxLength += arrayToAdd.Length; bytes.Add(arrayToAdd); //Console.WriteLine("Added a new byte array, {0}: max = {1}", arrayToAdd.Length, maxLength); } Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); } public void Complete() { isCompleted = true; Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); } public void SetException(Exception ex) { exception = ex; Complete(); } } sealed class CancellableStreamContent : ProgressStreamContent { Action onDispose; public CancellableStreamContent(Stream source, Action onDispose) : base(source, CancellationToken.None) { this.onDispose = onDispose; } protected override void Dispose(bool disposing) { var disp = Interlocked.Exchange(ref onDispose, null); if (disp != null) disp(); // EVIL HAX: We have to let at least one ReadAsync of the underlying // stream fail with OperationCancelledException before we can dispose // the base, or else the exception coming out of the ReadAsync will // be an ObjectDisposedException from an internal MemoryStream. This isn't // the Ideal way to fix this, but #yolo. Task.Run(() => base.Dispose(disposing)); } } sealed class EmptyDisposable : IDisposable { static readonly IDisposable instance = new EmptyDisposable(); public static IDisposable Instance { get { return instance; } } EmptyDisposable() { } public void Dispose() { } } }
using UnityEngine; namespace Pathfinding { /** Extended Path. * \ingroup paths * This is the same as a standard path but it is possible to customize when the target should be considered reached. * Can be used to for example signal a path as complete when it is within a specific distance from the target. * * \note More customizations does make it slower to calculate than an ABPath but not by very much. * \astarpro * * \see Pathfinding.PathEndingCondition */ public class XPath : ABPath { /** * Ending Condition for the path. * The ending condition determines when the path has been completed. * Can be used to for example signal a path as complete when it is within a specific distance from the target. * * If ending conditions are used that are not centered around the endpoint of the path * you should also switch the #heuristic to None to make sure that optimal paths are still found. * This has quite a large performance impact so you might want to try to run it with the default * heuristic and see if the path is optimal in enough cases. */ public PathEndingCondition endingCondition; public XPath () {} public new static XPath Construct (Vector3 start, Vector3 end, OnPathDelegate callback = null) { var p = PathPool.GetPath<XPath>(); p.Setup(start, end, callback); p.endingCondition = new ABPathEndingCondition(p); return p; } public override void Reset () { base.Reset(); endingCondition = null; } /** The start node need to be special cased and checked here if it is a valid target */ protected override void CompletePathIfStartIsValidTarget () { var pNode = pathHandler.GetPathNode(startNode); if (endingCondition.TargetFound(pNode)) { endNode = pNode.node; endPoint = (Vector3)endNode.position; Trace(pNode); CompleteState = PathCompleteState.Complete; } } public override void CalculateStep (long targetTick) { int counter = 0; // Continue to search while there hasn't ocurred an error and the end hasn't been found while (CompleteState == PathCompleteState.NotCalculated) { searchedNodes++; // Close the current node, if the current node is the target node then the path is finished if (endingCondition.TargetFound(currentR)) { CompleteState = PathCompleteState.Complete; break; } // Loop through all walkable neighbours of the node and add them to the open list. currentR.node.Open(this, currentR, pathHandler); // Any nodes left to search? if (pathHandler.HeapEmpty()) { Error(); LogError("Searched whole area but could not find target"); return; } // Select the node with the lowest F score and remove it from the open list currentR = pathHandler.PopNode(); // Check for time every 500 nodes, roughly every 0.5 ms usually if (counter > 500) { // Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag if (System.DateTime.UtcNow.Ticks >= targetTick) { //Return instead of yield'ing, a separate function handles the yield (CalculatePaths) return; } counter = 0; if (searchedNodes > 1000000) { throw new System.Exception("Probable infinite loop. Over 1,000,000 nodes searched"); } } counter++; } if (CompleteState == PathCompleteState.Complete) { endNode = currentR.node; endPoint = (Vector3)endNode.position; Trace(currentR); } } } /** Customized ending condition for a path. * This class can be used to implement a custom ending condition for e.g an Pathfinding.XPath.\n * Inherit from this class and override the #TargetFound function to implement you own ending condition logic.\n * \n * For example, you might want to create an Ending Condition which stops when a node is close enough to a given point.\n * Then what you do is that you create your own class, let's call it MyEndingCondition and override the function TargetFound to specify our own logic. * We want to inherit from ABPathEndingCondition because only ABPaths have end points defined. * * \code * public class MyEndingCondition : ABPathEndingCondition { * * // Maximum world distance to the target node before terminating the path * public float maxDistance = 10; * * // Reuse the constructor in the superclass * public EndingConditionProximity (ABPath p) : base (p) {} * * public override bool TargetFound (PathNode node) { * return ((Vector3)node.node.position - abPath.originalEndPoint).sqrMagnitude <= maxDistance*maxDistance; * } * } * \endcode * * One part at a time. We need to cast the node's position to a Vector3 since internally, it is stored as an integer coordinate (Int3). * Then we subtract the Pathfinding.Path.originalEndPoint from it to get their difference. * The original end point is always the exact point specified when calling the path. * As a last step we check the squared magnitude (squared distance, it is much faster than the non-squared distance) and check if it is lower or equal to our maxDistance squared.\n * There you have it, it is as simple as that. * Then you simply assign it to the \a endingCondition variable on, for example an XPath which uses the EndingCondition. * * \code * EndingConditionProximity ec = new MyEndingCondition (); * ec.maxDistance = 100; //Or some other value * myXPath.endingCondition = ec; * * //Call the path! * mySeeker.StartPath (ec); * \endcode * * Where \a mySeeker is a Seeker component, and \a myXPath is an Pathfinding.XPath.\n * * \note The above was written without testing. I hope I haven't made any mistakes, if you try it out, and it doesn't seem to work. Please post a comment below. * * \note Written for 3.0.8.3 * * \version Method structure changed in 3.2 * \version Updated in version 3.6.8 * * \see Pathfinding.XPath * \see Pathfinding.ConstantPath * */ public abstract class PathEndingCondition { /** Path which this ending condition is used on */ protected Path path; protected PathEndingCondition () {} public PathEndingCondition (Path p) { if (p == null) throw new System.ArgumentNullException("p"); this.path = p; } /** Has the ending condition been fulfilled. * \param node The current node. */ public abstract bool TargetFound (PathNode node); } /** Ending condition which emulates the default one for the ABPath */ public class ABPathEndingCondition : PathEndingCondition { /** * Path which this ending condition is used on. * Same as #path but downcasted to ABPath */ protected ABPath abPath; public ABPathEndingCondition (ABPath p) { if (p == null) throw new System.ArgumentNullException("p"); abPath = p; path = p; } /** Has the ending condition been fulfilled. * \param node The current node. * This is per default the same as asking if \a node == \a p.endNode */ public override bool TargetFound (PathNode node) { return node.node == abPath.endNode; } } /** Ending condition which stops a fixed distance from the target point */ public class EndingConditionProximity : ABPathEndingCondition { /** Maximum world distance to the target node before terminating the path */ public float maxDistance = 10; public EndingConditionProximity (ABPath p, float maxDistance) : base(p) { this.maxDistance = maxDistance; } public override bool TargetFound (PathNode node) { return ((Vector3)node.node.position - abPath.originalEndPoint).sqrMagnitude <= maxDistance*maxDistance; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using MvcSeed.Web.Areas.HelpPage.Models; namespace MvcSeed.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data{ /// <summary> /// Strongly-typed collection for the VStationDataset class. /// </summary> [Serializable] public partial class VStationDatasetCollection : ReadOnlyList<VStationDataset, VStationDatasetCollection> { public VStationDatasetCollection() {} } /// <summary> /// This is Read-only wrapper class for the vStationDatasets view. /// </summary> [Serializable] public partial class VStationDataset : ReadOnlyRecord<VStationDataset>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("vStationDatasets", TableType.View, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Int64; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = true; colvarId.IsPrimaryKey = false; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarOrganisationID = new TableSchema.TableColumn(schema); colvarOrganisationID.ColumnName = "OrganisationID"; colvarOrganisationID.DataType = DbType.Guid; colvarOrganisationID.MaxLength = 0; colvarOrganisationID.AutoIncrement = false; colvarOrganisationID.IsNullable = true; colvarOrganisationID.IsPrimaryKey = false; colvarOrganisationID.IsForeignKey = false; colvarOrganisationID.IsReadOnly = false; schema.Columns.Add(colvarOrganisationID); TableSchema.TableColumn colvarOrganisationCode = new TableSchema.TableColumn(schema); colvarOrganisationCode.ColumnName = "OrganisationCode"; colvarOrganisationCode.DataType = DbType.AnsiString; colvarOrganisationCode.MaxLength = 50; colvarOrganisationCode.AutoIncrement = false; colvarOrganisationCode.IsNullable = true; colvarOrganisationCode.IsPrimaryKey = false; colvarOrganisationCode.IsForeignKey = false; colvarOrganisationCode.IsReadOnly = false; schema.Columns.Add(colvarOrganisationCode); TableSchema.TableColumn colvarOrganisationName = new TableSchema.TableColumn(schema); colvarOrganisationName.ColumnName = "OrganisationName"; colvarOrganisationName.DataType = DbType.AnsiString; colvarOrganisationName.MaxLength = 150; colvarOrganisationName.AutoIncrement = false; colvarOrganisationName.IsNullable = true; colvarOrganisationName.IsPrimaryKey = false; colvarOrganisationName.IsForeignKey = false; colvarOrganisationName.IsReadOnly = false; schema.Columns.Add(colvarOrganisationName); TableSchema.TableColumn colvarOrganisationDescription = new TableSchema.TableColumn(schema); colvarOrganisationDescription.ColumnName = "OrganisationDescription"; colvarOrganisationDescription.DataType = DbType.AnsiString; colvarOrganisationDescription.MaxLength = 5000; colvarOrganisationDescription.AutoIncrement = false; colvarOrganisationDescription.IsNullable = true; colvarOrganisationDescription.IsPrimaryKey = false; colvarOrganisationDescription.IsForeignKey = false; colvarOrganisationDescription.IsReadOnly = false; schema.Columns.Add(colvarOrganisationDescription); TableSchema.TableColumn colvarOrganisationUrl = new TableSchema.TableColumn(schema); colvarOrganisationUrl.ColumnName = "OrganisationUrl"; colvarOrganisationUrl.DataType = DbType.AnsiString; colvarOrganisationUrl.MaxLength = 250; colvarOrganisationUrl.AutoIncrement = false; colvarOrganisationUrl.IsNullable = true; colvarOrganisationUrl.IsPrimaryKey = false; colvarOrganisationUrl.IsForeignKey = false; colvarOrganisationUrl.IsReadOnly = false; schema.Columns.Add(colvarOrganisationUrl); TableSchema.TableColumn colvarProgrammeID = new TableSchema.TableColumn(schema); colvarProgrammeID.ColumnName = "ProgrammeID"; colvarProgrammeID.DataType = DbType.Guid; colvarProgrammeID.MaxLength = 0; colvarProgrammeID.AutoIncrement = false; colvarProgrammeID.IsNullable = true; colvarProgrammeID.IsPrimaryKey = false; colvarProgrammeID.IsForeignKey = false; colvarProgrammeID.IsReadOnly = false; schema.Columns.Add(colvarProgrammeID); TableSchema.TableColumn colvarProgrammeCode = new TableSchema.TableColumn(schema); colvarProgrammeCode.ColumnName = "ProgrammeCode"; colvarProgrammeCode.DataType = DbType.AnsiString; colvarProgrammeCode.MaxLength = 50; colvarProgrammeCode.AutoIncrement = false; colvarProgrammeCode.IsNullable = true; colvarProgrammeCode.IsPrimaryKey = false; colvarProgrammeCode.IsForeignKey = false; colvarProgrammeCode.IsReadOnly = false; schema.Columns.Add(colvarProgrammeCode); TableSchema.TableColumn colvarProgrammeName = new TableSchema.TableColumn(schema); colvarProgrammeName.ColumnName = "ProgrammeName"; colvarProgrammeName.DataType = DbType.AnsiString; colvarProgrammeName.MaxLength = 150; colvarProgrammeName.AutoIncrement = false; colvarProgrammeName.IsNullable = true; colvarProgrammeName.IsPrimaryKey = false; colvarProgrammeName.IsForeignKey = false; colvarProgrammeName.IsReadOnly = false; schema.Columns.Add(colvarProgrammeName); TableSchema.TableColumn colvarProgrammeDescription = new TableSchema.TableColumn(schema); colvarProgrammeDescription.ColumnName = "ProgrammeDescription"; colvarProgrammeDescription.DataType = DbType.AnsiString; colvarProgrammeDescription.MaxLength = 5000; colvarProgrammeDescription.AutoIncrement = false; colvarProgrammeDescription.IsNullable = true; colvarProgrammeDescription.IsPrimaryKey = false; colvarProgrammeDescription.IsForeignKey = false; colvarProgrammeDescription.IsReadOnly = false; schema.Columns.Add(colvarProgrammeDescription); TableSchema.TableColumn colvarProgrammeUrl = new TableSchema.TableColumn(schema); colvarProgrammeUrl.ColumnName = "ProgrammeUrl"; colvarProgrammeUrl.DataType = DbType.AnsiString; colvarProgrammeUrl.MaxLength = 250; colvarProgrammeUrl.AutoIncrement = false; colvarProgrammeUrl.IsNullable = true; colvarProgrammeUrl.IsPrimaryKey = false; colvarProgrammeUrl.IsForeignKey = false; colvarProgrammeUrl.IsReadOnly = false; schema.Columns.Add(colvarProgrammeUrl); TableSchema.TableColumn colvarProjectID = new TableSchema.TableColumn(schema); colvarProjectID.ColumnName = "ProjectID"; colvarProjectID.DataType = DbType.Guid; colvarProjectID.MaxLength = 0; colvarProjectID.AutoIncrement = false; colvarProjectID.IsNullable = true; colvarProjectID.IsPrimaryKey = false; colvarProjectID.IsForeignKey = false; colvarProjectID.IsReadOnly = false; schema.Columns.Add(colvarProjectID); TableSchema.TableColumn colvarProjectCode = new TableSchema.TableColumn(schema); colvarProjectCode.ColumnName = "ProjectCode"; colvarProjectCode.DataType = DbType.AnsiString; colvarProjectCode.MaxLength = 50; colvarProjectCode.AutoIncrement = false; colvarProjectCode.IsNullable = true; colvarProjectCode.IsPrimaryKey = false; colvarProjectCode.IsForeignKey = false; colvarProjectCode.IsReadOnly = false; schema.Columns.Add(colvarProjectCode); TableSchema.TableColumn colvarProjectName = new TableSchema.TableColumn(schema); colvarProjectName.ColumnName = "ProjectName"; colvarProjectName.DataType = DbType.AnsiString; colvarProjectName.MaxLength = 150; colvarProjectName.AutoIncrement = false; colvarProjectName.IsNullable = true; colvarProjectName.IsPrimaryKey = false; colvarProjectName.IsForeignKey = false; colvarProjectName.IsReadOnly = false; schema.Columns.Add(colvarProjectName); TableSchema.TableColumn colvarProjectDescription = new TableSchema.TableColumn(schema); colvarProjectDescription.ColumnName = "ProjectDescription"; colvarProjectDescription.DataType = DbType.AnsiString; colvarProjectDescription.MaxLength = 5000; colvarProjectDescription.AutoIncrement = false; colvarProjectDescription.IsNullable = true; colvarProjectDescription.IsPrimaryKey = false; colvarProjectDescription.IsForeignKey = false; colvarProjectDescription.IsReadOnly = false; schema.Columns.Add(colvarProjectDescription); TableSchema.TableColumn colvarProjectUrl = new TableSchema.TableColumn(schema); colvarProjectUrl.ColumnName = "ProjectUrl"; colvarProjectUrl.DataType = DbType.AnsiString; colvarProjectUrl.MaxLength = 250; colvarProjectUrl.AutoIncrement = false; colvarProjectUrl.IsNullable = true; colvarProjectUrl.IsPrimaryKey = false; colvarProjectUrl.IsForeignKey = false; colvarProjectUrl.IsReadOnly = false; schema.Columns.Add(colvarProjectUrl); TableSchema.TableColumn colvarSiteID = new TableSchema.TableColumn(schema); colvarSiteID.ColumnName = "SiteID"; colvarSiteID.DataType = DbType.Guid; colvarSiteID.MaxLength = 0; colvarSiteID.AutoIncrement = false; colvarSiteID.IsNullable = false; colvarSiteID.IsPrimaryKey = false; colvarSiteID.IsForeignKey = false; colvarSiteID.IsReadOnly = false; schema.Columns.Add(colvarSiteID); TableSchema.TableColumn colvarSiteCode = new TableSchema.TableColumn(schema); colvarSiteCode.ColumnName = "SiteCode"; colvarSiteCode.DataType = DbType.AnsiString; colvarSiteCode.MaxLength = 50; colvarSiteCode.AutoIncrement = false; colvarSiteCode.IsNullable = false; colvarSiteCode.IsPrimaryKey = false; colvarSiteCode.IsForeignKey = false; colvarSiteCode.IsReadOnly = false; schema.Columns.Add(colvarSiteCode); TableSchema.TableColumn colvarSiteName = new TableSchema.TableColumn(schema); colvarSiteName.ColumnName = "SiteName"; colvarSiteName.DataType = DbType.AnsiString; colvarSiteName.MaxLength = 150; colvarSiteName.AutoIncrement = false; colvarSiteName.IsNullable = false; colvarSiteName.IsPrimaryKey = false; colvarSiteName.IsForeignKey = false; colvarSiteName.IsReadOnly = false; schema.Columns.Add(colvarSiteName); TableSchema.TableColumn colvarSiteDescription = new TableSchema.TableColumn(schema); colvarSiteDescription.ColumnName = "SiteDescription"; colvarSiteDescription.DataType = DbType.AnsiString; colvarSiteDescription.MaxLength = 5000; colvarSiteDescription.AutoIncrement = false; colvarSiteDescription.IsNullable = true; colvarSiteDescription.IsPrimaryKey = false; colvarSiteDescription.IsForeignKey = false; colvarSiteDescription.IsReadOnly = false; schema.Columns.Add(colvarSiteDescription); TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema); colvarStationID.ColumnName = "StationID"; colvarStationID.DataType = DbType.Guid; colvarStationID.MaxLength = 0; colvarStationID.AutoIncrement = false; colvarStationID.IsNullable = false; colvarStationID.IsPrimaryKey = false; colvarStationID.IsForeignKey = false; colvarStationID.IsReadOnly = false; schema.Columns.Add(colvarStationID); TableSchema.TableColumn colvarStationCode = new TableSchema.TableColumn(schema); colvarStationCode.ColumnName = "StationCode"; colvarStationCode.DataType = DbType.AnsiString; colvarStationCode.MaxLength = 50; colvarStationCode.AutoIncrement = false; colvarStationCode.IsNullable = false; colvarStationCode.IsPrimaryKey = false; colvarStationCode.IsForeignKey = false; colvarStationCode.IsReadOnly = false; schema.Columns.Add(colvarStationCode); TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema); colvarStationName.ColumnName = "StationName"; colvarStationName.DataType = DbType.AnsiString; colvarStationName.MaxLength = 150; colvarStationName.AutoIncrement = false; colvarStationName.IsNullable = false; colvarStationName.IsPrimaryKey = false; colvarStationName.IsForeignKey = false; colvarStationName.IsReadOnly = false; schema.Columns.Add(colvarStationName); TableSchema.TableColumn colvarStationDescription = new TableSchema.TableColumn(schema); colvarStationDescription.ColumnName = "StationDescription"; colvarStationDescription.DataType = DbType.AnsiString; colvarStationDescription.MaxLength = 5000; colvarStationDescription.AutoIncrement = false; colvarStationDescription.IsNullable = true; colvarStationDescription.IsPrimaryKey = false; colvarStationDescription.IsForeignKey = false; colvarStationDescription.IsReadOnly = false; schema.Columns.Add(colvarStationDescription); TableSchema.TableColumn colvarPhenomenonID = new TableSchema.TableColumn(schema); colvarPhenomenonID.ColumnName = "PhenomenonID"; colvarPhenomenonID.DataType = DbType.Guid; colvarPhenomenonID.MaxLength = 0; colvarPhenomenonID.AutoIncrement = false; colvarPhenomenonID.IsNullable = false; colvarPhenomenonID.IsPrimaryKey = false; colvarPhenomenonID.IsForeignKey = false; colvarPhenomenonID.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonID); TableSchema.TableColumn colvarPhenomenonCode = new TableSchema.TableColumn(schema); colvarPhenomenonCode.ColumnName = "PhenomenonCode"; colvarPhenomenonCode.DataType = DbType.AnsiString; colvarPhenomenonCode.MaxLength = 50; colvarPhenomenonCode.AutoIncrement = false; colvarPhenomenonCode.IsNullable = false; colvarPhenomenonCode.IsPrimaryKey = false; colvarPhenomenonCode.IsForeignKey = false; colvarPhenomenonCode.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonCode); TableSchema.TableColumn colvarPhenomenonName = new TableSchema.TableColumn(schema); colvarPhenomenonName.ColumnName = "PhenomenonName"; colvarPhenomenonName.DataType = DbType.AnsiString; colvarPhenomenonName.MaxLength = 150; colvarPhenomenonName.AutoIncrement = false; colvarPhenomenonName.IsNullable = false; colvarPhenomenonName.IsPrimaryKey = false; colvarPhenomenonName.IsForeignKey = false; colvarPhenomenonName.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonName); TableSchema.TableColumn colvarPhenomenonDescription = new TableSchema.TableColumn(schema); colvarPhenomenonDescription.ColumnName = "PhenomenonDescription"; colvarPhenomenonDescription.DataType = DbType.AnsiString; colvarPhenomenonDescription.MaxLength = 5000; colvarPhenomenonDescription.AutoIncrement = false; colvarPhenomenonDescription.IsNullable = true; colvarPhenomenonDescription.IsPrimaryKey = false; colvarPhenomenonDescription.IsForeignKey = false; colvarPhenomenonDescription.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonDescription); TableSchema.TableColumn colvarPhenomenonOfferingID = new TableSchema.TableColumn(schema); colvarPhenomenonOfferingID.ColumnName = "PhenomenonOfferingID"; colvarPhenomenonOfferingID.DataType = DbType.Guid; colvarPhenomenonOfferingID.MaxLength = 0; colvarPhenomenonOfferingID.AutoIncrement = false; colvarPhenomenonOfferingID.IsNullable = false; colvarPhenomenonOfferingID.IsPrimaryKey = false; colvarPhenomenonOfferingID.IsForeignKey = false; colvarPhenomenonOfferingID.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonOfferingID); TableSchema.TableColumn colvarOfferingID = new TableSchema.TableColumn(schema); colvarOfferingID.ColumnName = "OfferingID"; colvarOfferingID.DataType = DbType.Guid; colvarOfferingID.MaxLength = 0; colvarOfferingID.AutoIncrement = false; colvarOfferingID.IsNullable = false; colvarOfferingID.IsPrimaryKey = false; colvarOfferingID.IsForeignKey = false; colvarOfferingID.IsReadOnly = false; schema.Columns.Add(colvarOfferingID); TableSchema.TableColumn colvarOfferingCode = new TableSchema.TableColumn(schema); colvarOfferingCode.ColumnName = "OfferingCode"; colvarOfferingCode.DataType = DbType.AnsiString; colvarOfferingCode.MaxLength = 50; colvarOfferingCode.AutoIncrement = false; colvarOfferingCode.IsNullable = false; colvarOfferingCode.IsPrimaryKey = false; colvarOfferingCode.IsForeignKey = false; colvarOfferingCode.IsReadOnly = false; schema.Columns.Add(colvarOfferingCode); TableSchema.TableColumn colvarOfferingName = new TableSchema.TableColumn(schema); colvarOfferingName.ColumnName = "OfferingName"; colvarOfferingName.DataType = DbType.AnsiString; colvarOfferingName.MaxLength = 150; colvarOfferingName.AutoIncrement = false; colvarOfferingName.IsNullable = false; colvarOfferingName.IsPrimaryKey = false; colvarOfferingName.IsForeignKey = false; colvarOfferingName.IsReadOnly = false; schema.Columns.Add(colvarOfferingName); TableSchema.TableColumn colvarOfferingDescription = new TableSchema.TableColumn(schema); colvarOfferingDescription.ColumnName = "OfferingDescription"; colvarOfferingDescription.DataType = DbType.AnsiString; colvarOfferingDescription.MaxLength = 5000; colvarOfferingDescription.AutoIncrement = false; colvarOfferingDescription.IsNullable = true; colvarOfferingDescription.IsPrimaryKey = false; colvarOfferingDescription.IsForeignKey = false; colvarOfferingDescription.IsReadOnly = false; schema.Columns.Add(colvarOfferingDescription); TableSchema.TableColumn colvarPhenomenonUOMID = new TableSchema.TableColumn(schema); colvarPhenomenonUOMID.ColumnName = "PhenomenonUOMID"; colvarPhenomenonUOMID.DataType = DbType.Guid; colvarPhenomenonUOMID.MaxLength = 0; colvarPhenomenonUOMID.AutoIncrement = false; colvarPhenomenonUOMID.IsNullable = false; colvarPhenomenonUOMID.IsPrimaryKey = false; colvarPhenomenonUOMID.IsForeignKey = false; colvarPhenomenonUOMID.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonUOMID); TableSchema.TableColumn colvarUnitOfMeasureID = new TableSchema.TableColumn(schema); colvarUnitOfMeasureID.ColumnName = "UnitOfMeasureID"; colvarUnitOfMeasureID.DataType = DbType.Guid; colvarUnitOfMeasureID.MaxLength = 0; colvarUnitOfMeasureID.AutoIncrement = false; colvarUnitOfMeasureID.IsNullable = false; colvarUnitOfMeasureID.IsPrimaryKey = false; colvarUnitOfMeasureID.IsForeignKey = false; colvarUnitOfMeasureID.IsReadOnly = false; schema.Columns.Add(colvarUnitOfMeasureID); TableSchema.TableColumn colvarUnitOfMeasureCode = new TableSchema.TableColumn(schema); colvarUnitOfMeasureCode.ColumnName = "UnitOfMeasureCode"; colvarUnitOfMeasureCode.DataType = DbType.AnsiString; colvarUnitOfMeasureCode.MaxLength = 50; colvarUnitOfMeasureCode.AutoIncrement = false; colvarUnitOfMeasureCode.IsNullable = false; colvarUnitOfMeasureCode.IsPrimaryKey = false; colvarUnitOfMeasureCode.IsForeignKey = false; colvarUnitOfMeasureCode.IsReadOnly = false; schema.Columns.Add(colvarUnitOfMeasureCode); TableSchema.TableColumn colvarUnitOfMeasureUnit = new TableSchema.TableColumn(schema); colvarUnitOfMeasureUnit.ColumnName = "UnitOfMeasureUnit"; colvarUnitOfMeasureUnit.DataType = DbType.AnsiString; colvarUnitOfMeasureUnit.MaxLength = 100; colvarUnitOfMeasureUnit.AutoIncrement = false; colvarUnitOfMeasureUnit.IsNullable = false; colvarUnitOfMeasureUnit.IsPrimaryKey = false; colvarUnitOfMeasureUnit.IsForeignKey = false; colvarUnitOfMeasureUnit.IsReadOnly = false; schema.Columns.Add(colvarUnitOfMeasureUnit); TableSchema.TableColumn colvarUnitOfMeasureSymbol = new TableSchema.TableColumn(schema); colvarUnitOfMeasureSymbol.ColumnName = "UnitOfMeasureSymbol"; colvarUnitOfMeasureSymbol.DataType = DbType.AnsiString; colvarUnitOfMeasureSymbol.MaxLength = 20; colvarUnitOfMeasureSymbol.AutoIncrement = false; colvarUnitOfMeasureSymbol.IsNullable = false; colvarUnitOfMeasureSymbol.IsPrimaryKey = false; colvarUnitOfMeasureSymbol.IsForeignKey = false; colvarUnitOfMeasureSymbol.IsReadOnly = false; schema.Columns.Add(colvarUnitOfMeasureSymbol); TableSchema.TableColumn colvarCount = new TableSchema.TableColumn(schema); colvarCount.ColumnName = "Count"; colvarCount.DataType = DbType.Int32; colvarCount.MaxLength = 0; colvarCount.AutoIncrement = false; colvarCount.IsNullable = true; colvarCount.IsPrimaryKey = false; colvarCount.IsForeignKey = false; colvarCount.IsReadOnly = false; schema.Columns.Add(colvarCount); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.DateTime; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.DateTime; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarLatitudeNorth = new TableSchema.TableColumn(schema); colvarLatitudeNorth.ColumnName = "LatitudeNorth"; colvarLatitudeNorth.DataType = DbType.Double; colvarLatitudeNorth.MaxLength = 0; colvarLatitudeNorth.AutoIncrement = false; colvarLatitudeNorth.IsNullable = true; colvarLatitudeNorth.IsPrimaryKey = false; colvarLatitudeNorth.IsForeignKey = false; colvarLatitudeNorth.IsReadOnly = false; schema.Columns.Add(colvarLatitudeNorth); TableSchema.TableColumn colvarLatitudeSouth = new TableSchema.TableColumn(schema); colvarLatitudeSouth.ColumnName = "LatitudeSouth"; colvarLatitudeSouth.DataType = DbType.Double; colvarLatitudeSouth.MaxLength = 0; colvarLatitudeSouth.AutoIncrement = false; colvarLatitudeSouth.IsNullable = true; colvarLatitudeSouth.IsPrimaryKey = false; colvarLatitudeSouth.IsForeignKey = false; colvarLatitudeSouth.IsReadOnly = false; schema.Columns.Add(colvarLatitudeSouth); TableSchema.TableColumn colvarLongitudeWest = new TableSchema.TableColumn(schema); colvarLongitudeWest.ColumnName = "LongitudeWest"; colvarLongitudeWest.DataType = DbType.Double; colvarLongitudeWest.MaxLength = 0; colvarLongitudeWest.AutoIncrement = false; colvarLongitudeWest.IsNullable = true; colvarLongitudeWest.IsPrimaryKey = false; colvarLongitudeWest.IsForeignKey = false; colvarLongitudeWest.IsReadOnly = false; schema.Columns.Add(colvarLongitudeWest); TableSchema.TableColumn colvarLongitudeEast = new TableSchema.TableColumn(schema); colvarLongitudeEast.ColumnName = "LongitudeEast"; colvarLongitudeEast.DataType = DbType.Double; colvarLongitudeEast.MaxLength = 0; colvarLongitudeEast.AutoIncrement = false; colvarLongitudeEast.IsNullable = true; colvarLongitudeEast.IsPrimaryKey = false; colvarLongitudeEast.IsForeignKey = false; colvarLongitudeEast.IsReadOnly = false; schema.Columns.Add(colvarLongitudeEast); TableSchema.TableColumn colvarElevationMinimum = new TableSchema.TableColumn(schema); colvarElevationMinimum.ColumnName = "ElevationMinimum"; colvarElevationMinimum.DataType = DbType.Double; colvarElevationMinimum.MaxLength = 0; colvarElevationMinimum.AutoIncrement = false; colvarElevationMinimum.IsNullable = true; colvarElevationMinimum.IsPrimaryKey = false; colvarElevationMinimum.IsForeignKey = false; colvarElevationMinimum.IsReadOnly = false; schema.Columns.Add(colvarElevationMinimum); TableSchema.TableColumn colvarElevationMaximum = new TableSchema.TableColumn(schema); colvarElevationMaximum.ColumnName = "ElevationMaximum"; colvarElevationMaximum.DataType = DbType.Double; colvarElevationMaximum.MaxLength = 0; colvarElevationMaximum.AutoIncrement = false; colvarElevationMaximum.IsNullable = true; colvarElevationMaximum.IsPrimaryKey = false; colvarElevationMaximum.IsForeignKey = false; colvarElevationMaximum.IsReadOnly = false; schema.Columns.Add(colvarElevationMaximum); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("vStationDatasets",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VStationDataset() { SetSQLProps(); SetDefaults(); MarkNew(); } public VStationDataset(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VStationDataset(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VStationDataset(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public long? Id { get { return GetColumnValue<long?>("ID"); } set { SetColumnValue("ID", value); } } [XmlAttribute("OrganisationID")] [Bindable(true)] public Guid? OrganisationID { get { return GetColumnValue<Guid?>("OrganisationID"); } set { SetColumnValue("OrganisationID", value); } } [XmlAttribute("OrganisationCode")] [Bindable(true)] public string OrganisationCode { get { return GetColumnValue<string>("OrganisationCode"); } set { SetColumnValue("OrganisationCode", value); } } [XmlAttribute("OrganisationName")] [Bindable(true)] public string OrganisationName { get { return GetColumnValue<string>("OrganisationName"); } set { SetColumnValue("OrganisationName", value); } } [XmlAttribute("OrganisationDescription")] [Bindable(true)] public string OrganisationDescription { get { return GetColumnValue<string>("OrganisationDescription"); } set { SetColumnValue("OrganisationDescription", value); } } [XmlAttribute("OrganisationUrl")] [Bindable(true)] public string OrganisationUrl { get { return GetColumnValue<string>("OrganisationUrl"); } set { SetColumnValue("OrganisationUrl", value); } } [XmlAttribute("ProgrammeID")] [Bindable(true)] public Guid? ProgrammeID { get { return GetColumnValue<Guid?>("ProgrammeID"); } set { SetColumnValue("ProgrammeID", value); } } [XmlAttribute("ProgrammeCode")] [Bindable(true)] public string ProgrammeCode { get { return GetColumnValue<string>("ProgrammeCode"); } set { SetColumnValue("ProgrammeCode", value); } } [XmlAttribute("ProgrammeName")] [Bindable(true)] public string ProgrammeName { get { return GetColumnValue<string>("ProgrammeName"); } set { SetColumnValue("ProgrammeName", value); } } [XmlAttribute("ProgrammeDescription")] [Bindable(true)] public string ProgrammeDescription { get { return GetColumnValue<string>("ProgrammeDescription"); } set { SetColumnValue("ProgrammeDescription", value); } } [XmlAttribute("ProgrammeUrl")] [Bindable(true)] public string ProgrammeUrl { get { return GetColumnValue<string>("ProgrammeUrl"); } set { SetColumnValue("ProgrammeUrl", value); } } [XmlAttribute("ProjectID")] [Bindable(true)] public Guid? ProjectID { get { return GetColumnValue<Guid?>("ProjectID"); } set { SetColumnValue("ProjectID", value); } } [XmlAttribute("ProjectCode")] [Bindable(true)] public string ProjectCode { get { return GetColumnValue<string>("ProjectCode"); } set { SetColumnValue("ProjectCode", value); } } [XmlAttribute("ProjectName")] [Bindable(true)] public string ProjectName { get { return GetColumnValue<string>("ProjectName"); } set { SetColumnValue("ProjectName", value); } } [XmlAttribute("ProjectDescription")] [Bindable(true)] public string ProjectDescription { get { return GetColumnValue<string>("ProjectDescription"); } set { SetColumnValue("ProjectDescription", value); } } [XmlAttribute("ProjectUrl")] [Bindable(true)] public string ProjectUrl { get { return GetColumnValue<string>("ProjectUrl"); } set { SetColumnValue("ProjectUrl", value); } } [XmlAttribute("SiteID")] [Bindable(true)] public Guid SiteID { get { return GetColumnValue<Guid>("SiteID"); } set { SetColumnValue("SiteID", value); } } [XmlAttribute("SiteCode")] [Bindable(true)] public string SiteCode { get { return GetColumnValue<string>("SiteCode"); } set { SetColumnValue("SiteCode", value); } } [XmlAttribute("SiteName")] [Bindable(true)] public string SiteName { get { return GetColumnValue<string>("SiteName"); } set { SetColumnValue("SiteName", value); } } [XmlAttribute("SiteDescription")] [Bindable(true)] public string SiteDescription { get { return GetColumnValue<string>("SiteDescription"); } set { SetColumnValue("SiteDescription", value); } } [XmlAttribute("StationID")] [Bindable(true)] public Guid StationID { get { return GetColumnValue<Guid>("StationID"); } set { SetColumnValue("StationID", value); } } [XmlAttribute("StationCode")] [Bindable(true)] public string StationCode { get { return GetColumnValue<string>("StationCode"); } set { SetColumnValue("StationCode", value); } } [XmlAttribute("StationName")] [Bindable(true)] public string StationName { get { return GetColumnValue<string>("StationName"); } set { SetColumnValue("StationName", value); } } [XmlAttribute("StationDescription")] [Bindable(true)] public string StationDescription { get { return GetColumnValue<string>("StationDescription"); } set { SetColumnValue("StationDescription", value); } } [XmlAttribute("PhenomenonID")] [Bindable(true)] public Guid PhenomenonID { get { return GetColumnValue<Guid>("PhenomenonID"); } set { SetColumnValue("PhenomenonID", value); } } [XmlAttribute("PhenomenonCode")] [Bindable(true)] public string PhenomenonCode { get { return GetColumnValue<string>("PhenomenonCode"); } set { SetColumnValue("PhenomenonCode", value); } } [XmlAttribute("PhenomenonName")] [Bindable(true)] public string PhenomenonName { get { return GetColumnValue<string>("PhenomenonName"); } set { SetColumnValue("PhenomenonName", value); } } [XmlAttribute("PhenomenonDescription")] [Bindable(true)] public string PhenomenonDescription { get { return GetColumnValue<string>("PhenomenonDescription"); } set { SetColumnValue("PhenomenonDescription", value); } } [XmlAttribute("PhenomenonOfferingID")] [Bindable(true)] public Guid PhenomenonOfferingID { get { return GetColumnValue<Guid>("PhenomenonOfferingID"); } set { SetColumnValue("PhenomenonOfferingID", value); } } [XmlAttribute("OfferingID")] [Bindable(true)] public Guid OfferingID { get { return GetColumnValue<Guid>("OfferingID"); } set { SetColumnValue("OfferingID", value); } } [XmlAttribute("OfferingCode")] [Bindable(true)] public string OfferingCode { get { return GetColumnValue<string>("OfferingCode"); } set { SetColumnValue("OfferingCode", value); } } [XmlAttribute("OfferingName")] [Bindable(true)] public string OfferingName { get { return GetColumnValue<string>("OfferingName"); } set { SetColumnValue("OfferingName", value); } } [XmlAttribute("OfferingDescription")] [Bindable(true)] public string OfferingDescription { get { return GetColumnValue<string>("OfferingDescription"); } set { SetColumnValue("OfferingDescription", value); } } [XmlAttribute("PhenomenonUOMID")] [Bindable(true)] public Guid PhenomenonUOMID { get { return GetColumnValue<Guid>("PhenomenonUOMID"); } set { SetColumnValue("PhenomenonUOMID", value); } } [XmlAttribute("UnitOfMeasureID")] [Bindable(true)] public Guid UnitOfMeasureID { get { return GetColumnValue<Guid>("UnitOfMeasureID"); } set { SetColumnValue("UnitOfMeasureID", value); } } [XmlAttribute("UnitOfMeasureCode")] [Bindable(true)] public string UnitOfMeasureCode { get { return GetColumnValue<string>("UnitOfMeasureCode"); } set { SetColumnValue("UnitOfMeasureCode", value); } } [XmlAttribute("UnitOfMeasureUnit")] [Bindable(true)] public string UnitOfMeasureUnit { get { return GetColumnValue<string>("UnitOfMeasureUnit"); } set { SetColumnValue("UnitOfMeasureUnit", value); } } [XmlAttribute("UnitOfMeasureSymbol")] [Bindable(true)] public string UnitOfMeasureSymbol { get { return GetColumnValue<string>("UnitOfMeasureSymbol"); } set { SetColumnValue("UnitOfMeasureSymbol", value); } } [XmlAttribute("Count")] [Bindable(true)] public int? Count { get { return GetColumnValue<int?>("Count"); } set { SetColumnValue("Count", value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>("StartDate"); } set { SetColumnValue("StartDate", value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>("EndDate"); } set { SetColumnValue("EndDate", value); } } [XmlAttribute("LatitudeNorth")] [Bindable(true)] public double? LatitudeNorth { get { return GetColumnValue<double?>("LatitudeNorth"); } set { SetColumnValue("LatitudeNorth", value); } } [XmlAttribute("LatitudeSouth")] [Bindable(true)] public double? LatitudeSouth { get { return GetColumnValue<double?>("LatitudeSouth"); } set { SetColumnValue("LatitudeSouth", value); } } [XmlAttribute("LongitudeWest")] [Bindable(true)] public double? LongitudeWest { get { return GetColumnValue<double?>("LongitudeWest"); } set { SetColumnValue("LongitudeWest", value); } } [XmlAttribute("LongitudeEast")] [Bindable(true)] public double? LongitudeEast { get { return GetColumnValue<double?>("LongitudeEast"); } set { SetColumnValue("LongitudeEast", value); } } [XmlAttribute("ElevationMinimum")] [Bindable(true)] public double? ElevationMinimum { get { return GetColumnValue<double?>("ElevationMinimum"); } set { SetColumnValue("ElevationMinimum", value); } } [XmlAttribute("ElevationMaximum")] [Bindable(true)] public double? ElevationMaximum { get { return GetColumnValue<double?>("ElevationMaximum"); } set { SetColumnValue("ElevationMaximum", value); } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string OrganisationID = @"OrganisationID"; public static string OrganisationCode = @"OrganisationCode"; public static string OrganisationName = @"OrganisationName"; public static string OrganisationDescription = @"OrganisationDescription"; public static string OrganisationUrl = @"OrganisationUrl"; public static string ProgrammeID = @"ProgrammeID"; public static string ProgrammeCode = @"ProgrammeCode"; public static string ProgrammeName = @"ProgrammeName"; public static string ProgrammeDescription = @"ProgrammeDescription"; public static string ProgrammeUrl = @"ProgrammeUrl"; public static string ProjectID = @"ProjectID"; public static string ProjectCode = @"ProjectCode"; public static string ProjectName = @"ProjectName"; public static string ProjectDescription = @"ProjectDescription"; public static string ProjectUrl = @"ProjectUrl"; public static string SiteID = @"SiteID"; public static string SiteCode = @"SiteCode"; public static string SiteName = @"SiteName"; public static string SiteDescription = @"SiteDescription"; public static string StationID = @"StationID"; public static string StationCode = @"StationCode"; public static string StationName = @"StationName"; public static string StationDescription = @"StationDescription"; public static string PhenomenonID = @"PhenomenonID"; public static string PhenomenonCode = @"PhenomenonCode"; public static string PhenomenonName = @"PhenomenonName"; public static string PhenomenonDescription = @"PhenomenonDescription"; public static string PhenomenonOfferingID = @"PhenomenonOfferingID"; public static string OfferingID = @"OfferingID"; public static string OfferingCode = @"OfferingCode"; public static string OfferingName = @"OfferingName"; public static string OfferingDescription = @"OfferingDescription"; public static string PhenomenonUOMID = @"PhenomenonUOMID"; public static string UnitOfMeasureID = @"UnitOfMeasureID"; public static string UnitOfMeasureCode = @"UnitOfMeasureCode"; public static string UnitOfMeasureUnit = @"UnitOfMeasureUnit"; public static string UnitOfMeasureSymbol = @"UnitOfMeasureSymbol"; public static string Count = @"Count"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string LatitudeNorth = @"LatitudeNorth"; public static string LatitudeSouth = @"LatitudeSouth"; public static string LongitudeWest = @"LongitudeWest"; public static string LongitudeEast = @"LongitudeEast"; public static string ElevationMinimum = @"ElevationMinimum"; public static string ElevationMaximum = @"ElevationMaximum"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace ConnectQl.Parser.Ast.Visitors { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using Expressions; using JetBrains.Annotations; using Sources; using Statements; using Targets; /// <summary> /// The node visitor. /// </summary> internal abstract class NodeVisitor { /// <summary> /// Visits the node and ensures the result is of type <typeparamref name="T"/>. When node is <c>null</c>, returns /// <c>null</c>. /// </summary> /// <typeparam name="T"> /// The type of the result. /// </typeparam> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <typeparamref name="T"/>. /// </returns> [CanBeNull] [DebuggerHidden] protected internal virtual T Visit<T>([CanBeNull] T node) where T : Node { if (node == null) { return null; } var result = (T)node.Accept(this); if (result == null) { throw new InvalidOperationException($"Node was not a valid {typeof(T).Name} node."); } return result; } /// <summary> /// Visits a collection of nodes. /// </summary> /// <param name="list"> /// The list to visit. /// </param> /// <typeparam name="T"> /// The type of the nodes. /// </typeparam> /// <returns> /// The list, or a copy of the list if any of the elements was changed. /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown when a visitor doesn't return the correct type. /// </exception> [NotNull] protected internal virtual ReadOnlyCollection<T> Visit<T>([NotNull] ReadOnlyCollection<T> list) where T : Node { List<T> result = null; for (var i = 0; i < list.Count; i++) { var item = this.Visit(list[i]); if (item == null && list[i] != null) { throw new InvalidOperationException($"Item {i} was not a {typeof(T).Name}."); } if (result == null && item != list[i]) { result = new List<T>(list.Count); for (var j = 0; j < i; j++) { result.Add(list[j]); } } result?.Add(item); } return result == null ? list : new ReadOnlyCollection<T>(result); } /// <summary> /// Visits a <see cref="AliasedConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitAliasedSqlExpression([NotNull] AliasedConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="ApplySource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitApplySource([NotNull] ApplySource node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="BinaryConnectQlExpression"/> expression. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitBinarySqlExpression([NotNull] BinaryConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="Block"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitBlock([NotNull] Block node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="ConstConnectQlExpression"/> expression. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitConstSqlExpression([NotNull] ConstConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="DeclareJobStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitDeclareJobStatement([NotNull] DeclareJobStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a declare statement. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitDeclareStatement([NotNull] DeclareStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="FieldReferenceConnectQlExpression"/> expression. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitFieldReferenceSqlExpression([NotNull] FieldReferenceConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="FunctionCallConnectQlExpression"/> expression. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitFunctionCallSqlExpression([NotNull] FunctionCallConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="FunctionSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitFunctionSource([NotNull] FunctionSource node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="FunctionTarget"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitFunctionTarget([NotNull] FunctionTarget node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="ImportPluginStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitImportPluginStatement([NotNull] ImportPluginStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="ImportStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitImportStatement([NotNull] ImportStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="InsertStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitInsertStatement([NotNull] InsertStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="JoinSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitJoinSource([NotNull] JoinSource node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="OrderByConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitOrderBySqlExpression([NotNull] OrderByConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="SelectFromStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitSelectFromStatement([NotNull] SelectFromStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="SelectSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitSelectSource([NotNull] SelectSource node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="SelectUnionStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitSelectUnionStatement([NotNull] SelectUnionStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="Trigger"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitTrigger([NotNull] Trigger node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="TriggerStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitTriggerStatement([NotNull] TriggerStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="UnaryConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitUnarySqlExpression([NotNull] UnaryConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="UseStatement"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitUseStatement([NotNull] UseStatement node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="VariableDeclaration"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitVariableDeclaration([NotNull] VariableDeclaration node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="VariableSource"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitVariableSource([NotNull] VariableSource node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="VariableConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitVariableSqlExpression([NotNull] VariableConnectQlExpression node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="VariableTarget"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitVariableTarget([NotNull] VariableTarget node) { return node.VisitChildren(this); } /// <summary> /// Visits a <see cref="WildcardConnectQlExpression"/>. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The node, or a new version of the node. /// </returns> protected internal virtual Node VisitWildCardSqlExpression([NotNull] WildcardConnectQlExpression node) { return node.VisitChildren(this); } } }
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; namespace Sanford.Multimedia.Midi { /// <summary> /// Represents a collection of Tracks. /// </summary> public sealed class Sequence : IComponent, ICollection<Track> { #region Sequence Members #region Fields // The collection of Tracks for the Sequence. private List<Track> tracks = new List<Track>(); // The Sequence's MIDI file properties. private MidiFileProperties properties = new MidiFileProperties(); private BackgroundWorker loadWorker = new BackgroundWorker(); private BackgroundWorker saveWorker = new BackgroundWorker(); private ISite site = null; private bool disposed = false; #endregion #region Events public event EventHandler<AsyncCompletedEventArgs> LoadCompleted; public event ProgressChangedEventHandler LoadProgressChanged; public event EventHandler<AsyncCompletedEventArgs> SaveCompleted; public event ProgressChangedEventHandler SaveProgressChanged; #endregion #region Construction /// <summary> /// Initializes a new instance of the Sequence class. /// </summary> public Sequence() { InitializeBackgroundWorkers(); } /// <summary> /// Initializes a new instance of the Sequence class with the specified division. /// </summary> /// <param name="division"> /// The Sequence's division value. /// </param> public Sequence(int division) { properties.Division = division; properties.Format = 1; InitializeBackgroundWorkers(); } /// <summary> /// Initializes a new instance of the Sequence class with the specified /// file name of the MIDI file to load. /// </summary> /// <param name="fileName"> /// The name of the MIDI file to load. /// </param> public Sequence(string fileName) { InitializeBackgroundWorkers(); Load(fileName); } private void InitializeBackgroundWorkers() { loadWorker.DoWork += new DoWorkEventHandler(LoadDoWork); loadWorker.ProgressChanged += new ProgressChangedEventHandler(OnLoadProgressChanged); loadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnLoadCompleted); loadWorker.WorkerReportsProgress = true; saveWorker.DoWork += new DoWorkEventHandler(SaveDoWork); saveWorker.ProgressChanged += new ProgressChangedEventHandler(OnSaveProgressChanged); saveWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnSaveCompleted); saveWorker.WorkerReportsProgress = true; } #endregion #region Methods /// <summary> /// Loads a MIDI file into the Sequence. /// </summary> /// <param name="fileName"> /// The MIDI file's name. /// </param> public void Load(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); using(stream) { MidiFileProperties newProperties = new MidiFileProperties(); TrackReader reader = new TrackReader(); List<Track> newTracks = new List<Track>(); newProperties.Read(stream); for(int i = 0; i < newProperties.TrackCount; i++) { reader.Read(stream); newTracks.Add(reader.Track); } properties = newProperties; tracks = newTracks; } #region Ensure Debug.Assert(Count == properties.TrackCount); #endregion } public void LoadAsync(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion loadWorker.RunWorkerAsync(fileName); } public void LoadAsyncCancel() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion loadWorker.CancelAsync(); } /// <summary> /// Saves the Sequence as a MIDI file. /// </summary> /// <param name="fileName"> /// The name to use for saving the MIDI file. /// </param> public void Save(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); using(stream) { properties.Write(stream); TrackWriter writer = new TrackWriter(); foreach(Track trk in tracks) { writer.Track = trk; writer.Write(stream); } } } public void SaveAsync(string fileName) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } else if(fileName == null) { throw new ArgumentNullException("fileName"); } #endregion saveWorker.RunWorkerAsync(fileName); } public void SaveAsyncCancel() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion saveWorker.CancelAsync(); } /// <summary> /// Gets the length in ticks of the Sequence. /// </summary> /// <returns> /// The length in ticks of the Sequence. /// </returns> /// <remarks> /// The length in ticks of the Sequence is represented by the Track /// with the longest length. /// </remarks> public int GetLength() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion int length = 0; foreach(Track t in this) { if(t.Length > length) { length = t.Length; } } return length; } private void OnLoadCompleted(object sender, RunWorkerCompletedEventArgs e) { EventHandler<AsyncCompletedEventArgs> handler = LoadCompleted; if(handler != null) { handler(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, null)); } } private void OnLoadProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressChangedEventHandler handler = LoadProgressChanged; if(handler != null) { handler(this, e); } } private void LoadDoWork(object sender, DoWorkEventArgs e) { string fileName = (string)e.Argument; FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); using(stream) { MidiFileProperties newProperties = new MidiFileProperties(); TrackReader reader = new TrackReader(); List<Track> newTracks = new List<Track>(); newProperties.Read(stream); float percentage; for(int i = 0; i < newProperties.TrackCount && !loadWorker.CancellationPending; i++) { reader.Read(stream); newTracks.Add(reader.Track); percentage = (i + 1f) / newProperties.TrackCount; loadWorker.ReportProgress((int)(100 * percentage)); } if(loadWorker.CancellationPending) { e.Cancel = true; } else { properties = newProperties; tracks = newTracks; } } } private void OnSaveCompleted(object sender, RunWorkerCompletedEventArgs e) { EventHandler<AsyncCompletedEventArgs> handler = SaveCompleted; if(handler != null) { handler(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, null)); } } private void OnSaveProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressChangedEventHandler handler = SaveProgressChanged; if(handler != null) { handler(this, e); } } private void SaveDoWork(object sender, DoWorkEventArgs e) { string fileName = (string)e.Argument; FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); using(stream) { properties.Write(stream); TrackWriter writer = new TrackWriter(); float percentage; for(int i = 0; i < tracks.Count && !saveWorker.CancellationPending; i++) { writer.Track = tracks[i]; writer.Write(stream); percentage = (i + 1f) / properties.TrackCount; saveWorker.ReportProgress((int)(100 * percentage)); } if(saveWorker.CancellationPending) { e.Cancel = true; } } } #endregion #region Properties /// <summary> /// Gets the Track at the specified index. /// </summary> /// <param name="index"> /// The index of the Track to get. /// </param> /// <returns> /// The Track at the specified index. /// </returns> public Track this[int index] { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", index, "Sequence index out of range."); } #endregion return tracks[index]; } } /// <summary> /// Gets the Sequence's division value. /// </summary> public int Division { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return properties.Division; } } /// <summary> /// Gets or sets the Sequence's format value. /// </summary> public int Format { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return properties.Format; } set { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(IsBusy) { throw new InvalidOperationException(); } #endregion properties.Format = value; } } /// <summary> /// Gets the Sequence's type. /// </summary> public SequenceType SequenceType { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return properties.SequenceType; } } public bool IsBusy { get { return loadWorker.IsBusy || saveWorker.IsBusy; } } #endregion #endregion #region ICollection<Track> Members public void Add(Track item) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } else if(item == null) { throw new ArgumentNullException("item"); } #endregion tracks.Add(item); properties.TrackCount = tracks.Count; } public void Clear() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion tracks.Clear(); properties.TrackCount = tracks.Count; } public bool Contains(Track item) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.Contains(item); } public void CopyTo(Track[] array, int arrayIndex) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion tracks.CopyTo(array, arrayIndex); } public int Count { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.Count; } } public bool IsReadOnly { get { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return false; } } public bool Remove(Track item) { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion bool result = tracks.Remove(item); if(result) { properties.TrackCount = tracks.Count; } return result; } #endregion #region IEnumerable<Track> Members public IEnumerator<Track> GetEnumerator() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { #region Require if(disposed) { throw new ObjectDisposedException("Sequence"); } #endregion return tracks.GetEnumerator(); } #endregion #region IComponent Members public event EventHandler Disposed; public ISite Site { get { return site; } set { site = value; } } #endregion #region IDisposable Members public void Dispose() { #region Guard if(disposed) { return; } #endregion loadWorker.Dispose(); saveWorker.Dispose(); disposed = true; EventHandler handler = Disposed; if(handler != null) { handler(this, EventArgs.Empty); } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using Alist.Common; namespace Alist.Error { /// <summary> /// contains several exceptions /// </summary> /// <remarks>usually not raises, but passes, in situation if some operation failed, may be usefull to store all exception raised in that class</remarks> /// <seealso cref="ExecuteReport" /> public class MultyException : Exception { /// <summary> /// exception message /// </summary> protected internal const string DefaultMessage = "multiply exceptions"; public List<Exception> Error { get; protected internal set; } /// <summary> /// creates multyException with specified message and exceptios /// </summary> public MultyException(string message, params Exception[] error) : base(message) { this.Error = new List<Exception>(error ?? new Exception[] { }); } /// <summary> /// creates multyexception with specified message /// </summary> public MultyException(string message) : this(message, error: null) { } /// <summary> /// creates multy exception with specified exception /// </summary> /// <param name="exception"></param> public MultyException(params Exception[] exception) : this(message: MultyException.DefaultMessage, error: exception) { } protected internal MultyException(MultyException exception) : this(message: exception?.Message, error: exception?.Error?.ToArray()) { } /// <summary> /// indicates if contains any exceptions /// </summary> public bool HasErrors => this.Error.Any(); /// <summary> /// returns all exceptions /// </summary> /// <seealso cref="Exception.Data"/> public override IDictionary Data { get { Dictionary<int, Exception> result = new Dictionary<int, Exception> { }; for (int i = 0; i < this.Error.Count; i++) { result.Add(i, this.Error[i]); } return result; } } public void Add(MultyException exception) { if (exception == null) { throw new ArgumentNullException( paramName: "exception", message: "Can't add null to MultyException" ); } this.Error.AddRange(exception?.Error ?? new List<Exception> { }); } public void Add(Exception exception) { if (exception == null) { throw new ArgumentNullException( paramName: "exception", message: "Can't add null to MultyException" ); } this.Error.Add(exception ?? new Exception()); } public void Remove(Exception exception) => this.Error = this.Error.Where(x => !x.Equals(exception)).ToList(); public void Remove(List<Exception> exception) => exception.ForEach(x => this.Remove(x)); protected internal FilteredList<Exception> FilterByTypeOrDerived<T>(bool isDerived) { List<Exception> resultIs = new List<Exception>(); List<Exception> resultNot = new List<Exception>(); foreach (Exception exception in this.Error) { if ((isDerived) ? Helper.IsTypeOrDerived<T>(exception) : Helper.IsType<T>(exception)) { resultIs.Add(exception); } else { resultNot.Add(exception); } } return new FilteredList<Exception>(passed: resultIs, failed: resultNot); } public FilteredList<Exception> FilterByType<T>() => this.FilterByTypeOrDerived<T>(false); public FilteredList<Exception> FilterByDerivedType<T>() => this.FilterByTypeOrDerived<T>(true); /// <summary> /// raise this exception /// </summary> /// <remarks>only raises exception if <see cref="HasErrors" /> is true</remarks> public void Raise() { if (this.HasErrors) { throw this; } } /// <summary> /// creates new Multy exception including exceptions of other two /// </summary> /// <seealso cref="operator +(MultyException, Exception)"/> public static MultyException operator +( MultyException exception1, MultyException exception2) { MultyException result = new MultyException(exception1?.Message ?? exception2?.Message); result.Add(exception1); result.Add(exception2); return result; } /// <summary> /// creates new Multy exception with exceptions of specified multyException and /// </summary> /// <seealso cref="operator +(MultyException, MultyException)"/> public static MultyException operator +( Exception exception1, MultyException exception2) => new MultyException(exception1) + exception2; /// <summary> /// creates new Multy exception including exception of operators /// </summary> /// <seealso cref="operator +(MultyException, MultyException)"/> public static MultyException operator +( MultyException exception1, Exception exception2) => exception1 + new MultyException(exception2); /// <summary> /// add new exception with specified message /// </summary> /// <seealso cref="operator +(MultyException, Exception)"/> public static MultyException operator +( MultyException exception, string exceptionMessage) => exception + new Exception(exceptionMessage); /// <summary> /// deletes specified exceptions /// </summary> /// <seealso cref="operator +(MultyException, Exception)"/> public static MultyException operator -( MultyException multyException1, MultyException multyException2) { MultyException result = new MultyException(multyException1); if (multyException2 == null) { return result; } result.Remove(multyException2.Error); return result; } /// <summary> /// deletes specified exceptions /// </summary> /// <seealso cref="operator +(MultyException, Exception)"/> public static MultyException operator -( MultyException multyException, Exception exception) => multyException - new MultyException(exception); /// <summary> /// returns string version of exception for human observation /// </summary> public override string ToString() // Yeah, I know... You should skip these lines for your own sake { StringBuilder result = new StringBuilder(); result.Append(base.ToString()); result.Append($"\n\n\nMultyExcepton: {this.Message}"); if (this.HasErrors) { result.Append(" error(s): \n"); this.Error.ForEach(x => result.Append($"\n\n --- --- --- error: \n {x.ToString()}")); } result.Append("\n --- --- --- multy exception end\n"); return result.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Security.Cryptography.Encryption.Aes.Tests { using Aes = System.Security.Cryptography.Aes; public class AesContractTests { [Fact] public static void VerifyDefaults() { using (Aes aes = AesFactory.Create()) { Assert.Equal(128, aes.BlockSize); Assert.Equal(256, aes.KeySize); Assert.Equal(CipherMode.CBC, aes.Mode); Assert.Equal(PaddingMode.PKCS7, aes.Padding); } } [Fact] public static void LegalBlockSizes() { using (Aes aes = AesFactory.Create()) { KeySizes[] blockSizes = aes.LegalBlockSizes; Assert.NotNull(blockSizes); Assert.Equal(1, blockSizes.Length); KeySizes blockSizeLimits = blockSizes[0]; Assert.Equal(128, blockSizeLimits.MinSize); Assert.Equal(128, blockSizeLimits.MaxSize); Assert.Equal(0, blockSizeLimits.SkipSize); } } [Fact] public static void LegalKeySizes() { using (Aes aes = AesFactory.Create()) { KeySizes[] keySizes = aes.LegalKeySizes; Assert.NotNull(keySizes); Assert.Equal(1, keySizes.Length); KeySizes keySizeLimits = keySizes[0]; Assert.Equal(128, keySizeLimits.MinSize); Assert.Equal(256, keySizeLimits.MaxSize); Assert.Equal(64, keySizeLimits.SkipSize); } } [Theory] [InlineData(64, false)] // too small [InlineData(129, false)] // in valid range but not valid increment [InlineData(384, false)] // too large // Skip on netfx because change is not ported https://github.com/dotnet/corefx/issues/18690 [InlineData(536870928, true)] // number of bits overflows and wraps around to a valid size public static void InvalidKeySizes(int invalidKeySize, bool skipOnNetfx) { if (skipOnNetfx && PlatformDetection.IsFullFramework) return; using (Aes aes = AesFactory.Create()) { // Test KeySize property Assert.Throws<CryptographicException>(() => aes.KeySize = invalidKeySize); // Test passing a key to CreateEncryptor and CreateDecryptor aes.GenerateIV(); byte[] iv = aes.IV; byte[] key; try { key = new byte[invalidKeySize]; } catch (OutOfMemoryException) // in case there isn't enough memory at test-time to allocate the large array { return; } Exception e = Record.Exception(() => aes.CreateEncryptor(key, iv)); Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}"); e = Record.Exception(() => aes.CreateDecryptor(key, iv)); Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}"); } } [Theory] [InlineData(64, false)] // smaller than default BlockSize [InlineData(129, false)] // larger than default BlockSize // Skip on netfx because change is not ported https://github.com/dotnet/corefx/issues/18690 [InlineData(536870928, true)] // number of bits overflows and wraps around to default BlockSize public static void InvalidIVSizes(int invalidIvSize, bool skipOnNetfx) { if (skipOnNetfx && PlatformDetection.IsFullFramework) return; using (Aes aes = AesFactory.Create()) { aes.GenerateKey(); byte[] key = aes.Key; byte[] iv; try { iv = new byte[invalidIvSize]; } catch (OutOfMemoryException) // in case there isn't enough memory at test-time to allocate the large array { return; } Exception e = Record.Exception(() => aes.CreateEncryptor(key, iv)); Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}"); e = Record.Exception(() => aes.CreateDecryptor(key, iv)); Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}"); } } [Fact] public static void VerifyKeyGeneration_Default() { using (Aes aes = AesFactory.Create()) { VerifyKeyGeneration(aes); } } [Fact] public static void VerifyKeyGeneration_128() { using (Aes aes = AesFactory.Create()) { aes.KeySize = 128; VerifyKeyGeneration(aes); } } [Fact] public static void VerifyKeyGeneration_192() { using (Aes aes = AesFactory.Create()) { aes.KeySize = 192; VerifyKeyGeneration(aes); } } [Fact] public static void VerifyKeyGeneration_256() { using (Aes aes = AesFactory.Create()) { aes.KeySize = 256; VerifyKeyGeneration(aes); } } [Fact] public static void VerifyIVGeneration() { using (Aes aes = AesFactory.Create()) { int blockSize = aes.BlockSize; aes.GenerateIV(); byte[] iv = aes.IV; Assert.NotNull(iv); Assert.Equal(blockSize, aes.BlockSize); Assert.Equal(blockSize, iv.Length * 8); // Standard randomness caveat: There's a very low chance that the generated IV -is- // all zeroes. This works out to 1/2^128, which is more unlikely than 1/10^38. Assert.NotEqual(new byte[iv.Length], iv); } } [Fact] public static void ValidateEncryptorProperties() { using (Aes aes = AesFactory.Create()) { ValidateTransformProperties(aes, aes.CreateEncryptor()); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In NetFX AesCryptoServiceProvider requires a set key and throws otherwise. See #19023.")] public static void ValidateDecryptorProperties() { using (Aes aes = AesFactory.Create()) { ValidateTransformProperties(aes, aes.CreateDecryptor()); } } [Fact] public static void CreateTransformExceptions() { byte[] key; byte[] iv; using (Aes aes = AesFactory.Create()) { aes.GenerateKey(); aes.GenerateIV(); key = aes.Key; iv = aes.IV; } using (Aes aes = AesFactory.Create()) { aes.Mode = CipherMode.CBC; Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, iv)); Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, null)); Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, iv)); Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, null)); // CBC requires an IV. Assert.Throws<CryptographicException>(() => aes.CreateEncryptor(key, null)); Assert.Throws<CryptographicException>(() => aes.CreateDecryptor(key, null)); } using (Aes aes = AesFactory.Create()) { aes.Mode = CipherMode.ECB; Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, iv)); Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, null)); Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, iv)); Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, null)); // ECB will accept an IV (but ignore it), and doesn't require it. using (ICryptoTransform didNotThrow = aes.CreateEncryptor(key, null)) { Assert.NotNull(didNotThrow); } using (ICryptoTransform didNotThrow = aes.CreateDecryptor(key, null)) { Assert.NotNull(didNotThrow); } } } [Fact] public static void ValidateOffsetAndCount() { using (Aes aes = AesFactory.Create()) { aes.GenerateKey(); aes.GenerateIV(); // aes.BlockSize is in bits, new byte[] is in bytes, so we have 8 blocks. byte[] full = new byte[aes.BlockSize]; int blockByteCount = aes.BlockSize / 8; for (int i = 0; i < full.Length; i++) { full[i] = unchecked((byte)i); } byte[] firstBlock = new byte[blockByteCount]; byte[] middleHalf = new byte[4 * blockByteCount]; // Copy the first blockBytes of full into firstBlock. Buffer.BlockCopy(full, 0, firstBlock, 0, blockByteCount); // [Skip][Skip][Take][Take][Take][Take][Skip][Skip] => "middle half" Buffer.BlockCopy(full, 2 * blockByteCount, middleHalf, 0, middleHalf.Length); byte[] firstBlockEncrypted; byte[] firstBlockEncryptedFromCount; byte[] middleHalfEncrypted; byte[] middleHalfEncryptedFromOffsetAndCount; using (ICryptoTransform encryptor = aes.CreateEncryptor()) { firstBlockEncrypted = encryptor.TransformFinalBlock(firstBlock, 0, firstBlock.Length); } using (ICryptoTransform encryptor = aes.CreateEncryptor()) { firstBlockEncryptedFromCount = encryptor.TransformFinalBlock(full, 0, firstBlock.Length); } using (ICryptoTransform encryptor = aes.CreateEncryptor()) { middleHalfEncrypted = encryptor.TransformFinalBlock(middleHalf, 0, middleHalf.Length); } using (ICryptoTransform encryptor = aes.CreateEncryptor()) { middleHalfEncryptedFromOffsetAndCount = encryptor.TransformFinalBlock(full, 2 * blockByteCount, middleHalf.Length); } Assert.Equal(firstBlockEncrypted, firstBlockEncryptedFromCount); Assert.Equal(middleHalfEncrypted, middleHalfEncryptedFromOffsetAndCount); } } private static void ValidateTransformProperties(Aes aes, ICryptoTransform transform) { Assert.NotNull(transform); Assert.Equal(aes.BlockSize, transform.InputBlockSize * 8); Assert.Equal(aes.BlockSize, transform.OutputBlockSize * 8); Assert.True(transform.CanTransformMultipleBlocks); } private static void VerifyKeyGeneration(Aes aes) { int keySize = aes.KeySize; aes.GenerateKey(); byte[] key = aes.Key; Assert.NotNull(key); Assert.Equal(keySize, aes.KeySize); Assert.Equal(keySize, key.Length * 8); // Standard randomness caveat: There's a very low chance that the generated key -is- // all zeroes. For a 128-bit key this is 1/2^128, which is more unlikely than 1/10^38. Assert.NotEqual(new byte[key.Length], key); } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.Tasks; using Microsoft.IO; namespace Cassandra.Connections { /// <summary> /// Represents a Tcp connection to a host. /// It emits Read and WriteCompleted events when data is received. /// Similar to Netty's Channel or Node.js's net.Socket /// It handles TLS validation and encryption when required. /// </summary> internal class TcpSocket : ITcpSocket { public static readonly Logger Logger = new Logger(typeof(TcpSocket)); private readonly Socket _socket; private readonly SocketAsyncEventArgs _receiveSocketEvent; private readonly SocketAsyncEventArgs _sendSocketEvent; private byte[] _receiveBuffer; private Action _writeFlushCallback; private volatile Stream _socketStream; private volatile bool _isClosing; public IConnectionEndPoint EndPoint { get; protected set; } public SocketOptions Options { get; protected set; } public SSLOptions SSLOptions { get; set; } /// <summary> /// Event that gets fired when new data is received. /// </summary> public event Action<byte[], int> Read; /// <summary> /// Event that gets fired when a write async request have been completed. /// </summary> public event Action WriteCompleted; /// <summary> /// Event that is fired when the host is closing the connection. /// </summary> public event Action Closing; public event Action<Exception, SocketError?> Error; /// <summary> /// Creates a new instance of TcpSocket using the endpoint and options provided. /// </summary> public TcpSocket(IConnectionEndPoint endPoint, SocketOptions options, SSLOptions sslOptions) { EndPoint = endPoint; Options = options; SSLOptions = sslOptions; _socket = new Socket(EndPoint.SocketIpEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = Options.ConnectTimeoutMillis }; if (Options.KeepAlive != null) { _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, Options.KeepAlive.Value); } if (Options.SoLinger != null) { _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, Options.SoLinger.Value)); } if (Options.ReceiveBufferSize != null) { _socket.ReceiveBufferSize = Options.ReceiveBufferSize.Value; } if (Options.SendBufferSize != null) { _socket.SendBufferSize = Options.SendBufferSize.Value; } if (Options.TcpNoDelay != null) { _socket.NoDelay = Options.TcpNoDelay.Value; } _receiveBuffer = new byte[_socket.ReceiveBufferSize]; if (SSLOptions == null && !Options.UseStreamMode) { _receiveSocketEvent = new SocketAsyncEventArgs(); _receiveSocketEvent.SetBuffer(_receiveBuffer, 0, _receiveBuffer.Length); _receiveSocketEvent.Completed += OnReceiveCompleted; _sendSocketEvent = new SocketAsyncEventArgs(); _sendSocketEvent.Completed += OnSendCompleted; } } /// <summary> /// Get this socket's local address. /// </summary> /// <returns>The socket's local address.</returns> public IPEndPoint GetLocalIpEndPoint() { try { var s = _socket; return (IPEndPoint)s?.LocalEndPoint; } catch (Exception ex) { TcpSocket.Logger.Warning("Exception thrown when trying to get LocalIpEndpoint: {0}", ex.ToString()); return null; } } /// <summary> /// Connects asynchronously to the host and starts reading /// </summary> /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception> public async Task<bool> Connect() { var tcs = TaskHelper.TaskCompletionSourceWithTimeout<bool>( Options.ConnectTimeoutMillis, () => new SocketException((int)SocketError.TimedOut)); var socketConnectTask = tcs.Task; using (var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = EndPoint.SocketIpEndPoint }) { eventArgs.Completed += (sender, e) => { OnConnectComplete(tcs, e); }; var willCompleteAsync = _socket.ConnectAsync(eventArgs); if (!willCompleteAsync) { // Make the task complete asynchronously Task.Run(() => OnConnectComplete(tcs, eventArgs)).Forget(); } await socketConnectTask.ConfigureAwait(false); } if (SSLOptions != null) { return await ConnectSsl().ConfigureAwait(false); } // Prepare read and write // There are 2 modes: using SocketAsyncEventArgs (most performant) and Stream mode if (Options.UseStreamMode) { TcpSocket.Logger.Verbose("Socket connected, start reading using Stream interface"); //Stream mode: not the most performant but it is a choice _socketStream = new NetworkStream(_socket); ReceiveAsync(); return true; } TcpSocket.Logger.Verbose("Socket connected, start reading using SocketEventArgs interface"); //using SocketAsyncEventArgs ReceiveAsync(); return true; } private void OnConnectComplete(TaskCompletionSource<bool> tcs, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { tcs.TrySetException(new SocketException((int)e.SocketError)); return; } tcs.TrySetResult(true); } private async Task<bool> ConnectSsl() { TcpSocket.Logger.Verbose("Socket connected, starting SSL client authentication"); //Stream mode: not the most performant but it has ssl support TcpSocket.Logger.Verbose("Starting SSL authentication"); var sslStream = new SslStream(new NetworkStream(_socket), false, SSLOptions.RemoteCertValidationCallback, null); _socketStream = sslStream; // Use a timer to ensure that it does callback var tcs = TaskHelper.TaskCompletionSourceWithTimeout<bool>( Options.ConnectTimeoutMillis, () => new TimeoutException("The timeout period elapsed prior to completion of SSL authentication operation.")); sslStream.AuthenticateAsClientAsync(await EndPoint.GetServerNameAsync().ConfigureAwait(false), SSLOptions.CertificateCollection, SSLOptions.SslProtocol, SSLOptions.CheckCertificateRevocation) .ContinueWith(t => { if (t.Exception != null) { t.Exception.Handle(_ => true); // ReSharper disable once AssignNullToNotNullAttribute tcs.TrySetException(t.Exception.InnerException); return; } tcs.TrySetResult(true); }, TaskContinuationOptions.ExecuteSynchronously) // Avoid awaiting as it may never yield .Forget(); await tcs.Task.ConfigureAwait(false); TcpSocket.Logger.Verbose("SSL authentication successful"); ReceiveAsync(); return true; } /// <summary> /// Begins an asynchronous request to receive data from a connected Socket object. /// It handles the exceptions in case there is one. /// </summary> protected virtual void ReceiveAsync() { //Receive the next bytes if (_receiveSocketEvent != null) { var willRaiseEvent = true; try { willRaiseEvent = _socket.ReceiveAsync(_receiveSocketEvent); } catch (ObjectDisposedException) { OnError(null, SocketError.NotConnected); } catch (NullReferenceException) { // Mono can throw a NRE when being disposed concurrently // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs#L184-L185 // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/Socket.cs#L1873-L1874 OnError(null, SocketError.NotConnected); } catch (Exception ex) { OnError(ex); } if (!willRaiseEvent) { OnReceiveCompleted(this, _receiveSocketEvent); } } else { // Stream mode try { _socketStream .ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length) .ContinueWith(OnReceiveStreamCallback, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception ex) { HandleStreamException(ex); } } } protected virtual void OnError(Exception ex, SocketError? socketError = null) { Error?.Invoke(ex, socketError); } /// <summary> /// Handles the receive completed event /// </summary> protected void OnReceiveCompleted(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { //There was a socket error or the connection is being closed. OnError(null, e.SocketError); return; } if (e.BytesTransferred == 0) { OnClosing(); return; } //Emit event try { Read?.Invoke(e.Buffer, e.BytesTransferred); } catch (Exception ex) { OnError(ex); } ReceiveAsync(); } /// <summary> /// Handles the callback for Completed or Cancelled Task on Stream mode /// </summary> protected void OnReceiveStreamCallback(Task<int> readTask) { if (readTask.Exception != null) { readTask.Exception.Handle(_ => true); HandleStreamException(readTask.Exception.InnerException); return; } var bytesRead = readTask.Result; if (bytesRead == 0) { OnClosing(); return; } //Emit event try { Read?.Invoke(_receiveBuffer, bytesRead); } catch (Exception ex) { OnError(ex); } ReceiveAsync(); } /// <summary> /// Handles exceptions that the methods <c>NetworkStream.ReadAsync()</c> and <c>NetworkStream.WriteAsync()</c> can throw. /// </summary> private void HandleStreamException(Exception ex) { if (ex is IOException) { if (ex.InnerException is SocketException) { OnError((SocketException)ex.InnerException); return; } // Wrapped ObjectDisposedException and others: we can consider it as not connected OnError(null, SocketError.NotConnected); return; } if (ex is ObjectDisposedException) { // Wrapped ObjectDisposedException and others: we can consider it as not connected OnError(null, SocketError.NotConnected); return; } OnError(ex); } /// <summary> /// Handles the send completed event /// </summary> protected void OnSendCompleted(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { OnError(null, e.SocketError); } OnWriteFlushed(); WriteCompleted?.Invoke(); } /// <summary> /// Handles the continuation for WriteAsync faulted or Task on Stream mode /// </summary> protected void OnSendStreamCallback(Task writeTask) { if (writeTask.Exception != null) { writeTask.Exception.Handle(_ => true); HandleStreamException(writeTask.Exception.InnerException); return; } OnWriteFlushed(); WriteCompleted?.Invoke(); } protected void OnClosing() { _isClosing = true; Closing?.Invoke(); Dispose(); } private void OnWriteFlushed() { Interlocked.Exchange(ref _writeFlushCallback, null)?.Invoke(); } /// <summary> /// Sends data asynchronously /// </summary> public void Write(RecyclableMemoryStream stream, Action onBufferFlush) { Interlocked.Exchange(ref _writeFlushCallback, onBufferFlush); if (_isClosing) { OnError(new SocketException((int)SocketError.Shutdown)); OnWriteFlushed(); return; } if (_sendSocketEvent != null) { _sendSocketEvent.BufferList = stream.GetBufferList(); var isWritePending = false; try { isWritePending = _socket.SendAsync(_sendSocketEvent); } catch (ObjectDisposedException) { OnError(null, SocketError.NotConnected); } catch (NullReferenceException) { // Mono can throw a NRE when being disposed concurrently // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs#L184-L185 // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/Socket.cs#L2477-L2478 OnError(null, SocketError.NotConnected); } catch (Exception ex) { OnError(ex); } if (!isWritePending) { OnSendCompleted(this, _sendSocketEvent); } } else { var length = (int)stream.Length; try { _socketStream .WriteAsync(stream.GetBuffer(), 0, length) .ContinueWith(OnSendStreamCallback, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception ex) { HandleStreamException(ex); } } } public void Dispose() { _isClosing = true; try { _sendSocketEvent?.Dispose(); } catch { // ignore } try { _receiveSocketEvent?.Dispose(); } catch { // ignore } try { _socketStream?.Dispose(); } catch { // ignore } try { //Try to close it. //Some operations could make the socket to dispose itself _socket.Shutdown(SocketShutdown.Both); } catch { // Shutdown might throw an exception if the socket was not open-open } try { _socket.Dispose(); } catch { //We should not mind if socket's Close method throws an exception } //dereference to make the byte array GC-able as soon as possible _receiveBuffer = 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. using System; using System.Runtime.InteropServices; public struct ValX1<T> {} public struct ValX2<T,U> {} public struct ValX3<T,U,V>{} public class RefX1<T> {} public class RefX2<T,U> {} public class RefX3<T,U,V>{} [StructLayout(LayoutKind.Auto)] public class GenBase<T> { public T Fld10; public int _int0 = 0; public double _double0 = 0; public string _string0 = "string0"; public Guid _Guid0 = new Guid(); public T Fld11; public int _int1 = int.MaxValue; public double _double1 = double.MaxValue; public string _string1 = "string1"; public Guid _Guid1 = new Guid(1,2,3,4,5,6,7,8,9,10,11); public T Fld12; } public class GenInt : GenBase<int> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenDouble: GenBase<double> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenString : GenBase<String> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenObject : GenBase<object> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenGuid : GenBase<Guid> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenConstructedReference : GenBase<RefX1<int>> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenConstructedValue: GenBase<ValX1<string>> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenInt1DArray : GenBase<int[]> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenString2DArray : GenBase<string[,]> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class GenIntJaggedArray : GenBase<int[][]> { public void VerifyLayout() { Test.Eval(_int0 == 0); Test.Eval(_int1 == int.MaxValue) ; Test.Eval(_double0 == 0) ; Test.Eval(_double1 == double.MaxValue) ; Test.Eval(base._string0.Equals("string0")); Test.Eval(base._string1.Equals("string1")); Test.Eval(_Guid0 == new Guid()); Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11)); } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { new GenInt().VerifyLayout(); new GenDouble().VerifyLayout(); new GenString().VerifyLayout(); new GenObject().VerifyLayout(); new GenGuid().VerifyLayout(); new GenConstructedReference().VerifyLayout(); new GenConstructedValue().VerifyLayout(); new GenInt1DArray().VerifyLayout(); new GenString2DArray().VerifyLayout(); new GenIntJaggedArray().VerifyLayout(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using SlimDX; namespace BspDemo { public struct BspBrush { public int FirstSide { get; set; } public int NumSides { get; set; } public int ShaderNum { get; set; } } public struct BspBrushSide { public int PlaneNum { get; set; } public int ShaderNum { get; set; } } [DebuggerDisplay("ClassName: {ClassName}")] public class BspEntity { public string ClassName { get; set; } public Vector3 Origin { get; set; } public Dictionary<string, string> KeyValues { get; set; } public BspEntity() { KeyValues = new Dictionary<string, string>(); } } public struct BspLeaf { public int Cluster; public int Area; public Vector3 Min; public Vector3 Max; public int FirstLeafFace; public int NumLeafFaces; public int FirstLeafBrush; public int NumLeafBrushes; } [DebuggerDisplay("Offset: {Offset}, Length: {Length}")] public struct BspLump { public int Offset; public int Length; } public struct BspPlane { public Vector3 Normal; public float Distance; } [Flags] public enum ContentFlags { Solid = 1, AreaPortal = 0x8000 } public class BspShader { public string Shader; public int SurfaceFlags; public ContentFlags ContentFlags; } public enum BspLumpType { Entities = 0, Shaders, Planes, Nodes, Leaves, LeafFaces, LeafBrushes, Models, Brushes, BrushSides, Vertices, MeshIndices, Faces, Lightmaps, LightVols, VisData } public class BspLoader { public BspBrush[] Brushes { get; set; } public BspBrushSide[] BrushSides { get; set; } public List<BspEntity> Entities { get; set; } public BspLeaf[] Leaves { get; set; } public int[] LeafBrushes { get; set; } public BspPlane[] Planes { get; set; } public List<BspShader> Shaders { get; set; } public bool LoadBspFile(string filename) { return LoadBspFile(new FileStream(filename, FileMode.Open, FileAccess.Read)); } public bool LoadBspFile(Stream buffer) { BinaryReader reader = new BinaryReader(buffer); BspLump[] lumps = new BspLump[17]; // read header string id = Encoding.ASCII.GetString(reader.ReadBytes(4), 0, 4); int version = reader.ReadInt32(); if (id != "IBSP" || version != 0x2E) return false; for (int i = 0; i < lumps.Length; i++) { lumps[i].Offset = reader.ReadInt32(); lumps[i].Length = reader.ReadInt32(); } // read brushes buffer.Position = lumps[(int)BspLumpType.Brushes].Offset; int length = lumps[(int)BspLumpType.Brushes].Length / Marshal.SizeOf(typeof(BspBrush)); Brushes = new BspBrush[length]; for (int i = 0; i < length; i++) { Brushes[i].FirstSide = reader.ReadInt32(); Brushes[i].NumSides = reader.ReadInt32(); Brushes[i].ShaderNum = reader.ReadInt32(); } // read brush sides buffer.Position = lumps[(int)BspLumpType.BrushSides].Offset; length = lumps[(int)BspLumpType.BrushSides].Length / Marshal.SizeOf(typeof(BspBrushSide)); BrushSides = new BspBrushSide[length]; for (int i = 0; i < length; i++) { BrushSides[i].PlaneNum = reader.ReadInt32(); BrushSides[i].ShaderNum = reader.ReadInt32(); } // read entities Entities = new List<BspEntity>(); buffer.Position = lumps[(int)BspLumpType.Entities].Offset; length = lumps[(int)BspLumpType.Entities].Length; byte[] entityBytes = new byte[length]; reader.Read(entityBytes, 0, length); string entityString = Encoding.ASCII.GetString(entityBytes); string[] entityStrings = entityString.Split('\n'); BspEntity bspEntity = null; foreach (string entity in entityStrings) { switch (entity) { case "\0": continue; case "{": bspEntity = new BspEntity(); break; case "}": Entities.Add(bspEntity); break; default: string[] keyValue = entity.Trim('\"').Split(new string[] { "\" \"" }, 2, 0); if (keyValue[0] == "classname") { bspEntity.ClassName = keyValue[1]; } else if (keyValue[0] == "origin") { string[] originStrings = keyValue[1].Split(' '); bspEntity.Origin = new Vector3( float.Parse(originStrings[0], CultureInfo.InvariantCulture), float.Parse(originStrings[1], CultureInfo.InvariantCulture), float.Parse(originStrings[2], CultureInfo.InvariantCulture)); } else { bspEntity.KeyValues.Add(keyValue[0], keyValue[1]); } break; } } // read leaves buffer.Position = lumps[(int)BspLumpType.Leaves].Offset; length = lumps[(int)BspLumpType.Leaves].Length / Marshal.SizeOf(typeof(BspLeaf)); Leaves = new BspLeaf[length]; for (int i = 0; i < length; i++ ) { Leaves[i].Cluster = reader.ReadInt32(); Leaves[i].Area = reader.ReadInt32(); //Swap Y and Z; invert Z Leaves[i].Min.X = reader.ReadInt32(); Leaves[i].Min.Z = -reader.ReadInt32(); Leaves[i].Min.Y = reader.ReadInt32(); //Swap Y and Z; invert Z Leaves[i].Max.X = reader.ReadInt32(); Leaves[i].Max.Z = -reader.ReadInt32(); Leaves[i].Max.Y = reader.ReadInt32(); Leaves[i].FirstLeafFace = reader.ReadInt32(); Leaves[i].NumLeafFaces = reader.ReadInt32(); Leaves[i].FirstLeafBrush = reader.ReadInt32(); Leaves[i].NumLeafBrushes = reader.ReadInt32(); } // read leaf brushes buffer.Position = lumps[(int)BspLumpType.LeafBrushes].Offset; length = lumps[(int)BspLumpType.LeafBrushes].Length / sizeof(int); LeafBrushes = new int[length]; for (int i = 0; i < length; i++) { LeafBrushes[i] = reader.ReadInt32(); } // read planes buffer.Position = lumps[(int)BspLumpType.Planes].Offset; length = lumps[(int)BspLumpType.Planes].Length / Marshal.SizeOf(typeof(BspPlane)); Planes = new BspPlane[length]; for (int i = 0; i < length; i++) { Planes[i].Normal.X = reader.ReadSingle(); Planes[i].Normal.Y = reader.ReadSingle(); Planes[i].Normal.Z = reader.ReadSingle(); Planes[i].Distance = reader.ReadSingle(); } // read shaders Shaders = new List<BspShader>(); buffer.Position = lumps[(int)BspLumpType.Shaders].Offset; length = lumps[(int)BspLumpType.Shaders].Length; for (int i = 0; i < length; i += (64 + 2 * sizeof(int))) { BspShader shader = new BspShader(); byte[] shaderBytes = new byte[64]; reader.Read(shaderBytes, 0, 64); shader.Shader = Encoding.ASCII.GetString(shaderBytes); shader.SurfaceFlags = reader.ReadInt32(); shader.ContentFlags = (ContentFlags)reader.ReadInt32(); Shaders.Add(shader); } return true; } public bool FindVectorByName(string name, ref Vector3 outVector) { foreach (BspEntity entity in Entities) { if (entity.ClassName == name && (entity.ClassName == "info_player_start" || entity.ClassName == "info_player_deathmatch")) { outVector = entity.Origin; return true; } } return false; } } }
/* 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.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS; namespace InkSketchCommit { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox gpbInkSketch; private System.Windows.Forms.GroupBox gpbReport; private System.Windows.Forms.Label lblInfo; private System.Windows.Forms.RadioButton radManual; private System.Windows.Forms.RadioButton radAutoGraphic; private System.Windows.Forms.RadioButton radAutoText; private System.Windows.Forms.Label lbl1sec; private System.Windows.Forms.Label lbl10sec; private System.Windows.Forms.Label lblAutoComplete; private System.Windows.Forms.Label lblCollectingStatus; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbxNumber; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.TrackBar tbrAutoComplete; private IMap m_pMap; private ESRI.ArcGIS.Controls.IEngineInkEnvironment m_EngineInkEnvironment; private IEngineInkEnvironmentEvents_OnStartEventHandler m_startInkE; private IEngineInkEnvironmentEvents_OnStopEventHandler m_stopInkE; private IEngineInkEnvironmentEvents_OnGestureEventHandler m_gestureInkE; private TableLayoutPanel tableLayoutPanel1; private AxToolbarControl axToolbarControl1; private AxMapControl axMapControl1; private AxLicenseControl axLicenseControl1; ///Tablet PC system metric value used by GetSystemMetrics to identify whether the application ///is running on a Tablet PC. private const int SM_TABLETPC = 86; /// <summary> /// The GetSystemMetrics function retrieves system metrics and system configuration settings. /// </summary> public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.gpbInkSketch = new System.Windows.Forms.GroupBox(); this.lblAutoComplete = new System.Windows.Forms.Label(); this.lbl10sec = new System.Windows.Forms.Label(); this.lbl1sec = new System.Windows.Forms.Label(); this.tbrAutoComplete = new System.Windows.Forms.TrackBar(); this.radAutoText = new System.Windows.Forms.RadioButton(); this.radAutoGraphic = new System.Windows.Forms.RadioButton(); this.radManual = new System.Windows.Forms.RadioButton(); this.lblInfo = new System.Windows.Forms.Label(); this.gpbReport = new System.Windows.Forms.GroupBox(); this.tbxNumber = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.lblCollectingStatus = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); this.gpbInkSketch.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbrAutoComplete)).BeginInit(); this.gpbReport.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // gpbInkSketch // this.gpbInkSketch.Controls.Add(this.lblAutoComplete); this.gpbInkSketch.Controls.Add(this.lbl10sec); this.gpbInkSketch.Controls.Add(this.lbl1sec); this.gpbInkSketch.Controls.Add(this.tbrAutoComplete); this.gpbInkSketch.Controls.Add(this.radAutoText); this.gpbInkSketch.Controls.Add(this.radAutoGraphic); this.gpbInkSketch.Controls.Add(this.radManual); this.gpbInkSketch.Controls.Add(this.lblInfo); this.gpbInkSketch.Location = new System.Drawing.Point(433, 51); this.gpbInkSketch.Name = "gpbInkSketch"; this.gpbInkSketch.Size = new System.Drawing.Size(296, 352); this.gpbInkSketch.TabIndex = 3; this.gpbInkSketch.TabStop = false; this.gpbInkSketch.Text = "Ink Sketch Commit Options"; // // lblAutoComplete // this.lblAutoComplete.Location = new System.Drawing.Point(24, 240); this.lblAutoComplete.Name = "lblAutoComplete"; this.lblAutoComplete.Size = new System.Drawing.Size(263, 23); this.lblAutoComplete.TabIndex = 7; this.lblAutoComplete.Text = "Automatically Commit the Ink Sketch after:"; // // lbl10sec // this.lbl10sec.Location = new System.Drawing.Point(216, 303); this.lbl10sec.Name = "lbl10sec"; this.lbl10sec.Size = new System.Drawing.Size(64, 24); this.lbl10sec.TabIndex = 6; this.lbl10sec.Text = "(10 sec)"; // // lbl1sec // this.lbl1sec.Location = new System.Drawing.Point(8, 303); this.lbl1sec.Name = "lbl1sec"; this.lbl1sec.Size = new System.Drawing.Size(65, 24); this.lbl1sec.TabIndex = 5; this.lbl1sec.Text = "(1 sec)"; // // tbrAutoComplete // this.tbrAutoComplete.Location = new System.Drawing.Point(8, 264); this.tbrAutoComplete.Minimum = 1; this.tbrAutoComplete.Name = "tbrAutoComplete"; this.tbrAutoComplete.Size = new System.Drawing.Size(264, 56); this.tbrAutoComplete.TabIndex = 4; this.tbrAutoComplete.Value = 1; this.tbrAutoComplete.MouseUp += new System.Windows.Forms.MouseEventHandler(this.tbrAutoComplete_MouseUp); // // radAutoText // this.radAutoText.Location = new System.Drawing.Point(16, 167); this.radAutoText.Name = "radAutoText"; this.radAutoText.Size = new System.Drawing.Size(272, 54); this.radAutoText.TabIndex = 3; this.radAutoText.Text = "Automatically Committed and Recognized as Text (Tablet PC only)"; this.radAutoText.CheckedChanged += new System.EventHandler(this.radAutoText_CheckedChanged); // // radAutoGraphic // this.radAutoGraphic.Location = new System.Drawing.Point(16, 144); this.radAutoGraphic.Name = "radAutoGraphic"; this.radAutoGraphic.Size = new System.Drawing.Size(271, 24); this.radAutoGraphic.TabIndex = 2; this.radAutoGraphic.Text = "Automatically Committed to Graphic"; this.radAutoGraphic.CheckedChanged += new System.EventHandler(this.radAutoGraphic_CheckedChanged); // // radManual // this.radManual.Location = new System.Drawing.Point(16, 112); this.radManual.Name = "radManual"; this.radManual.Size = new System.Drawing.Size(160, 24); this.radManual.TabIndex = 1; this.radManual.Text = "Manually Committed"; this.radManual.CheckedChanged += new System.EventHandler(this.radManual_CheckedChanged); // // lblInfo // this.lblInfo.Location = new System.Drawing.Point(16, 40); this.lblInfo.Name = "lblInfo"; this.lblInfo.Size = new System.Drawing.Size(264, 56); this.lblInfo.TabIndex = 0; this.lblInfo.Text = "Ink sketches can be committed manually or automatically. Click on the buttons belo" + "w to change the commit method."; // // gpbReport // this.gpbReport.Controls.Add(this.tbxNumber); this.gpbReport.Controls.Add(this.label1); this.gpbReport.Controls.Add(this.lblCollectingStatus); this.gpbReport.Location = new System.Drawing.Point(433, 409); this.gpbReport.Name = "gpbReport"; this.gpbReport.Size = new System.Drawing.Size(296, 112); this.gpbReport.TabIndex = 4; this.gpbReport.TabStop = false; this.gpbReport.Text = "Sketch Report"; // // tbxNumber // this.tbxNumber.BackColor = System.Drawing.SystemColors.Control; this.tbxNumber.BorderStyle = System.Windows.Forms.BorderStyle.None; this.tbxNumber.Location = new System.Drawing.Point(176, 32); this.tbxNumber.Name = "tbxNumber"; this.tbxNumber.Size = new System.Drawing.Size(100, 15); this.tbxNumber.TabIndex = 2; this.tbxNumber.Text = "0"; // // label1 // this.label1.Location = new System.Drawing.Point(8, 32); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(168, 23); this.label1.TabIndex = 1; this.label1.Text = "Number of Ink Sketches = "; // // lblCollectingStatus // this.lblCollectingStatus.Location = new System.Drawing.Point(8, 80); this.lblCollectingStatus.Name = "lblCollectingStatus"; this.lblCollectingStatus.Size = new System.Drawing.Size(272, 16); this.lblCollectingStatus.TabIndex = 0; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 58.46906F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 41.53094F)); this.tableLayoutPanel1.Controls.Add(this.gpbInkSketch, 1, 1); this.tableLayoutPanel1.Controls.Add(this.axToolbarControl1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.axMapControl1, 0, 1); this.tableLayoutPanel1.Controls.Add(this.gpbReport, 1, 2); this.tableLayoutPanel1.Controls.Add(this.axLicenseControl1, 0, 2); this.tableLayoutPanel1.Location = new System.Drawing.Point(14, 8); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 3; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 11.88406F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 88.11594F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 120F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(737, 527); this.tableLayoutPanel1.TabIndex = 5; // // axToolbarControl1 // this.tableLayoutPanel1.SetColumnSpan(this.axToolbarControl1, 2); this.axToolbarControl1.Location = new System.Drawing.Point(3, 3); this.axToolbarControl1.Name = "axToolbarControl1"; this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState"))); this.axToolbarControl1.Size = new System.Drawing.Size(729, 28); this.axToolbarControl1.TabIndex = 5; // // axMapControl1 // this.axMapControl1.Location = new System.Drawing.Point(3, 51); this.axMapControl1.Name = "axMapControl1"; this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState"))); this.axMapControl1.Size = new System.Drawing.Size(423, 352); this.axMapControl1.TabIndex = 6; this.axMapControl1.OnAfterScreenDraw += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnAfterScreenDrawEventHandler(this.axMapControl1_OnAfterScreenDraw); // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(3, 409); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 7; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.ClientSize = new System.Drawing.Size(767, 540); this.Controls.Add(this.tableLayoutPanel1); this.MaximumSize = new System.Drawing.Size(775, 580); this.MinimumSize = new System.Drawing.Size(775, 580); this.Name = "Form1"; this.Text = "Ink Sketch Commit"; this.Load += new System.EventHandler(this.Form1_Load); this.gpbInkSketch.ResumeLayout(false); this.gpbInkSketch.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbrAutoComplete)).EndInit(); this.gpbReport.ResumeLayout(false); this.gpbReport.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { //Set buddy control axToolbarControl1.SetBuddyControl(axMapControl1); //Add items to the ToolbarControl axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsInkToolbar", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsSelectTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); //Set the EngineInkEnviroment Singleton m_EngineInkEnvironment = new EngineInkEnvironmentClass(); //Set the Ink Tool commit type to be manual m_EngineInkEnvironment.ToolCommitType = esriEngineInkToolCommitType.esriEngineInkToolCommitTypeManual; //Set the Form Controls tbrAutoComplete.Enabled = false; tbrAutoComplete.Minimum = 1; tbrAutoComplete.Maximum = 10; tbrAutoComplete.TickFrequency = 1; tbrAutoComplete.TickStyle = TickStyle.BottomRight; lblAutoComplete.Enabled = false; lbl1sec.Enabled = false; lbl10sec.Enabled = false; lblCollectingStatus.Text = "Not Collecting Ink"; tbxNumber.Text = "0"; radManual.Checked = true; //The radAutoText Radio button is only available on a Tablet PC. //Converting ink to text requires a Recognizer which can only //run on Windows XP Tablet PC Edition. if (IsRunningOnTabletPC()) { radAutoText.Enabled = true; } else { radAutoText.Enabled = false; } //Set the EngineInkEnvironment OnStart events m_startInkE = new IEngineInkEnvironmentEvents_OnStartEventHandler(OnStartInk); ((IEngineInkEnvironmentEvents_Event)m_EngineInkEnvironment).OnStart += m_startInkE; //Set the EngineInkEnvironment OnStop events m_stopInkE = new IEngineInkEnvironmentEvents_OnStopEventHandler(OnStopInk); ((IEngineInkEnvironmentEvents_Event)m_EngineInkEnvironment).OnStop += m_stopInkE; //Set the EngineInkEnvironment OnGesture events m_gestureInkE = new IEngineInkEnvironmentEvents_OnGestureEventHandler(OnGestureInk); ((IEngineInkEnvironmentEvents_Event)m_EngineInkEnvironment).OnGesture += m_gestureInkE; } private void OnStartInk() { //Report to the user the mode of the Ink Collector lblCollectingStatus.Text = "Collecting Ink Sketch"; } private void OnStopInk() { //Report to the user the mode of the Ink Collector lblCollectingStatus.Text = "Not Collecting Ink Sketch"; } private void OnGestureInk(esriEngineInkGesture p_gesture, object p_point) { //Report to the user that a Gesture has been made lblCollectingStatus.Text = "Gesture Made Sketch"; } private bool IsRunningOnTabletPC() { // Check to see if the application is running on a Tablet PC // MSDN Help GetSystemMetrics(86) // Nonzero if the current operating system is the Windows XP Tablet PC edition, // 0 (zero) if not. if (Win32.GetSystemMetrics(SM_TABLETPC) != 0) return true; else return false; } private void radManual_CheckedChanged(object sender, System.EventArgs e) { //Manually committed ink sketch if (radManual.Checked) { tbrAutoComplete.Enabled = false; lblAutoComplete.Enabled = false; lbl1sec.Enabled = false; lbl10sec.Enabled = false; m_EngineInkEnvironment.ToolCommitType = esriEngineInkToolCommitType.esriEngineInkToolCommitTypeManual; } } private void radAutoGraphic_CheckedChanged(object sender, System.EventArgs e) { //Automatically commit and save as ink graphic if (radAutoGraphic.Checked) { tbrAutoComplete.Enabled = true; lblAutoComplete.Enabled = true; lbl1sec.Enabled = true; lbl10sec.Enabled = true; m_EngineInkEnvironment.ToolCommitType = esriEngineInkToolCommitType.esriEngineInkToolCommitTypeAutoGraphic; m_EngineInkEnvironment.ToolCommitDelay = tbrAutoComplete.Value; } } private void radAutoText_CheckedChanged(object sender, System.EventArgs e) { //Automatically commit and recognize as ink text //This is only available on a Tablet PC if (radAutoText.Checked) { tbrAutoComplete.Enabled = true; lblAutoComplete.Enabled = true; lbl1sec.Enabled = true; lbl10sec.Enabled = true; m_EngineInkEnvironment.ToolCommitType = esriEngineInkToolCommitType.esriEngineInkToolCommitTypeAutoText; m_EngineInkEnvironment.ToolCommitDelay = tbrAutoComplete.Value; } } private void axMapControl1_OnAfterScreenDraw(object sender, IMapControlEvents2_OnAfterScreenDrawEvent e) { //Report to the user the number of Ink Sketches that are present IElement pElement; IGraphicsContainer pContainer; int i = 0; m_pMap = axMapControl1.Map; pContainer = (IGraphicsContainer)m_pMap; pContainer.Reset(); pElement = pContainer.Next(); while (pElement != null) { if (pElement is InkGraphic) i = i + 1; pElement = pContainer.Next(); } tbxNumber.Text = i.ToString(); } private void tbrAutoComplete_MouseUp(object sender, MouseEventArgs e) { //Set the ToolCommitDelay using the value of the TrackBar m_EngineInkEnvironment.ToolCommitDelay = tbrAutoComplete.Value; } } public class Win32 { [DllImport("user32.dll",EntryPoint="GetSystemMetrics")] public static extern int GetSystemMetrics(int abc); } }
/* * 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 OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Globalization; using System.Text; using System.Threading; using System.Xml; using System.Security.Cryptography.X509Certificates; using System.Security.Authentication; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using Amib.Threading; using System.IO.Compression; namespace OpenSim.Framework.Servers.HttpServer { public class BaseHttpServer : IHttpServer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Gets or sets the debug level. /// </summary> /// <value> /// See MainServer.DebugLevel. /// </value> public int DebugLevel { get; set; } private volatile uint RequestNumber = 0; protected HttpListener m_httpListener; protected Dictionary<string, XmlRpcMethod> m_rpcHandlers = new Dictionary<string, XmlRpcMethod>(); protected Dictionary<string, bool> m_rpcHandlersKeepAlive = new Dictionary<string, bool>(); protected Dictionary<string, LLSDMethod> m_llsdHandlers = new Dictionary<string, LLSDMethod>(); protected Dictionary<string, IRequestHandler> m_streamHandlers = new Dictionary<string, IRequestHandler>(); protected Dictionary<string, GenericHTTPMethod> m_HTTPHandlers = new Dictionary<string, GenericHTTPMethod>(); // The Main Thread Pool protected const int c_ThreadIdleTimeout = 1000; protected const int c_ThreadPoolMaxSize = 64; protected const int c_ThreadPoolMinSize = 2; protected SmartThreadPool m_Threads = new SmartThreadPool(c_ThreadIdleTimeout, c_ThreadPoolMaxSize, c_ThreadPoolMinSize); // SSL Support protected X509Certificate2 m_cert; protected SslProtocols m_sslProtocol = SslProtocols.None; protected bool m_isSecure; protected uint m_port; protected string m_hostName; protected IPAddress m_listenIPAddress = IPAddress.Any; public uint Port { get { return m_port; } } public bool Secure { get { return m_isSecure; } } public IPAddress ListenIPAddress { get { return m_listenIPAddress; } set { m_listenIPAddress = value; } } public string HostName { get { return m_hostName; } set { m_hostName = value; } } public string Protocol { get { string protocol = "http://"; if (Secure) protocol = "https://"; return protocol; } } public string FullHostName { get { string protocol = "http://"; if (Secure) protocol = "https://"; return protocol + m_hostName; } } /// <summary> /// A well-formed URI for the host region server (namely "http://ExternalHostName:Port) /// </summary> public string ServerURI { get { string protocol = "http://"; if (Secure) protocol = "https://"; return protocol + m_hostName + ":" + m_port.ToString(); } } public bool IsRunning { get { return m_httpListener.IsListening; } } public BaseHttpServer(uint port, IPAddress ipaddr) { m_Threads.Name = "HttpServer"; m_port = port; m_isSecure = false; if (ipaddr == null) m_listenIPAddress = IPAddress.Any; else m_listenIPAddress = ipaddr; } private X509Certificate2 GetCertificateFromStore(string certName) { // Get the certificate store for the current user. X509Store store = new X509Store(StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); // Place all certificates in an X509Certificate2Collection object. X509Certificate2Collection certCollection = store.Certificates; // If using a certificate with a trusted root you do not need to FindByTimeValid, instead: // currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true); X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false); if (signingCert.Count == 0) return null; // Return the first certificate in the collection, has the right name and is current. return signingCert[0]; } finally { store.Close(); } } /// <summary> /// Set the SSL params based on lookup of the cert in the local store using /// the common name provided. /// </summary> /// <param name="commonName"></param> /// <param name="protocol"></param> public void SetSecureParams(string commonName, SslProtocols protocol) { m_isSecure = true; m_cert = GetCertificateFromStore(commonName); m_sslProtocol = protocol; } /// <summary> /// Set the SSL params based on a filepath and password to access and unlock a certificate. /// </summary> /// <param name="path"></param> /// <param name="password"></param> /// <param name="protocol"></param> public void SetSecureParams(string path, string password, SslProtocols protocol) { m_isSecure = true; m_cert = new X509Certificate2(path, password); m_sslProtocol = protocol; } /// <summary> /// Add a stream handler to the http server. If the handler already exists, then nothing happens. /// </summary> /// <param name="handler"></param> public void AddStreamHandler(IRequestHandler handler) { string httpMethod = handler.HttpMethod; string path = handler.Path; string handlerKey = GetHandlerKey(httpMethod, path); lock (m_streamHandlers) { if (!m_streamHandlers.ContainsKey(handlerKey)) { // m_log.DebugFormat("[BASE HTTP SERVER]: Adding handler key {0}", handlerKey); m_streamHandlers.Add(handlerKey, handler); } } } public List<string> GetStreamHandlerKeys() { lock (m_streamHandlers) return new List<string>(m_streamHandlers.Keys); } private static string GetHandlerKey(string httpMethod, string path) { return httpMethod + ":" + path; } public bool AddXmlRPCHandler(string method, XmlRpcMethod handler) { return AddXmlRPCHandler(method, handler, true); } public bool AddXmlRPCHandler(string method, XmlRpcMethod handler, bool keepAlive) { lock (m_rpcHandlers) { m_rpcHandlers[method] = handler; m_rpcHandlersKeepAlive[method] = keepAlive; // default } return true; } public XmlRpcMethod GetXmlRPCHandler(string method) { lock (m_rpcHandlers) { if (m_rpcHandlers.ContainsKey(method)) { return m_rpcHandlers[method]; } else { return null; } } } public List<string> GetXmlRpcHandlerKeys() { lock (m_rpcHandlers) return new List<string>(m_rpcHandlers.Keys); } public bool AddHTTPHandler(string methodName, GenericHTTPMethod handler) { //m_log.DebugFormat("[BASE HTTP SERVER]: Registering {0}", methodName); lock (m_HTTPHandlers) { if (!m_HTTPHandlers.ContainsKey(methodName)) { m_HTTPHandlers.Add(methodName, handler); return true; } } //must already have a handler for that path so return false return false; } public List<string> GetHTTPHandlerKeys() { lock (m_HTTPHandlers) return new List<string>(m_HTTPHandlers.Keys); } public bool AddLLSDHandler(string path, LLSDMethod handler) { lock (m_llsdHandlers) { if (!m_llsdHandlers.ContainsKey(path)) { m_llsdHandlers.Add(path, handler); return true; } } return false; } public List<string> GetLLSDHandlerKeys() { lock (m_llsdHandlers) return new List<string>(m_llsdHandlers.Keys); } private void OnRequest(IAsyncResult result) { if (m_httpListener == null) return; try { HttpListenerContext context = m_httpListener.EndGetContext(result); // *** Immediately set up the next context if (m_httpListener.IsListening) m_httpListener.BeginGetContext(new AsyncCallback(OnRequest), m_httpListener); m_Threads.QueueWorkItem(HandleRequest, context); } catch (Exception e) { m_log.ErrorFormat("[BASE HTTP SERVER]: OnRequest() failed with {0}{1}", e.Message, e.StackTrace); } } /// <summary> /// This methods is the start of incoming HTTP request handling. /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void HandleRequest(HttpListenerContext context) { OSHttpRequest request = new OSHttpRequest(context.Request); OSHttpResponse response = new OSHttpResponse(context.Response); request.SeqNo = RequestNumber++; request.StartTime = Environment.TickCount; string requestMethod = request.HttpMethod; string uriString = request.RawUrl; IRequestHandler requestHandler = null; Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", true); // If they ask for it we'll use it. response.KeepAlive = request.KeepAlive; response.SendChunked = false; string path = request.RawUrl; string handlerKey = GetHandlerKey(request.HttpMethod, path); byte[] buffer = null; try { if (String.IsNullOrEmpty(request.HttpMethod)) // Can't handle empty requests, not wasting a thread { buffer = SendHTML500(response); } else if (TryGetStreamHandler(handlerKey, out requestHandler)) { if (DebugLevel >= 3) LogIncomingToStreamHandler(request, requestHandler); response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type. if (requestHandler is IAsyncRequestHandler) { // Call the request handler. The Response is sent Async from the handler IAsyncRequestHandler asyncHandler = requestHandler as IAsyncRequestHandler; asyncHandler.Handle(this, path, request, response); return; } else if (requestHandler is IStreamedRequestHandler) { IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler; buffer = streamedRequestHandler.Handle(path, request.InputStream, request, response); } else if (requestHandler is IGenericHTTPHandler) { IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler; Stream requestStream = request.InputStream; Encoding encoding = Encoding.UTF8; StreamReader reader = new StreamReader(requestStream, encoding); string requestBody = reader.ReadToEnd(); reader.Close(); //requestStream.Close(); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); //string host = String.Empty; foreach (string queryname in request.QueryString.AllKeys) keysvals.Add(queryname, request.QueryString[queryname]); foreach (string headername in request.Headers.AllKeys) headervals[headername] = request.Headers[headername]; headervals["remote_addr"] = request.RemoteIPEndPoint.ToString(); keysvals.Add("requestbody", requestBody); keysvals.Add("headers", headervals); if (keysvals.Contains("method")) { //m_log.Warn("[HTTP]: Contains Method"); //string method = (string)keysvals["method"]; //m_log.Warn("[HTTP]: " + requestBody); } buffer = DoHTTPGruntWork(HTTPRequestHandler.Handle(path, keysvals), request, response); } else { IStreamHandler streamHandler = (IStreamHandler)requestHandler; using (MemoryStream memoryStream = new MemoryStream()) { streamHandler.Handle(path, request.InputStream, memoryStream, request, response); memoryStream.Flush(); buffer = memoryStream.ToArray(); } } } else { switch (request.ContentType) { case null: case "text/html": if (DebugLevel >= 3) m_log.DebugFormat( "[BASE HTTP SERVER]: HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}", request.SeqNo, Port, request.ContentType, request.HttpMethod, request.Url.PathAndQuery, request.RemoteIPEndPoint); buffer = HandleHTTPRequest(request, response); break; case "application/llsd+xml": case "application/xml+llsd": case "application/llsd+json": if (DebugLevel >= 3) m_log.DebugFormat( "[BASE HTTP SERVER]: HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}", request.SeqNo, Port, request.ContentType, request.HttpMethod, request.Url.PathAndQuery, request.RemoteIPEndPoint); buffer = HandleLLSDRequests(request, response); break; case "text/xml": case "application/xml": case "application/json": default: if (DoWeHaveALLSDHandler(request.RawUrl)) { if (DebugLevel >= 3) LogIncomingToContentTypeHandler(request); buffer = HandleLLSDRequests(request, response); } else if (DoWeHaveAHTTPHandler(request.RawUrl)) { if (DebugLevel >= 3) LogIncomingToContentTypeHandler(request); buffer = HandleHTTPRequest(request, response); } else { if (DebugLevel >= 3) LogIncomingToXmlRpcHandler(request); // generic login request. buffer = HandleXmlRpcRequests(request, response); } break; } } } catch (Exception e) { m_log.ErrorFormat("[BASE HTTP SERVER] Caught exception while handling request: {0} {1}", path, e); buffer = SendHTML500(response); } SendResponse(request, response, requestHandler, buffer); } public void SendResponse(OSHttpRequest request, OSHttpResponse response, IRequestHandler requestHandler, byte[] buffer) { try { request.InputStream.Close(); // Do not include the time taken to actually send the response to the caller in the measurement // time. This is to avoid logging when it's the client that is slow to process rather than the // server request.EndTime = Environment.TickCount; // Every month or so this will wrap and give bad numbers, not really a problem // since its just for reporting int tickdiff = request.EndTime - request.StartTime; // Dont log EQG messages. They always run long due to the way the queue works if ((tickdiff > 3000) && (request.Url.AbsolutePath.StartsWith("/CAPS/EQG") == false)) { m_log.InfoFormat( "[BASE HTTP SERVER]: Slow handling of {0} {1} {2} {3} {4} from {5} took {6}ms", request.SeqNo, request.HttpMethod, request.Url.AbsolutePath, requestHandler != null ? requestHandler.Name : String.Empty, requestHandler != null ? requestHandler.Description : String.Empty, request.RemoteIPEndPoint, tickdiff); } else if (DebugLevel >= 4) { m_log.DebugFormat( "[BASE HTTP SERVER]: HTTP IN {0} :{1} took {2}ms", request.SeqNo, Port, tickdiff); } if (buffer != null) { //find the accept encoding key string acceptEncodingKey = null; foreach (string key in request.Headers.AllKeys) { if (key.ToLower() == "accept-encoding") { acceptEncodingKey = request.Headers[key]; } } // GZip compress the response if the client says they can handle that if (acceptEncodingKey != null && request.Headers["accept-encoding"].Contains("gzip")) { using (MemoryStream ms = new MemoryStream()) { using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress)) { gs.Write(buffer, 0, buffer.Length); } buffer = ms.ToArray(); } response.AddHeader("Content-Encoding", "gzip"); } if (!response.SendChunked) response.ContentLength64 = buffer.LongLength; response.OutputStream.BeginWrite(buffer, 0, buffer.Length, ResponseWriteFinished, Tuple.Create(request, response, requestHandler)); } } catch (Exception e) { //fill out request end time to get an actual count in case the exception is thrown in response.Write request.EndTime = Environment.TickCount; int tickdiff = request.EndTime - request.StartTime; m_log.ErrorFormat( "[BASE HTTP SERVER]: HandleRequest() threw {0} while processing {1} {2} {3} {4} {5} took {6}ms", e, request.SeqNo, request.HttpMethod, request.Url.AbsolutePath, requestHandler != null ? requestHandler.Name : String.Empty, requestHandler != null ? requestHandler.Description : String.Empty, tickdiff); // note that request.RemoteIPEndPoint is often disposed when we reach here (e.g. remote end has crashed) } } private void ResponseWriteFinished(IAsyncResult ar) { var parms = (Tuple<OSHttpRequest, OSHttpResponse, IRequestHandler>)ar.AsyncState; OSHttpRequest request = parms.Item1; OSHttpResponse response = parms.Item2; IRequestHandler requestHandler = parms.Item3; try { response.OutputStream.EndWrite(ar); parms.Item2.OutputStream.Flush(); //should be a NOP parms.Item2.OutputStream.Close(); } catch (Exception e) { m_log.ErrorFormat( "[BASE HTTP SERVER]: ResponseWriteFinished() threw {0} while processing {1} {2} {3} {4} {5}", e, request.SeqNo, request.HttpMethod, request.Url.AbsolutePath, requestHandler != null ? requestHandler.Name : String.Empty, requestHandler != null ? requestHandler.Description : String.Empty); try { parms.Item2.Response.Abort(); } catch { } } } private void LogIncomingToStreamHandler(OSHttpRequest request, IRequestHandler requestHandler) { m_log.DebugFormat( "[BASE HTTP SERVER]: HTTP IN {0} :{1} stream handler {2} {3} {4} {5} from {6}", request.SeqNo, Port, request.HttpMethod, request.Url.PathAndQuery, requestHandler.Name, requestHandler.Description, request.RemoteIPEndPoint); if (DebugLevel >= 5) LogIncomingInDetail(request); } private void LogIncomingToContentTypeHandler(OSHttpRequest request) { m_log.DebugFormat( "[BASE HTTP SERVER]: HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}", request.SeqNo, Port, request.ContentType, request.HttpMethod, request.Url.PathAndQuery, request.RemoteIPEndPoint); if (DebugLevel >= 5) LogIncomingInDetail(request); } private void LogIncomingToXmlRpcHandler(OSHttpRequest request) { m_log.DebugFormat( "[BASE HTTP SERVER]: HTTP IN {0} :{1} assumed generic XMLRPC request {2} {3} from {4}", request.SeqNo, Port, request.HttpMethod, request.Url.PathAndQuery, request.RemoteIPEndPoint); if (DebugLevel >= 5) LogIncomingInDetail(request); } private void LogIncomingInDetail(OSHttpRequest request) { using (StreamReader reader = new StreamReader(Util.Copy(request.InputStream), Encoding.UTF8)) { string output; if (DebugLevel == 5) { const int sampleLength = 80; char[] sampleChars = new char[sampleLength]; reader.Read(sampleChars, 0, sampleLength); output = new string(sampleChars); } else { output = reader.ReadToEnd(); } m_log.DebugFormat("[BASE HTTP SERVER]: {0}...", output.Replace("\n", @"\n")); } } private bool TryGetStreamHandler(string handlerKey, out IRequestHandler streamHandler) { string bestMatch = null; lock (m_streamHandlers) { foreach (string pattern in m_streamHandlers.Keys) { if (handlerKey.StartsWith(pattern)) { if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length) { bestMatch = pattern; } } } if (String.IsNullOrEmpty(bestMatch)) { streamHandler = null; return false; } else { streamHandler = m_streamHandlers[bestMatch]; return true; } } } private bool TryGetHTTPHandler(string handlerKey, out GenericHTTPMethod HTTPHandler) { // m_log.DebugFormat("[BASE HTTP HANDLER]: Looking for HTTP handler for {0}", handlerKey); string bestMatch = null; lock (m_HTTPHandlers) { foreach (string pattern in m_HTTPHandlers.Keys) { if (handlerKey.StartsWith(pattern)) { if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length) { bestMatch = pattern; } } } if (String.IsNullOrEmpty(bestMatch)) { HTTPHandler = null; return false; } else { HTTPHandler = m_HTTPHandlers[bestMatch]; return true; } } } /// <summary> /// Try all the registered xmlrpc handlers when an xmlrpc request is received. /// Sends back an XMLRPC unknown request response if no handler is registered for the requested method. /// </summary> /// <param name="request"></param> /// <param name="response"></param> private byte[] HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response) { Stream requestStream = request.InputStream; Encoding encoding = Encoding.UTF8; StreamReader reader = new StreamReader(requestStream, encoding); string requestBody = reader.ReadToEnd(); reader.Close(); requestStream.Close(); string responseString = String.Empty; XmlRpcRequest xmlRprcRequest = null; string methodName = null; try { xmlRprcRequest = (XmlRpcRequest) (new XmlRpcRequestDeserializer()).Deserialize(requestBody); methodName = xmlRprcRequest.MethodName; } catch (XmlException e) { if (DebugLevel >= 2) { m_log.Warn( string.Format( "[BASE HTTP SERVER]: Got XMLRPC request with invalid XML from {0}. XML was '{1}'. Sending 404 response. Exception ", request.RemoteIPEndPoint, requestBody), e); } else if (DebugLevel >= 1) { m_log.WarnFormat( "[BASE HTTP SERVER]: Got XMLRPC request with invalid XML from {0}, length {1}. Sending 404 response.", request.RemoteIPEndPoint, requestBody.Length); } } if ((xmlRprcRequest == null) || (methodName == null)) { //HandleLLSDRequests(request, response); response.ContentType = "text/plain"; response.StatusCode = 404; response.StatusDescription = "Not Found"; response.ProtocolVersion = new System.Version("1.0"); responseString = "Not found"; response.KeepAlive = false; if (DebugLevel >= 1) { m_log.WarnFormat( "[BASE HTTP SERVER]: Handler not found for http request {0} {1}", request.HttpMethod, request.Url.PathAndQuery); } } else { xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1] XmlRpcResponse xmlRpcResponse; XmlRpcMethod method; bool methodWasFound; bool keepAlive = false; lock (m_rpcHandlers) { methodWasFound = m_rpcHandlers.TryGetValue(methodName, out method); if (methodWasFound) keepAlive = m_rpcHandlersKeepAlive[methodName]; } if (methodWasFound) { xmlRprcRequest.Params.Add(request.Url); // Param[2] string xff = "X-Forwarded-For"; string xfflower = xff.ToLower(); foreach (string s in request.Headers.AllKeys) { if (s != null && s.Equals(xfflower)) { xff = xfflower; break; } } xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3] try { xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint); } catch(Exception e) { string errorMessage = String.Format( "Requested method [{0}] from {1} threw exception: {2} {3}", methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace); m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage); // if the registered XmlRpc method threw an exception, we pass a fault-code along xmlRpcResponse = new XmlRpcResponse(); // Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php xmlRpcResponse.SetFault(-32603, errorMessage); } // if the method wasn't found, we can't determine KeepAlive state anyway, so lets do it only here response.KeepAlive = keepAlive; } else { xmlRpcResponse = new XmlRpcResponse(); // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php xmlRpcResponse.SetFault( XmlRpcErrorCodes.SERVER_ERROR_METHOD, String.Format("Requested method [{0}] not found", methodName)); } response.ContentType = "text/xml"; responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse); } byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.LongLength; response.ContentEncoding = Encoding.UTF8; response.SendChunked = false; return buffer; } private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response) { //m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request"); Stream requestStream = request.InputStream; Encoding encoding = Encoding.UTF8; StreamReader reader = new StreamReader(requestStream, encoding); string requestBody = reader.ReadToEnd(); reader.Close(); requestStream.Close(); //m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody); // If they ask for it we'll use it. response.KeepAlive = request.KeepAlive; OSD llsdRequest = null; OSD llsdResponse = null; bool LegacyLLSDLoginLibOMV = (requestBody.Contains("passwd") && requestBody.Contains("mac") && requestBody.Contains("viewer_digest")); if (String.IsNullOrEmpty(requestBody)) // Get Request { requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>"; } try { llsdRequest = OSDParser.Deserialize(requestBody); } catch (Exception ex) { m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message); } if (llsdRequest != null)// && m_defaultLlsdHandler != null) { LLSDMethod llsdhandler = null; if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV) { // we found a registered llsd handler to service this request llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint); } else { // we didn't find a registered llsd handler to service this request // Oops, no handler for this.. give em the failed message llsdResponse = GenerateNoLLSDHandlerResponse(); } } else { llsdResponse = GenerateNoLLSDHandlerResponse(); } byte[] buffer = new byte[0]; if (llsdResponse.ToString() == "shutdown404!") { response.ContentType = "text/plain"; response.StatusCode = 404; response.StatusDescription = "Not Found"; response.ProtocolVersion = new System.Version("1.0"); buffer = Encoding.UTF8.GetBytes("Not found"); } else { // Select an appropriate response format buffer = BuildLLSDResponse(request, response, llsdResponse); } response.SendChunked = false; response.ContentLength64 = buffer.Length; response.ContentEncoding = Encoding.UTF8; return buffer; } private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse) { if (request.AcceptTypes != null && request.AcceptTypes.Length > 0) { foreach (string strAccept in request.AcceptTypes) { switch (strAccept) { case "application/llsd+xml": case "application/xml": case "text/xml": response.ContentType = strAccept; return OSDParser.SerializeLLSDXmlBytes(llsdResponse); case "application/llsd+json": case "application/json": response.ContentType = strAccept; return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse)); } } } if (!String.IsNullOrEmpty(request.ContentType)) { switch (request.ContentType) { case "application/llsd+xml": case "application/xml": case "text/xml": response.ContentType = request.ContentType; return OSDParser.SerializeLLSDXmlBytes(llsdResponse); case "application/llsd+json": case "application/json": response.ContentType = request.ContentType; return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse)); } } // response.ContentType = "application/llsd+json"; // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse)); response.ContentType = "application/llsd+xml"; return OSDParser.SerializeLLSDXmlBytes(llsdResponse); } /// <summary> /// Checks if we have an Exact path in the LLSD handlers for the path provided /// </summary> /// <param name="path">URI of the request</param> /// <returns>true if we have one, false if not</returns> private bool DoWeHaveALLSDHandler(string path) { string[] pathbase = path.Split('/'); string searchquery = "/"; if (pathbase.Length < 1) return false; for (int i = 1; i < pathbase.Length; i++) { searchquery += pathbase[i]; if (pathbase.Length - 1 != i) searchquery += "/"; } string bestMatch = null; lock (m_llsdHandlers) { foreach (string pattern in m_llsdHandlers.Keys) { if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length) bestMatch = pattern; } } // extra kicker to remove the default XMLRPC login case.. just in case.. if (path != "/" && bestMatch == "/" && searchquery != "/") return false; if (path == "/") return false; if (String.IsNullOrEmpty(bestMatch)) { return false; } else { return true; } } /// <summary> /// Checks if we have an Exact path in the HTTP handlers for the path provided /// </summary> /// <param name="path">URI of the request</param> /// <returns>true if we have one, false if not</returns> private bool DoWeHaveAHTTPHandler(string path) { string[] pathbase = path.Split('/'); string searchquery = "/"; if (pathbase.Length < 1) return false; for (int i = 1; i < pathbase.Length; i++) { searchquery += pathbase[i]; if (pathbase.Length - 1 != i) searchquery += "/"; } string bestMatch = null; //m_log.DebugFormat("[BASE HTTP HANDLER]: Checking if we have an HTTP handler for {0}", searchquery); lock (m_HTTPHandlers) { foreach (string pattern in m_HTTPHandlers.Keys) { if (searchquery.StartsWith(pattern) && searchquery.Length >= pattern.Length) { bestMatch = pattern; } } // extra kicker to remove the default XMLRPC login case.. just in case.. if (path == "/") return false; if (String.IsNullOrEmpty(bestMatch)) { return false; } else { return true; } } } private bool TryGetLLSDHandler(string path, out LLSDMethod llsdHandler) { llsdHandler = null; // Pull out the first part of the path // splitting the path by '/' means we'll get the following return.. // {0}/{1}/{2} // where {0} isn't something we really control 100% string[] pathbase = path.Split('/'); string searchquery = "/"; if (pathbase.Length < 1) return false; for (int i = 1; i < pathbase.Length; i++) { searchquery += pathbase[i]; if (pathbase.Length - 1 != i) searchquery += "/"; } // while the matching algorithm below doesn't require it, we're expecting a query in the form // // [] = optional // /resource/UUID/action[/action] // // now try to get the closest match to the reigstered path // at least for OGP, registered path would probably only consist of the /resource/ string bestMatch = null; lock (m_llsdHandlers) { foreach (string pattern in m_llsdHandlers.Keys) { if (searchquery.ToLower().StartsWith(pattern.ToLower())) { if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length) { // You have to specifically register for '/' and to get it, you must specificaly request it // if (pattern == "/" && searchquery == "/" || pattern != "/") bestMatch = pattern; } } } if (String.IsNullOrEmpty(bestMatch)) { llsdHandler = null; return false; } else { llsdHandler = m_llsdHandlers[bestMatch]; return true; } } } private OSDMap GenerateNoLLSDHandlerResponse() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("LLSDRequest"); map["message"] = OSD.FromString("No handler registered for LLSD Requests"); map["login"] = OSD.FromString("false"); return map; } public byte[] HandleHTTPRequest(OSHttpRequest request, OSHttpResponse response) { // m_log.DebugFormat( // "[BASE HTTP SERVER]: HandleHTTPRequest for request to {0}, method {1}", // request.RawUrl, request.HttpMethod); switch (request.HttpMethod) { case "OPTIONS": response.StatusCode = (int)OSHttpStatusCode.SuccessOk; return null; default: return HandleContentVerbs(request, response); } } private byte[] HandleContentVerbs(OSHttpRequest request, OSHttpResponse response) { // m_log.DebugFormat("[BASE HTTP SERVER]: HandleContentVerbs for request to {0}", request.RawUrl); // This is a test. There's a workable alternative.. as this way sucks. // We'd like to put this into a text file parhaps that's easily editable. // // For this test to work, I used the following secondlife.exe parameters // "C:\Program Files\SecondLifeWindLight\SecondLifeWindLight.exe" -settings settings_windlight.xml -channel "Second Life WindLight" -set SystemLanguage en-us -loginpage http://10.1.1.2:8002/?show_login_form=TRUE -loginuri http://10.1.1.2:8002 -user 10.1.1.2 // // Even after all that, there's still an error, but it's a start. // // I depend on show_login_form being in the secondlife.exe parameters to figure out // to display the form, or process it. // a better way would be nifty. byte[] buffer; Stream requestStream = request.InputStream; Encoding encoding = Encoding.UTF8; StreamReader reader = new StreamReader(requestStream, encoding); string requestBody = reader.ReadToEnd(); // avoid warning for now reader.ReadToEnd(); reader.Close(); requestStream.Close(); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); Hashtable requestVars = new Hashtable(); string host = String.Empty; string[] querystringkeys = request.QueryString.AllKeys; string[] rHeaders = request.Headers.AllKeys; keysvals.Add("body", requestBody); keysvals.Add("uri", request.RawUrl); keysvals.Add("content-type", request.ContentType); keysvals.Add("http-method", request.HttpMethod); foreach (string queryname in querystringkeys) { // m_log.DebugFormat( // "[BASE HTTP SERVER]: Got query paremeter {0}={1}", queryname, request.QueryString[queryname]); // HttpRequest.QueryString.AllKeys returns a one-item array, with a null only, // if passed something without an '=' in the query, such as URL/?abc or URL/?abc+def if (queryname != null) { keysvals.Add(queryname, request.QueryString[queryname]); requestVars.Add(queryname, keysvals[queryname]); } } foreach (string headername in rHeaders) { // m_log.Debug("[BASE HTTP SERVER]: " + headername + "=" + request.Headers[headername]); headervals[headername] = request.Headers[headername]; } if (headervals.Contains("Host")) { host = (string)headervals["Host"]; } headervals["remote_addr"] = request.RemoteIPEndPoint.ToString(); keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); keysvals.Add("requestvars", requestVars); // keysvals.Add("form", request.Form); if (keysvals.Contains("method")) { // m_log.Debug("[BASE HTTP SERVER]: Contains Method"); string method = (string) keysvals["method"]; // m_log.Debug("[BASE HTTP SERVER]: " + requestBody); GenericHTTPMethod requestprocessor; bool foundHandler = TryGetHTTPHandler(method, out requestprocessor); if (foundHandler) { Hashtable responsedata1 = requestprocessor(keysvals); buffer = DoHTTPGruntWork(responsedata1, request, response); //SendHTML500(response); } else { // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found"); buffer = SendHTML404(response); } } else { GenericHTTPMethod requestprocessor; bool foundHandler = TryGetHTTPHandlerPathBased(request.RawUrl, out requestprocessor); if (foundHandler) { Hashtable responsedata2 = requestprocessor(keysvals); buffer = DoHTTPGruntWork(responsedata2, request, response); //SendHTML500(response); } else { // m_log.Warn("[BASE HTTP SERVER]: Handler Not Found2"); buffer = SendHTML404(response); } } return buffer; } private bool TryGetHTTPHandlerPathBased(string path, out GenericHTTPMethod httpHandler) { httpHandler = null; // Pull out the first part of the path // splitting the path by '/' means we'll get the following return.. // {0}/{1}/{2} // where {0} isn't something we really control 100% string[] pathbase = path.Split('/'); string searchquery = "/"; if (pathbase.Length < 1) return false; for (int i = 1; i < pathbase.Length; i++) { searchquery += pathbase[i]; if (pathbase.Length - 1 != i) searchquery += "/"; } // while the matching algorithm below doesn't require it, we're expecting a query in the form // // [] = optional // /resource/UUID/action[/action] // // now try to get the closest match to the reigstered path // at least for OGP, registered path would probably only consist of the /resource/ string bestMatch = null; // m_log.DebugFormat( // "[BASE HTTP HANDLER]: TryGetHTTPHandlerPathBased() looking for HTTP handler to match {0}", searchquery); lock (m_HTTPHandlers) { foreach (string pattern in m_HTTPHandlers.Keys) { if (searchquery.ToLower().StartsWith(pattern.ToLower())) { if (String.IsNullOrEmpty(bestMatch) || searchquery.Length > bestMatch.Length) { // You have to specifically register for '/' and to get it, you must specifically request it if (pattern == "/" && searchquery == "/" || pattern != "/") bestMatch = pattern; } } } if (String.IsNullOrEmpty(bestMatch)) { httpHandler = null; return false; } else { if (bestMatch == "/" && searchquery != "/") return false; httpHandler = m_HTTPHandlers[bestMatch]; return true; } } } public byte[] DoHTTPGruntWork(Hashtable responsedata, OSHttpRequest request, OSHttpResponse response) { //m_log.Info("[BASE HTTP SERVER]: Doing HTTP Grunt work with response"); int responsecode = (int)responsedata["int_response_code"]; string responseString = (string)responsedata["str_response_string"]; string contentType = (string)responsedata["content_type"]; byte[] responseBinary = responsedata.Contains("response_binary") ? (byte[])responsedata["response_binary"] : null; if (responsedata.ContainsKey("error_status_text")) { response.StatusDescription = (string)responsedata["error_status_text"]; } if (responsedata.ContainsKey("http_protocol_version")) { response.ProtocolVersion = new System.Version((string)responsedata["http_protocol_version"]); } if (responsedata.ContainsKey("keepalive")) { bool keepalive = (bool)responsedata["keepalive"]; response.KeepAlive = keepalive; } // Cross-Origin Resource Sharing with simple requests if (responsedata.ContainsKey("access_control_allow_origin")) response.AddHeader("Access-Control-Allow-Origin", (string)responsedata["access_control_allow_origin"]); // The client ignores anything but 200 here for web login, so ensure that this is 200 for that response.StatusCode = responsecode; if (responsecode == (int)OSHttpStatusCode.RedirectMovedPermanently) { response.RedirectLocation = (string)responsedata["str_redirect_location"]; response.StatusCode = responsecode; } if (string.IsNullOrEmpty(contentType)) contentType = "text/html"; response.AddHeader("Content-Type", contentType); byte[] buffer; if (responseBinary != null) { buffer = responseBinary; } else { if (!(contentType.Contains("image") || contentType.Contains("x-shockwave-flash") || contentType.Contains("application/x-oar") || contentType.Contains("application/vnd.ll.mesh"))) { // Text buffer = Encoding.UTF8.GetBytes(responseString); } else { // Binary! buffer = Convert.FromBase64String(responseString); } } response.SendChunked = false; response.ContentLength64 = buffer.LongLength; response.ContentEncoding = System.Text.Encoding.UTF8; return buffer; } public byte[] SendHTML404(OSHttpResponse response) { response.StatusCode = 404; response.AddHeader("Content-type", "text/html"); string responseString = GetHTTP404(); byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.SendChunked = false; response.ContentLength64 = buffer.Length; response.ContentEncoding = Encoding.UTF8; return buffer; } public byte[] SendHTML500(OSHttpResponse response) { response.StatusCode = (int)OSHttpStatusCode.ServerErrorInternalError; response.AddHeader("Content-type", "text/html"); string responseString = GetHTTP500(); byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.SendChunked = false; response.ContentLength64 = buffer.Length; response.ContentEncoding = Encoding.UTF8; return buffer; } public void Start() { m_log.InfoFormat( "[BASE HTTP SERVER]: Starting {0} server on port {1}", Secure ? "HTTPS" : "HTTP", Port); // netsh http add urlacl url=http://+:9000/ user=mdickson // netsh http add urlacl url=https://+:9016/ user=mdickson try { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; m_httpListener = new HttpListener(); m_httpListener.Prefixes.Add(Protocol + "+:" + Port.ToString() + "/"); // Start Listening m_httpListener.Start(); m_httpListener.BeginGetContext(new AsyncCallback(OnRequest), m_httpListener); } catch (Exception e) { m_log.ErrorFormat("[BASE HTTP SERVER]: Error - {0}", e.Message); m_log.ErrorFormat("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port {0} ?", m_port); m_log.ErrorFormat("[BASE HTTP SERVER]: Try: netsh http add urlacl url={0}://+:{1}/ user={2}", Secure ? "https" : "http", m_port, Environment.UserName); // We want this exception to halt the entire server since in current configurations we aren't too // useful without inbound HTTP. throw; } } public void Stop() { if (m_httpListener != null) { m_httpListener.Close(); m_httpListener = null; } } public void RemoveStreamHandler(string httpMethod, string path) { string handlerKey = GetHandlerKey(httpMethod, path); //m_log.DebugFormat("[BASE HTTP SERVER]: Removing handler key {0}", handlerKey); lock (m_streamHandlers) m_streamHandlers.Remove(handlerKey); } public void RemoveHTTPHandler(string httpMethod, string path) { lock (m_HTTPHandlers) { if (String.IsNullOrEmpty(httpMethod)) { m_HTTPHandlers.Remove(path); return; } m_HTTPHandlers.Remove(GetHandlerKey(httpMethod, path)); } } public void RemoveXmlRPCHandler(string method) { lock (m_rpcHandlers) { if (m_rpcHandlers.ContainsKey(method)) { m_rpcHandlers.Remove(method); } } } public bool RemoveLLSDHandler(string path, LLSDMethod handler) { lock (m_llsdHandlers) { LLSDMethod foundHandler; if (m_llsdHandlers.TryGetValue(path, out foundHandler) && foundHandler == handler) { m_llsdHandlers.Remove(path); return true; } } return false; } public string GetHTTP404() { string file = Path.Combine(".", "http_404.html"); if (!File.Exists(file)) return getDefaultHTTP404(FullHostName); StreamReader sr = File.OpenText(file); string result = sr.ReadToEnd(); sr.Close(); return result; } public string GetHTTP500() { string file = Path.Combine(".", "http_500.html"); if (!File.Exists(file)) return getDefaultHTTP500(); StreamReader sr = File.OpenText(file); string result = sr.ReadToEnd(); sr.Close(); return result; } // Fallback HTTP responses in case the HTTP error response files don't exist private static string getDefaultHTTP404(string host) { return "<HTML><HEAD><TITLE>404 Page not found</TITLE><BODY><BR /><H1>Ooops!</H1><P>You have reached a Halcyon-based server.</P><P>To log in to this virtual world, you must connect with a viewer application or web-based viewer.</P></BODY></HTML>"; } private static string getDefaultHTTP500() { return "<HTML><HEAD><TITLE>500 Internal Server Error</TITLE><BODY><BR /><H1>Ooops!</H1><P>The Halcyon-based server you requested does not support browser logins.</P></BODY></HTML>"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Mail { public partial class AlternateView : System.Net.Mail.AttachmentBase { public AlternateView(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { } public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public AlternateView(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { } public AlternateView(string fileName) : base (default(System.IO.Stream)) { } public AlternateView(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public AlternateView(string fileName, string mediaType) : base (default(System.IO.Stream)) { } public System.Uri BaseUri { get { throw null; } set { } } public System.Net.Mail.LinkedResourceCollection LinkedResources { get { throw null; } } public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content) { throw null; } public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType contentType) { throw null; } public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; } protected override void Dispose(bool disposing) { } } public sealed partial class AlternateViewCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.AlternateView>, System.IDisposable { internal AlternateViewCollection() { } protected override void ClearItems() { } public void Dispose() { } protected override void InsertItem(int index, System.Net.Mail.AlternateView item) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, System.Net.Mail.AlternateView item) { } } public partial class Attachment : System.Net.Mail.AttachmentBase { public Attachment(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public Attachment(System.IO.Stream contentStream, string name) : base (default(System.IO.Stream)) { } public Attachment(System.IO.Stream contentStream, string name, string mediaType) : base (default(System.IO.Stream)) { } public Attachment(string fileName) : base (default(System.IO.Stream)) { } public Attachment(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public Attachment(string fileName, string mediaType) : base (default(System.IO.Stream)) { } public System.Net.Mime.ContentDisposition ContentDisposition { get { throw null; } } public string Name { get { throw null; } set { } } public System.Text.Encoding NameEncoding { get { throw null; } set { } } public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, System.Net.Mime.ContentType contentType) { throw null; } public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name) { throw null; } public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name, System.Text.Encoding contentEncoding, string mediaType) { throw null; } } public abstract partial class AttachmentBase : System.IDisposable { protected AttachmentBase(System.IO.Stream contentStream) { } protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) { } protected AttachmentBase(System.IO.Stream contentStream, string mediaType) { } protected AttachmentBase(string fileName) { } protected AttachmentBase(string fileName, System.Net.Mime.ContentType contentType) { } protected AttachmentBase(string fileName, string mediaType) { } public string ContentId { get { throw null; } set { } } public System.IO.Stream ContentStream { get { throw null; } } public System.Net.Mime.ContentType ContentType { get { throw null; } set { } } public System.Net.Mime.TransferEncoding TransferEncoding { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public sealed partial class AttachmentCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.Attachment>, System.IDisposable { internal AttachmentCollection() { } protected override void ClearItems() { } public void Dispose() { } protected override void InsertItem(int index, System.Net.Mail.Attachment item) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, System.Net.Mail.Attachment item) { } } [System.FlagsAttribute] public enum DeliveryNotificationOptions { None = 0, OnSuccess = 1, OnFailure = 2, Delay = 4, Never = 134217728, } public partial class LinkedResource : System.Net.Mail.AttachmentBase { public LinkedResource(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { } public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public LinkedResource(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { } public LinkedResource(string fileName) : base (default(System.IO.Stream)) { } public LinkedResource(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public LinkedResource(string fileName, string mediaType) : base (default(System.IO.Stream)) { } public System.Uri ContentLink { get { throw null; } set { } } public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content) { throw null; } public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType) { throw null; } public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; } } public sealed partial class LinkedResourceCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.LinkedResource>, System.IDisposable { internal LinkedResourceCollection() { } protected override void ClearItems() { } public void Dispose() { } protected override void InsertItem(int index, System.Net.Mail.LinkedResource item) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, System.Net.Mail.LinkedResource item) { } } public partial class MailAddress { public MailAddress(string address) { } public MailAddress(string address, string displayName) { } public MailAddress(string address, string displayName, System.Text.Encoding displayNameEncoding) { } public string Address { get { throw null; } } public string DisplayName { get { throw null; } } public string Host { get { throw null; } } public string User { get { throw null; } } public override bool Equals(object value) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public partial class MailAddressCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.MailAddress> { public MailAddressCollection() { } public void Add(string addresses) { } protected override void InsertItem(int index, System.Net.Mail.MailAddress item) { } protected override void SetItem(int index, System.Net.Mail.MailAddress item) { } public override string ToString() { throw null; } } public partial class MailMessage : System.IDisposable { public MailMessage() { } public MailMessage(System.Net.Mail.MailAddress from, System.Net.Mail.MailAddress to) { } public MailMessage(string from, string to) { } public MailMessage(string from, string to, string subject, string body) { } public System.Net.Mail.AlternateViewCollection AlternateViews { get { throw null; } } public System.Net.Mail.AttachmentCollection Attachments { get { throw null; } } public System.Net.Mail.MailAddressCollection Bcc { get { throw null; } } public string Body { get { throw null; } set { } } public System.Text.Encoding BodyEncoding { get { throw null; } set { } } public System.Net.Mime.TransferEncoding BodyTransferEncoding { get { throw null; } set { } } public System.Net.Mail.MailAddressCollection CC { get { throw null; } } public System.Net.Mail.DeliveryNotificationOptions DeliveryNotificationOptions { get { throw null; } set { } } public System.Net.Mail.MailAddress From { get { throw null; } set { } } public System.Collections.Specialized.NameValueCollection Headers { get { throw null; } } public System.Text.Encoding HeadersEncoding { get { throw null; } set { } } public bool IsBodyHtml { get { throw null; } set { } } public System.Net.Mail.MailPriority Priority { get { throw null; } set { } } [System.ObsoleteAttribute("ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. https://go.microsoft.com/fwlink/?linkid=14202")] public System.Net.Mail.MailAddress ReplyTo { get { throw null; } set { } } public System.Net.Mail.MailAddressCollection ReplyToList { get { throw null; } } public System.Net.Mail.MailAddress Sender { get { throw null; } set { } } public string Subject { get { throw null; } set { } } public System.Text.Encoding SubjectEncoding { get { throw null; } set { } } public System.Net.Mail.MailAddressCollection To { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public enum MailPriority { Normal = 0, Low = 1, High = 2, } public delegate void SendCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); public partial class SmtpClient : System.IDisposable { public SmtpClient() { } public SmtpClient(string host) { } public SmtpClient(string host, int port) { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } } public System.Net.ICredentialsByHost Credentials { get { throw null; } set { } } public System.Net.Mail.SmtpDeliveryFormat DeliveryFormat { get { throw null; } set { } } public System.Net.Mail.SmtpDeliveryMethod DeliveryMethod { get { throw null; } set { } } public bool EnableSsl { get { throw null; } set { } } public string Host { get { throw null; } set { } } public string PickupDirectoryLocation { get { throw null; } set { } } public int Port { get { throw null; } set { } } public System.Net.ServicePoint ServicePoint { get { throw null; } } public string TargetName { get { throw null; } set { } } public int Timeout { get { throw null; } set { } } public bool UseDefaultCredentials { get { throw null; } set { } } public event System.Net.Mail.SendCompletedEventHandler SendCompleted { add { } remove { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected void OnSendCompleted(System.ComponentModel.AsyncCompletedEventArgs e) { } public void Send(System.Net.Mail.MailMessage message) { } public void Send(string from, string recipients, string subject, string body) { } public void SendAsync(System.Net.Mail.MailMessage message, object userToken) { } public void SendAsync(string from, string recipients, string subject, string body, object userToken) { } public void SendAsyncCancel() { } public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message) { throw null; } public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string subject, string body) { throw null; } } public enum SmtpDeliveryFormat { SevenBit = 0, International = 1, } public enum SmtpDeliveryMethod { Network = 0, SpecifiedPickupDirectory = 1, PickupDirectoryFromIis = 2, } public partial class SmtpException : System.Exception, System.Runtime.Serialization.ISerializable { public SmtpException() { } public SmtpException(System.Net.Mail.SmtpStatusCode statusCode) { } public SmtpException(System.Net.Mail.SmtpStatusCode statusCode, string message) { } protected SmtpException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public SmtpException(string message) { } public SmtpException(string message, System.Exception innerException) { } public System.Net.Mail.SmtpStatusCode StatusCode { get { throw null; } set { } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class SmtpFailedRecipientException : System.Net.Mail.SmtpException, System.Runtime.Serialization.ISerializable { public SmtpFailedRecipientException() { } public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient) { } public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient, string serverResponse) { } protected SmtpFailedRecipientException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SmtpFailedRecipientException(string message) { } public SmtpFailedRecipientException(string message, System.Exception innerException) { } public SmtpFailedRecipientException(string message, string failedRecipient, System.Exception innerException) { } public string FailedRecipient { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class SmtpFailedRecipientsException : System.Net.Mail.SmtpFailedRecipientException, System.Runtime.Serialization.ISerializable { public SmtpFailedRecipientsException() { } protected SmtpFailedRecipientsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SmtpFailedRecipientsException(string message) { } public SmtpFailedRecipientsException(string message, System.Exception innerException) { } public SmtpFailedRecipientsException(string message, System.Net.Mail.SmtpFailedRecipientException[] innerExceptions) { } public System.Net.Mail.SmtpFailedRecipientException[] InnerExceptions { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public enum SmtpStatusCode { GeneralFailure = -1, SystemStatus = 211, HelpMessage = 214, ServiceReady = 220, ServiceClosingTransmissionChannel = 221, Ok = 250, UserNotLocalWillForward = 251, CannotVerifyUserWillAttemptDelivery = 252, StartMailInput = 354, ServiceNotAvailable = 421, MailboxBusy = 450, LocalErrorInProcessing = 451, InsufficientStorage = 452, ClientNotPermitted = 454, CommandUnrecognized = 500, SyntaxError = 501, CommandNotImplemented = 502, BadCommandSequence = 503, CommandParameterNotImplemented = 504, MustIssueStartTlsFirst = 530, MailboxUnavailable = 550, UserNotLocalTryAlternatePath = 551, ExceededStorageAllocation = 552, MailboxNameNotAllowed = 553, TransactionFailed = 554, } } namespace System.Net.Mime { public partial class ContentDisposition { public ContentDisposition() { } public ContentDisposition(string disposition) { } public System.DateTime CreationDate { get { throw null; } set { } } public string DispositionType { get { throw null; } set { } } public string FileName { get { throw null; } set { } } public bool Inline { get { throw null; } set { } } public System.DateTime ModificationDate { get { throw null; } set { } } public System.Collections.Specialized.StringDictionary Parameters { get { throw null; } } public System.DateTime ReadDate { get { throw null; } set { } } public long Size { get { throw null; } set { } } public override bool Equals(object rparam) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public partial class ContentType { public ContentType() { } public ContentType(string contentType) { } public string Boundary { get { throw null; } set { } } public string CharSet { get { throw null; } set { } } public string MediaType { get { throw null; } set { } } public string Name { get { throw null; } set { } } public System.Collections.Specialized.StringDictionary Parameters { get { throw null; } } public override bool Equals(object rparam) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public static partial class DispositionTypeNames { public const string Attachment = "attachment"; public const string Inline = "inline"; } public static partial class MediaTypeNames { public static partial class Application { public const string Json = "application/json"; public const string Octet = "application/octet-stream"; public const string Pdf = "application/pdf"; public const string Rtf = "application/rtf"; public const string Soap = "application/soap+xml"; public const string Xml = "application/xml"; public const string Zip = "application/zip"; } public static partial class Image { public const string Gif = "image/gif"; public const string Jpeg = "image/jpeg"; public const string Tiff = "image/tiff"; } public static partial class Text { public const string Html = "text/html"; public const string Plain = "text/plain"; public const string RichText = "text/richtext"; public const string Xml = "text/xml"; } } public enum TransferEncoding { Unknown = -1, QuotedPrintable = 0, Base64 = 1, SevenBit = 2, EightBit = 3, } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : brian.nickel@gmail.com based on : id3v2header.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System; namespace TagLib.Id3v2 { public class Footer { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private uint major_version; private uint revision_number; private bool unsynchronisation; private bool extended_header; private bool experimental_indicator; private uint tag_size; private static uint size = 10; ////////////////////////////////////////////////////////////////////////// // public static fields ////////////////////////////////////////////////////////////////////////// public static uint Size {get {return size;}} public static readonly ByteVector FileIdentifier = "3DI"; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public Footer () { major_version = 0; revision_number = 0; unsynchronisation = false; extended_header = false; experimental_indicator = false; tag_size = 0; } public Footer (ByteVector data) : this () { Parse (data); } public Footer (Header header) : this () { major_version = header.MajorVersion; revision_number = header.RevisionNumber; unsynchronisation = header.Unsynchronisation; extended_header = header.ExtendedHeader; experimental_indicator = header.ExperimentalIndicator; tag_size = header.TagSize; } public void SetData (ByteVector data) { Parse (data); } public ByteVector Render () { ByteVector v = new ByteVector (); // add the file identifier -- "3DI" v.Add (FileIdentifier); // add the version number -- we always render a 2.4.0 tag regardless of what // the tag originally was. v.Add ((byte)4); v.Add ((byte)0); // render and add the flags byte flags = 0; if (Unsynchronisation) flags |= 128; if (ExtendedHeader) flags |= 64; if (ExperimentalIndicator) flags |= 32; flags |= 16; v.Add (flags); // add the size v.Add (SynchData.FromUInt (TagSize)); return v; } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public uint MajorVersion { get {return major_version;} set {major_version = value;} } public uint RevisionNumber { get {return revision_number;} set {revision_number = value;} } public bool Unsynchronisation { get {return unsynchronisation;} set {unsynchronisation = value;} } public bool ExtendedHeader { get {return extended_header;} set {extended_header = value;} } public bool ExperimentalIndicator { get {return experimental_indicator;} set {experimental_indicator = value;} } public bool FooterPresent { get {return true;} } public uint TagSize { get {return tag_size;} set {tag_size = value;} } public uint CompleteTagSize { get { return TagSize + Header.Size + Size; } } ////////////////////////////////////////////////////////////////////////// // protected methods ////////////////////////////////////////////////////////////////////////// protected void Parse (ByteVector data) { if(data.Count < Size) return; // do some sanity checking -- even in ID3v2.3.0 and less the tag size is a // synch-safe integer, so all bytes must be less than 128. If this is not // true then this is an invalid tag. // note that we're doing things a little out of order here -- the size is // later in the bytestream than the version ByteVector size_data = data.Mid (6, 4); if (size_data.Count != 4) { tag_size = 0; Debugger.Debug ("ID3v2.Footer.Parse () - The tag size as read was 0 bytes!"); return; } foreach (byte b in size_data) if (b >= 128) { tag_size = 0; Debugger.Debug ("ID3v2.Footer.Parse () - One of the size bytes in the id3v2 header was greater than the allowed 128."); return; } // The first three bytes, data[0..2], are the File Identifier, "ID3". (structure 3.1 "file identifier") // Read the version number from the fourth and fifth bytes. major_version = data [3]; // (structure 3.1 "major version") revision_number = data [4]; // (structure 3.1 "revision number") // Read the flags, the first four bits of the sixth byte. byte flags = data [5]; unsynchronisation = ((flags >> 7) & 1) == 1; // (structure 3.1.a) extended_header = ((flags >> 6) & 1) == 1; // (structure 3.1.b) experimental_indicator = ((flags >> 5) & 1) == 1; // (structure 3.1.c) // Get the size from the remaining four bytes (read above) tag_size = SynchData.ToUInt (size_data); // (structure 3.1 "size") } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes { #region Delegates public delegate uint GenerateClientFlagsHandler(UUID userID, UUID objectID); public delegate void SetBypassPermissionsHandler(bool value); public delegate bool BypassPermissionsHandler(); public delegate bool PropagatePermissionsHandler(); public delegate bool RezObjectHandler(int objectCount, UUID owner, Vector3 objectPosition, Scene scene); public delegate bool DeleteObjectHandler(UUID objectID, UUID deleter, Scene scene); public delegate bool TransferObjectHandler(UUID objectID, UUID recipient, Scene scene); public delegate bool TakeObjectHandler(UUID objectID, UUID stealer, Scene scene); public delegate bool TakeCopyObjectHandler(UUID objectID, UUID userID, Scene inScene); public delegate bool DuplicateObjectHandler(int objectCount, UUID objectID, UUID owner, Scene scene, Vector3 objectPosition); public delegate bool EditObjectHandler(UUID objectID, UUID editorID, Scene scene); public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID, Scene scene); public delegate bool MoveObjectHandler(UUID objectID, UUID moverID, Scene scene); public delegate bool ObjectEntryHandler(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene); public delegate bool ReturnObjectsHandler(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene); public delegate bool InstantMessageHandler(UUID user, UUID target, Scene startScene); public delegate bool InventoryTransferHandler(UUID user, UUID target, Scene startScene); public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user, Scene scene); public delegate bool RunScriptHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool CompileScriptHandler(UUID ownerUUID, int scriptType, Scene scene); public delegate bool StartScriptHandler(UUID script, UUID user, Scene scene); public delegate bool StopScriptHandler(UUID script, UUID user, Scene scene); public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user, Scene scene); public delegate bool TerraformLandHandler(UUID user, Vector3 position, Scene requestFromScene); public delegate bool RunConsoleCommandHandler(UUID user, Scene requestFromScene); public delegate bool IssueEstateCommandHandler(UUID user, Scene requestFromScene, bool ownerCommand); public delegate bool IsGodHandler(UUID user, Scene requestFromScene); public delegate bool IsGridGodHandler(UUID user, Scene requestFromScene); public delegate bool IsAdministratorHandler(UUID user); public delegate bool EditParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool EditParcelPropertiesHandler(UUID user, ILandObject parcel, GroupPowers p, Scene scene, bool allowManager); public delegate bool SellParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool DeedParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool DeedObjectHandler(UUID user, UUID group, Scene scene); public delegate bool BuyLandHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool LinkObjectHandler(UUID user, UUID objectID); public delegate bool DelinkObjectHandler(UUID user, UUID objectID); public delegate bool CreateObjectInventoryHandler(int invType, UUID objectID, UUID userID); public delegate bool CopyObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID); public delegate bool DeleteObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID); public delegate bool TransferObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID); public delegate bool CreateUserInventoryHandler(int invType, UUID userID); public delegate bool EditUserInventoryHandler(UUID itemID, UUID userID); public delegate bool CopyUserInventoryHandler(UUID itemID, UUID userID); public delegate bool DeleteUserInventoryHandler(UUID itemID, UUID userID); public delegate bool TransferUserInventoryHandler(UUID itemID, UUID userID, UUID recipientID); public delegate bool TeleportHandler(UUID userID, Scene scene); public delegate bool ControlPrimMediaHandler(UUID userID, UUID primID, int face); public delegate bool InteractWithPrimMediaHandler(UUID userID, UUID primID, int face); #endregion public class ScenePermissions { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; public ScenePermissions(Scene scene) { m_scene = scene; } #region Events public event GenerateClientFlagsHandler OnGenerateClientFlags; public event SetBypassPermissionsHandler OnSetBypassPermissions; public event BypassPermissionsHandler OnBypassPermissions; public event PropagatePermissionsHandler OnPropagatePermissions; public event RezObjectHandler OnRezObject; public event DeleteObjectHandler OnDeleteObject; public event TransferObjectHandler OnTransferObject; public event TakeObjectHandler OnTakeObject; public event TakeCopyObjectHandler OnTakeCopyObject; public event DuplicateObjectHandler OnDuplicateObject; public event EditObjectHandler OnEditObject; public event EditObjectInventoryHandler OnEditObjectInventory; public event MoveObjectHandler OnMoveObject; public event ObjectEntryHandler OnObjectEntry; public event ReturnObjectsHandler OnReturnObjects; public event InstantMessageHandler OnInstantMessage; public event InventoryTransferHandler OnInventoryTransfer; public event ViewScriptHandler OnViewScript; public event ViewNotecardHandler OnViewNotecard; public event EditScriptHandler OnEditScript; public event EditNotecardHandler OnEditNotecard; public event RunScriptHandler OnRunScript; public event CompileScriptHandler OnCompileScript; public event StartScriptHandler OnStartScript; public event StopScriptHandler OnStopScript; public event ResetScriptHandler OnResetScript; public event TerraformLandHandler OnTerraformLand; public event RunConsoleCommandHandler OnRunConsoleCommand; public event IssueEstateCommandHandler OnIssueEstateCommand; public event IsGodHandler OnIsGod; public event IsGridGodHandler OnIsGridGod; public event IsAdministratorHandler OnIsAdministrator; // public event EditParcelHandler OnEditParcel; public event EditParcelPropertiesHandler OnEditParcelProperties; public event SellParcelHandler OnSellParcel; public event AbandonParcelHandler OnAbandonParcel; public event ReclaimParcelHandler OnReclaimParcel; public event DeedParcelHandler OnDeedParcel; public event DeedObjectHandler OnDeedObject; public event BuyLandHandler OnBuyLand; public event LinkObjectHandler OnLinkObject; public event DelinkObjectHandler OnDelinkObject; public event CreateObjectInventoryHandler OnCreateObjectInventory; public event CopyObjectInventoryHandler OnCopyObjectInventory; public event DeleteObjectInventoryHandler OnDeleteObjectInventory; public event TransferObjectInventoryHandler OnTransferObjectInventory; public event CreateUserInventoryHandler OnCreateUserInventory; public event EditUserInventoryHandler OnEditUserInventory; public event CopyUserInventoryHandler OnCopyUserInventory; public event DeleteUserInventoryHandler OnDeleteUserInventory; public event TransferUserInventoryHandler OnTransferUserInventory; public event TeleportHandler OnTeleport; public event ControlPrimMediaHandler OnControlPrimMedia; public event InteractWithPrimMediaHandler OnInteractWithPrimMedia; #endregion #region Object Permission Checks public uint GenerateClientFlags(UUID userID, UUID objectID) { // libomv will moan about PrimFlags.ObjectYouOfficer being // obsolete... #pragma warning disable 0612 const PrimFlags DEFAULT_FLAGS = PrimFlags.ObjectModify | PrimFlags.ObjectCopy | PrimFlags.ObjectMove | PrimFlags.ObjectTransfer | PrimFlags.ObjectYouOwner | PrimFlags.ObjectAnyOwner | PrimFlags.ObjectOwnerModify | PrimFlags.ObjectYouOfficer; #pragma warning restore 0612 SceneObjectPart part = m_scene.GetSceneObjectPart(objectID); if (part == null) return 0; uint perms = part.GetEffectiveObjectFlags() | (uint)DEFAULT_FLAGS; GenerateClientFlagsHandler handlerGenerateClientFlags = OnGenerateClientFlags; if (handlerGenerateClientFlags != null) { Delegate[] list = handlerGenerateClientFlags.GetInvocationList(); foreach (GenerateClientFlagsHandler check in list) { perms &= check(userID, objectID); } } return perms; } public void SetBypassPermissions(bool value) { SetBypassPermissionsHandler handler = OnSetBypassPermissions; if (handler != null) handler(value); } public bool BypassPermissions() { BypassPermissionsHandler handler = OnBypassPermissions; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (BypassPermissionsHandler h in list) { if (h() == false) return false; } } return true; } public bool PropagatePermissions() { PropagatePermissionsHandler handler = OnPropagatePermissions; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (PropagatePermissionsHandler h in list) { if (h() == false) return false; } } return true; } #region REZ OBJECT public bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition) { RezObjectHandler handler = OnRezObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (RezObjectHandler h in list) { if (h(objectCount, owner,objectPosition, m_scene) == false) return false; } } return true; } #endregion #region DELETE OBJECT public bool CanDeleteObject(UUID objectID, UUID deleter) { bool result = true; DeleteObjectHandler handler = OnDeleteObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeleteObjectHandler h in list) { if (h(objectID, deleter, m_scene) == false) { result = false; break; } } } return result; } public bool CanTransferObject(UUID objectID, UUID recipient) { bool result = true; TransferObjectHandler handler = OnTransferObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TransferObjectHandler h in list) { if (h(objectID, recipient, m_scene) == false) { result = false; break; } } } return result; } #endregion #region TAKE OBJECT public bool CanTakeObject(UUID objectID, UUID AvatarTakingUUID) { bool result = true; TakeObjectHandler handler = OnTakeObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TakeObjectHandler h in list) { if (h(objectID, AvatarTakingUUID, m_scene) == false) { result = false; break; } } } // m_log.DebugFormat( // "[SCENE PERMISSIONS]: CanTakeObject() fired for object {0}, taker {1}, result {2}", // objectID, AvatarTakingUUID, result); return result; } #endregion #region TAKE COPY OBJECT public bool CanTakeCopyObject(UUID objectID, UUID userID) { bool result = true; TakeCopyObjectHandler handler = OnTakeCopyObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TakeCopyObjectHandler h in list) { if (h(objectID, userID, m_scene) == false) { result = false; break; } } } // m_log.DebugFormat( // "[SCENE PERMISSIONS]: CanTakeCopyObject() fired for object {0}, user {1}, result {2}", // objectID, userID, result); return result; } #endregion #region DUPLICATE OBJECT public bool CanDuplicateObject(int objectCount, UUID objectID, UUID owner, Vector3 objectPosition) { DuplicateObjectHandler handler = OnDuplicateObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DuplicateObjectHandler h in list) { if (h(objectCount, objectID, owner, m_scene, objectPosition) == false) return false; } } return true; } #endregion #region EDIT OBJECT public bool CanEditObject(UUID objectID, UUID editorID) { EditObjectHandler handler = OnEditObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditObjectHandler h in list) { if (h(objectID, editorID, m_scene) == false) return false; } } return true; } public bool CanEditObjectInventory(UUID objectID, UUID editorID) { EditObjectInventoryHandler handler = OnEditObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditObjectInventoryHandler h in list) { if (h(objectID, editorID, m_scene) == false) return false; } } return true; } #endregion #region MOVE OBJECT public bool CanMoveObject(UUID objectID, UUID moverID) { MoveObjectHandler handler = OnMoveObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (MoveObjectHandler h in list) { if (h(objectID, moverID, m_scene) == false) return false; } } return true; } #endregion #region OBJECT ENTRY public bool CanObjectEntry(UUID objectID, bool enteringRegion, Vector3 newPoint) { ObjectEntryHandler handler = OnObjectEntry; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ObjectEntryHandler h in list) { if (h(objectID, enteringRegion, newPoint, m_scene) == false) return false; } } return true; } #endregion #region RETURN OBJECT public bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects) { bool result = true; ReturnObjectsHandler handler = OnReturnObjects; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ReturnObjectsHandler h in list) { if (h(land, user, objects, m_scene) == false) { result = false; break; } } } // m_log.DebugFormat( // "[SCENE PERMISSIONS]: CanReturnObjects() fired for user {0} for {1} objects on {2}, result {3}", // user, objects.Count, land.LandData.Name, result); return result; } #endregion #region INSTANT MESSAGE public bool CanInstantMessage(UUID user, UUID target) { InstantMessageHandler handler = OnInstantMessage; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (InstantMessageHandler h in list) { if (h(user, target, m_scene) == false) return false; } } return true; } #endregion #region INVENTORY TRANSFER public bool CanInventoryTransfer(UUID user, UUID target) { InventoryTransferHandler handler = OnInventoryTransfer; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (InventoryTransferHandler h in list) { if (h(user, target, m_scene) == false) return false; } } return true; } #endregion #region VIEW SCRIPT public bool CanViewScript(UUID script, UUID objectID, UUID user) { ViewScriptHandler handler = OnViewScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ViewScriptHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } public bool CanViewNotecard(UUID script, UUID objectID, UUID user) { ViewNotecardHandler handler = OnViewNotecard; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ViewNotecardHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } #endregion #region EDIT SCRIPT public bool CanEditScript(UUID script, UUID objectID, UUID user) { EditScriptHandler handler = OnEditScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditScriptHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } public bool CanEditNotecard(UUID script, UUID objectID, UUID user) { EditNotecardHandler handler = OnEditNotecard; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditNotecardHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } #endregion #region RUN SCRIPT (When Script Placed in Object) public bool CanRunScript(UUID script, UUID objectID, UUID user) { RunScriptHandler handler = OnRunScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (RunScriptHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } #endregion #region COMPILE SCRIPT (When Script needs to get (re)compiled) public bool CanCompileScript(UUID ownerUUID, int scriptType) { CompileScriptHandler handler = OnCompileScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CompileScriptHandler h in list) { if (h(ownerUUID, scriptType, m_scene) == false) return false; } } return true; } #endregion #region START SCRIPT (When Script run box is Checked after placed in object) public bool CanStartScript(UUID script, UUID user) { StartScriptHandler handler = OnStartScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (StartScriptHandler h in list) { if (h(script, user, m_scene) == false) return false; } } return true; } #endregion #region STOP SCRIPT (When Script run box is unchecked after placed in object) public bool CanStopScript(UUID script, UUID user) { StopScriptHandler handler = OnStopScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (StopScriptHandler h in list) { if (h(script, user, m_scene) == false) return false; } } return true; } #endregion #region RESET SCRIPT public bool CanResetScript(UUID prim, UUID script, UUID user) { ResetScriptHandler handler = OnResetScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ResetScriptHandler h in list) { if (h(prim, script, user, m_scene) == false) return false; } } return true; } #endregion #region TERRAFORM LAND public bool CanTerraformLand(UUID user, Vector3 pos) { TerraformLandHandler handler = OnTerraformLand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TerraformLandHandler h in list) { if (h(user, pos, m_scene) == false) return false; } } return true; } #endregion #region RUN CONSOLE COMMAND public bool CanRunConsoleCommand(UUID user) { RunConsoleCommandHandler handler = OnRunConsoleCommand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (RunConsoleCommandHandler h in list) { if (h(user, m_scene) == false) return false; } } return true; } #endregion #region CAN ISSUE ESTATE COMMAND public bool CanIssueEstateCommand(UUID user, bool ownerCommand) { IssueEstateCommandHandler handler = OnIssueEstateCommand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IssueEstateCommandHandler h in list) { if (h(user, m_scene, ownerCommand) == false) return false; } } return true; } #endregion #region CAN BE GODLIKE public bool IsGod(UUID user) { IsGodHandler handler = OnIsGod; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IsGodHandler h in list) { if (h(user, m_scene) == false) return false; } } return true; } public bool IsGridGod(UUID user) { IsGridGodHandler handler = OnIsGridGod; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IsGridGodHandler h in list) { if (h(user, m_scene) == false) return false; } } return true; } public bool IsAdministrator(UUID user) { IsAdministratorHandler handler = OnIsAdministrator; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IsAdministratorHandler h in list) { if (h(user) == false) return false; } } return true; } #endregion #region EDIT PARCEL public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers p, bool allowManager) { EditParcelPropertiesHandler handler = OnEditParcelProperties; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditParcelPropertiesHandler h in list) { if (h(user, parcel, p, m_scene, allowManager) == false) return false; } } return true; } #endregion #region SELL PARCEL public bool CanSellParcel(UUID user, ILandObject parcel) { SellParcelHandler handler = OnSellParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (SellParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } #endregion #region ABANDON PARCEL public bool CanAbandonParcel(UUID user, ILandObject parcel) { AbandonParcelHandler handler = OnAbandonParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (AbandonParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } #endregion public bool CanReclaimParcel(UUID user, ILandObject parcel) { ReclaimParcelHandler handler = OnReclaimParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ReclaimParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } public bool CanDeedParcel(UUID user, ILandObject parcel) { DeedParcelHandler handler = OnDeedParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeedParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } public bool CanDeedObject(UUID user, UUID group) { DeedObjectHandler handler = OnDeedObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeedObjectHandler h in list) { if (h(user, group, m_scene) == false) return false; } } return true; } public bool CanBuyLand(UUID user, ILandObject parcel) { BuyLandHandler handler = OnBuyLand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (BuyLandHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } public bool CanLinkObject(UUID user, UUID objectID) { LinkObjectHandler handler = OnLinkObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (LinkObjectHandler h in list) { if (h(user, objectID) == false) return false; } } return true; } public bool CanDelinkObject(UUID user, UUID objectID) { DelinkObjectHandler handler = OnDelinkObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DelinkObjectHandler h in list) { if (h(user, objectID) == false) return false; } } return true; } #endregion /// Check whether the specified user is allowed to directly create the given inventory type in a prim's /// inventory (e.g. the New Script button in the 1.21 Linden Lab client). /// </summary> /// <param name="invType"></param> /// <param name="objectID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanCreateObjectInventory(int invType, UUID objectID, UUID userID) { CreateObjectInventoryHandler handler = OnCreateObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CreateObjectInventoryHandler h in list) { if (h(invType, objectID, userID) == false) return false; } } return true; } public bool CanCopyObjectInventory(UUID itemID, UUID objectID, UUID userID) { CopyObjectInventoryHandler handler = OnCopyObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CopyObjectInventoryHandler h in list) { if (h(itemID, objectID, userID) == false) return false; } } return true; } public bool CanDeleteObjectInventory(UUID itemID, UUID objectID, UUID userID) { DeleteObjectInventoryHandler handler = OnDeleteObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeleteObjectInventoryHandler h in list) { if (h(itemID, objectID, userID) == false) return false; } } return true; } public bool CanTransferObjectInventory(UUID itemID, UUID objectID, UUID userID) { TransferObjectInventoryHandler handler = OnTransferObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TransferObjectInventoryHandler h in list) { if (h(itemID, objectID, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to create the given inventory type in their inventory. /// </summary> /// <param name="invType"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanCreateUserInventory(int invType, UUID userID) { CreateUserInventoryHandler handler = OnCreateUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CreateUserInventoryHandler h in list) { if (h(invType, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to edit the given inventory item within their own inventory. /// </summary> /// <param name="itemID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanEditUserInventory(UUID itemID, UUID userID) { EditUserInventoryHandler handler = OnEditUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditUserInventoryHandler h in list) { if (h(itemID, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to copy the given inventory item from their own inventory. /// </summary> /// <param name="itemID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanCopyUserInventory(UUID itemID, UUID userID) { CopyUserInventoryHandler handler = OnCopyUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CopyUserInventoryHandler h in list) { if (h(itemID, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to edit the given inventory item within their own inventory. /// </summary> /// <param name="itemID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanDeleteUserInventory(UUID itemID, UUID userID) { DeleteUserInventoryHandler handler = OnDeleteUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeleteUserInventoryHandler h in list) { if (h(itemID, userID) == false) return false; } } return true; } public bool CanTransferUserInventory(UUID itemID, UUID userID, UUID recipientID) { TransferUserInventoryHandler handler = OnTransferUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TransferUserInventoryHandler h in list) { if (h(itemID, userID, recipientID) == false) return false; } } return true; } public bool CanTeleport(UUID userID) { TeleportHandler handler = OnTeleport; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TeleportHandler h in list) { if (h(userID, m_scene) == false) return false; } } return true; } public bool CanControlPrimMedia(UUID userID, UUID primID, int face) { ControlPrimMediaHandler handler = OnControlPrimMedia; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ControlPrimMediaHandler h in list) { if (h(userID, primID, face) == false) return false; } } return true; } public bool CanInteractWithPrimMedia(UUID userID, UUID primID, int face) { InteractWithPrimMediaHandler handler = OnInteractWithPrimMedia; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (InteractWithPrimMediaHandler h in list) { if (h(userID, primID, face) == false) return false; } } return true; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class KinectGestures { public interface GestureListenerInterface { // Invoked when a new user is detected and tracking starts // Here you can start gesture detection with KinectManager.DetectGesture() void UserDetected(ulong userId, int userIndex); // Invoked when a user is lost // Gestures for this user are cleared automatically, but you can free the used resources void UserLost(ulong userId, int userIndex); // Invoked when a gesture is in progress void GestureInProgress(ulong userId, int userIndex, Gestures gesture, float progress, KinectCommon.NuiSkeletonPositionIndex joint, Vector3 screenPos); // Invoked if a gesture is completed. // Returns true, if the gesture detection must be restarted, false otherwise bool GestureCompleted(ulong userId, int userIndex, Gestures gesture, KinectCommon.NuiSkeletonPositionIndex joint, Vector3 screenPos); // Invoked if a gesture is cancelled. // Returns true, if the gesture detection must be retarted, false otherwise bool GestureCancelled(ulong userId, int userIndex, Gestures gesture, KinectCommon.NuiSkeletonPositionIndex joint); } public enum Gestures { None = 0, RaiseRightHand, RaiseLeftHand, Psi, Tpose, Stop, Wave, Click, SwipeLeft, SwipeRight, SwipeUp, SwipeDown, RightHandCursor, LeftHandCursor, ZoomOut, ZoomIn, Wheel, Jump, Squat, Push, Pull } public struct GestureData { public ulong userId; public Gestures gesture; public int state; public float timestamp; public int joint; public Vector3 jointPos; public Vector3 screenPos; public float tagFloat; public Vector3 tagVector; public Vector3 tagVector2; public float progress; public bool complete; public bool cancelled; public List<Gestures> checkForGestures; public float startTrackingAtTime; } // Gesture related constants, variables and functions private const int leftHandIndex = (int)KinectCommon.NuiSkeletonPositionIndex.HandLeft; private const int rightHandIndex = (int)KinectCommon.NuiSkeletonPositionIndex.HandRight; private const int leftElbowIndex = (int)KinectCommon.NuiSkeletonPositionIndex.ElbowLeft; private const int rightElbowIndex = (int)KinectCommon.NuiSkeletonPositionIndex.ElbowRight; private const int leftShoulderIndex = (int)KinectCommon.NuiSkeletonPositionIndex.ShoulderLeft; private const int rightShoulderIndex = (int)KinectCommon.NuiSkeletonPositionIndex.ShoulderRight; private const int SpineBaseIndex = (int)KinectCommon.NuiSkeletonPositionIndex.SpineBase; private const int SpineShoulderIndex = (int)KinectCommon.NuiSkeletonPositionIndex.SpineShoulder; private const int leftHipIndex = (int)KinectCommon.NuiSkeletonPositionIndex.HipLeft; private const int rightHipIndex = (int)KinectCommon.NuiSkeletonPositionIndex.HipRight; private static void SetGestureJoint(ref GestureData gestureData, float timestamp, int joint, Vector3 jointPos) { gestureData.joint = joint; gestureData.jointPos = jointPos; gestureData.timestamp = timestamp; gestureData.state++; } private static void SetGestureCancelled(ref GestureData gestureData) { gestureData.state = 0; gestureData.progress = 0f; gestureData.cancelled = true; } private static void CheckPoseComplete(ref GestureData gestureData, float timestamp, Vector3 jointPos, bool isInPose, float durationToComplete) { if(isInPose) { float timeLeft = timestamp - gestureData.timestamp; gestureData.progress = durationToComplete > 0f ? Mathf.Clamp01(timeLeft / durationToComplete) : 1.0f; if(timeLeft >= durationToComplete) { gestureData.timestamp = timestamp; gestureData.jointPos = jointPos; gestureData.state++; gestureData.complete = true; } } else { SetGestureCancelled(ref gestureData); } } private static void SetScreenPos(ulong userId, ref GestureData gestureData, ref Vector3[] jointsPos, ref bool[] jointsTracked) { Vector3 handPos = jointsPos[rightHandIndex]; // Vector3 elbowPos = jointsPos[rightElbowIndex]; // Vector3 shoulderPos = jointsPos[rightShoulderIndex]; bool calculateCoords = false; if(gestureData.joint == rightHandIndex) { if(jointsTracked[rightHandIndex] /**&& jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex]*/) { calculateCoords = true; } } else if(gestureData.joint == leftHandIndex) { if(jointsTracked[leftHandIndex] /**&& jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex]*/) { handPos = jointsPos[leftHandIndex]; // elbowPos = jointsPos[leftElbowIndex]; // shoulderPos = jointsPos[leftShoulderIndex]; calculateCoords = true; } } if(calculateCoords) { // if(gestureData.tagFloat == 0f || gestureData.userId != userId) // { // // get length from shoulder to hand (screen range) // Vector3 shoulderToElbow = elbowPos - shoulderPos; // Vector3 elbowToHand = handPos - elbowPos; // gestureData.tagFloat = (shoulderToElbow.magnitude + elbowToHand.magnitude); // } if(jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex]) { Vector3 neckToHips = jointsPos[SpineShoulderIndex] - jointsPos[SpineBaseIndex]; Vector3 rightToLeft = jointsPos[rightShoulderIndex] - jointsPos[leftShoulderIndex]; gestureData.tagVector2.x = rightToLeft.x; // * 1.2f; gestureData.tagVector2.y = neckToHips.y; // * 1.2f; if(gestureData.joint == rightHandIndex) { gestureData.tagVector.x = jointsPos[rightShoulderIndex].x - gestureData.tagVector2.x / 2; gestureData.tagVector.y = jointsPos[SpineBaseIndex].y; } else { gestureData.tagVector.x = jointsPos[leftShoulderIndex].x - gestureData.tagVector2.x / 2; gestureData.tagVector.y = jointsPos[SpineBaseIndex].y; } } // Vector3 shoulderToHand = handPos - shoulderPos; // gestureData.screenPos.x = Mathf.Clamp01((gestureData.tagFloat / 2 + shoulderToHand.x) / gestureData.tagFloat); // gestureData.screenPos.y = Mathf.Clamp01((gestureData.tagFloat / 2 + shoulderToHand.y) / gestureData.tagFloat); if(gestureData.tagVector2.x != 0 && gestureData.tagVector2.y != 0) { Vector3 relHandPos = handPos - gestureData.tagVector; gestureData.screenPos.x = Mathf.Clamp01(relHandPos.x / gestureData.tagVector2.x); gestureData.screenPos.y = Mathf.Clamp01(relHandPos.y / gestureData.tagVector2.y); } //Debug.Log(string.Format("{0} - S: {1}, H: {2}, SH: {3}, L : {4}", gestureData.gesture, shoulderPos, handPos, shoulderToHand, gestureData.tagFloat)); } } private static void SetZoomFactor(ulong userId, ref GestureData gestureData, float initialZoom, ref Vector3[] jointsPos, ref bool[] jointsTracked) { Vector3 vectorZooming = jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; if(gestureData.tagFloat == 0f || gestureData.userId != userId) { gestureData.tagFloat = 0.5f; // this is 100% } float distZooming = vectorZooming.magnitude; gestureData.screenPos.z = initialZoom + (distZooming / gestureData.tagFloat); } // private static void SetWheelRotation(ulong userId, ref GestureData gestureData, Vector3 initialPos, Vector3 currentPos) // { // float angle = Vector3.Angle(initialPos, currentPos) * Mathf.Sign(currentPos.y - initialPos.y); // gestureData.screenPos.z = angle; // } // estimate the next state and completeness of the gesture public static void CheckForGesture(ulong userId, ref GestureData gestureData, float timestamp, ref Vector3[] jointsPos, ref bool[] jointsTracked) { if(gestureData.complete) return; float bandSize = (jointsPos[SpineShoulderIndex].y - jointsPos[SpineBaseIndex].y); float gestureTop = jointsPos[SpineShoulderIndex].y + bandSize / 2; float gestureBottom = jointsPos[SpineShoulderIndex].y - bandSize; float gestureRight = jointsPos[rightHipIndex].x; float gestureLeft = jointsPos[leftHipIndex].x; switch(gestureData.gesture) { // check for RaiseRightHand case Gestures.RaiseRightHand: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectCommon.Constants.PoseCompleteDuration); break; } break; // check for RaiseLeftHand case Gestures.RaiseLeftHand: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectCommon.Constants.PoseCompleteDuration); break; } break; // check for Psi case Gestures.Psi: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f && jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f && jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectCommon.Constants.PoseCompleteDuration); break; } break; // check for Tpose case Gestures.Tpose: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex] && Mathf.Abs(jointsPos[rightElbowIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.07f Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex] && Mathf.Abs(jointsPos[leftElbowIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f && Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex] && Mathf.Abs(jointsPos[rightElbowIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex] && Mathf.Abs(jointsPos[leftElbowIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f && Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectCommon.Constants.PoseCompleteDuration); break; } break; // check for Stop case Gestures.Stop: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) < 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightHipIndex].x) >= 0.4f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } else if(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) < 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftHipIndex].x) <= -0.4f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); } break; case 1: // gesture complete bool isInPose = (gestureData.joint == rightHandIndex) ? (jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) < 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightHipIndex].x) >= 0.4f) : (jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) < 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftHipIndex].x) <= -0.4f); Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectCommon.Constants.PoseCompleteDuration); break; } break; // check for Wave case Gestures.Wave: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0.05f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.3f; } else if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < -0.05f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.3f; } break; case 1: // gesture - phase 2 if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) < -0.05f : jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) > 0.05f; if(isInPose) { gestureData.timestamp = timestamp; gestureData.state++; gestureData.progress = 0.7f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; case 2: // gesture phase 3 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0.05f : jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < -0.05f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Click case Gestures.Click: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.3f; // set screen position at the start, because this is the most accurate click position SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); } else if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.3f; // set screen position at the start, because this is the most accurate click position SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); } break; case 1: // gesture - phase 2 // if((timestamp - gestureData.timestamp) < 1.0f) // { // bool isInPose = gestureData.joint == rightHandIndex ? // jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // //(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && // Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.08f && // (jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.05f : // jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // //(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && // Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.08f && // (jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.05f; // // if(isInPose) // { // gestureData.timestamp = timestamp; // gestureData.jointPos = jointsPos[gestureData.joint]; // gestureData.state++; // gestureData.progress = 0.7f; // } // else // { // // check for stay-in-place // Vector3 distVector = jointsPos[gestureData.joint] - gestureData.jointPos; // isInPose = distVector.magnitude < 0.05f; // // Vector3 jointPos = jointsPos[gestureData.joint]; // CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, Constants.ClickStayDuration); // } // } // else { // check for stay-in-place Vector3 distVector = jointsPos[gestureData.joint] - gestureData.jointPos; bool isInPose = distVector.magnitude < 0.05f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectCommon.Constants.ClickStayDuration); // SetGestureCancelled(gestureData); } break; // case 2: // gesture phase 3 = complete // if((timestamp - gestureData.timestamp) < 1.0f) // { // bool isInPose = gestureData.joint == rightHandIndex ? // jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // //(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && // Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.08f && // (jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.05f : // jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // //(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && // Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.08f && // (jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.05f; // // if(isInPose) // { // Vector3 jointPos = jointsPos[gestureData.joint]; // CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); // } // } // else // { // // cancel the gesture // SetGestureCancelled(ref gestureData); // } // break; } break; // check for SwipeLeft case Gestures.SwipeLeft: switch(gestureData.state) { case 0: // gesture detection - phase 1 // if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.05f && // (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0f) // { // SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); // gestureData.progress = 0.5f; // } if(jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && jointsPos[rightHandIndex].x <= gestureRight && jointsPos[rightHandIndex].x > gestureLeft) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.1f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { // bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) < 0.1f && // Mathf.Abs(jointsPos[rightHandIndex].y - gestureData.jointPos.y) < 0.08f && // (jointsPos[rightHandIndex].x - gestureData.jointPos.x) < -0.15f; bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && jointsPos[rightHandIndex].x < gestureLeft; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } else if(jointsPos[rightHandIndex].x <= gestureRight) { float gestureSize = gestureRight - gestureLeft; gestureData.progress = gestureSize > 0.01f ? (gestureRight - jointsPos[rightHandIndex].x) / gestureSize : 0f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for SwipeRight case Gestures.SwipeRight: switch(gestureData.state) { case 0: // gesture detection - phase 1 // if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.05f && // (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < 0f) // { // SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); // gestureData.progress = 0.5f; // } if(jointsTracked[leftHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[leftHandIndex].x >= gestureLeft && jointsPos[leftHandIndex].x < gestureRight) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.1f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { // bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) < 0.1f && // Mathf.Abs(jointsPos[leftHandIndex].y - gestureData.jointPos.y) < 0.08f && // (jointsPos[leftHandIndex].x - gestureData.jointPos.x) > 0.15f; bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[leftHandIndex].x > gestureRight; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } else if(jointsPos[leftHandIndex].x >= gestureLeft) { float gestureSize = gestureRight - gestureLeft; gestureData.progress = gestureSize > 0.01f ? (jointsPos[leftHandIndex].x - gestureLeft) / gestureSize : 0f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for SwipeUp case Gestures.SwipeUp: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) < 0.0f && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.15f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) < 0.0f && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.15f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.05f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) <= 0.1f : jointsTracked[leftHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.05f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) <= 0.1f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for SwipeDown case Gestures.SwipeDown: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.05f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.05f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) < -0.15f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) <= 0.1f : jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) < -0.15f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) <= 0.1f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for RightHandCursor case Gestures.RightHandCursor: switch(gestureData.state) { case 0: // gesture detection - phase 1 (perpetual) if(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) > -0.1f) { gestureData.joint = rightHandIndex; gestureData.timestamp = timestamp; //gestureData.jointPos = jointsPos[rightHandIndex]; SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); gestureData.progress = 0.7f; } else { // cancel the gesture //SetGestureCancelled(ref gestureData); gestureData.progress = 0f; } break; } break; // check for LeftHandCursor case Gestures.LeftHandCursor: switch(gestureData.state) { case 0: // gesture detection - phase 1 (perpetual) if(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) > -0.1f) { gestureData.joint = leftHandIndex; gestureData.timestamp = timestamp; //gestureData.jointPos = jointsPos[leftHandIndex]; SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); gestureData.progress = 0.7f; } else { // cancel the gesture //SetGestureCancelled(ref gestureData); gestureData.progress = 0f; } break; } break; // check for ZoomOut case Gestures.ZoomOut: Vector3 vectorZoomOut = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; float distZoomOut = vectorZoomOut.magnitude; switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomOut < 0.3f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.tagVector = Vector3.right; gestureData.tagFloat = 0f; gestureData.progress = 0.3f; } break; case 1: // gesture phase 2 = zooming if((timestamp - gestureData.timestamp) < 1.5f) { float angleZoomOut = Vector3.Angle(gestureData.tagVector, vectorZoomOut) * Mathf.Sign(vectorZoomOut.y - gestureData.tagVector.y); bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomOut < 1.5f && Mathf.Abs(angleZoomOut) < 20f; if(isInPose) { SetZoomFactor(userId, ref gestureData, 1.0f, ref jointsPos, ref jointsTracked); gestureData.timestamp = timestamp; gestureData.progress = 0.7f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for ZoomIn case Gestures.ZoomIn: Vector3 vectorZoomIn = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; float distZoomIn = vectorZoomIn.magnitude; switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomIn >= 0.7f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.tagVector = Vector3.right; gestureData.tagFloat = distZoomIn; gestureData.progress = 0.3f; } break; case 1: // gesture phase 2 = zooming if((timestamp - gestureData.timestamp) < 1.5f) { float angleZoomIn = Vector3.Angle(gestureData.tagVector, vectorZoomIn) * Mathf.Sign(vectorZoomIn.y - gestureData.tagVector.y); bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomIn >= 0.2f && Mathf.Abs(angleZoomIn) < 20f; if(isInPose) { SetZoomFactor(userId, ref gestureData, 0.0f, ref jointsPos, ref jointsTracked); gestureData.timestamp = timestamp; gestureData.progress = 0.7f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Wheel case Gestures.Wheel: Vector3 vectorWheel = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; float distWheel = vectorWheel.magnitude; // Debug.Log(string.Format("{0}. Dist: {1:F1}, Tag: {2:F1}, Diff: {3:F1}", gestureData.state, // distWheel, gestureData.tagFloat, Mathf.Abs(distWheel - gestureData.tagFloat))); switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distWheel >= 0.3f && distWheel < 0.7f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.tagVector = Vector3.right; gestureData.tagFloat = distWheel; gestureData.progress = 0.3f; } break; case 1: // gesture phase 2 = turning wheel if((timestamp - gestureData.timestamp) < 1.5f) { float angle = Vector3.Angle(gestureData.tagVector, vectorWheel) * Mathf.Sign(vectorWheel.y - gestureData.tagVector.y); bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[SpineBaseIndex] && jointsTracked[SpineShoulderIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distWheel >= 0.3f && distWheel < 0.7f && Mathf.Abs(distWheel - gestureData.tagFloat) < 0.1f; if(isInPose) { //SetWheelRotation(userId, ref gestureData, gestureData.tagVector, vectorWheel); gestureData.screenPos.z = angle; // wheel angle gestureData.timestamp = timestamp; gestureData.tagFloat = distWheel; gestureData.progress = 0.7f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Jump case Gestures.Jump: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[SpineBaseIndex] && (jointsPos[SpineBaseIndex].y > 0.9f) && (jointsPos[SpineBaseIndex].y < 1.3f)) { SetGestureJoint(ref gestureData, timestamp, SpineBaseIndex, jointsPos[SpineBaseIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[SpineBaseIndex] && (jointsPos[SpineBaseIndex].y - gestureData.jointPos.y) > 0.15f && Mathf.Abs(jointsPos[SpineBaseIndex].x - gestureData.jointPos.x) < 0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Squat case Gestures.Squat: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[SpineBaseIndex] && (jointsPos[SpineBaseIndex].y <= 0.9f)) { SetGestureJoint(ref gestureData, timestamp, SpineBaseIndex, jointsPos[SpineBaseIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[SpineBaseIndex] && (jointsPos[SpineBaseIndex].y - gestureData.jointPos.y) < -0.15f && Mathf.Abs(jointsPos[SpineBaseIndex].x - gestureData.jointPos.x) < 0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Push case Gestures.Push: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f && (jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.2f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f && (jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.2f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.1f : jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.1f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Pull case Gestures.Pull: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f && (jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.3f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f && (jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.3f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.1f : jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.1f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // here come more gesture-cases } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; #if !WINDOWS_UWP using System.Runtime.ConstrainedExecution; #endif using System.Runtime.InteropServices; using System.Security; using System.Threading; #if !WINDOWS_UWP using System.Transactions; #endif using Microsoft.Win32; using Microsoft.Azure.Devices.Client.Exceptions; static class Fx { // This is only used for EventLog Source therefore matching EventLog source rather than ETL source const string DefaultEventSource = "Microsoft.IotHub"; #if DEBUG const string SBRegistryKey = @"SOFTWARE\Microsoft\IotHub\v2.0"; const string AssertsFailFastName = "AssertsFailFast"; const string BreakOnExceptionTypesName = "BreakOnExceptionTypes"; const string FastDebugName = "FastDebug"; static bool breakOnExceptionTypesRetrieved; static Type[] breakOnExceptionTypesCache; static bool fastDebugRetrieved; static bool fastDebugCache; #endif #if UNUSED [Fx.Tag.SecurityNote(Critical = "This delegate is called from within a ConstrainedExecutionRegion, must not be settable from PT code")] [SecurityCritical] static ExceptionHandler asynchronousThreadExceptionHandler; #endif // UNUSED static ExceptionTrace exceptionTrace; ////static DiagnosticTrace diagnosticTrace; ////[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical field EtwProvider", //// Safe = "Doesn't leak info\\resources")] ////[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, //// Justification = "This is a method that creates ETW provider passing Guid Provider ID.")] ////static DiagnosticTrace InitializeTracing() ////{ //// DiagnosticTrace trace = new DiagnosticTrace(DefaultEventSource, DiagnosticTrace.DefaultEtwProviderId); //// return trace; ////} #if UNUSED public static ExceptionHandler AsynchronousThreadExceptionHandler { [Fx.Tag.SecurityNote(Critical = "access critical field", Safe = "ok for get-only access")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return Fx.asynchronousThreadExceptionHandler; } [Fx.Tag.SecurityNote(Critical = "sets a critical field")] [SecurityCritical] set { Fx.asynchronousThreadExceptionHandler = value; } } #endif // UNUSED public static ExceptionTrace Exception { get { if (exceptionTrace == null) { //need not be a true singleton. No locking needed here. exceptionTrace = new ExceptionTrace(DefaultEventSource); } return exceptionTrace; } } ////public static DiagnosticTrace Trace ////{ //// get //// { //// if (diagnosticTrace == null) //// { //// diagnosticTrace = InitializeTracing(); //// } //// return diagnosticTrace; //// } ////} public static byte[] AllocateByteArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new byte[size]; } catch (OutOfMemoryException exception) { #if WINDOWS_UWP // InsufficientMemoryException does not exit in UWP, fall back to OutOfMemoryException throw Fx.Exception.AsError(new OutOfMemoryException(CommonResources.GetString(CommonResources.BufferAllocationFailed, size), exception)); #else // Convert OOM into an exception that can be safely handled by higher layers. throw Fx.Exception.AsError(new InsufficientMemoryException(CommonResources.GetString(CommonResources.BufferAllocationFailed, size), exception)); #endif } } // Do not call the parameter "message" or else FxCop thinks it should be localized. [Conditional("DEBUG")] public static void Assert(bool condition, string description) { if (!condition) { Assert(description); } } [Conditional("DEBUG")] public static void Assert(string description) { Debug.Assert(false, description); } public static void AssertAndThrow(bool condition, string description) { if (!condition) { AssertAndThrow(description); } } public static void AssertIsNotNull(object objectMayBeNull, string description) { if (objectMayBeNull == null) { Fx.AssertAndThrow(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrow(string description) { Fx.Assert(description); throw Fx.Exception.AsError(new AssertionFailedException(description)); } public static void AssertAndThrowFatal(bool condition, string description) { if (!condition) { AssertAndThrowFatal(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrowFatal(string description) { Fx.Assert(description); throw Fx.Exception.AsError(new FatalException(description)); } public static void AssertAndFailFastService(bool condition, string description) { if (!condition) { AssertAndFailFastService(description); } } // This never returns. The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that // execution stops. [Fx.Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast", Safe = "The side affect of the app crashing is actually intended here")] [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndFailFastService(string description) { Fx.Assert(description); string failFastMessage = CommonResources.GetString(CommonResources.FailFastMessage, description); // The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch. // The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach. try { try { ////MessagingClientEtwProvider.Provider.EventWriteFailFastOccurred(description); Fx.Exception.TraceFailFast(failFastMessage); // Mark that a FailFast is in progress, so that we can take ourselves out of the NLB if for // any reason we can't kill ourselves quickly. Wait 15 seconds so this state gets picked up for sure. Fx.FailFastInProgress = true; #if !WINDOWS_UWP Thread.Sleep(TimeSpan.FromSeconds(15)); #endif } finally { #if !WINDOWS_UWP // ########################## NOTE ########################### // Environment.FailFast does not collect crash dumps when used in Azure services. // Environment.FailFast(failFastMessage); // ################## WORKAROUND ############################# // Workaround for the issue above. Throwing an unhandled exception on a separate thread to trigger process crash and crash dump collection // Throwing FatalException since our service does not morph/eat up fatal exceptions // We should find the tracking bug in Azure for this issue, and remove the workaround when fixed by Azure Thread failFastWorkaroundThread = new Thread(delegate() { throw new FatalException(failFastMessage); }); failFastWorkaroundThread.Start(); failFastWorkaroundThread.Join(); #endif } } catch { throw; } return null; // we'll never get here since we've just fail-fasted } internal static bool FailFastInProgress { get; private set; } public static bool IsFatal(Exception exception) { while (exception != null) { // FYI, CallbackException is-a FatalException if (exception is FatalException || #if WINDOWS_UWP exception is OutOfMemoryException || #else (exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || exception is ThreadAbortException || exception is AccessViolationException || #endif exception is SEHException) { return true; } // These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions, // we want to check to see whether they've been used to wrap a fatal exception. If so, then they // count as fatal. if (exception is TypeInitializationException || exception is TargetInvocationException) { exception = exception.InnerException; } else if (exception is AggregateException) { // AggregateExceptions have a collection of inner exceptions, which may themselves be other // wrapping exceptions (including nested AggregateExceptions). Recursively walk this // hierarchy. The (singular) InnerException is included in the collection. ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions; foreach (Exception innerException in innerExceptions) { if (IsFatal(innerException)) { return true; } } break; } else if (exception is NullReferenceException) { ////MessagingClientEtwProvider.Provider.EventWriteNullReferenceErrorOccurred(exception.ToString()); break; } else { break; } } return false; } #if !WINDOWS_UWP // If the transaction has aborted then we switch over to a new transaction // which we will immediately abort after setting Transaction.Current public static TransactionScope CreateTransactionScope(Transaction transaction) { try { return transaction == null ? null : new TransactionScope(transaction); } catch (TransactionAbortedException) { CommittableTransaction tempTransaction = new CommittableTransaction(); try { return new TransactionScope(tempTransaction.Clone()); } finally { tempTransaction.Rollback(); } } } public static void CompleteTransactionScope(ref TransactionScope scope) { TransactionScope localScope = scope; if (localScope != null) { scope = null; try { localScope.Complete(); } finally { localScope.Dispose(); } } } #endif #if UNUSED public static AsyncCallback ThunkCallback(AsyncCallback callback) { return (new AsyncThunk(callback)).ThunkFrame; } public static WaitCallback ThunkCallback(WaitCallback callback) { return (new WaitThunk(callback)).ThunkFrame; } public static TimerCallback ThunkCallback(TimerCallback callback) { return (new TimerThunk(callback)).ThunkFrame; } public static WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback) { return (new WaitOrTimerThunk(callback)).ThunkFrame; } public static SendOrPostCallback ThunkCallback(SendOrPostCallback callback) { return (new SendOrPostThunk(callback)).ThunkFrame; } #endif [Fx.Tag.SecurityNote(Critical = "Construct the unsafe object IOCompletionThunk")] [SecurityCritical] public static IOCompletionCallback ThunkCallback(IOCompletionCallback callback) { return (new IOCompletionThunk(callback)).ThunkFrame; } #if !WINDOWS_UWP public static TransactionCompletedEventHandler ThunkTransactionEventHandler(TransactionCompletedEventHandler handler) { return (new TransactionEventHandlerThunk(handler)).ThunkFrame; } #endif #if DEBUG internal static bool AssertsFailFast { get { object value; return TryGetDebugSwitch(Fx.AssertsFailFastName, out value) && typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; } } internal static Type[] BreakOnExceptionTypes { get { if (!Fx.breakOnExceptionTypesRetrieved) { object value; if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value)) { string[] typeNames = value as string[]; if (typeNames != null && typeNames.Length > 0) { List<Type> types = new List<Type>(typeNames.Length); for (int i = 0; i < typeNames.Length; i++) { types.Add(Type.GetType(typeNames[i], false)); } if (types.Count != 0) { Fx.breakOnExceptionTypesCache = types.ToArray(); } } } Fx.breakOnExceptionTypesRetrieved = true; } return Fx.breakOnExceptionTypesCache; } } internal static bool FastDebug { get { if (!Fx.fastDebugRetrieved) { object value; if (TryGetDebugSwitch(Fx.FastDebugName, out value)) { Fx.fastDebugCache = typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; } Fx.fastDebugRetrieved = true; ////MessagingClientEtwProvider.Provider.EventWriteLogAsWarning(string.Format(CultureInfo.InvariantCulture, "AppDomain({0}).Fx.FastDebug={1}", AppDomain.CurrentDomain.FriendlyName, Fx.fastDebugCache.ToString())); } return Fx.fastDebugCache; } } static bool TryGetDebugSwitch(string name, out object value) { #if WINDOWS_UWP // No registry access in UWP value = null; return false; #else value = null; try { RegistryKey key = Registry.LocalMachine.OpenSubKey(Fx.SBRegistryKey); if (key != null) { using (key) { value = key.GetValue(name); } } } catch (SecurityException) { // This debug-only code shouldn't trace. } return value != null; #endif } #endif // DEBUG [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] #if !WINDOWS_UWP [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif static void TraceExceptionNoThrow(Exception exception) { try { // This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented. // Rude ThreadAbort will still be allowed to terminate processing. Fx.Exception.TraceUnhandled(exception); } catch { // This empty catch is only acceptable because we are a) in a CER and b) processing an exception // which is about to crash the process anyway. } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule, Justification = "Don't want to hide the exception which is about to crash the process.")] [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] #if !WINDOWS_UWP [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif static bool HandleAtThreadBase(Exception exception) { // This area is too sensitive to do anything but return. if (exception == null) { Fx.Assert("Null exception in HandleAtThreadBase."); return false; } TraceExceptionNoThrow(exception); #if UNUSED try { ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler; return handler == null ? false : handler.HandleException(exception); } catch (Exception secondException) { // Don't let a new exception hide the original exception. TraceExceptionNoThrow(secondException); } #endif // UNUSED return false; } #if UNUSED abstract class Thunk<T> where T : class { [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] [SecurityCritical] T callback; [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] protected Thunk(T callback) { this.callback = callback; } internal T Callback { [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")] get { return this.callback; } } } sealed class TimerThunk : Thunk<TimerCallback> { public TimerThunk(TimerCallback callback) : base(callback) { } public TimerCallback ThunkFrame { get { return new TimerCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class WaitOrTimerThunk : Thunk<WaitOrTimerCallback> { public WaitOrTimerThunk(WaitOrTimerCallback callback) : base(callback) { } public WaitOrTimerCallback ThunkFrame { get { return new WaitOrTimerCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state, bool timedOut) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state, timedOut); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class WaitThunk : Thunk<WaitCallback> { public WaitThunk(WaitCallback callback) : base(callback) { } public WaitCallback ThunkFrame { get { return new WaitCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class AsyncThunk : Thunk<AsyncCallback> { public AsyncThunk(AsyncCallback callback) : base(callback) { } public AsyncCallback ThunkFrame { get { return new AsyncCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(IAsyncResult result) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(result); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } public abstract class ExceptionHandler { [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] public abstract bool HandleException(Exception exception); } #endif // UNUSED // This can't derive from Thunk since T would be unsafe. [Fx.Tag.SecurityNote(Critical = "unsafe object")] [SecurityCritical] unsafe sealed class IOCompletionThunk { [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] IOCompletionCallback callback; [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] public IOCompletionThunk(IOCompletionCallback callback) { this.callback = callback; } public IOCompletionCallback ThunkFrame { [Fx.Tag.SecurityNote(Safe = "returns a delegate around the safe method UnhandledExceptionFrame")] get { return new IOCompletionCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Accesses critical field, calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Delegates can be invoked, guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped) { #if !WINDOWS_UWP RuntimeHelpers.PrepareConstrainedRegions(); #endif try { this.callback(error, bytesRead, nativeOverlapped); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } #if UNUSED sealed class SendOrPostThunk : Thunk<SendOrPostCallback> { public SendOrPostThunk(SendOrPostCallback callback) : base(callback) { } public SendOrPostCallback ThunkFrame { get { return new SendOrPostCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } #endif // UNUSED #if !WINDOWS_UWP sealed class TransactionEventHandlerThunk { readonly TransactionCompletedEventHandler callback; public TransactionEventHandlerThunk(TransactionCompletedEventHandler callback) { this.callback = callback; } public TransactionCompletedEventHandler ThunkFrame { get { return new TransactionCompletedEventHandler(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(object sender, TransactionEventArgs args) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(sender, args); } catch (Exception exception) { throw AssertAndFailFastService(exception.ToString()); } } } #endif public static class Tag { public enum CacheAttrition { None, ElementOnTimer, // A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an // inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the // item from the cache. ElementOnGC, // A cache that provides a per-element token, delegate, interface, or other piece of context that can // be used to remove the element (such as IDisposable). ElementOnCallback, FullPurgeOnTimer, FullPurgeOnEachAccess, PartialPurgeOnTimer, PartialPurgeOnEachAccess, } public enum Location { InProcess, OutOfProcess, LocalSystem, LocalOrRemoteSystem, // as in a file that might live on a share RemoteSystem, } public enum SynchronizationKind { LockStatement, MonitorWait, MonitorExplicit, InterlockedNoSpin, InterlockedWithSpin, // Same as LockStatement if the field type is object. FromFieldType, } [Flags] public enum BlocksUsing { MonitorEnter, MonitorWait, ManualResetEvent, AutoResetEvent, AsyncResult, IAsyncResult, PInvoke, InputQueue, ThreadNeutralSemaphore, PrivatePrimitive, OtherInternalPrimitive, OtherFrameworkPrimitive, OtherInterop, Other, NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler } public static class Strings { internal const string ExternallyManaged = "externally managed"; internal const string AppDomain = "AppDomain"; internal const string DeclaringInstance = "instance of declaring class"; internal const string Unbounded = "unbounded"; internal const string Infinite = "infinite"; } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class ExternalResourceAttribute : Attribute { readonly Location location; readonly string description; public ExternalResourceAttribute(Location location, string description) { this.location = location; this.description = description; } public Location Location { get { return this.location; } } public string Description { get { return this.description; } } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS")] public sealed class CacheAttribute : Attribute { readonly Type elementType; readonly CacheAttrition cacheAttrition; public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; Timeout = Strings.Infinite; if (elementType == null) { throw Fx.Exception.ArgumentNull("elementType"); } this.elementType = elementType; this.cacheAttrition = cacheAttrition; } public Type ElementType { get { return this.elementType; } } public CacheAttrition CacheAttrition { get { return this.cacheAttrition; } } public string Scope { get; set; } public string SizeLimit { get; set; } public string Timeout { get; set; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS")] public sealed class QueueAttribute : Attribute { readonly Type elementType; public QueueAttribute(Type elementType) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; if (elementType == null) { throw Fx.Exception.ArgumentNull("elementType"); } this.elementType = elementType; } public Type ElementType { get { return this.elementType; } } public string Scope { get; set; } public string SizeLimit { get; set; } public bool StaleElementsRemovedImmediately { get; set; } public bool EnqueueThrowsIfFull { get; set; } } // Set on a class when that class uses lock (this) - acts as though it were on a field // private object this; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationObjectAttribute : Attribute { public SynchronizationObjectAttribute() { Blocking = true; Scope = Strings.DeclaringInstance; Kind = SynchronizationKind.FromFieldType; } public bool Blocking { get; set; } public string Scope { get; set; } public SynchronizationKind Kind { get; set; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationPrimitiveAttribute : Attribute { readonly BlocksUsing blocksUsing; public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { this.blocksUsing = blocksUsing; } public BlocksUsing BlocksUsing { get { return this.blocksUsing; } } public bool SupportsAsync { get; set; } public bool Spins { get; set; } public string ReleaseMethod { get; set; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class BlockingAttribute : Attribute { public BlockingAttribute() { } public string CancelMethod { get; set; } public Type CancelDeclaringType { get; set; } public string Conditional { get; set; } } // Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed // not to block (i.e. the condition can be Asserted false). Such a method can be marked as // GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method. // // Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so // they do not require this attribute. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class GuaranteeNonBlockingAttribute : Attribute { public GuaranteeNonBlockingAttribute() { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class NonThrowingAttribute : Attribute { public NonThrowingAttribute() { } } [SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes", Justification = "This is intended to be an attribute heirarchy. It does not affect product perf.")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS")] public class ThrowsAttribute : Attribute { readonly Type exceptionType; readonly string diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { if (exceptionType == null) { throw Fx.Exception.ArgumentNull("exceptionType"); } if (string.IsNullOrEmpty(diagnosis)) { throw Fx.Exception.ArgumentNullOrEmpty("diagnosis"); } this.exceptionType = exceptionType; this.diagnosis = diagnosis; } public Type ExceptionType { get { return this.exceptionType; } } public string Diagnosis { get { return this.diagnosis; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class InheritThrowsAttribute : Attribute { public InheritThrowsAttribute() { } public Type FromDeclaringType { get; set; } public string From { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class SecurityNoteAttribute : Attribute { public SecurityNoteAttribute() { } public string Critical { get; set; } public string Safe { get; set; } public string Miscellaneous { get; set; } } } } }
#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.Configuration; using System.Reflection; using log4net.Util; using log4net.Repository; namespace log4net.Core { /// <summary> /// Static manager that controls the creation of repositories /// </summary> /// <remarks> /// <para> /// Static manager that controls the creation of repositories /// </para> /// <para> /// This class is used by the wrapper managers (e.g. <see cref="log4net.LogManager"/>) /// to provide access to the <see cref="ILogger"/> objects. /// </para> /// <para> /// This manager also holds the <see cref="IRepositorySelector"/> that is used to /// lookup and create repositories. The selector can be set either programmatically using /// the <see cref="RepositorySelector"/> property, or by setting the <c>log4net.RepositorySelector</c> /// AppSetting in the applications config file to the fully qualified type name of the /// selector to use. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class LoggerManager { #region Private Instance Constructors /// <summary> /// Private constructor to prevent instances. Only static methods should be used. /// </summary> /// <remarks> /// <para> /// Private constructor to prevent instances. Only static methods should be used. /// </para> /// </remarks> private LoggerManager() { } #endregion Private Instance Constructors #region Static Constructor /// <summary> /// Hook the shutdown event /// </summary> /// <remarks> /// <para> /// On the full .NET runtime, the static constructor hooks up the /// <c>AppDomain.ProcessExit</c> and <c>AppDomain.DomainUnload</c>> events. /// These are used to shutdown the log4net system as the application exits. /// </para> /// </remarks> static LoggerManager() { try { // Register the AppDomain events, note we have to do this with a // method call rather than directly here because the AppDomain // makes a LinkDemand which throws the exception during the JIT phase. RegisterAppDomainEvents(); } catch(System.Security.SecurityException) { LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying "+ "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+ "will not be called automatically when the AppDomain exits. It must be called "+ "programmatically."); } // Dump out our assembly version into the log if debug is enabled LogLog.Debug(declaringType, GetVersionInfo()); // Set the default repository selector #if NETCF s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); #else // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) { // Resolve the config string into a Type Type appRepositorySelectorType = null; try { appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); } catch(Exception ex) { LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex); } if (appRepositorySelectorType != null) { // Create an instance of the RepositorySelectorType object appRepositorySelectorObj = null; try { appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); } catch(Exception ex) { LogLog.Error(declaringType, "Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex); } if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) { s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; } else { LogLog.Error(declaringType, "RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector"); } } } // Create the DefaultRepositorySelector if not configured above if (s_repositorySelector == null) { s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); } #endif } /// <summary> /// Register for ProcessExit and DomainUnload events on the AppDomain /// </summary> /// <remarks> /// <para> /// This needs to be in a separate method because the events make /// a LinkDemand for the ControlAppDomain SecurityPermission. Because /// this is a LinkDemand it is demanded at JIT time. Therefore we cannot /// catch the exception in the method itself, we have to catch it in the /// caller. /// </para> /// </remarks> private static void RegisterAppDomainEvents() { #if !NETCF // ProcessExit seems to be fired if we are part of the default domain AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); // Otherwise DomainUnload is fired AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); #endif } #endregion Static Constructor #region Public Static Methods /// <summary> /// Return the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repository">the repository to lookup in</param> /// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> [Obsolete("Use GetRepository instead of GetLoggerRepository")] public static ILoggerRepository GetLoggerRepository(string repository) { return GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> [Obsolete("Use GetRepository instead of GetLoggerRepository")] public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) { return GetRepository(repositoryAssembly); } /// <summary> /// Return the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repository">the repository to lookup in</param> /// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> public static ILoggerRepository GetRepository(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } return RepositorySelector.GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </para> /// </remarks> public static ILoggerRepository GetRepository(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } return RepositorySelector.GetRepository(repositoryAssembly); } /// <summary> /// Returns the named logger if it exists. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger found, or <c>null</c> if the named logger does not exist in the /// specified repository. /// </returns> /// <remarks> /// <para> /// If the named logger exists (in the specified repository) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> public static ILogger Exists(string repository, string name) { if (repository == null) { throw new ArgumentNullException("repository"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repository).Exists(name); } /// <summary> /// Returns the named logger if it exists. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger found, or <c>null</c> if the named logger does not exist in the /// specified assembly's repository. /// </returns> /// <remarks> /// <para> /// If the named logger exists (in the specified assembly's repository) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> public static ILogger Exists(Assembly repositoryAssembly, string name) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repositoryAssembly).Exists(name); } /// <summary> /// Returns all the currently defined loggers in the specified repository. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <returns>All the defined loggers.</returns> /// <remarks> /// <para> /// The root logger is <b>not</b> included in the returned array. /// </para> /// </remarks> public static ILogger[] GetCurrentLoggers(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } return RepositorySelector.GetRepository(repository).GetCurrentLoggers(); } /// <summary> /// Returns all the currently defined loggers in the specified assembly's repository. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <returns>All the defined loggers.</returns> /// <remarks> /// <para> /// The root logger is <b>not</b> included in the returned array. /// </para> /// </remarks> public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers(); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Retrieves a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> public static ILogger GetLogger(string repository, string name) { if (repository == null) { throw new ArgumentNullException("repository"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repository).GetLogger(name); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Retrieves a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> public static ILogger GetLogger(Assembly repositoryAssembly, string name) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Gets the logger for the fully qualified name of the type specified. /// </para> /// </remarks> public static ILogger GetLogger(string repository, Type type) { if (repository == null) { throw new ArgumentNullException("repository"); } if (type == null) { throw new ArgumentNullException("type"); } return RepositorySelector.GetRepository(repository).GetLogger(type.FullName); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <param name="repositoryAssembly">the assembly to use to lookup the repository</param> /// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Gets the logger for the fully qualified name of the type specified. /// </para> /// </remarks> public static ILogger GetLogger(Assembly repositoryAssembly, Type type) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (type == null) { throw new ArgumentNullException("type"); } return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName); } /// <summary> /// Shuts down the log4net system. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in all the /// default repositories. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void Shutdown() { foreach(ILoggerRepository repository in GetAllRepositories()) { repository.Shutdown(); } } /// <summary> /// Shuts down the repository for the repository specified. /// </summary> /// <param name="repository">The repository to shutdown.</param> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// repository for the <paramref name="repository"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void ShutdownRepository(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } RepositorySelector.GetRepository(repository).Shutdown(); } /// <summary> /// Shuts down the repository for the repository specified. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// repository for the repository. The repository is looked up using /// the <paramref name="repositoryAssembly"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void ShutdownRepository(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } RepositorySelector.GetRepository(repositoryAssembly).Shutdown(); } /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <param name="repository">The repository to reset.</param> /// <remarks> /// <para> /// Resets all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set its default "off" value. /// </para> /// </remarks> public static void ResetConfiguration(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } RepositorySelector.GetRepository(repository).ResetConfiguration(); } /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param> /// <remarks> /// <para> /// Resets all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set its default "off" value. /// </para> /// </remarks> public static void ResetConfiguration(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration(); } /// <summary> /// Creates a repository with the specified name. /// </summary> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(string repository) { return CreateRepository(repository); } /// <summary> /// Creates a repository with the specified name. /// </summary> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } return RepositorySelector.CreateRepository(repository, null); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An Exception will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(string repository, Type repositoryType) { return CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An Exception will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository, Type repositoryType) { if (repository == null) { throw new ArgumentNullException("repository"); } if (repositoryType == null) { throw new ArgumentNullException("repositoryType"); } return RepositorySelector.CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) { return CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (repositoryType == null) { throw new ArgumentNullException("repositoryType"); } return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Gets an array of all currently defined repositories. /// </summary> /// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns> /// <remarks> /// <para> /// Gets an array of all currently defined repositories. /// </para> /// </remarks> public static ILoggerRepository[] GetAllRepositories() { return RepositorySelector.GetAllRepositories(); } /// <summary> /// Gets or sets the repository selector used by the <see cref="LogManager" />. /// </summary> /// <value> /// The repository selector used by the <see cref="LogManager" />. /// </value> /// <remarks> /// <para> /// The repository selector (<see cref="IRepositorySelector"/>) is used by /// the <see cref="LogManager"/> to create and select repositories /// (<see cref="ILoggerRepository"/>). /// </para> /// <para> /// The caller to <see cref="LogManager"/> supplies either a string name /// or an assembly (if not supplied the assembly is inferred using /// <see cref="M:Assembly.GetCallingAssembly()"/>). /// </para> /// <para> /// This context is used by the selector to lookup a specific repository. /// </para> /// <para> /// For the full .NET Framework, the default repository is <c>DefaultRepositorySelector</c>; /// for the .NET Compact Framework <c>CompactRepositorySelector</c> is the default /// repository. /// </para> /// </remarks> public static IRepositorySelector RepositorySelector { get { return s_repositorySelector; } set { s_repositorySelector = value; } } #endregion Public Static Methods #region Private Static Methods /// <summary> /// Internal method to get pertinent version info. /// </summary> /// <returns>A string of version info.</returns> private static string GetVersionInfo() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Grab the currently executing assembly Assembly myAssembly = Assembly.GetExecutingAssembly(); // Build Up message sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. "); sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. "); sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]"); #if (!SSCLI) sb.Append(" on ").Append(Environment.OSVersion.ToString()); #endif sb.Append(")"); return sb.ToString(); } #if (!NETCF) /// <summary> /// Called when the <see cref="AppDomain.DomainUnload"/> event fires /// </summary> /// <param name="sender">the <see cref="AppDomain"/> that is exiting</param> /// <param name="e">null</param> /// <remarks> /// <para> /// Called when the <see cref="AppDomain.DomainUnload"/> event fires. /// </para> /// <para> /// When the event is triggered the log4net system is <see cref="M:Shutdown()"/>. /// </para> /// </remarks> private static void OnDomainUnload(object sender, EventArgs e) { Shutdown(); } /// <summary> /// Called when the <see cref="AppDomain.ProcessExit"/> event fires /// </summary> /// <param name="sender">the <see cref="AppDomain"/> that is exiting</param> /// <param name="e">null</param> /// <remarks> /// <para> /// Called when the <see cref="AppDomain.ProcessExit"/> event fires. /// </para> /// <para> /// When the event is triggered the log4net system is <see cref="M:Shutdown()"/>. /// </para> /// </remarks> private static void OnProcessExit(object sender, EventArgs e) { Shutdown(); } #endif #endregion Private Static Methods #region Private Static Fields /// <summary> /// The fully qualified type of the LoggerManager class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LoggerManager); /// <summary> /// Initialize the default repository selector /// </summary> private static IRepositorySelector s_repositorySelector; #endregion Private Static Fields } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Diagnostics; using JustGestures.GestureParts; using JustGestures.TypeOfAction; using JustGestures.Languages; namespace JustGestures.ControlItems { public partial class UC_actions : BaseActionControl { MouseCore.ExtraMouseHook m_mouse; Dictionary<string, TreeNode> m_actions; List<MyGesture> m_selectedGroups; List<MyGesture> m_newGroups; Dictionary<string, TreeView> m_actionTrees; string m_prevSelected = string.Empty; TreeNode m_selectedNode = null; public List<MyGesture> SelectedGroups { get { return m_selectedGroups; } set { m_selectedGroups = value; } } public List<MyGesture> NewGroups { get { return m_newGroups; } } public MouseCore.ExtraMouseHook MouseEngine { set { m_mouse = value; } } public UC_actions() { InitializeComponent(); m_identifier = Page.Action; m_next = Page.Gesture; //default m_previous = Page.None; m_actions = new Dictionary<string, TreeNode>(); typeof(UserControl).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, this, new object[] { true }); m_newGroups = new List<MyGesture>(); m_selectedGroups = new List<MyGesture>(); m_actionTrees = new Dictionary<string, TreeView>(); cCB_groups.ItemChecked += new ItemCheckedEventHandler(cCB_groups_ItemChecked); cCB_groups.ImageList = iL_applications; //tV_actions.Visible = false; m_about = Translation.GetText("C_Act_about"); m_info = Translation.GetText("C_Act_info"); gB_category.Text = Translation.GetText("C_Act_gB_category"); gB_action.Text = Translation.GetText("C_Act_gB_action"); gB_useOfAction.Text = Translation.GetText("C_Act_gB_useOfAction"); rB_global.Text = Translation.GetText("C_Act_rB_globally"); rB_local.Text = Translation.GetText("C_Act_rB_locally"); btn_addApp.Text = Translation.GetText("Btn_addNew"); } private void UserControl_actions_Load(object sender, EventArgs e) { tV_category.Nodes.Add(ActionCategory.GetCategories(iL_actions)); foreach (TreeNode node in tV_category.Nodes[0].Nodes) { m_actions.Add(node.Name, ActionCategory.GetActions(node.Name, iL_actions)); TreeView actionTree = new TreeView(); //actionTree.HideSelection = false; actionTree.Nodes.Add(m_actions[node.Name]); actionTree.Visible = false; actionTree.ShowPlusMinus = false; actionTree.ShowRootLines = false; actionTree.ImageList = iL_actions; actionTree.AfterSelect += new TreeViewEventHandler(tV_actions_AfterSelect); actionTree.BeforeCollapse += new TreeViewCancelEventHandler(tV_actions_BeforeCollapse); gB_action.Controls.Add(actionTree); actionTree.Dock = DockStyle.Fill; m_actionTrees.Add(node.Name, actionTree); } foreach (MyGesture gest in m_gesturesCollection.Groups) { if (gest.ID != AppGroupOptions.APP_GROUP_GLOBAL) { gest.SetActionIcon(iL_applications); cCB_groups.AddItem(gest.ID, gest.Caption); } } if (m_selectedGroups.Count == 0 || m_selectedGroups[0].ID == AppGroupOptions.APP_GROUP_GLOBAL) rB_global.Checked = true; else { foreach (MyGesture group in m_selectedGroups) cCB_groups.ListItems[group.ID].Checked = true; cCB_groups.CheckListItems(); rB_local.Checked = true; } if (cCB_groups.ListItems.Count > 0) cCB_groups.ListItems[0].Selected = true; } private void tV_category_AfterSelect(object sender, TreeViewEventArgs e) { if (tV_category.SelectedNode.Nodes.Count != 0) return; if (m_selectedNode != null) m_selectedNode.TreeView.HideSelection = true; m_selectedNode = null; if (m_prevSelected != string.Empty) { m_actionTrees[m_prevSelected].Visible = false; m_actionTrees[m_prevSelected].SelectedNode = null; } else tV_actions.Visible = false; m_actionTrees[tV_category.SelectedNode.Name].Visible = true; m_prevSelected = tV_category.SelectedNode.Name; //tV_actions.Nodes.Clear(); //tV_actions.Nodes.Add(m_actions[tV_category.SelectedNode.Name]); OnCanContinue(false); } void cCB_groups_ItemChecked(object sender, ItemCheckedEventArgs e) { m_selectedGroups = new List<MyGesture>(); foreach (ListViewItem item in cCB_groups.CheckedListItems) m_selectedGroups.Add(m_gesturesCollection.Groups[item.Index + 1]); if (m_selectedNode != null && m_selectedGroups.Count != 0) OnCanContinue(true); else OnCanContinue(false); } private void tV_actions_AfterSelect(object sender, TreeViewEventArgs e) { TreeView actionTreeView = (TreeView)sender; if (actionTreeView.SelectedNode.Parent == null) { m_selectedNode = null; OnCanContinue(false); } else { m_selectedNode = actionTreeView.SelectedNode; m_selectedNode.TreeView.HideSelection = false; m_tempGesture.Action = (BaseActionClass)((BaseActionClass)m_selectedNode.Tag).Clone(); m_tempGesture.Caption = m_selectedNode.Text; //m_tempGesture.Action.Details = string.Empty; switch (m_tempGesture.Action.Name) { case WindowsShell.SHELL_OPEN_FLDR: case WindowsShell.SHELL_START_PRG: m_next = Page.PrgWwwFld; break; case KeystrokesOptions.KEYSTROKES_PRIVATE_COPY_TEXT: case KeystrokesOptions.KEYSTROKES_PRIVATE_PASTE_TEXT: m_next = Page.Clipboard; break; case InternetOptions.INTERNET_OPEN_WEBSITE: case InternetOptions.INTERNET_SEND_EMAIL: case InternetOptions.INTERNET_SEARCH_WEB: m_next = Page.MailSearchWeb; break; case InternetOptions.INTERNET_TAB_NEW: case InternetOptions.INTERNET_TAB_CLOSE: case InternetOptions.INTERNET_TAB_REOPEN: case KeystrokesOptions.KEYSTROKES_ZOOM_IN: case KeystrokesOptions.KEYSTROKES_ZOOM_OUT: case KeystrokesOptions.KEYSTROKES_SYSTEM_COPY: case KeystrokesOptions.KEYSTROKES_SYSTEM_PASTE: case KeystrokesOptions.KEYSTROKES_SYSTEM_CUT: case KeystrokesOptions.KEYSTROKES_CUSTOM: case ExtrasOptions.EXTRAS_TAB_SWITCHER: case ExtrasOptions.EXTRAS_TASK_SWITCHER: case ExtrasOptions.EXTRAS_ZOOM: case ExtrasOptions.EXTRAS_CUSTOM_WHEEL_BTN: m_next = Page.Keystrokes; break; case KeystrokesOptions.KEYSTROKES_PLAIN_TEXT: m_next = Page.PlainText; break; default: m_next = Page.Gesture; break; } if (m_selectedGroups.Count > 0) OnCanContinue(true); else OnCanContinue(false); } } private void UserControl_actions_VisibleChanged(object sender, EventArgs e) { if (((UC_actions)sender).Visible) { OnChangeAboutText(m_about); OnChangeInfoText(ToolTipIcon.Info, Translation.Text_info, m_info); if (m_selectedNode != null) m_selectedNode.TreeView.Focus(); OnCanContinue(false); if (m_tempGesture.Action != null) OnCanContinue(true); } } private void rB_GlobalLocal_CheckedChanged(object sender, EventArgs e) { if (((RadioButton)sender).Checked) CheckCheckedState(); } private void CheckCheckedState() { if (rB_global.Checked) { cCB_groups.Enabled = false; btn_addApp.Enabled = false; m_selectedGroups = new List<MyGesture>(); m_selectedGroups.Add(m_gesturesCollection.Groups[0]); } else { m_selectedGroups = new List<MyGesture>(); foreach (ListViewItem item in cCB_groups.CheckedListItems) m_selectedGroups.Add(m_gesturesCollection.Groups[item.Index + 1]); cCB_groups.Enabled = true; btn_addApp.Enabled = true; } //if (m_selectedNode != null) if (m_selectedGroups.Count != 0 && m_selectedNode != null) OnCanContinue(true); else OnCanContinue(false); //if (m_selectedNode != null) // m_selectedNode.TreeView.Select(); } private void btn_addApp_Click(object sender, EventArgs e) { GUI.Form_addGesture addGesture = new GUI.Form_addGesture(); addGesture.Gestures = m_gesturesCollection; addGesture.AppMode = true; if (addGesture.ShowDialog() == DialogResult.OK) { foreach (MyGesture gesture in addGesture.NewGestures) { MyGesture gestureToAdd = new MyGesture(gesture); gesture.SetActionIcon(iL_applications); m_gesturesCollection.Add(gestureToAdd); m_newGroups.Add(gestureToAdd); cCB_groups.AddItem(gestureToAdd.ID, gestureToAdd.Caption); } } } private void tV_actions_BeforeCollapse(object sender, TreeViewCancelEventArgs e) { e.Cancel = true; } private void tV_category_BeforeCollapse(object sender, TreeViewCancelEventArgs e) { e.Cancel = true; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using System; using System.Reflection; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGAssetBroker")] public class HGAssetBroker : ISharedRegionModule, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IImprovedAssetCache m_Cache = null; private IAssetService m_GridService; private IAssetService m_HGService; private Scene m_aScene; private string m_LocalAssetServiceURI; private bool m_Enabled = false; private AssetPermissions m_AssetPerms; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "HGAssetBroker"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetServices", ""); if (name == Name) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); return; } string localDll = assetConfig.GetString("LocalGridAssetService", String.Empty); string HGDll = assetConfig.GetString("HypergridAssetService", String.Empty); if (localDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService"); return; } if (HGDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IAssetService>(localDll, args); m_HGService = ServerUtils.LoadPlugin<IAssetService>(HGDll, args); if (m_GridService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service"); return; } if (m_HGService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service"); return; } m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty); if (m_LocalAssetServiceURI == string.Empty) { IConfig netConfig = source.Configs["Network"]; m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty); } if (m_LocalAssetServiceURI != string.Empty) m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/'); IConfig hgConfig = source.Configs["HGAssetService"]; m_AssetPerms = new AssetPermissions(hgConfig); // it's ok if arg is null m_Enabled = true; m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_aScene = scene; m_aScene.RegisterModuleInterface<IAssetService>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_Cache == null) { m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>(); if (!(m_Cache is ISharedRegionModule)) m_Cache = null; } m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName); if (m_Cache != null) { m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName); } } private bool IsHG(string id) { Uri assetUri; if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) && assetUri.Scheme == Uri.UriSchemeHttp) return true; return false; } public AssetBase Get(string id) { //m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id); AssetBase asset = null; if (m_Cache != null) { asset = m_Cache.Get(id); if (asset != null) return asset; } if (IsHG(id)) { asset = m_HGService.Get(id); if (asset != null) { // Now store it locally, if allowed if (m_AssetPerms.AllowedImport(asset.Type)) m_GridService.Store(asset); else return null; } } else asset = m_GridService.Get(id); if (m_Cache != null) m_Cache.Cache(asset); return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Metadata; } AssetMetadata metadata; if (IsHG(id)) metadata = m_HGService.GetMetadata(id); else metadata = m_GridService.GetMetadata(id); return metadata; } public byte[] GetData(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Data; } if (IsHG(id)) return m_HGService.GetData(id); else return m_GridService.GetData(id); } public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { handler(id, sender, asset); return true; } if (IsHG(id)) { return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } else { return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } } public virtual bool[] AssetsExist(string[] ids) { int numHG = 0; foreach (string id in ids) { if (IsHG(id)) ++numHG; } if (numHG == 0) return m_GridService.AssetsExist(ids); else if (numHG == ids.Length) return m_HGService.AssetsExist(ids); else throw new Exception("[HG ASSET CONNECTOR]: AssetsExist: all the assets must be either local or foreign"); } public string Store(AssetBase asset) { bool isHG = IsHG(asset.ID); if ((m_Cache != null) && !isHG) // Don't store it in the cache if the asset is to // be sent to the other grid, because this is already // a copy of the local asset. m_Cache.Cache(asset); if (asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string id; if (IsHG(asset.ID)) { if (m_AssetPerms.AllowedExport(asset.Type)) id = m_HGService.Store(asset); else return String.Empty; } else id = m_GridService.Store(asset); if (String.IsNullOrEmpty(id)) return string.Empty; asset.ID = id; if (m_Cache != null) m_Cache.Cache(asset); return id; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { asset.Data = data; m_Cache.Cache(asset); } if (IsHG(id)) return m_HGService.UpdateContent(id, data); else return m_GridService.UpdateContent(id, data); } public bool Delete(string id) { if (m_Cache != null) m_Cache.Expire(id); bool result = false; if (IsHG(id)) result = m_HGService.Delete(id); else result = m_GridService.Delete(id); if (result && m_Cache != null) m_Cache.Expire(id); return result; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace KeeAnywhere.Forms.ImagedComboBox { [ToolboxItem(true)] [ToolboxBitmap(typeof(ImageComboBox),"ComboBMP.bmp")] //[Designer(typeof(System.Windows.Forms.Design.ControlDesigner))] public class ImageComboBox : System.Windows.Forms.ComboBox { #region Variables private DrawMode ComboBoxDrawMode = DrawMode.OwnerDrawFixed ; // set the default drawmode to owner drawselected. private ImageComboBoxItemCollection ListItems; // the collection of imagecomboboxitems private string ItemText = string.Empty; private ImageList imgList = null; // the images to be used in the imagecombobox are stored in an imagelist. private ComboEditWindow EditBox = new ComboEditWindow(); // the NativeWindow object, used to access and repaint the TextBox. private object[] DrawModes = new object[2]; private string ComboText = string.Empty ; private int indentValue = 0; [DllImport("user32", CharSet=CharSet.Auto)] private extern static IntPtr FindWindowEx( IntPtr hwndParent, IntPtr hwndChildAfter, [MarshalAs(UnmanagedType.LPTStr)] string lpszClass, [MarshalAs(UnmanagedType.LPTStr)] string lpszWindow); [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } #endregion Variables public ImageComboBox() { // supported drawmodes are OwnerDrawFixed and OwnerDrawVariable only. this.DrawMode = DrawMode.OwnerDrawFixed ; DrawModes[0] = DrawMode.OwnerDrawFixed ; DrawModes[1]= DrawMode.OwnerDrawVariable ; base.ItemHeight = 15; ListItems = new ImageComboBoxItemCollection (this); } #region Properties /// <summary> /// The imagelist holds the images displayed with the items in the combobox. /// </summary> [Category("Behavior")] [Browsable(true)] [Description("The ImageList control from which the images to be displayed with the items are taken.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public ImageList ImageList { get { return imgList; } set { imgList = value; // prepare the dropdown Images List from which user can choose an image for corresponding item DropDownImages.imageList = imgList; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public new int ItemHeight { get { return base.ItemHeight; } set { base.ItemHeight = value; } } /// <summary> /// A new drawmode property is added so that only ownerdrawn and ownerdrawvariable are displayed. /// </summary> [Browsable(true)] [Editor(typeof(DropDownDrawModes),typeof(System.Drawing.Design.UITypeEditor))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public new DrawMode DrawMode { get { DropDownDrawModes.List =DrawModes; return ComboBoxDrawMode; } set { DropDownDrawModes.List =DrawModes; if(value == DrawMode.OwnerDrawFixed ) { ComboBoxDrawMode = DrawMode.OwnerDrawFixed ; base.DrawMode = DrawMode.OwnerDrawFixed ; } else if(value == DrawMode.OwnerDrawVariable ) { ComboBoxDrawMode = DrawMode.OwnerDrawVariable ; base.DrawMode = DrawMode.OwnerDrawVariable ; } else throw new System .Exception ("The ImageComboBox does not support the "+value.ToString()+" mode."); } } /// <summary> /// A new Items Property is introduced, so that the items of type ImageComboBoxItem could be /// added/removed/edited. An ImageComboBoxItem can have a corresponding image and font property. /// So using the ImageComboBoxItem collection editor, the image and font can be set on the spot. /// </summary> [Category("Behavior")] [Description("The collection of items in the ImageComboBox.")] [Localizable(true)] [MergableProperty(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] //[EditorAttribute(typeof(CollectionEditor),typeof(UITypeEditor))] [TypeConverter(typeof(ImageComboBoxItemCollection))] public new ImageComboBoxItemCollection Items { get { this.ImageList = imgList; return this.ListItems; } set { // when the datasource property is set, it takes precedence over Items Property. // This is the default combobox behavior. if(this.DataSource != null) throw new System.Exception ("The Items cannot be used concurrently with the DataSource."); else this.ListItems = (ImageComboBoxItemCollection)value; } } /// <summary> /// The ImageComboBox supports three levels of indentation. /// The Indent property represents the width of indentation of each item in pixels. /// For each level the value of Indent is multiplied by the indent level to properly indent the item; /// </summary> [Category("Behavior")] [Browsable(true)] [Description("The Indentation width of an item in pixels.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public int Indent { get { return indentValue; } set { indentValue = value; } } #endregion Properties #region Methods to access base class items. public void ComboBoxSetElement(int index, object value) { base.Items[index] = value; } public ImageComboBoxItem ComboBoxGetElement(int index) { return (ImageComboBoxItem)base.Items[index]; } public IEnumerator ComboBoxGetEnumerator() { return base.Items.GetEnumerator(); } public int ComboBoxGetItemCount() { return base.Items.Count; } public bool ComboBoxContains(ImageComboBoxItem item) { return base.Items.Contains (item); } public int ComboBoxInsertItem(int index, ImageComboBoxItem item) { item.Text = (item.Text.Length == 0)?item.GetType ().Name+index.ToString ():item.Text; base.Items.Insert(index, item); return index; } public int ComboBoxAddItem(ImageComboBoxItem item) { item.Text = (item.Text.Length == 0)?item.GetType ().Name+base.Items.Count.ToString ():item.Text; base.Items.Add (item); return base.Items.Count-1; } public void ComboBoxRemoveItemAt(int index) { base.Items.RemoveAt(index); } public void ComboBoxRemoveItem(ImageComboBoxItem item) { base.Items.Remove (item); } public void ComboBoxClear() { base.Items.Clear(); } #endregion #region Overrided Methods /// <summary> /// Once the handle of the ImageComboBox is available, we can release NativeWindow's /// own handle and assign the TextBox'es handle to it. /// </summary> /// <param name="e"></param> protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated (e); if((this.DropDownStyle == ComboBoxStyle.DropDown) || (this.DropDownStyle == ComboBoxStyle.Simple)) EditBox.AssignTextBoxHandle(this); } /// <summary> /// When the RightToLeft property is changed the margin of the TextBox also should be changed accordingly. /// </summary> /// <param name="e"></param> protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged (e); if((this.DropDownStyle == ComboBoxStyle.DropDown) || (this.DropDownStyle == ComboBoxStyle.Simple)) { EditBox.SetMargin(); EditBox.SetImageToDraw(); // the image on the textbox has to be redrawn } } /// <summary> /// The TextBox need to be updated when combobox'es selection changes. /// </summary> /// <param name="e"></param> protected override void OnSelectedIndexChanged(EventArgs e) { base.OnSelectedIndexChanged (e); object selectedItem = base.Items [this.SelectedIndex]; EditBox.SetImageToDraw(); // the image on the textbox has to be redrawn EditBox.SetMargin(); // the margin needs be set according the width of the image. } /// <summary> /// when the imagecombobox drawmode is ownerdraw variable, /// each item's height and width need to be measured, inorder to display them properly. /// </summary> /// <param name="e"></param> protected override void OnMeasureItem(MeasureItemEventArgs e) { base.OnMeasureItem (e); if(this.DataSource != null) { return; // currently ownerdrawvariable support is implemented only for Items Collection. } if (e.Index >= 0 && this.Items.Count > 0 && e.Index < this.Items.Count) { //Font itemFont =((ImageComboBoxItem) this.Items[e.Index]).Font == null ? this.Font : ((ImageComboBoxItem)this.Items[e.Index]).Font; // SizeF TextSize = e.Graphics .MeasureString (((ImageComboBoxItem)this.Items[e.Index ]).Text,itemFont); //e.ItemHeight = (int)TextSize.Height; //e.ItemWidth = (int)TextSize.Width; var scaleX = e.Graphics.DpiX / 96.0; var scaleY = e.Graphics.DpiY / 96.0; e.ItemHeight = (int)(this.ItemHeight * scaleY); } } /// <summary> /// Because the combobox is ownerdrawn we have draw each item along with the associated image. /// In the case of datasource the displaymember and imagemember are taken from the datasource. /// If datasource is not set the items in the Items collection are drawn. /// </summary> /// <param name="e"></param> protected override void OnDrawItem(DrawItemEventArgs e) { base.OnDrawItem (e); if (e.Index >= 0 && Items.Count > 0 && e.Index < Items.Count) { DrawItemHelperForItems(e); } } /// <summary> /// Helper method for drawing items . /// </summary> /// <param name="e"></param> private void DrawItemHelperForItems(DrawItemEventArgs e) { e.DrawFocusRectangle (); e.DrawBackground (); ImageComboBoxItem item = (ImageComboBoxItem)this.Items [e.Index ]; if(item.Font == null) item.Font = this.Font; StringFormat format = new StringFormat (); //format.FormatFlags = StringFormatFlags.NoWrap; format.FormatFlags = StringFormatFlags.NoClip; int indent = (item.IndentLevel*this.Indent); if(item.ImageIndex != -1) { Image theIcon = this.ImageList.Images [item.ImageIndex ]; Bitmap ImageToDraw = new Bitmap (theIcon,e.Bounds.Height-1,e.Bounds.Height-1); int IconHeight = ImageToDraw.Height; int IconWidth = ImageToDraw.Width; int offset = 1; if(this.RightToLeft == RightToLeft.Yes) { ImageToDraw.RotateFlip(RotateFlipType.RotateNoneFlipX); format.Alignment = StringAlignment.Far; RectangleF itemRect = new RectangleF ((float)(e.Bounds.X-offset),(float)(e.Bounds .Y),(float)(e.Bounds.Width-IconWidth-indent-offset) ,(float)(e.Bounds.Height)); e.Graphics.DrawString (item.Text,item.Font,new SolidBrush (e.ForeColor),itemRect,format); Rectangle imageRect = new Rectangle(e.Bounds.X+offset+(e.Bounds.Width-(IconWidth+indent)),e.Bounds.Y,IconWidth,IconHeight); e.Graphics.DrawImage(ImageToDraw,imageRect); } else { format.Alignment = StringAlignment.Near ; RectangleF itemRect = new RectangleF ((float)(e.Bounds.X+IconWidth+indent+offset),(float)(e.Bounds .Y),(float)(e.Bounds .Width-IconWidth-indent-offset),(float)(e.Bounds.Height)) ; e.Graphics.DrawString (item.Text,item.Font,new SolidBrush (e.ForeColor),itemRect,format); Rectangle imageRect = new Rectangle(e.Bounds.X+offset+indent,e.Bounds.Y,IconWidth,IconHeight); e.Graphics.DrawImage(ImageToDraw,imageRect); } } else { if(this.RightToLeft == RightToLeft.Yes) { format.Alignment = StringAlignment.Far ; e.Graphics.DrawString (item.Text,item.Font,new SolidBrush (e.ForeColor),new RectangleF ((float)e.Bounds .X,(float)e.Bounds .Y,(float)(e.Bounds .Width - indent),(float)e.Bounds.Height),format); } else { format.Alignment = StringAlignment.Near ; e.Graphics.DrawString (item.Text,item.Font,new SolidBrush (e.ForeColor),new RectangleF ((float)(e.Bounds .X+indent),(float)e.Bounds .Y,(float)e.Bounds .Width ,(float)e.Bounds.Height),format); } } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged (e); if(this.SelectedIndex > -1) { object selectedItem = base.Items [this.SelectedIndex]; EditBox.SetImageToDraw(); EditBox.SetMargin(); } } #endregion Overrided Methods } }
using System; namespace Trionic5Controls { partial class MapViewer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapViewer)); DevExpress.XtraCharts.XYDiagram xyDiagram1 = new DevExpress.XtraCharts.XYDiagram(); DevExpress.XtraCharts.Series series1 = new DevExpress.XtraCharts.Series(); DevExpress.XtraCharts.SeriesPoint seriesPoint1 = new DevExpress.XtraCharts.SeriesPoint(0); DevExpress.XtraCharts.LineSeriesView lineSeriesView1 = new DevExpress.XtraCharts.LineSeriesView(); DevExpress.XtraCharts.PolygonGradientFillOptions polygonGradientFillOptions1 = new DevExpress.XtraCharts.PolygonGradientFillOptions(); DevExpress.XtraCharts.PointSeriesLabel pointSeriesLabel1 = new DevExpress.XtraCharts.PointSeriesLabel(); DevExpress.XtraCharts.PointOptions pointOptions1 = new DevExpress.XtraCharts.PointOptions(); DevExpress.XtraCharts.LineSeriesView lineSeriesView2 = new DevExpress.XtraCharts.LineSeriesView(); DevExpress.XtraCharts.PointSeriesLabel pointSeriesLabel2 = new DevExpress.XtraCharts.PointSeriesLabel(); this.simpleButton3 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton(); this.groupControl1 = new DevExpress.XtraEditors.GroupControl(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.panel1 = new System.Windows.Forms.Panel(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.copySelectedCellsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteSelectedCellsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.inOrgininalPositionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.atCurrentlySelectedLocationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editXaxisSymbolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editYaxisSymbolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.smoothSelectionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.asPreferredSettingInT5DashboardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.lockCellsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.unlockCellsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.xtraTabControl1 = new DevExpress.XtraTab.XtraTabControl(); this.xtraTabPage1 = new DevExpress.XtraTab.XtraTabPage(); this.simpleButton4 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton5 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton6 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton7 = new DevExpress.XtraEditors.SimpleButton(); this.surfaceGraphViewer1 = new Trionic5Controls.SurfaceGraphViewer(); this.xtraTabPage2 = new DevExpress.XtraTab.XtraTabPage(); this.labelControl9 = new DevExpress.XtraEditors.LabelControl(); this.labelControl8 = new DevExpress.XtraEditors.LabelControl(); this.trackBarControl1 = new DevExpress.XtraEditors.TrackBarControl(); this.chartControl1 = new DevExpress.XtraCharts.ChartControl(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.timer2 = new System.Windows.Forms.Timer(this.components); this.toolTipController1 = new DevExpress.Utils.ToolTipController(this.components); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox3 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton7 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton6 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton4 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton5 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox2 = new System.Windows.Forms.ToolStripComboBox(); this.timer3 = new System.Windows.Forms.Timer(this.components); this.timer4 = new System.Windows.Forms.Timer(this.components); this.btnSaveToRAM = new DevExpress.XtraEditors.SimpleButton(); this.btnReadFromRAM = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton(); clearDataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit(); this.groupControl1.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).BeginInit(); this.xtraTabControl1.SuspendLayout(); this.xtraTabPage1.SuspendLayout(); this.xtraTabPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarControl1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.chartControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(xyDiagram1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(series1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(lineSeriesView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(lineSeriesView2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel2)).BeginInit(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // clearDataToolStripMenuItem // clearDataToolStripMenuItem.Name = "clearDataToolStripMenuItem"; clearDataToolStripMenuItem.Size = new System.Drawing.Size(178, 22); clearDataToolStripMenuItem.Text = "Clear data"; clearDataToolStripMenuItem.Click += new System.EventHandler(this.clearDataToolStripMenuItem_Click); // // simpleButton3 // this.simpleButton3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.simpleButton3.Enabled = false; this.simpleButton3.Location = new System.Drawing.Point(5, 638); this.simpleButton3.Name = "simpleButton3"; this.simpleButton3.Size = new System.Drawing.Size(92, 23); this.simpleButton3.TabIndex = 9; this.simpleButton3.Text = "Undo changes"; this.simpleButton3.Click += new System.EventHandler(this.simpleButton3_Click); // // simpleButton2 // this.simpleButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton2.Enabled = false; this.simpleButton2.Location = new System.Drawing.Point(791, 638); this.simpleButton2.Name = "simpleButton2"; this.simpleButton2.Size = new System.Drawing.Size(75, 23); this.simpleButton2.TabIndex = 8; this.simpleButton2.Text = "Save"; this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click); // // groupControl1 // this.toolTipController1.SetAllowHtmlText(this.groupControl1, DevExpress.Utils.DefaultBoolean.False); this.groupControl1.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.groupControl1.Controls.Add(this.splitContainer1); this.groupControl1.Location = new System.Drawing.Point(3, 28); this.groupControl1.Name = "groupControl1"; this.groupControl1.Size = new System.Drawing.Size(870, 604); this.toolTipController1.SetSuperTip(this.groupControl1, null); this.groupControl1.TabIndex = 5; this.groupControl1.Text = "Symbol data"; this.groupControl1.DoubleClick += new System.EventHandler(this.groupControl1_DoubleClick); this.groupControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.groupControl1_Paint); this.groupControl1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.groupControl1_MouseMove); this.groupControl1.MouseHover += new System.EventHandler(this.groupControl1_MouseHover); // // splitContainer1 // this.toolTipController1.SetAllowHtmlText(this.splitContainer1, DevExpress.Utils.DefaultBoolean.False); this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(2, 20); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.toolTipController1.SetAllowHtmlText(this.splitContainer1.Panel1, DevExpress.Utils.DefaultBoolean.False); this.splitContainer1.Panel1.Controls.Add(this.panel1); this.toolTipController1.SetSuperTip(this.splitContainer1.Panel1, null); // // splitContainer1.Panel2 // this.toolTipController1.SetAllowHtmlText(this.splitContainer1.Panel2, DevExpress.Utils.DefaultBoolean.False); this.splitContainer1.Panel2.Controls.Add(this.xtraTabControl1); this.toolTipController1.SetSuperTip(this.splitContainer1.Panel2, null); this.splitContainer1.Size = new System.Drawing.Size(866, 582); this.splitContainer1.SplitterDistance = 288; this.toolTipController1.SetSuperTip(this.splitContainer1, null); this.splitContainer1.TabIndex = 1; this.splitContainer1.MouseLeave += new System.EventHandler(this.splitContainer1_MouseLeave); this.splitContainer1.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.splitContainer1_SplitterMoved); this.splitContainer1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.splitContainer1_MouseDown); this.splitContainer1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.splitContainer1_MouseUp); // // panel1 // this.toolTipController1.SetAllowHtmlText(this.panel1, DevExpress.Utils.DefaultBoolean.False); this.panel1.Controls.Add(this.gridControl1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(866, 288); this.toolTipController1.SetSuperTip(this.panel1, null); this.panel1.TabIndex = 2; // // gridControl1 // this.gridControl1.ContextMenuStrip = this.contextMenuStrip1; this.gridControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.gridControl1.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.gridControl1.Location = new System.Drawing.Point(0, 0); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.Size = new System.Drawing.Size(866, 288); this.gridControl1.TabIndex = 0; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); // // contextMenuStrip1 // this.toolTipController1.SetAllowHtmlText(this.contextMenuStrip1, DevExpress.Utils.DefaultBoolean.False); this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.copySelectedCellsToolStripMenuItem, this.pasteSelectedCellsToolStripMenuItem, this.editXaxisSymbolToolStripMenuItem, this.editYaxisSymbolToolStripMenuItem, this.smoothSelectionToolStripMenuItem, this.exportMapToolStripMenuItem, clearDataToolStripMenuItem, this.lockCellsToolStripMenuItem, this.unlockCellsToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(179, 202); this.toolTipController1.SetSuperTip(this.contextMenuStrip1, null); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // copySelectedCellsToolStripMenuItem // this.copySelectedCellsToolStripMenuItem.Name = "copySelectedCellsToolStripMenuItem"; this.copySelectedCellsToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.copySelectedCellsToolStripMenuItem.Text = "Copy selected cells"; this.copySelectedCellsToolStripMenuItem.Click += new System.EventHandler(this.copySelectedCellsToolStripMenuItem_Click); // // pasteSelectedCellsToolStripMenuItem // this.pasteSelectedCellsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.inOrgininalPositionToolStripMenuItem, this.atCurrentlySelectedLocationToolStripMenuItem}); this.pasteSelectedCellsToolStripMenuItem.Name = "pasteSelectedCellsToolStripMenuItem"; this.pasteSelectedCellsToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.pasteSelectedCellsToolStripMenuItem.Text = "Paste selected cells"; // // inOrgininalPositionToolStripMenuItem // this.inOrgininalPositionToolStripMenuItem.Name = "inOrgininalPositionToolStripMenuItem"; this.inOrgininalPositionToolStripMenuItem.Size = new System.Drawing.Size(225, 22); this.inOrgininalPositionToolStripMenuItem.Text = "At original position"; this.inOrgininalPositionToolStripMenuItem.Click += new System.EventHandler(this.inOrgininalPositionToolStripMenuItem_Click); // // atCurrentlySelectedLocationToolStripMenuItem // this.atCurrentlySelectedLocationToolStripMenuItem.Name = "atCurrentlySelectedLocationToolStripMenuItem"; this.atCurrentlySelectedLocationToolStripMenuItem.Size = new System.Drawing.Size(225, 22); this.atCurrentlySelectedLocationToolStripMenuItem.Text = "At currently selected location"; this.atCurrentlySelectedLocationToolStripMenuItem.Click += new System.EventHandler(this.atCurrentlySelectedLocationToolStripMenuItem_Click); // // editXaxisSymbolToolStripMenuItem // this.editXaxisSymbolToolStripMenuItem.Name = "editXaxisSymbolToolStripMenuItem"; this.editXaxisSymbolToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.editXaxisSymbolToolStripMenuItem.Text = "Edit x-axis"; this.editXaxisSymbolToolStripMenuItem.Click += new System.EventHandler(this.editXaxisSymbolToolStripMenuItem_Click); // // editYaxisSymbolToolStripMenuItem // this.editYaxisSymbolToolStripMenuItem.Name = "editYaxisSymbolToolStripMenuItem"; this.editYaxisSymbolToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.editYaxisSymbolToolStripMenuItem.Text = "Edit y-axis"; this.editYaxisSymbolToolStripMenuItem.Click += new System.EventHandler(this.editYaxisSymbolToolStripMenuItem_Click); // // smoothSelectionToolStripMenuItem // this.smoothSelectionToolStripMenuItem.Name = "smoothSelectionToolStripMenuItem"; this.smoothSelectionToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.smoothSelectionToolStripMenuItem.Text = "Smooth selection"; this.smoothSelectionToolStripMenuItem.Click += new System.EventHandler(this.smoothSelectionToolStripMenuItem_Click); // // exportMapToolStripMenuItem // this.exportMapToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.asPreferredSettingInT5DashboardToolStripMenuItem}); this.exportMapToolStripMenuItem.Name = "exportMapToolStripMenuItem"; this.exportMapToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.exportMapToolStripMenuItem.Text = "Export map"; this.exportMapToolStripMenuItem.Visible = false; // // asPreferredSettingInT5DashboardToolStripMenuItem // this.asPreferredSettingInT5DashboardToolStripMenuItem.Name = "asPreferredSettingInT5DashboardToolStripMenuItem"; this.asPreferredSettingInT5DashboardToolStripMenuItem.Size = new System.Drawing.Size(260, 22); this.asPreferredSettingInT5DashboardToolStripMenuItem.Text = "As preferred setting in T5Dashboard"; this.asPreferredSettingInT5DashboardToolStripMenuItem.Click += new System.EventHandler(this.asPreferredSettingInT5DashboardToolStripMenuItem_Click); // // lockCellsToolStripMenuItem // this.lockCellsToolStripMenuItem.Name = "lockCellsToolStripMenuItem"; this.lockCellsToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.lockCellsToolStripMenuItem.Text = "Lock cells"; this.lockCellsToolStripMenuItem.Click += new System.EventHandler(this.lockCellsToolStripMenuItem_Click); // // unlockCellsToolStripMenuItem // this.unlockCellsToolStripMenuItem.Name = "unlockCellsToolStripMenuItem"; this.unlockCellsToolStripMenuItem.Size = new System.Drawing.Size(178, 22); this.unlockCellsToolStripMenuItem.Text = "Unlock cells"; this.unlockCellsToolStripMenuItem.Click += new System.EventHandler(this.unlockCellsToolStripMenuItem_Click); // // gridView1 // this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsCustomization.AllowColumnMoving = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsCustomization.AllowGroup = false; this.gridView1.OptionsCustomization.AllowSort = false; this.gridView1.OptionsNavigation.EnterMoveNextColumn = true; this.gridView1.OptionsSelection.EnableAppearanceFocusedRow = false; this.gridView1.OptionsSelection.MultiSelect = true; this.gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CellSelect; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.SelectionChanged += new DevExpress.Data.SelectionChangedEventHandler(this.gridView1_SelectionChanged_1); this.gridView1.ValidatingEditor += new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(this.gridView1_ValidatingEditor); this.gridView1.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(this.gridView1_CustomDrawRowIndicator); this.gridView1.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(this.gridView1_CellValueChanged); this.gridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.gridView1_KeyDown); this.gridView1.CellValueChanging += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(this.gridView1_CellValueChanging); this.gridView1.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(this.gridView1_CustomDrawCell); this.gridView1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.gridView1_MouseMove); this.gridView1.ShownEditor += new System.EventHandler(this.gridView1_ShownEditor); this.gridView1.RowUpdated += new DevExpress.XtraGrid.Views.Base.RowObjectEventHandler(this.gridView1_RowUpdated); this.gridView1.ShowingEditor += new System.ComponentModel.CancelEventHandler(this.gridView1_ShowingEditor); this.gridView1.HiddenEditor += new System.EventHandler(this.gridView1_HiddenEditor); this.gridView1.CustomDrawColumnHeader += new DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventHandler(this.gridView1_CustomDrawColumnHeader); // // xtraTabControl1 // this.xtraTabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.xtraTabControl1.HeaderLocation = DevExpress.XtraTab.TabHeaderLocation.Left; this.xtraTabControl1.HeaderOrientation = DevExpress.XtraTab.TabOrientation.Vertical; this.xtraTabControl1.Location = new System.Drawing.Point(0, 0); this.xtraTabControl1.Name = "xtraTabControl1"; this.xtraTabControl1.SelectedTabPage = this.xtraTabPage1; this.xtraTabControl1.Size = new System.Drawing.Size(866, 290); this.xtraTabControl1.TabIndex = 2; this.xtraTabControl1.TabPages.AddRange(new DevExpress.XtraTab.XtraTabPage[] { this.xtraTabPage1, this.xtraTabPage2}); this.xtraTabControl1.SelectedPageChanged += new DevExpress.XtraTab.TabPageChangedEventHandler(this.xtraTabControl1_SelectedPageChanged); // // xtraTabPage1 // this.xtraTabPage1.Controls.Add(this.simpleButton4); this.xtraTabPage1.Controls.Add(this.simpleButton5); this.xtraTabPage1.Controls.Add(this.simpleButton6); this.xtraTabPage1.Controls.Add(this.simpleButton7); this.xtraTabPage1.Controls.Add(this.surfaceGraphViewer1); this.xtraTabPage1.Name = "xtraTabPage1"; this.xtraTabPage1.Size = new System.Drawing.Size(836, 281); this.xtraTabPage1.Text = "3D Graph"; // // simpleButton4 // this.simpleButton4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton4.Image = ((System.Drawing.Image)(resources.GetObject("simpleButton4.Image"))); this.simpleButton4.Location = new System.Drawing.Point(803, 60); this.simpleButton4.Name = "simpleButton4"; this.simpleButton4.Size = new System.Drawing.Size(23, 23); this.simpleButton4.TabIndex = 12; this.simpleButton4.ToolTip = "Turn graph counter clockwise"; this.simpleButton4.Click += new System.EventHandler(this.simpleButton4_Click); // // simpleButton5 // this.simpleButton5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton5.Image = ((System.Drawing.Image)(resources.GetObject("simpleButton5.Image"))); this.simpleButton5.Location = new System.Drawing.Point(803, 89); this.simpleButton5.Name = "simpleButton5"; this.simpleButton5.Size = new System.Drawing.Size(23, 23); this.simpleButton5.TabIndex = 11; this.simpleButton5.ToolTip = "Turn graph clockwise"; this.simpleButton5.Click += new System.EventHandler(this.simpleButton5_Click); // // simpleButton6 // this.simpleButton6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton6.Image = ((System.Drawing.Image)(resources.GetObject("simpleButton6.Image"))); this.simpleButton6.Location = new System.Drawing.Point(803, 32); this.simpleButton6.Name = "simpleButton6"; this.simpleButton6.Size = new System.Drawing.Size(23, 23); this.simpleButton6.TabIndex = 10; this.simpleButton6.ToolTip = "Zoom out"; this.simpleButton6.Click += new System.EventHandler(this.simpleButton6_Click); // // simpleButton7 // this.simpleButton7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton7.Image = ((System.Drawing.Image)(resources.GetObject("simpleButton7.Image"))); this.simpleButton7.Location = new System.Drawing.Point(803, 3); this.simpleButton7.Name = "simpleButton7"; this.simpleButton7.Size = new System.Drawing.Size(23, 23); this.simpleButton7.TabIndex = 9; this.simpleButton7.ToolTip = "Zoom in"; this.simpleButton7.Click += new System.EventHandler(this.simpleButton7_Click); // // surfaceGraphViewer1 // this.toolTipController1.SetAllowHtmlText(this.surfaceGraphViewer1, DevExpress.Utils.DefaultBoolean.False); this.surfaceGraphViewer1.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.surfaceGraphViewer1.IsRedWhite = false; this.surfaceGraphViewer1.IsSixteenbit = false; this.surfaceGraphViewer1.IsUpsideDown = false; this.surfaceGraphViewer1.Location = new System.Drawing.Point(0, 0); this.surfaceGraphViewer1.Map_compare_content = null; this.surfaceGraphViewer1.Map_content = null; this.surfaceGraphViewer1.Map_length = 0; this.surfaceGraphViewer1.Map_name = ""; this.surfaceGraphViewer1.Map_original_content = null; this.surfaceGraphViewer1.Name = "surfaceGraphViewer1"; this.surfaceGraphViewer1.NumberOfColumns = 8; this.surfaceGraphViewer1.Pan_x = 45; this.surfaceGraphViewer1.Pan_y = 77; this.surfaceGraphViewer1.Pov_d = 0.6; this.surfaceGraphViewer1.Pov_x = 30; this.surfaceGraphViewer1.Pov_y = 56; this.surfaceGraphViewer1.Pov_z = 21; this.surfaceGraphViewer1.ShowinBlue = false; this.surfaceGraphViewer1.Size = new System.Drawing.Size(797, 278); this.toolTipController1.SetSuperTip(this.surfaceGraphViewer1, null); this.surfaceGraphViewer1.TabIndex = 0; this.surfaceGraphViewer1.X_axis = null; this.surfaceGraphViewer1.X_axis_descr = ""; this.surfaceGraphViewer1.Y_axis = null; this.surfaceGraphViewer1.Y_axis_descr = ""; this.surfaceGraphViewer1.Z_axis = null; this.surfaceGraphViewer1.Z_axis_descr = ""; // // xtraTabPage2 // this.xtraTabPage2.Controls.Add(this.labelControl9); this.xtraTabPage2.Controls.Add(this.labelControl8); this.xtraTabPage2.Controls.Add(this.trackBarControl1); this.xtraTabPage2.Controls.Add(this.chartControl1); this.xtraTabPage2.Name = "xtraTabPage2"; this.xtraTabPage2.Size = new System.Drawing.Size(836, 281); this.xtraTabPage2.Text = "2D Graph"; // // labelControl9 // this.labelControl9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.labelControl9.AutoEllipsis = true; this.labelControl9.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None; this.labelControl9.Location = new System.Drawing.Point(645, 201); this.labelControl9.Name = "labelControl9"; this.labelControl9.Size = new System.Drawing.Size(188, 34); this.labelControl9.TabIndex = 4; this.labelControl9.Text = "MAP"; // // labelControl8 // this.labelControl8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.labelControl8.AutoEllipsis = true; this.labelControl8.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None; this.labelControl8.Location = new System.Drawing.Point(6, 201); this.labelControl8.Name = "labelControl8"; this.labelControl8.Size = new System.Drawing.Size(104, 34); this.labelControl8.TabIndex = 3; this.labelControl8.Text = "MAP values"; // // trackBarControl1 // this.trackBarControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarControl1.EditValue = null; this.trackBarControl1.Location = new System.Drawing.Point(125, 201); this.trackBarControl1.Name = "trackBarControl1"; this.trackBarControl1.Size = new System.Drawing.Size(500, 45); this.trackBarControl1.TabIndex = 2; this.trackBarControl1.ValueChanged += new System.EventHandler(this.trackBarControl1_ValueChanged); // // chartControl1 // this.toolTipController1.SetAllowHtmlText(this.chartControl1, DevExpress.Utils.DefaultBoolean.False); this.chartControl1.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.chartControl1.CacheToMemory = true; xyDiagram1.AxisX.VisibleInPanesSerializable = "-1"; xyDiagram1.AxisX.Range.SideMarginsEnabled = false; xyDiagram1.AxisX.Range.ScrollingRange.SideMarginsEnabled = true; xyDiagram1.AxisY.VisibleInPanesSerializable = "-1"; xyDiagram1.AxisY.Range.SideMarginsEnabled = false; xyDiagram1.AxisY.Range.ScrollingRange.SideMarginsEnabled = true; this.chartControl1.Diagram = xyDiagram1; this.chartControl1.Legend.Border.Visible = false; this.chartControl1.Location = new System.Drawing.Point(3, 3); this.chartControl1.Name = "chartControl1"; this.chartControl1.RefreshDataOnRepaint = false; this.chartControl1.RuntimeHitTesting = false; this.chartControl1.RuntimeSeriesSelectionMode = DevExpress.XtraCharts.SeriesSelectionMode.Point; series1.Name = "Values"; series1.Points.AddRange(new DevExpress.XtraCharts.SeriesPoint[] { seriesPoint1}); lineSeriesView1.LineMarkerOptions.Size = 8; lineSeriesView1.LineMarkerOptions.FillStyle.FillMode = DevExpress.XtraCharts.FillMode.Gradient; polygonGradientFillOptions1.Color2 = System.Drawing.Color.Gold; lineSeriesView1.LineMarkerOptions.FillStyle.Options = polygonGradientFillOptions1; lineSeriesView1.Color = System.Drawing.Color.DarkGoldenrod; series1.View = lineSeriesView1; series1.ArgumentDataMember = "X"; series1.ArgumentScaleType = DevExpress.XtraCharts.ScaleType.Numerical; pointSeriesLabel1.Angle = 90; pointSeriesLabel1.TextColor = System.Drawing.Color.MidnightBlue; pointSeriesLabel1.Font = new System.Drawing.Font("Tahoma", 6F, System.Drawing.FontStyle.Bold); pointSeriesLabel1.Border.Visible = false; pointSeriesLabel1.Antialiasing = true; pointSeriesLabel1.LineVisible = true; series1.Label = pointSeriesLabel1; pointOptions1.PointView = DevExpress.XtraCharts.PointView.ArgumentAndValues; series1.PointOptions = pointOptions1; this.chartControl1.SeriesSerializable = new DevExpress.XtraCharts.Series[] { series1}; this.chartControl1.SeriesTemplate.View = lineSeriesView2; pointSeriesLabel2.LineVisible = true; this.chartControl1.SeriesTemplate.Label = pointSeriesLabel2; this.chartControl1.Size = new System.Drawing.Size(830, 185); this.toolTipController1.SetSuperTip(this.chartControl1, null); this.chartControl1.TabIndex = 1; this.chartControl1.Visible = false; this.chartControl1.CustomDrawSeriesPoint += new DevExpress.XtraCharts.CustomDrawSeriesPointEventHandler(this.chartControl1_CustomDrawSeriesPoint); this.chartControl1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.chartControl1_MouseUp); this.chartControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.chartControl1_MouseDoubleClick); this.chartControl1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.chartControl1_MouseMove); this.chartControl1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.chartControl1_MouseDown); this.chartControl1.ObjectHotTracked += new DevExpress.XtraCharts.HotTrackEventHandler(this.chartControl1_ObjectHotTracked); this.chartControl1.CustomDrawSeries += new DevExpress.XtraCharts.CustomDrawSeriesEventHandler(this.chartControl1_CustomDrawSeries); this.chartControl1.Click += new System.EventHandler(this.chartControl1_Click); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // timer2 // this.timer2.Tick += new System.EventHandler(this.timer2_Tick); // // toolTipController1 // this.toolTipController1.Rounded = true; // // toolStrip1 // this.toolTipController1.SetAllowHtmlText(this.toolStrip1, DevExpress.Utils.DefaultBoolean.False); this.toolStrip1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripComboBox1, this.toolStripTextBox1, this.toolStripButton3, this.toolStripSeparator4, this.toolStripLabel3, this.toolStripComboBox3, this.toolStripSeparator2, this.toolStripButton7, this.toolStripButton6, this.toolStripButton1, this.toolStripButton2, this.toolStripButton4, this.toolStripButton5, this.toolStripSeparator1, this.toolStripLabel1, this.toolStripComboBox2}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(876, 25); this.toolTipController1.SetSuperTip(this.toolStrip1, null); this.toolStrip1.TabIndex = 10; this.toolStrip1.Text = "toolStrip1"; // // toolStripComboBox1 // this.toolStripComboBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.toolStripComboBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.toolStripComboBox1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.toolStripComboBox1.Items.AddRange(new object[] { "Addition", "Multiply", "Divide", "Fill"}); this.toolStripComboBox1.Name = "toolStripComboBox1"; this.toolStripComboBox1.Size = new System.Drawing.Size(121, 25); // // toolStripTextBox1 // this.toolStripTextBox1.Name = "toolStripTextBox1"; this.toolStripTextBox1.Size = new System.Drawing.Size(60, 25); this.toolStripTextBox1.Text = "2"; this.toolStripTextBox1.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image"))); this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Size = new System.Drawing.Size(23, 22); this.toolStripButton3.Text = "Execute"; this.toolStripButton3.Click += new System.EventHandler(this.toolStripButton3_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(51, 22); this.toolStripLabel3.Text = "Viewtype"; // // toolStripComboBox3 // this.toolStripComboBox3.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.toolStripComboBox3.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.toolStripComboBox3.Items.AddRange(new object[] { "Hex view ", "Decimal view ", "Easy view", "ASCII", "Decimal view (3 bar sensor)", "Easy view (3 bar sensor)", "Decimal view (3.5 bar sensor)", "Easy view (3.5 bar sensor)", "Decimal view (4 bar sensor)", "Easy view (4 bar sensor)", "Decimal view (5 bar sensor)", "Easy view (5 bar sensor)"}); this.toolStripComboBox3.Name = "toolStripComboBox3"; this.toolStripComboBox3.Size = new System.Drawing.Size(160, 25); this.toolStripComboBox3.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox3_SelectedIndexChanged); this.toolStripComboBox3.KeyDown += new System.Windows.Forms.KeyEventHandler(this.toolStripComboBox3_KeyDown); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // toolStripButton7 // this.toolStripButton7.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton7.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton7.Image"))); this.toolStripButton7.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton7.Name = "toolStripButton7"; this.toolStripButton7.Size = new System.Drawing.Size(23, 22); this.toolStripButton7.Text = "Toggle graph/map"; this.toolStripButton7.Click += new System.EventHandler(this.toolStripButton7_Click); // // toolStripButton6 // this.toolStripButton6.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton6.Image"))); this.toolStripButton6.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton6.Name = "toolStripButton6"; this.toolStripButton6.Size = new System.Drawing.Size(23, 22); this.toolStripButton6.Text = "Maximize window"; this.toolStripButton6.Click += new System.EventHandler(this.toolStripButton6_Click); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; 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(23, 22); this.toolStripButton1.Text = "Toggle graph section"; this.toolStripButton1.Visible = false; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; 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(23, 22); this.toolStripButton2.Text = "Toggle hexview"; this.toolStripButton2.Visible = false; this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click); // // toolStripButton4 // this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image"))); this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton4.Name = "toolStripButton4"; this.toolStripButton4.Size = new System.Drawing.Size(23, 22); this.toolStripButton4.Text = "Maximize graph"; this.toolStripButton4.Visible = false; this.toolStripButton4.Click += new System.EventHandler(this.toolStripButton4_Click); // // toolStripButton5 // this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton5.Image"))); this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton5.Name = "toolStripButton5"; this.toolStripButton5.Size = new System.Drawing.Size(23, 22); this.toolStripButton5.Text = "Maximize table"; this.toolStripButton5.Visible = false; this.toolStripButton5.Click += new System.EventHandler(this.toolStripButton5_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(77, 22); this.toolStripLabel1.Text = "Axis lock mode"; // // toolStripComboBox2 // this.toolStripComboBox2.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.toolStripComboBox2.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.toolStripComboBox2.Items.AddRange(new object[] { "Autoscale", "Lock to peak in maps", "Lock to map limit"}); this.toolStripComboBox2.Name = "toolStripComboBox2"; this.toolStripComboBox2.Size = new System.Drawing.Size(121, 25); this.toolStripComboBox2.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox2_SelectedIndexChanged); // // timer3 // this.timer3.Tick += new System.EventHandler(this.timer3_Tick); // // timer4 // this.timer4.Enabled = true; this.timer4.Interval = 500; this.timer4.Tick += new System.EventHandler(this.timer4_Tick); // // btnSaveToRAM // this.btnSaveToRAM.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSaveToRAM.Location = new System.Drawing.Point(631, 638); this.btnSaveToRAM.Name = "btnSaveToRAM"; this.btnSaveToRAM.Size = new System.Drawing.Size(75, 23); this.btnSaveToRAM.TabIndex = 12; this.btnSaveToRAM.Text = "Save to RAM"; this.btnSaveToRAM.Visible = false; this.btnSaveToRAM.Click += new System.EventHandler(this.btnSaveToRAM_Click); // // btnReadFromRAM // this.btnReadFromRAM.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnReadFromRAM.Location = new System.Drawing.Point(712, 638); this.btnReadFromRAM.Name = "btnReadFromRAM"; this.btnReadFromRAM.Size = new System.Drawing.Size(73, 23); this.btnReadFromRAM.TabIndex = 13; this.btnReadFromRAM.Text = "Refresh"; this.btnReadFromRAM.Click += new System.EventHandler(this.btnReadFromRAM_Click); // // simpleButton1 // this.simpleButton1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton1.Location = new System.Drawing.Point(103, 638); this.simpleButton1.Name = "simpleButton1"; this.simpleButton1.Size = new System.Drawing.Size(522, 23); this.simpleButton1.TabIndex = 14; this.simpleButton1.Text = "Close"; this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click_1); // // MapViewer // this.toolTipController1.SetAllowHtmlText(this, DevExpress.Utils.DefaultBoolean.False); this.Appearance.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Appearance.Options.UseFont = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.simpleButton1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.groupControl1); this.Controls.Add(this.simpleButton2); this.Controls.Add(this.btnReadFromRAM); this.Controls.Add(this.simpleButton3); this.Controls.Add(this.btnSaveToRAM); this.Name = "MapViewer"; this.Size = new System.Drawing.Size(876, 664); this.toolTipController1.SetSuperTip(this, null); this.VisibleChanged += new System.EventHandler(this.MapViewer_VisibleChanged); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit(); this.groupControl1.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).EndInit(); this.xtraTabControl1.ResumeLayout(false); this.xtraTabPage1.ResumeLayout(false); this.xtraTabPage2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.trackBarControl1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(xyDiagram1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(lineSeriesView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(series1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(lineSeriesView2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.chartControl1)).EndInit(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private DevExpress.XtraEditors.SimpleButton simpleButton3; private DevExpress.XtraEditors.SimpleButton simpleButton2; private DevExpress.XtraEditors.GroupControl groupControl1; public DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private System.Windows.Forms.SplitContainer splitContainer1; private SurfaceGraphViewer surfaceGraphViewer1; private DevExpress.XtraCharts.ChartControl chartControl1; private DevExpress.XtraTab.XtraTabControl xtraTabControl1; private DevExpress.XtraTab.XtraTabPage xtraTabPage1; private DevExpress.XtraTab.XtraTabPage xtraTabPage2; private DevExpress.XtraEditors.LabelControl labelControl9; private DevExpress.XtraEditors.LabelControl labelControl8; private DevExpress.XtraEditors.TrackBarControl trackBarControl1; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Timer timer2; private DevExpress.Utils.ToolTipController toolTipController1; private System.Windows.Forms.Timer timer3; private DevExpress.XtraEditors.SimpleButton simpleButton4; private DevExpress.XtraEditors.SimpleButton simpleButton5; private DevExpress.XtraEditors.SimpleButton simpleButton6; private DevExpress.XtraEditors.SimpleButton simpleButton7; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem copySelectedCellsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteSelectedCellsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem inOrgininalPositionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem atCurrentlySelectedLocationToolStripMenuItem; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripButton toolStripButton4; private System.Windows.Forms.ToolStripButton toolStripButton5; private System.Windows.Forms.ToolStripButton toolStripButton6; private System.Windows.Forms.ToolStripButton toolStripButton7; private System.Windows.Forms.ToolStripComboBox toolStripComboBox1; private System.Windows.Forms.ToolStripTextBox toolStripTextBox1; private System.Windows.Forms.ToolStripButton toolStripButton3; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripComboBox toolStripComboBox2; private System.Windows.Forms.Timer timer4; private System.Windows.Forms.ToolStripComboBox toolStripComboBox3; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripMenuItem editXaxisSymbolToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editYaxisSymbolToolStripMenuItem; private DevExpress.XtraEditors.SimpleButton btnSaveToRAM; private DevExpress.XtraEditors.SimpleButton btnReadFromRAM; private System.Windows.Forms.ToolStripMenuItem smoothSelectionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exportMapToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem asPreferredSettingInT5DashboardToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private DevExpress.XtraEditors.SimpleButton simpleButton1; private System.Windows.Forms.ToolStripMenuItem lockCellsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem unlockCellsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearDataToolStripMenuItem; } }
using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Threading; using System.Windows.Forms; using IdSharp.AudioInfo; using IdSharp.AudioInfo.Inspection; using IdSharp.Tagging.ID3v1; using IdSharp.Tagging.ID3v2; using IdSharp.Tagging.ID3v2.Frames; namespace IdSharp.Tagging.Harness.WinForms.UserControls { public partial class ID3v2UserControl : UserControl { private IID3v2Tag _id3v2; public ID3v2UserControl() { InitializeComponent(); cmbGenre.Sorted = true; cmbGenre.Items.AddRange(GenreHelper.GenreByIndex); cmbImageType.Items.AddRange(PictureTypeHelper.PictureTypeStrings); } private void bindingSource_CurrentChanged(object sender, EventArgs e) { IAttachedPicture attachedPicture = GetCurrentPictureFrame(); if (attachedPicture != null) LoadImageData(attachedPicture); else ClearImageData(); } private void imageContextMenu_Opening(object sender, CancelEventArgs e) { miSaveImage.Enabled = (this.pictureBox1.Image != null); miLoadImage.Enabled = (GetCurrentPictureFrame() != null); } private void miSaveImage_Click(object sender, EventArgs e) { IAttachedPicture attachedPicture = GetCurrentPictureFrame(); SaveImageToFile(attachedPicture); } private void miLoadImage_Click(object sender, EventArgs e) { IAttachedPicture attachedPicture = GetCurrentPictureFrame(); LoadImageFromFile(attachedPicture); } private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) { IAttachedPicture attachedPicture = GetCurrentPictureFrame(); LoadImageFromFile(attachedPicture); } private void cmbImageType_SelectedIndexChanged(object sender, EventArgs e) { IAttachedPicture attachedPicture = GetCurrentPictureFrame(); if (attachedPicture != null) attachedPicture.PictureType = PictureTypeHelper.GetPictureTypeFromString(cmbImageType.Text); } private void txtImageDescription_Validated(object sender, EventArgs e) { IAttachedPicture attachedPicture = GetCurrentPictureFrame(); if (attachedPicture != null) attachedPicture.Description = txtImageDescription.Text; } private void LoadImageData(IAttachedPicture attachedPicture) { pictureBox1.Image = attachedPicture.Picture; txtImageDescription.Text = attachedPicture.Description; cmbImageType.SelectedIndex = cmbImageType.Items.IndexOf(PictureTypeHelper.GetStringFromPictureType(attachedPicture.PictureType)); txtImageDescription.Enabled = true; cmbImageType.Enabled = true; } private void ClearImageData() { pictureBox1.Image = null; txtImageDescription.Text = ""; cmbImageType.SelectedIndex = -1; txtImageDescription.Enabled = false; cmbImageType.Enabled = false; } private void SaveImageToFile(IAttachedPicture attachedPicture) { string extension = attachedPicture.PictureExtension; imageSaveFileDialog.FileName = "image." + extension; DialogResult dialogResult = imageSaveFileDialog.ShowDialog(); if (dialogResult == DialogResult.OK) { using (FileStream fs = File.Open(imageSaveFileDialog.FileName, FileMode.Create, FileAccess.Write, FileShare.None)) { fs.Write(attachedPicture.PictureData, 0, attachedPicture.PictureData.Length); } } } private void LoadImageFromFile(IAttachedPicture attachedPicture) { DialogResult dialogResult = imageOpenFileDialog.ShowDialog(); if (dialogResult == DialogResult.OK) { attachedPicture.Picture = Image.FromFile(imageOpenFileDialog.FileName); pictureBox1.Image = attachedPicture.Picture; } } private IAttachedPicture GetCurrentPictureFrame() { if (imageBindingNavigator.BindingSource == null) return null; return imageBindingNavigator.BindingSource.Current as IAttachedPicture; } public void LoadFile(string path) { ClearImageData(); _id3v2 = new ID3v2Tag(path); txtFilename.Text = Path.GetFileName(path); txtArtist.Text = _id3v2.Artist; txtTitle.Text = _id3v2.Title; txtAlbum.Text = _id3v2.Album; cmbGenre.Text = _id3v2.Genre; txtYear.Text = _id3v2.Year; txtTrackNumber.Text = _id3v2.TrackNumber; chkPodcast.Checked = _id3v2.IsPodcast; txtPodcastFeedUrl.Text = _id3v2.PodcastFeedUrl; BindingSource bindingSource = new BindingSource(); imageBindingNavigator.BindingSource = bindingSource; bindingSource.CurrentChanged += bindingSource_CurrentChanged; bindingSource.DataSource = _id3v2.PictureList; switch (_id3v2.Header.TagVersion) { case ID3v2TagVersion.ID3v22: cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.2"); break; case ID3v2TagVersion.ID3v23: cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.3"); break; case ID3v2TagVersion.ID3v24: cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.4"); break; } txtPlayLength.Text = string.Empty; txtBitrate.Text = string.Empty; txtEncoderPreset.Text = string.Empty; Thread t = new Thread(LoadAudioFileDetails); t.Start(path); } private void LoadAudioFileDetails(object pathObject) { string path = (string)pathObject; IAudioFile audioFile = AudioFile.Create(path, false); decimal bitrate = audioFile.Bitrate; // force bitrate calculation DescriptiveLameTagReader lameTagReader = new DescriptiveLameTagReader(path); Invoke(new Action<IAudioFile, DescriptiveLameTagReader>(SetAudioFileDetails), audioFile, lameTagReader); } private void SetAudioFileDetails(IAudioFile audioFile, DescriptiveLameTagReader lameTagReader) { txtPlayLength.Text = string.Format("{0}:{1:00}", (int)audioFile.TotalSeconds / 60, (int)audioFile.TotalSeconds % 60); txtBitrate.Text = string.Format("{0:#,0} kbps", audioFile.Bitrate); txtEncoderPreset.Text = string.Format("{0} {1}", lameTagReader.LameTagInfoEncoder, lameTagReader.UsePresetGuess == UsePresetGuess.NotNeeded ? lameTagReader.Preset : lameTagReader.PresetGuess); } public void SaveFile(string path) { if (_id3v2 == null) { MessageBox.Show("Nothing to save!"); return; } if (cmbID3v2.SelectedIndex == cmbID3v2.Items.IndexOf("ID3v2.2")) _id3v2.Header.TagVersion = ID3v2TagVersion.ID3v22; else if (cmbID3v2.SelectedIndex == cmbID3v2.Items.IndexOf("ID3v2.3")) _id3v2.Header.TagVersion = ID3v2TagVersion.ID3v23; else if (cmbID3v2.SelectedIndex == cmbID3v2.Items.IndexOf("ID3v2.4")) _id3v2.Header.TagVersion = ID3v2TagVersion.ID3v24; else throw new Exception("Unknown tag version"); _id3v2.Artist = txtArtist.Text; _id3v2.Title = txtTitle.Text; _id3v2.Album = txtAlbum.Text; _id3v2.Genre = cmbGenre.Text; _id3v2.Year = txtYear.Text; _id3v2.TrackNumber = txtTrackNumber.Text; _id3v2.IsPodcast = chkPodcast.Checked; _id3v2.PodcastFeedUrl = txtPodcastFeedUrl.Text; _id3v2.Save(path); } private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e) { Console.WriteLine(_id3v2.PictureList.Count); } } }
// ---------------------------------------------------------------------- // // Microsoft Windows NT // Copyright (C) Microsoft Corporation, 2007. // // Contents: Entry points for managed PowerShell plugin worker used to // host powershell in a WSMan service. // ---------------------------------------------------------------------- using System.Collections.ObjectModel; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using System.Management.Automation.Internal; using System.Management.Automation.Remoting.Client; using System.Management.Automation.Remoting.Server; using System.Management.Automation.Tracing; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// Abstract class that defines common functionality for WinRM Plugin API Server Sessions /// </summary> internal abstract class WSManPluginServerSession : IDisposable { private object _syncObject; protected bool isClosed; protected bool isContextReported; // used to keep track of last error..this will be used // for reporting operation complete to WSMan. protected Exception lastErrorReported; // request context passed by WSMan while creating a shell or command. internal WSManNativeApi.WSManPluginRequest creationRequestDetails; // request context passed by WSMan while sending Plugin data. internal WSManNativeApi.WSManPluginRequest sendRequestDetails; internal WSManPluginOperationShutdownContext shutDownContext; // tracker used in conjunction with WSMan API to identigy a particular // shell context. internal RegisteredWaitHandle registeredShutDownWaitHandle; internal WSManPluginServerTransportManager transportMgr; internal System.Int32 registeredShutdownNotification; // event that gets raised when session is closed.."source" will provide // IntPtr for "creationRequestDetails" which can be used to free // the context. internal event EventHandler<EventArgs> SessionClosed; // Track whether Dispose has been called. private bool _disposed = false; protected WSManPluginServerSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager trnsprtMgr) { _syncObject = new Object(); this.creationRequestDetails = creationRequestDetails; this.transportMgr = trnsprtMgr; transportMgr.PrepareCalled += new EventHandler<EventArgs>(this.HandlePrepareFromTransportManager); transportMgr.WSManTransportErrorOccured += new EventHandler<TransportErrorOccuredEventArgs>(this.HandleTransportError); } public void Dispose() { // Dispose of unmanaged resources. Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> True when called from Dispose(), False when called from Finalize(). protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!_disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Dispose managed resources. //Close(false); } // Call the appropriate methods to clean up // unmanaged resources here. // If disposing is false, // only the following code is executed. Close(false); // Note disposing has been done. _disposed = true; } } /// <summary> /// Use C# destructor syntax for finalization code. /// This destructor will run only if the Dispose method /// does not get called. /// It gives your base class the opportunity to finalize. /// Do not provide destructors in types derived from this class. /// </summary> ~WSManPluginServerSession() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } internal void SendOneItemToSession( WSManNativeApi.WSManPluginRequest requestDetails, int flags, string stream, WSManNativeApi.WSManData_UnToMan inboundData) { if ((!String.Equals(stream, WSManPluginConstants.SupportedInputStream, StringComparison.Ordinal)) && (!String.Equals(stream, WSManPluginConstants.SupportedPromptResponseStream, StringComparison.Ordinal))) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidInputStream, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidInputStream, WSManPluginConstants.SupportedInputStream)); return; } if (null == inboundData) { // no data is supplied..just ignore. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.NoError); return; } if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_BINARY != inboundData.Type) { // only binary data is supported WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidInputDatatype, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidInputStream, "WSMAN_DATA_TYPE_BINARY")); return; } lock (_syncObject) { if (true == isClosed) { WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); return; } // store the send request details..because the operation complete // may happen from a different thread. sendRequestDetails = requestDetails; } SendOneItemToSessionHelper(inboundData.Data, stream); // report operation complete. ReportSendOperationComplete(); } internal void SendOneItemToSessionHelper( System.Byte[] data, string stream) { transportMgr.ProcessRawData(data, stream); } internal bool EnableSessionToSendDataToClient( WSManNativeApi.WSManPluginRequest requestDetails, int flags, WSManNativeApi.WSManStreamIDSet_UnToMan streamSet, WSManPluginOperationShutdownContext ctxtToReport) { if (true == isClosed) { WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); return false; } if ((null == streamSet) || (1 != streamSet.streamIDsCount)) { // only "stdout" is the supported output stream. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidOutputStream, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidOutputStream, WSManPluginConstants.SupportedOutputStream)); return false; } if (!String.Equals(streamSet.streamIDs[0], WSManPluginConstants.SupportedOutputStream, StringComparison.Ordinal)) { // only "stdout" is the supported output stream. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidOutputStream, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidOutputStream, WSManPluginConstants.SupportedOutputStream)); return false; } return transportMgr.EnableTransportManagerSendDataToClient(requestDetails, ctxtToReport); } /// <summary> /// Report session context to WSMan..this will let WSMan send ACK to /// client and client can send data. /// </summary> internal void ReportContext() { int result = 0; bool isRegisterWaitForSingleObjectFailed = false; lock (_syncObject) { if (true == isClosed) { return; } if (!isContextReported) { isContextReported = true; PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext, PSOpcode.Connect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, creationRequestDetails.ToString(), creationRequestDetails.ToString()); //RACE TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime // If Signal comes and executes before registering the notification handle, cleanup will be messed result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle); if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result)) { registeredShutdownNotification = 1; // Wrap the provided handle so it can be passed to the registration function SafeWaitHandle safeWaitHandle = new SafeWaitHandle(creationRequestDetails.shutdownNotificationHandle, false); // Owned by WinRM EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); // Register shutdown notification handle this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( eventWaitHandle, new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), shutDownContext, -1, // INFINITE true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? if (null == this.registeredShutDownWaitHandle) { isRegisterWaitForSingleObjectFailed = true; registeredShutdownNotification = 0; } } } } if ((WSManPluginConstants.ExitCodeSuccess != result) || (isRegisterWaitForSingleObjectFailed)) { string errorMessage; if (isRegisterWaitForSingleObjectFailed) { errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed); } else { errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginReportContextFailed); } // Report error and close the session Exception mgdException = new InvalidOperationException(errorMessage); Close(mgdException); } } /// <summary> /// Added to provide derived classes with the ability to send event notifications. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> protected internal void SafeInvokeSessionClosed(Object sender, EventArgs eventArgs) { SessionClosed.SafeInvoke(sender, eventArgs); } // handle transport manager related errors internal void HandleTransportError(Object sender, TransportErrorOccuredEventArgs eventArgs) { Exception reasonForClose = null; if (null != eventArgs) { reasonForClose = eventArgs.Exception; } Close(reasonForClose); } // handle prepare from tranport by reporting context to WSMan. internal void HandlePrepareFromTransportManager(Object sender, EventArgs eventArgs) { ReportContext(); ReportSendOperationComplete(); transportMgr.PrepareCalled -= new EventHandler<EventArgs>(this.HandlePrepareFromTransportManager); } internal void Close(bool isShuttingDown) { if (Interlocked.Exchange(ref registeredShutdownNotification, 0) == 1) { // release the shutdown notification handle. if (null != registeredShutDownWaitHandle) { registeredShutDownWaitHandle.Unregister(null); registeredShutDownWaitHandle = null; } } // Delete the context only if isShuttingDown != true. isShuttingDown will // be true only when the method is called from RegisterWaitForSingleObject // handler..in which case the context will be freed from the callback. if (null != shutDownContext) { shutDownContext = null; } transportMgr.WSManTransportErrorOccured -= new EventHandler<TransportErrorOccuredEventArgs>(this.HandleTransportError); // We should not use request details again after so releasing the resource. // Remember not to free this memory as this memory is allocated and owned by WSMan. creationRequestDetails = null; // if already disposing..no need to let finalizer thread // put resources to clean this object. //System.GC.SuppressFinalize(this); // TODO: This is already called in Dispose(). } // close current session and transport manager because of an exception internal void Close(Exception reasonForClose) { lastErrorReported = reasonForClose; WSManPluginOperationShutdownContext context = new WSManPluginOperationShutdownContext(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, false); CloseOperation(context, reasonForClose); } // Report Operation Complete using the send request details. internal void ReportSendOperationComplete() { lock (_syncObject) { if (null != sendRequestDetails) { // report and clear the send request details WSManPluginInstance.ReportWSManOperationComplete(sendRequestDetails, lastErrorReported); sendRequestDetails = null; } } } #region Pure virtual methods internal abstract void CloseOperation(WSManPluginOperationShutdownContext context, Exception reasonForClose); internal abstract void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, // in int flags, // in WSManNativeApi.WSManData_UnToMan inboundConnectInformation); // in optional #endregion } /// <summary> /// /// </summary> internal class WSManPluginShellSession : WSManPluginServerSession { #region Private Members private Dictionary<IntPtr, WSManPluginCommandSession> _activeCommandSessions; private ServerRemoteSession _remoteSession; #endregion #region Internally Visible Members internal object shellSyncObject; #endregion #region Constructor internal WSManPluginShellSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager trnsprtMgr, ServerRemoteSession remoteSession, WSManPluginOperationShutdownContext shutDownContext) : base(creationRequestDetails, trnsprtMgr) { _remoteSession = remoteSession; _remoteSession.Closed += new EventHandler<RemoteSessionStateMachineEventArgs>(this.HandleServerRemoteSessionClosed); _activeCommandSessions = new Dictionary<IntPtr, WSManPluginCommandSession>(); this.shellSyncObject = new System.Object(); this.shutDownContext = shutDownContext; } #endregion /// <summary> /// Main Routine for Connect on a Shell. /// Calls in server remotesessions ExecuteConnect to run the Connect algorithm /// This call is synchronous. i.e WSManOperationComplete will be called before the routine completes /// </summary> /// <param name="requestDetails"></param> /// <param name="flags"></param> /// <param name="inboundConnectInformation"></param> internal override void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, // in int flags, // in WSManNativeApi.WSManData_UnToMan inboundConnectInformation) // in optional { if (null == inboundConnectInformation) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.NullInvalidInput, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullInvalidInput, "inboundConnectInformation", "WSManPluginShellConnect")); return; } //not registering shutdown event as this is a synchronous operation. IntPtr responseXml = IntPtr.Zero; try { System.Byte[] inputData; System.Byte[] outputData; // Retrieve the string (Base64 encoded) inputData = ServerOperationHelpers.ExtractEncodedXmlElement( inboundConnectInformation.Text, WSManNativeApi.PS_CONNECT_XML_TAG); //this will raise exceptions on failure try { _remoteSession.ExecuteConnect(inputData, out outputData); //construct Xml to send back string responseData = String.Format(System.Globalization.CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}</{0}>", WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, Convert.ToBase64String(outputData)); //TODO: curretly using OperationComplete to report back the responseXml. This will need to change to use WSManReportObject //that is currently internal. WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.NoError, responseData); } catch (PSRemotingDataStructureException ex) { WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.PluginConnectOperationFailed, ex.Message); } } catch (OutOfMemoryException) { WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory); } finally { if (responseXml != IntPtr.Zero) { Marshal.FreeHGlobal(responseXml); } } return; } // Create a new command in the shell context. internal void CreateCommand( IntPtr pluginContext, WSManNativeApi.WSManPluginRequest requestDetails, int flags, string commandLine, WSManNativeApi.WSManCommandArgSet arguments) { try { // inbound cmd information is already verified.. so no need to verify here. WSManPluginCommandTransportManager serverCmdTransportMgr = new WSManPluginCommandTransportManager(transportMgr); serverCmdTransportMgr.Initialize(); // Apply quota limits on the command transport manager _remoteSession.ApplyQuotaOnCommandTransportManager(serverCmdTransportMgr); WSManPluginCommandSession mgdCmdSession = new WSManPluginCommandSession(requestDetails, serverCmdTransportMgr, _remoteSession); AddToActiveCmdSessions(mgdCmdSession); mgdCmdSession.SessionClosed += new EventHandler<EventArgs>(this.HandleCommandSessionClosed); mgdCmdSession.shutDownContext = new WSManPluginOperationShutdownContext( pluginContext, creationRequestDetails.unmanagedHandle, mgdCmdSession.creationRequestDetails.unmanagedHandle, false); do { if (!mgdCmdSession.ProcessArguments(arguments)) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidArgSet, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidArgSet, "WSManPluginCommand")); break; } // Report plugin context to WSMan mgdCmdSession.ReportContext(); } while (false); } catch (System.Exception e) { CommandProcessorBase.CheckForSevereException(e); // if there is an exception creating remote session send the message to client. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.ManagedException, StringUtil.Format( RemotingErrorIdStrings.WSManPluginManagedException, e.Message)); } } // Closes the command and clears associated resources internal void CloseCommandOperation( WSManPluginOperationShutdownContext context) { WSManPluginCommandSession mgdCmdSession = GetCommandSession(context.commandContext); if (null == mgdCmdSession) { // this should never be the case. this will protect the service. return; } // update the internal data store only if this is not receive operation. if (!context.isReceiveOperation) { DeleteFromActiveCmdSessions(mgdCmdSession.creationRequestDetails.unmanagedHandle); } mgdCmdSession.CloseOperation(context, null); } // adds command session to active command Sessions store and returns the id // at which the session is added. private void AddToActiveCmdSessions( WSManPluginCommandSession newCmdSession) { lock (shellSyncObject) { if (isClosed) { return; } IntPtr key = newCmdSession.creationRequestDetails.unmanagedHandle; Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided"); if (!_activeCommandSessions.ContainsKey(key)) { _activeCommandSessions.Add(key, newCmdSession); return; } } } private void DeleteFromActiveCmdSessions( IntPtr keyToDelete) { lock (shellSyncObject) { if (isClosed) { return; } _activeCommandSessions.Remove(keyToDelete); } } // closes all the active command sessions. private void CloseAndClearCommandSessions( Exception reasonForClose) { Collection<WSManPluginCommandSession> copyCmdSessions = new Collection<WSManPluginCommandSession>(); lock (shellSyncObject) { Dictionary<IntPtr, WSManPluginCommandSession>.Enumerator cmdEnumerator = _activeCommandSessions.GetEnumerator(); while (cmdEnumerator.MoveNext()) { copyCmdSessions.Add(cmdEnumerator.Current.Value); } _activeCommandSessions.Clear(); } // close the command sessions outside of the lock IEnumerator<WSManPluginCommandSession> cmdSessionEnumerator = copyCmdSessions.GetEnumerator(); while (cmdSessionEnumerator.MoveNext()) { WSManPluginCommandSession cmdSession = cmdSessionEnumerator.Current; // we are not interested in session closed events anymore as we are intiating the close // anyway/ cmdSession.SessionClosed -= new EventHandler<EventArgs>(this.HandleCommandSessionClosed); cmdSession.Close(reasonForClose); } copyCmdSessions.Clear(); } // returns the command session instance for a given command id. // null if not found. internal WSManPluginCommandSession GetCommandSession( IntPtr cmdContext) { lock (shellSyncObject) { WSManPluginCommandSession result = null; _activeCommandSessions.TryGetValue(cmdContext, out result); return result; } } private void HandleServerRemoteSessionClosed( Object sender, RemoteSessionStateMachineEventArgs eventArgs) { Exception reasonForClose = null; if (null != eventArgs) { reasonForClose = eventArgs.Reason; } Close(reasonForClose); } private void HandleCommandSessionClosed( Object source, EventArgs e) { // command context is passed as "source" parameter DeleteFromActiveCmdSessions((IntPtr)source); } internal override void CloseOperation( WSManPluginOperationShutdownContext context, Exception reasonForClose) { // let command sessions to close. lock (shellSyncObject) { if (true == isClosed) { return; } if (!context.isReceiveOperation) { isClosed = true; } } bool isRcvOpShuttingDown = (context.isShuttingDown) && (context.isReceiveOperation); bool isRcvOp = context.isReceiveOperation; bool isShuttingDown = context.isShuttingDown; // close the pending send operation if any ReportSendOperationComplete(); // close the shell's transport manager after commands handled the operation transportMgr.DoClose(isRcvOpShuttingDown, reasonForClose); if (!isRcvOp) { // Initiate close on the active command sessions and then clear the internal // Command Sesison dictionary CloseAndClearCommandSessions(reasonForClose); // raise session closed event and let dependent code to release resources. // null check is not performed here because the handler will take care of this. base.SafeInvokeSessionClosed(creationRequestDetails.unmanagedHandle, EventArgs.Empty); // Send Operation Complete to WSMan service WSManPluginInstance.ReportWSManOperationComplete(creationRequestDetails, reasonForClose); // let base class release its resources base.Close(isShuttingDown); } // TODO: Do this.Dispose(); here? } } internal class WSManPluginCommandSession : WSManPluginServerSession { #region Private Members private ServerRemoteSession _remoteSession; #endregion #region Internally Visible Members internal object cmdSyncObject; #endregion #region Constructor internal WSManPluginCommandSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager trnsprtMgr, ServerRemoteSession remoteSession) : base(creationRequestDetails, trnsprtMgr) { _remoteSession = remoteSession; cmdSyncObject = new System.Object(); } #endregion internal bool ProcessArguments( WSManNativeApi.WSManCommandArgSet arguments) { if (1 != arguments.argsCount) { return false; } System.Byte[] convertedBase64 = Convert.FromBase64String(arguments.args[0]); transportMgr.ProcessRawData(convertedBase64, WSManPluginConstants.SupportedInputStream); return true; } /// <summary> /// /// </summary> /// <param name="requestDetails"></param> internal void Stop( WSManNativeApi.WSManPluginRequest requestDetails) { // stop the command..command will be stoped if we raise ClosingEvent on // transport manager. transportMgr.PerformStop(); WSManPluginInstance.ReportWSManOperationComplete(requestDetails, null); } internal override void CloseOperation( WSManPluginOperationShutdownContext context, Exception reasonForClose) { // let command sessions to close. lock (cmdSyncObject) { if (true == isClosed) { return; } if (!context.isReceiveOperation) { isClosed = true; } } bool isRcvOp = context.isReceiveOperation; // only one thread will be here. bool isRcvOpShuttingDown = (context.isShuttingDown) && (context.isReceiveOperation) && (context.commandContext == creationRequestDetails.unmanagedHandle); bool isCmdShuttingDown = (context.isShuttingDown) && (!context.isReceiveOperation) && (context.commandContext == creationRequestDetails.unmanagedHandle); // close the pending send operation if any ReportSendOperationComplete(); // close the shell's transport manager first..so we wont send data. transportMgr.DoClose(isRcvOpShuttingDown, reasonForClose); if (!isRcvOp) { // raise session closed event and let dependent code to release resources. // null check is not performed here because Managed C++ will take care of this. base.SafeInvokeSessionClosed(creationRequestDetails.unmanagedHandle, EventArgs.Empty); // Send Operation Complete to WSMan service WSManPluginInstance.ReportWSManOperationComplete(creationRequestDetails, reasonForClose); // let base class release its resources this.Close(isCmdShuttingDown); } } /// <summary> /// Main routine for connect on a command/pipeline.. Currently NO-OP /// will be enhanced later to support intelligent connect... like ending input streams on pipelines /// that are still waiting for input data /// </summary> /// <param name="requestDetails"></param> /// <param name="flags"></param> /// <param name="inboundConnectInformation"></param> internal override void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, int flags, WSManNativeApi.WSManData_UnToMan inboundConnectInformation) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.NoError); return; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ContainerRegistry { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for RegistriesOperations. /// </summary> public static partial class RegistriesOperationsExtensions { /// <summary> /// Checks whether the container registry name is available for use. The name /// must contain only alphanumeric characters, be globally unique, and /// between 5 and 60 characters in length. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// The name of the container registry. /// </param> public static RegistryNameStatus CheckNameAvailability(this IRegistriesOperations operations, string name) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).CheckNameAvailabilityAsync(name), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether the container registry name is available for use. The name /// must contain only alphanumeric characters, be globally unique, and /// between 5 and 60 characters in length. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// The name of the container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<RegistryNameStatus> CheckNameAvailabilityAsync(this IRegistriesOperations operations, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the properties of the specified container registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> public static Registry GetProperties(this IRegistriesOperations operations, string resourceGroupName, string registryName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).GetPropertiesAsync(resourceGroupName, registryName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the properties of the specified container registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Registry> GetPropertiesAsync(this IRegistriesOperations operations, string resourceGroupName, string registryName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, registryName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a container registry with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registry'> /// The parameters for creating or updating a container registry. /// </param> public static Registry CreateOrUpdate(this IRegistriesOperations operations, string resourceGroupName, string registryName, Registry registry) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).CreateOrUpdateAsync(resourceGroupName, registryName, registry), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a container registry with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registry'> /// The parameters for creating or updating a container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Registry> CreateOrUpdateAsync(this IRegistriesOperations operations, string resourceGroupName, string registryName, Registry registry, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, registryName, registry, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a container registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> public static void Delete(this IRegistriesOperations operations, string resourceGroupName, string registryName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).DeleteAsync(resourceGroupName, registryName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a container registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this IRegistriesOperations operations, string resourceGroupName, string registryName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, registryName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a container registry with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registryUpdateParameters'> /// The parameters for updating a container registry. /// </param> public static Registry Update(this IRegistriesOperations operations, string resourceGroupName, string registryName, RegistryUpdateParameters registryUpdateParameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).UpdateAsync(resourceGroupName, registryName, registryUpdateParameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a container registry with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registryUpdateParameters'> /// The parameters for updating a container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Registry> UpdateAsync(this IRegistriesOperations operations, string resourceGroupName, string registryName, RegistryUpdateParameters registryUpdateParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, registryName, registryUpdateParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the available container registries under the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> public static Microsoft.Rest.Azure.IPage<Registry> ListByResourceGroup(this IRegistriesOperations operations, string resourceGroupName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available container registries under the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Registry>> ListByResourceGroupAsync(this IRegistriesOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the available container registries under the specified /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Microsoft.Rest.Azure.IPage<Registry> List(this IRegistriesOperations operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).ListAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available container registries under the specified /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Registry>> ListAsync(this IRegistriesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the administrator login credentials for the specified container /// registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> public static RegistryCredentials GetCredentials(this IRegistriesOperations operations, string resourceGroupName, string registryName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).GetCredentialsAsync(resourceGroupName, registryName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the administrator login credentials for the specified container /// registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<RegistryCredentials> GetCredentialsAsync(this IRegistriesOperations operations, string resourceGroupName, string registryName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetCredentialsWithHttpMessagesAsync(resourceGroupName, registryName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the administrator login credentials for the specified /// container registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> public static RegistryCredentials RegenerateCredentials(this IRegistriesOperations operations, string resourceGroupName, string registryName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).RegenerateCredentialsAsync(resourceGroupName, registryName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerates the administrator login credentials for the specified /// container registry. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<RegistryCredentials> RegenerateCredentialsAsync(this IRegistriesOperations operations, string resourceGroupName, string registryName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.RegenerateCredentialsWithHttpMessagesAsync(resourceGroupName, registryName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the available container registries under the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<Registry> ListByResourceGroupNext(this IRegistriesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available container registries under the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Registry>> ListByResourceGroupNextAsync(this IRegistriesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the available container registries under the specified /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<Registry> ListNext(this IRegistriesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRegistriesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available container registries under the specified /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Registry>> ListNextAsync(this IRegistriesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#region -- License Terms -- // // NLiblet // // Copyright (C) 2011-2017 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. // // Contributors: // Samuel Cragg // #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Text; namespace MsgPack.Serialization.Reflection { /// <summary> /// <see cref="ILGenerator"/> like IL stream builder with tracing. /// </summary> internal sealed partial class TracingILGenerator : IDisposable { private readonly ILGenerator _underlying; private readonly TextWriter _trace; private readonly Dictionary<LocalBuilder, string> _localDeclarations = new Dictionary<LocalBuilder, string>(); private readonly Dictionary<Label, string> _labels = new Dictionary<Label, string>(); private readonly Label _endOfMethod; /// <summary> /// Get <see cref="Label"/> for end of method. /// </summary> /// <value> /// <see cref="Label"/> for end of method. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For assertion" )] public Label EndOfMethod { get { return this._endOfMethod; } } private readonly Stack<Label> _endOfExceptionBlocks = new Stack<Label>(); #if DEBUG /// <summary> /// Get <see cref="Label"/> for end of current exception blocks. /// </summary> /// <value> /// <see cref="Label"/> for end of current exception blocks. /// When there are no exception blocks, then null. /// </value> public Label? EndOfCurrentExceptionBlock { get { if ( this._endOfExceptionBlocks.Count == 0 ) { return null; } else { return this._endOfExceptionBlocks.Peek(); } } } #endif // DEBUG /// <summary> /// Get whether there are any exception blocks in current positon. /// </summary> /// <value> /// If there are any exception blocks in current positon then <c>true</c>; otherwise, <c>false</c>. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For assertion" )] public bool IsInExceptionBlock { get { return 0 < this._endOfExceptionBlocks.Count; } } private bool _isInDynamicMethod; #if DEBUG /// <summary> /// Get the value whether this instance used for dynamic method. /// </summary> /// <value>If this instance used for dynamic method then <c>true</c>; otherwise <c>false</c>.</value> /// <remarks> /// Dynamic method does not support debugging information like local variable name. /// </remarks> public bool IsInDynamicMethod { get { return this._isInDynamicMethod; } } #endif // DEBUG private int _indentLevel; #if DEBUG /// <summary> /// Get level of indentation. /// </summary> public int IndentLevel { get { Contract.Ensures( 0 <= Contract.Result<int>() ); return this._indentLevel; } } #endif // DEBUG private string _indentChars = " "; #if DEBUG /// <summary> /// Get or set indent characters. /// </summary> /// <value> /// <see cref="String"/> to be used to indent. /// To reset default, specify null. /// </value> public string IndentCharacters { get { Contract.Ensures( Contract.Result<string>() != null ); return this._indentChars; } set { this._indentChars = value ?? " "; } } #endif // DEBUG private int _lineNumber; #if DEBUG /// <summary> /// Get current line number. /// </summary> /// <value>Current line number.</value> public int LineNumber { get { Contract.Ensures( 0 <= Contract.Result<int>() ); return this._lineNumber; } } #endif // DEBUG private bool _isEnded = false; /// <summary> /// Get whether this IL stream is ended with 'ret'. /// </summary> /// <returns> /// When this IL stream is ended with 'ret' then <c>true</c>; otherwise, <c>false</c>. /// </returns> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For assertion" )] public bool IsEnded { get { return this._isEnded; } } // TODO: NLiblet private readonly bool _isDebuggable; #if DEBUG /// <summary> /// Initializes a new instance of the <see cref="TracingILGenerator"/> class. /// </summary> /// <param name="methodBuilder">The method builder.</param> /// <param name="traceWriter">The trace writer.</param> public TracingILGenerator( MethodBuilder methodBuilder, TextWriter traceWriter ) : this( methodBuilder != null ? methodBuilder.GetILGenerator() : null, false, traceWriter, false ) { Contract.Assert( methodBuilder != null ); } #endif // DEBUG /// <summary> /// Initializes a new instance of the <see cref="TracingILGenerator"/> class. /// </summary> /// <param name="dynamicMethod">The dynamic method.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="isDebuggable"><c>true</c> if the underlying builders are debuggable; othersie <c>false</c>.</param> public TracingILGenerator( DynamicMethod dynamicMethod, TextWriter traceWriter, bool isDebuggable ) : this( dynamicMethod != null ? dynamicMethod.GetILGenerator() : null, true, traceWriter, isDebuggable ) { Contract.Assert( dynamicMethod != null ); } // TODO: NLIblet /// <summary> /// Initializes a new instance of the <see cref="TracingILGenerator"/> class. /// </summary> /// <param name="methodBuilder">The method builder.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="isDebuggable"><c>true</c> if the underlying builders are debuggable; othersie <c>false</c>.</param> public TracingILGenerator( MethodBuilder methodBuilder, TextWriter traceWriter, bool isDebuggable ) : this( methodBuilder != null ? methodBuilder.GetILGenerator() : null, false, traceWriter, isDebuggable ) { Contract.Assert( methodBuilder != null ); } /// <summary> /// Initializes a new instance of the <see cref="TracingILGenerator"/> class. /// </summary> /// <param name="constructorBuilder">The constructor builder.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="isDebuggable"><c>true</c> if the underlying builders are debuggable; othersie <c>false</c>.</param> public TracingILGenerator( ConstructorBuilder constructorBuilder, TextWriter traceWriter, bool isDebuggable ) : this( constructorBuilder != null ? constructorBuilder.GetILGenerator() : null, false, traceWriter, isDebuggable ) { Contract.Assert( constructorBuilder != null ); } // TODO: NLiblet private TracingILGenerator( ILGenerator underlying, bool isInDynamicMethod, TextWriter traceWriter, bool isDebuggable ) { this._underlying = underlying; this._trace = traceWriter ?? NullTextWriter.Instance; this._isInDynamicMethod = isInDynamicMethod; this._endOfMethod = underlying == null ? default( Label ) : underlying.DefineLabel(); this._isDebuggable = isDebuggable; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this._trace.Dispose(); } /// <summary> /// Emit 'ret' instruction with specified arguments. /// </summary> public void EmitRet() { Contract.Assert( !this.IsEnded ); this.TraceStart(); this.TraceOpCode( OpCodes.Ret ); this._underlying.Emit( OpCodes.Ret ); this.FlushTrace(); this._isEnded = true; } public void FlushTrace() { this._trace.Flush(); } #region -- Locals -- /// <summary> /// Declare local without pinning and name for debugging. /// </summary> /// <param name="localType"><see cref="Type"/> of local variable.</param> /// <returns><see cref="LocalBuilder"/> to refer declared local variable.</returns> public LocalBuilder DeclareLocal( Type localType ) { Contract.Assert( !this.IsEnded ); Contract.Assert( localType != null ); Contract.Ensures( Contract.Result<LocalBuilder>() != null ); return this.DeclareLocalCore( localType, null ); } #if DEBUG /// <summary> /// Declare local without name for debugging. /// </summary> /// <param name="localType"><see cref="Type"/> of local variable.</param> /// <param name="pinned">If <c>true</c>, the local variable will be pinned.</param> /// <returns><see cref="LocalBuilder"/> to refer declared local variable.</returns> public LocalBuilder DeclareLocal( Type localType, bool pinned ) { Contract.Assert( !this.IsEnded ); Contract.Assert( localType != null ); Contract.Ensures( Contract.Result<LocalBuilder>() != null ); return this.DeclareLocalCore( localType, null, pinned ); } #endif // DEBUG /// <summary> /// Declare local with name for debugging and without pinning. /// Note that this method is not enabled for dynamic method. /// </summary> /// <param name="localType"><see cref="Type"/> of local variable.</param> /// <param name="name">Name of the local variable.</param> /// <returns><see cref="LocalBuilder"/> to refer declared local variable.</returns> public LocalBuilder DeclareLocal( Type localType, string name ) { Contract.Assert( !this.IsEnded ); Contract.Assert( localType != null ); Contract.Assert( name != null ); Contract.Ensures( Contract.Result<LocalBuilder>() != null ); return this.DeclareLocalCore( localType, name ); } #if DEBUG /// <summary> /// Declare local with name for debugging. /// Note that this method is not enabled for dynamic method. /// </summary> /// <param name="localType"><see cref="Type"/> of local variable.</param> /// <param name="name">Name of the local variable.</param> /// <param name="pinned">If <c>true</c>, the local variable will be pinned.</param> /// <returns><see cref="LocalBuilder"/> to refer declared local variable.</returns> public LocalBuilder DeclareLocal( Type localType, string name, bool pinned ) { Contract.Assert( !this.IsEnded ); Contract.Assert( localType != null ); Contract.Assert( name != null ); Contract.Ensures( Contract.Result<LocalBuilder>() != null ); return this.DeclareLocalCore( localType, name, pinned ); } #endif // DEBUG private LocalBuilder DeclareLocalCore( Type localType, string name ) { var result = this._underlying.DeclareLocal( localType ); this._localDeclarations.Add( result, name ); // TODO: NLiblet #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( !this._isInDynamicMethod && this._isDebuggable ) { try { result.SetLocalSymInfo( name ); } catch ( NotSupportedException ) { this._isInDynamicMethod = true; } } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 return result; } #if DEBUG private LocalBuilder DeclareLocalCore( Type localType, string name, bool pinned ) { var result = this._underlying.DeclareLocal( localType, pinned ); this._localDeclarations.Add( result, name ); // TODO: NLiblet #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( !this._isInDynamicMethod && this._isDebuggable ) { try { result.SetLocalSymInfo( name ); } catch ( NotSupportedException ) { this._isInDynamicMethod = true; } } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 return result; } #endif // DEBUG #endregion #region -- Exceptions -- // Note: Leave always leave not leave.s. // FIXME: Integration check. #if DEBUG /// <summary> /// Emit exception block with catch blocks. /// </summary> /// <param name="tryBlockEmitter"> /// <see cref="Action{T1,T2}"/> which emits exception block (try in C#) body. /// A 1st argument is this <see cref="TracingILGenerator"/>, /// and a 2nd argument is <see cref="Label"/> will to be end of emitting exception block. /// The delegate do not have to emit leave or leave.s instrauction at tail of the body. /// </param> /// <param name="firstCatchBlock"> /// <see cref="Tuple{T1,T2}"/> for catch block body emittion. /// A 1st item of the tuple is <see cref="Type"/> which indicates catching exception type. /// A 2nd item of the tuple is <see cref="Action{T1,T2}"/> which emits catch block body. /// A 1st argument of the delegate is this <see cref="TracingILGenerator"/>, /// a 2nd argument of the delegate is <see cref="Label"/> will to be end of emitting exception block, /// and 3rd argument of the delegate is the 1st item of the tuple. /// The delegate do not have to emit leave or leave.s instrauction at tail of the body. /// </param> /// <param name="remainingCatchBlockEmitters"> /// <see cref="Tuple{T1,T2}"/> for catch block body emittion. /// A 1st item of the tuple is <see cref="Type"/> which indicates catching exception type. /// A 2nd item of the tuple is <see cref="Action{T1,T2}"/> which emits catch block body. /// A 1st argument of the delegate is this <see cref="TracingILGenerator"/>, /// a 2nd argument of the delegate is <see cref="Label"/> will to be end of emitting exception block, /// and 3rd argument of the delegate is the 1st item of the tuple. /// The delegate do not have to emit leave or leave.s instrauction at tail of the body. /// </param> [SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Tuple" )] public void EmitExceptionBlock( Action<TracingILGenerator, Label> tryBlockEmitter, Tuple<Type, Action<TracingILGenerator, Label, Type>> firstCatchBlock, params Tuple<Type, Action<TracingILGenerator, Label, Type>>[] remainingCatchBlockEmitters ) { Contract.Assert( !this.IsEnded ); Contract.Assert( tryBlockEmitter != null ); Contract.Assert( firstCatchBlock != null ); Contract.Assert( firstCatchBlock.Item1 != null && firstCatchBlock.Item2 != null ); Contract.Assert( remainingCatchBlockEmitters != null ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 Contract.Assert( Contract.ForAll( remainingCatchBlockEmitters, item => item != null && item.Item1 != null && item.Item2 != null ) ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 this.EmitExceptionBlockCore( tryBlockEmitter, firstCatchBlock, remainingCatchBlockEmitters, null ); } /// <summary> /// Emit exception block with catch blocks and a finally block. /// </summary> /// <param name="tryBlockEmitter"> /// <see cref="Action{T1,T2}"/> which emits exception block (try in C#) body. /// A 1st argument is this <see cref="TracingILGenerator"/>, /// and a 2nd argument is <see cref="Label"/> will to be end of emitting exception block. /// The delegate do not have to emit leave or leave.s instrauction at tail of the body. /// </param> /// <param name="finallyBlockEmitter"> /// <see cref="Action{T1,T2}"/> which emits finally block body. /// A 1st argument is this <see cref="TracingILGenerator"/>, /// and a 2nd argument is <see cref="Label"/> will to be end of emitting exception block. /// The delegate do not have to emit endfinally instrauction at tail of the body. /// </param> /// <param name="catchBlockEmitters"> /// <see cref="Tuple{T1,T2}"/> for catch block body emittion. /// A 1st item of the tuple is <see cref="Type"/> which indicates catching exception type. /// A 2nd item of the tuple is <see cref="Action{T1,T2}"/> which emits catch block body. /// A 1st argument of the delegate is this <see cref="TracingILGenerator"/>, /// a 2nd argument of the delegate is <see cref="Label"/> will to be end of emitting exception block, /// and 3rd argument of the delegate is the 1st item of the tuple. /// The delegate do not have to emit leave or leave.s instrauction at tail of the body. /// </param> public void EmitExceptionBlock( Action<TracingILGenerator, Label> tryBlockEmitter, Action<TracingILGenerator, Label> finallyBlockEmitter, params Tuple<Type, Action<TracingILGenerator, Label, Type>>[] catchBlockEmitters ) { Contract.Assert( !this.IsEnded ); Contract.Assert( tryBlockEmitter != null ); Contract.Assert( finallyBlockEmitter != null ); Contract.Assert( catchBlockEmitters != null ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 Contract.Assert( Contract.ForAll( catchBlockEmitters, item => item != null && item.Item1 != null && item.Item2 != null ) ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 this.EmitExceptionBlockCore( tryBlockEmitter, null, catchBlockEmitters, finallyBlockEmitter ); } private void EmitExceptionBlockCore( Action<TracingILGenerator, Label> tryBlockEmitter, Tuple<Type, Action<TracingILGenerator, Label, Type>> firstCatchBlockEmitter, Tuple<Type, Action<TracingILGenerator, Label, Type>>[] remainingCatchBlockEmitters, Action<TracingILGenerator, Label> finallyBlockEmitter ) { var endOfExceptionBlock = this.BeginExceptionBlock(); tryBlockEmitter( this, endOfExceptionBlock ); if ( firstCatchBlockEmitter != null ) { this.BeginCatchBlock( firstCatchBlockEmitter.Item1 ); firstCatchBlockEmitter.Item2( this, endOfExceptionBlock, firstCatchBlockEmitter.Item1 ); } foreach ( var catchBlockEmitter in remainingCatchBlockEmitters ) { this.BeginCatchBlock( catchBlockEmitter.Item1 ); firstCatchBlockEmitter.Item2( this, endOfExceptionBlock, catchBlockEmitter.Item1 ); } if ( finallyBlockEmitter != null ) { this.BeginFinallyBlock(); finallyBlockEmitter( this, endOfExceptionBlock ); } this.EndExceptionBlock(); } #endif // DEBUG /// <summary> /// Begin exception block (try in C#) here. /// Note that you do not have to emit leave or laeve.s instrauction at tail of the body. /// </summary> /// <returns><see cref="Label"/> will to be end of begun exception block.</returns> public Label BeginExceptionBlock() { Contract.Assert( !this.IsEnded ); this.TraceStart(); this.TraceWriteLine( ".try" ); this.Indent(); var result = this._underlying.BeginExceptionBlock(); this._endOfExceptionBlocks.Push( result ); this._labels[ result ] = "END_TRY_" + this._labels.Count.ToString( CultureInfo.InvariantCulture ); return result; } #if DEBUG /// <summary> /// Begin catch block with specified exception. /// Note that you do not have to emit leave or laeve.s instrauction at tail of the body. /// </summary> /// <param name="exceptionType"><see cref="Type"/> for catch.</param> public void BeginCatchBlock( Type exceptionType ) { Contract.Assert( !this.IsEnded ); Contract.Assert( exceptionType != null ); Contract.Assert( this.IsInExceptionBlock ); this.Unindent(); this.TraceStart(); this.TraceWrite( ".catch" ); this.TraceType( exceptionType ); this.TraceWriteLine(); this.Indent(); this._underlying.BeginCatchBlock( exceptionType ); } /// <summary> /// Begin filter block. /// Note that you do not have to emit leave or laeve.s instrauction at tail of the body. /// </summary> public void BeginExceptFilterBlock() { Contract.Assert( !this.IsEnded ); Contract.Assert( this.IsInExceptionBlock ); this.Unindent(); this.TraceStart(); this.TraceWriteLine( ".filter" ); this.Indent(); this._underlying.BeginExceptFilterBlock(); } /// <summary> /// Begin fault block. /// Note that you do not have to emit endfinally instrauction at tail of the body. /// </summary> public void BeginFaultBlock() { Contract.Assert( !this.IsEnded ); Contract.Assert( this.IsInExceptionBlock ); this.Unindent(); this.TraceStart(); this.TraceWriteLine( ".fault" ); this.Indent(); this._underlying.BeginFaultBlock(); } #endif // DEBUG /// <summary> /// Begin finally block. /// Note that you do not have to emit endfinally instrauction at tail of the body. /// </summary> public void BeginFinallyBlock() { Contract.Assert( !this.IsEnded ); Contract.Assert( this.IsInExceptionBlock ); this.Unindent(); this.TraceStart(); this.TraceWriteLine( ".finally" ); this.Indent(); this._underlying.BeginFinallyBlock(); } /// <summary> /// End current exception block and its last clause. /// </summary> public void EndExceptionBlock() { Contract.Assert( !this.IsEnded ); Contract.Assert( this.IsInExceptionBlock ); this.Unindent(); this._underlying.EndExceptionBlock(); this._endOfExceptionBlocks.Pop(); } #endregion #region -- Labels -- #if DEBUG /// <summary> /// Define new <see cref="Label"/> without name for tracing. /// </summary> /// <returns><see cref="Label"/> which will be target of branch instructions.</returns> public Label DefineLabel() { Contract.Assert( !this.IsEnded ); return this.DefineLabel( "LABEL_" + this._labels.Count.ToString( CultureInfo.InvariantCulture ) ); } #endif // DEBUG /// <summary> /// Define new <see cref="Label"/> with name for tracing. /// </summary> /// <param name="name">Name of label. Note that debugging information will not have this name.</param> /// <returns><see cref="Label"/> which will be target of branch instructions.</returns> public Label DefineLabel( string name ) { Contract.Assert( !this.IsEnded ); Contract.Assert( name != null ); var result = this._underlying.DefineLabel(); this._labels.Add( result, name ); return result; } /// <summary> /// Mark current position using specifieid <see cref="Label"/>. /// </summary> /// <param name="label"><see cref="Label"/>.</param> public void MarkLabel( Label label ) { this.TraceStart(); this.TraceWriteLine( this._labels[ label ] ); this._underlying.MarkLabel( label ); } #endregion #if !SILVERLIGHT #region -- Calli -- #if DEBUG #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 /// <summary> /// Emit 'calli' instruction for indirect unmanaged function call. /// </summary> /// <param name="unmanagedCallingConvention"><see cref="CallingConvention"/> of unmanaged function.</param> /// <param name="returnType">Return <see cref="Type"/> of the function.</param> /// <param name="parameterTypes">Parameter <see cref="Type"/>s of the function.</param> public void EmitCalli( CallingConvention unmanagedCallingConvention, Type returnType, Type[] parameterTypes ) { Contract.Assert( !this.IsEnded ); Contract.Assert( returnType != null ); Contract.Assert( parameterTypes != null ); Contract.Assert( Contract.ForAll( parameterTypes, item => item != null ) ); this.TraceStart(); this.TraceWrite( "calli " ); this.TraceSignature( null, unmanagedCallingConvention, returnType, parameterTypes, Type.EmptyTypes ); this._underlying.EmitCalli( OpCodes.Calli, unmanagedCallingConvention, returnType, parameterTypes ); } /// <summary> /// Emit 'calli' instruction for indirect managed method call. /// </summary> /// <param name="managedCallingConventions"><see cref="CallingConventions"/> of managed method.</param> /// <param name="returnType">Return <see cref="Type"/> of the method.</param> /// <param name="requiredParameterTypes">Required parameter <see cref="Type"/>s of the method.</param> /// <param name="optionalParameterTypes">Optional varargs parameter <see cref="Type"/>s of the method.</param> public void EmitCalli( CallingConventions managedCallingConventions, Type returnType, Type[] requiredParameterTypes, Type[] optionalParameterTypes ) { Contract.Assert( !this.IsEnded ); Contract.Assert( returnType != null ); Contract.Assert( requiredParameterTypes != null ); Contract.Assert( Contract.ForAll( requiredParameterTypes, item => item != null ) ); Contract.Assert( optionalParameterTypes != null ); Contract.Assert( optionalParameterTypes == null || optionalParameterTypes.Length == 0 || ( managedCallingConventions & CallingConventions.VarArgs ) == CallingConventions.VarArgs ); Contract.Assert( optionalParameterTypes == null || Contract.ForAll( optionalParameterTypes, item => item != null ) ); this.TraceStart(); this.TraceWrite( "calli " ); this.TraceSignature( managedCallingConventions, null, returnType, requiredParameterTypes, optionalParameterTypes ); this._underlying.EmitCalli( OpCodes.Calli, managedCallingConventions, returnType, requiredParameterTypes, optionalParameterTypes ); } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 #endif // DEBUG #endregion #endif // !SILVERLIGHT #region -- Constrained. -- #if DEBUG /// <summary> /// Emit constrained 'callvirt' instruction. /// </summary> /// <param name="constrainedTo"><see cref="Type"/> to be constrained to.</param> /// <param name="target">Target <see cref="MethodInfo"/> which must be virtual method.</param> public void EmitConstrainedCallvirt( Type constrainedTo, MethodInfo target ) { Contract.Assert( !this.IsEnded ); Contract.Assert( constrainedTo != null ); Contract.Assert( target != null ); this.TraceStart(); this.TraceWrite( "constraind." ); this.TraceType( constrainedTo ); this.TraceWriteLine(); this._underlying.Emit( OpCodes.Constrained, constrainedTo ); this.EmitCallvirt( target ); } #endif // DEBUG #endregion #region -- Readonly. -- #if DEBUG /// <summary> /// Emit readonly 'ldelema' instruction. /// </summary> /// <param name="elementType"><see cref="Type"/> of array element.</param> public void EmitReadOnlyLdelema( Type elementType ) { Contract.Assert( !this.IsEnded ); Contract.Assert( elementType != null ); this.TraceStart(); this.TraceWriteLine( "readonly." ); this._underlying.Emit( OpCodes.Readonly ); this.EmitLdelema( elementType ); } #endif // DEBUG #endregion #region -- Tail. -- #if DEBUG #if !NETSTANDARD1_1 && !NETSTANDARD1_3 /// <summary> /// Emit 'call' instruction with specified arguments as tail call. /// </summary> /// <param name="target"><see cref="System.Reflection.MethodInfo"/> as target.</param> /// <remarks> /// Subsequent 'ret' instruction will be emitted together. /// </remarks> public void EmitTailCall( MethodInfo target ) { Contract.Assert( !this.IsEnded ); Contract.Assert( target != null ); this.TraceStart(); this.TraceWriteLine( "tail." ); this._underlying.Emit( OpCodes.Tailcall ); this.EmitCall( target ); this.EmitRet(); } /// <summary> /// Emit 'callvirt' instruction with specified arguments as tail call. /// </summary> /// <param name="target"><see cref="System.Reflection.MethodInfo"/> as target.</param> /// <remarks> /// Subsequent 'ret' instruction will be emitted together. /// </remarks> public void EmitTailCallVirt( MethodInfo target ) { Contract.Assert( !this.IsEnded ); Contract.Assert( target != null ); this.TraceStart(); this.TraceWriteLine( "tail." ); this._underlying.Emit( OpCodes.Tailcall ); this.EmitCallvirt( target ); this.EmitRet(); } #if !SILVERLIGHT && !NETSTANDARD2_0 /// <summary> /// Emit 'calli' instruction for indirect unmanaged function call as tail call. /// </summary> /// <param name="unmanagedCallingConvention"><see cref="CallingConvention"/> of unmanaged function.</param> /// <param name="returnType">Return <see cref="Type"/> of the function.</param> /// <param name="parameterTypes">Parameter <see cref="Type"/>s of the function.</param> /// <remarks> /// Subsequent 'ret' instruction will be emitted together. /// </remarks> public void EmitTailCalli( CallingConvention unmanagedCallingConvention, Type returnType, Type[] parameterTypes ) { Contract.Assert( !this.IsEnded ); Contract.Assert( returnType != null ); Contract.Assert( parameterTypes != null ); Contract.Assert( Contract.ForAll( parameterTypes, item => item != null ) ); this.TraceStart(); this.TraceWriteLine( "tail." ); this._underlying.Emit( OpCodes.Tailcall ); this.EmitCalli( unmanagedCallingConvention, returnType, parameterTypes ); this.EmitRet(); } /// <summary> /// Emit 'calli' instruction for indirect managed method call as tail call. /// </summary> /// <param name="managedCallingConventions"><see cref="CallingConventions"/> of managed method.</param> /// <param name="returnType">Return <see cref="Type"/> of the method.</param> /// <param name="requiredParameterTypes">Required parameter <see cref="Type"/>s of the method.</param> /// <param name="optionalParameterTypes">Optional varargs parameter <see cref="Type"/>s of the method.</param> /// <remarks> /// Subsequent 'ret' instruction will be emitted together. /// </remarks> public void EmitTailCalli( CallingConventions managedCallingConventions, Type returnType, Type[] requiredParameterTypes, Type[] optionalParameterTypes ) { Contract.Assert( !this.IsEnded ); Contract.Assert( returnType != null ); Contract.Assert( requiredParameterTypes != null ); Contract.Assert( Contract.ForAll( requiredParameterTypes, item => item != null ) ); Contract.Assert( optionalParameterTypes != null ); Contract.Assert( optionalParameterTypes == null || optionalParameterTypes.Length == 0 || ( managedCallingConventions & CallingConventions.VarArgs ) == CallingConventions.VarArgs ); Contract.Assert( optionalParameterTypes == null || Contract.ForAll( optionalParameterTypes, item => item != null ) ); this.TraceStart(); this.TraceWriteLine( "tail." ); this._underlying.Emit( OpCodes.Tailcall ); this.EmitCalli( managedCallingConventions, returnType, requiredParameterTypes, optionalParameterTypes ); this.EmitRet(); } #endif // SILVERLIGHT && !NETSTANDARD2_0 #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // DEBUG #endregion #region -- Unaligned. -- #if DEBUG /// <summary> /// Emit 'unaligned.' prefix. /// </summary> /// <param name="alignment">Alignment.</param> public void EmitUnaligned( byte alignment ) { Contract.Assert( !this.IsEnded ); this.TraceStart(); this.TraceWrite( "unaligned." ); this.TraceOperand( alignment ); this.TraceWriteLine(); this._underlying.Emit( OpCodes.Unaligned, alignment ); } #endif // DEBUG #endregion #region -- Tracing -- /// <summary> /// Write trace message. /// </summary> /// <param name="value">The string.</param> public void TraceWrite( string value ) { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.Write( value ); } #if DEBUG /// <summary> /// Write trace message. /// </summary> /// <param name="format">The format string.</param> /// <param name="arg0">Format argument.</param> public void TraceWrite( string format, object arg0 ) { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.Write( format, arg0 ); } /// <summary> /// Write trace message. /// </summary> /// <param name="format">The format string.</param> /// <param name="args">Format arguments.</param> public void TraceWrite( string format, params object[] args ) { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.Write( format, args ); } #endif // DEBUG /// <summary> /// Write trace line break. /// </summary> public void TraceWriteLine() { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.WriteLine(); } /// <summary> /// Write trace message followed by line break. /// </summary> /// <param name="value">The string.</param> public void TraceWriteLine( string value ) { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.WriteLine( value ); } /// <summary> /// Write trace message followed by line break. /// </summary> /// <param name="format">The format string.</param> /// <param name="arg0">Format argument.</param> public void TraceWriteLine( string format, object arg0 ) { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.WriteLine( format, arg0 ); } #if DEBUG /// <summary> /// Write trace message followed by line break. /// </summary> /// <param name="format">The format string.</param> /// <param name="args">Format arguments.</param> public void TraceWriteLine( string format, params object[] args ) { Contract.Assert( !this.IsEnded ); Contract.Assert( this._trace != null ); this._trace.WriteLine( format, args ); } #endif // DEBUG private void TraceType( Type type ) { WriteType( this._trace, type ); } private static void WriteType( TextWriter writer, Type type ) { Contract.Assert( writer != null ); if ( writer == NullTextWriter.Instance ) { return; } if ( type == null || type == typeof( void ) ) { writer.Write( "void" ); } else if ( type.IsGenericParameter ) { writer.Write( "{0}{1}", type.GetDeclaringMethod() == null ? "!" : "!!", type.Name ); } else { #if SILVERLIGHT var endOfAssemblySimpleName = type.Assembly.FullName.IndexOf( ',' ); writer.Write( "[{0}]{1}", endOfAssemblySimpleName < 0 ? type.Assembly.FullName : type.Assembly.FullName.Remove( endOfAssemblySimpleName ), type.FullName ); #else writer.Write( "[{0}]{1}", type.GetAssembly().GetName().Name, type.GetFullName() ); #endif } } private void TraceField( FieldInfo field ) { // <instr_field> <type> <typeSpec> :: <id> Contract.Assert( field != null ); WriteType( this._trace, field.FieldType ); this._trace.Write( " " ); // TODO: NLiblet #if !SILVERLIGHT var asFieldBuilder = field as FieldBuilder; #if !NETSTANDARD1_1 && !NETSTANDARD1_3 if ( asFieldBuilder == null ) { var modreqs = field.GetRequiredCustomModifiers(); if ( 0 < modreqs.Length ) { this._trace.Write( "modreq(" ); foreach ( var modreq in modreqs ) { WriteType( this._trace, modreq ); } this._trace.Write( ") " ); } var modopts = field.GetOptionalCustomModifiers(); if ( 0 < modopts.Length ) { this._trace.Write( "modopt(" ); foreach ( var modopt in modopts ) { WriteType( this._trace, modopt ); } this._trace.Write( ") " ); } } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // !SILVERLIGHT #if !SILVERLIGHT if ( this._isInDynamicMethod || asFieldBuilder == null ) // declaring type of the field should be omitted for same type. #endif // !SILVERLIGHT { WriteType( this._trace, field.DeclaringType ); } this._trace.Write( "::" ); this._trace.Write( field.Name ); } #if DEBUG private void TraceSignature( CallingConventions? managedCallingConventions, CallingConvention? unmanagedCallingConvention, Type returnType, Type[] requiredParameterTypes, Type[] optionalParameterTypes ) { // <instr_sig> <callConv> <type> ( <parameters> ) WriteCallingConventions( this._trace, managedCallingConventions, unmanagedCallingConvention ); WriteType( this._trace, returnType ); this._trace.Write( " (" ); for ( int i = 0; i < requiredParameterTypes.Length; i++ ) { if ( 0 < i ) { this._trace.Write( ", " ); } else { this._trace.Write( " " ); } WriteType( this._trace, requiredParameterTypes[ i ] ); } if ( 0 < optionalParameterTypes.Length ) { if ( 0 < requiredParameterTypes.Length ) { this.TraceWrite( "," ); } this.TraceWrite( " [" ); for ( int i = 0; i < optionalParameterTypes.Length; i++ ) { if ( 0 < i ) { this._trace.Write( ", " ); } else { this._trace.Write( " " ); } WriteType( this._trace, optionalParameterTypes[ i ] ); } this.TraceWrite( " ]" ); } if ( 0 < ( requiredParameterTypes.Length + optionalParameterTypes.Length ) ) { this._trace.Write( " " ); } this._trace.WriteLine( ")" ); } #endif // DEBUG private void TraceMethod( MethodBase method ) { Contract.Assert( method != null ); #if !WINDOWS_PHONE bool isMethodBuilder = method is MethodBuilder || method is ConstructorBuilder; #endif if ( !isMethodBuilder ) { try { method.GetParameters(); } catch ( NotSupportedException ) { // For internal MethodBuilderInstantiationType isMethodBuilder = true; } } /* * <instr_method> <callConv> <type> [ <typeSpec> :: ] <methodName> ( <parameters> ) */ // <callConv> if ( !method.IsStatic ) { this._trace.Write( "instance " ); } var unamanagedCallingConvention = default( CallingConvention? ); // TODO: Back to NLiblet #if !WINDOWS_PHONE if ( !isMethodBuilder ) #endif { // TODO: C++/CLI etc... var dllImport = method.GetCustomAttribute<DllImportAttribute>(); if ( dllImport != null ) { unamanagedCallingConvention = dllImport.CallingConvention; } } WriteCallingConventions( this._trace, method.CallingConvention, unamanagedCallingConvention ); var asMethodInfo = method as MethodInfo; if ( asMethodInfo != null ) { WriteType( this._trace, asMethodInfo.ReturnType ); this._trace.Write( " " ); } if ( method.DeclaringType == null ) { // '[' '.module' name1 ']' this._trace.Write( "[.module" ); this._trace.Write( asMethodInfo.Module.Name ); this._trace.Write( "]::" ); } #if !WINDOWS_PHONE else if ( this._isInDynamicMethod || !isMethodBuilder ) // declaring type of the method should be omitted for same type. #else else #endif { WriteType( this._trace, method.DeclaringType ); this._trace.Write( "::" ); } this._trace.Write( method.Name ); this._trace.Write( "(" ); #if !WINDOWS_PHONE if ( !isMethodBuilder ) #endif { var parameters = method.GetParameters(); for ( int i = 0; i < parameters.Length; i++ ) { if ( i == 0 ) { this._trace.Write( " " ); } else { this._trace.Write( ", " ); } if ( parameters[ i ].IsOut ) { this._trace.Write( "out " ); } else if ( parameters[ i ].ParameterType.IsByRef ) { this._trace.Write( "ref " ); } WriteType( this._trace, parameters[ i ].ParameterType.IsByRef ? parameters[ i ].ParameterType.GetElementType() : parameters[ i ].ParameterType ); this._trace.Write( " " ); this._trace.Write( parameters[ i ].Name ); } if ( 0 < parameters.Length ) { this._trace.Write( " " ); } } this._trace.Write( ")" ); } [SuppressMessage( "Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "This is not normalization." )] private static void WriteCallingConventions( TextWriter writer, CallingConventions? managedCallingConverntions, CallingConvention? unamangedCallingConvention ) { Contract.Assert( writer != null ); if ( writer == NullTextWriter.Instance ) { return; } bool needsSpace = false; if ( managedCallingConverntions != null ) { if ( ( managedCallingConverntions & CallingConventions.ExplicitThis ) == CallingConventions.ExplicitThis ) { writer.Write( "explicit" ); needsSpace = true; } } if ( unamangedCallingConvention == null ) { if ( managedCallingConverntions != null ) { if ( ( managedCallingConverntions & CallingConventions.VarArgs ) == CallingConventions.VarArgs ) { if ( needsSpace ) { writer.Write( " " ); } writer.Write( "varargs" ); } } } else { switch ( unamangedCallingConvention.Value ) { case CallingConvention.Winapi: case CallingConvention.StdCall: { if ( needsSpace ) { writer.Write( " " ); } writer.Write( "unmanaged stdcall" ); break; } default: { if ( needsSpace ) { writer.Write( " " ); } writer.Write( "unmanaged " ); writer.Write( unamangedCallingConvention.Value.ToString().ToLowerInvariant() ); break; } } } } private void TraceOpCode( OpCode opCode ) { this._trace.Write( opCode.Name ); } private void TraceOperand( int value ) { this._trace.Write( value ); } private void TraceOperand( long value ) { this._trace.Write( value ); } private void TraceOperand( double value ) { this._trace.Write( value ); } private void TraceOperand( string value ) { // QSTRING this._trace.Write( "\"{0:L}\"", value ); } private void TraceOperand( Label value ) { this._trace.Write( this._labels[ value ] ); } #if DEBUG private void TraceOperand( Label[] values ) { for ( int i = 0; i < values.Length; i++ ) { if ( 0 < i ) { this._trace.Write( ", " ); } this.TraceOperand( values[ i ] ); } } #endif // DEBUG private void TraceOperand( Type value ) { this.TraceType( value ); } private void TraceOperand( FieldInfo value ) { this.TraceField( value ); } private void TraceOperand( MethodBase value ) { this.TraceMethod( value ); } private void TraceOperandToken( Type target ) { this.TraceType( target ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 this.TraceOperandTokenValue( target.MetadataToken ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 } private void TraceOperandToken( FieldInfo target ) { this._trace.Write( "field " ); this.TraceField( target ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 this.TraceOperandTokenValue( target.MetadataToken ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 } private void TraceOperandToken( MethodBase target ) { this._trace.Write( "method " ); this.TraceMethod( target ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 this.TraceOperandTokenValue( target.MetadataToken ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 } #if !NETSTANDARD1_1 && !NETSTANDARD1_3 private void TraceOperandTokenValue( int value ) { this._trace.Write( "<{0:x8}>", value ); } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 private void TraceStart() { this.WriteLineNumber(); this.WriteIndent(); } private void WriteLineNumber() { Contract.Assert( this._trace != null ); this._trace.Write( "L_{0:d4}\t", this._lineNumber ); this._lineNumber++; } private void WriteIndent() { this.WriteIndent( this._trace, this._indentLevel ); } private void WriteIndent( TextWriter writer, int indentLevel ) { Contract.Assert( writer != null ); Contract.Assert( 0 <= indentLevel ); for ( int i = 0; i < indentLevel; i++ ) { writer.Write( this._indentChars ); } } private void Indent() { this._indentLevel++; } private void Unindent() { Contract.Assert( 0 < this._indentLevel ); this._indentLevel--; } #endregion } }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Account.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "account.roles". /// </summary> public class Role : DbAccess, IRoleRepository { /// <summary> /// The schema of this table. Returns literal "account". /// </summary> public override string _ObjectNamespace => "account"; /// <summary> /// The schema unqualified name of this table. Returns literal "roles". /// </summary> public override string _ObjectName => "roles"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "account.roles". /// </summary> /// <returns>Returns the number of rows of the table "account.roles".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"Role\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM account.roles;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "account.roles" to return all instances of the "Role" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "Role" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.Role> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"Role\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles ORDER BY role_id;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "account.roles" to return all instances of the "Role" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "Role" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"Role\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles ORDER BY role_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "account.roles" with a where filter on the column "role_id" to return a single instance of the "Role" class. /// </summary> /// <param name="roleId">The column "role_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "Role" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.Role Get(int roleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"Role\" filtered by \"RoleId\" with value {RoleId} was denied to the user with Login ID {_LoginId}", roleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles WHERE role_id=@0;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql, roleId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "account.roles". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "Role" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.Role GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"Role\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles ORDER BY role_id LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "account.roles" sorted by roleId. /// </summary> /// <param name="roleId">The column "role_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "Role" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.Role GetPrevious(int roleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"Role\" by \"RoleId\" with value {RoleId} was denied to the user with Login ID {_LoginId}", roleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles WHERE role_id < @0 ORDER BY role_id DESC LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql, roleId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "account.roles" sorted by roleId. /// </summary> /// <param name="roleId">The column "role_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "Role" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.Role GetNext(int roleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"Role\" by \"RoleId\" with value {RoleId} was denied to the user with Login ID {_LoginId}", roleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles WHERE role_id > @0 ORDER BY role_id LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql, roleId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "account.roles". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "Role" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.Role GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"Role\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles ORDER BY role_id DESC LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "account.roles" with a where filter on the column "role_id" to return a multiple instances of the "Role" class. /// </summary> /// <param name="roleIds">Array of column "role_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "Role" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.Role> Get(int[] roleIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"Role\" was denied to the user with Login ID {LoginId}. roleIds: {roleIds}.", this._LoginId, roleIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles WHERE role_id IN (@0);"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql, roleIds); } /// <summary> /// Custom fields are user defined form elements for account.roles. /// </summary> /// <returns>Returns an enumerable custom field collection for the table account.roles</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"Role\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='account.roles' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('account.roles'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of account.roles. /// </summary> /// <returns>Returns an enumerable name and value collection for the table account.roles</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"Role\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT role_id AS key, role_name as value FROM account.roles;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of Role class on the database table "account.roles". /// </summary> /// <param name="role">The instance of "Role" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic role, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } role.audit_user_id = this._UserId; role.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = role.role_id; if (Cast.To<int>(primaryKeyValue) > 0) { this.Update(role, Cast.To<int>(primaryKeyValue)); } else { primaryKeyValue = this.Add(role); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('account.roles')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('account.roles', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of Role class on the database table "account.roles". /// </summary> /// <param name="role">The instance of "Role" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic role) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"Role\" was denied to the user with Login ID {LoginId}. {Role}", this._LoginId, role); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, role, "account.roles", "role_id"); } /// <summary> /// Inserts or updates multiple instances of Role class on the database table "account.roles"; /// </summary> /// <param name="roles">List of "Role" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> roles) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"Role\" was denied to the user with Login ID {LoginId}. {roles}", this._LoginId, roles); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic role in roles) { line++; role.audit_user_id = this._UserId; role.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = role.role_id; if (Cast.To<int>(primaryKeyValue) > 0) { result.Add(role.role_id); db.Update("account.roles", "role_id", role, role.role_id); } else { result.Add(db.Insert("account.roles", "role_id", role)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "account.roles" with an instance of "Role" class against the primary key value. /// </summary> /// <param name="role">The instance of "Role" class to update.</param> /// <param name="roleId">The value of the column "role_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic role, int roleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"Role\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {Role}", roleId, this._LoginId, role); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, role, roleId, "account.roles", "role_id"); } /// <summary> /// Deletes the row of the table "account.roles" against the primary key value. /// </summary> /// <param name="roleId">The value of the column "role_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(int roleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"Role\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", roleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM account.roles WHERE role_id=@0;"; Factory.NonQuery(this._Catalog, sql, roleId); } /// <summary> /// Performs a select statement on table "account.roles" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "Role" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.Role> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"Role\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.roles ORDER BY role_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "account.roles" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "Role" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.Role> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"Role\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM account.roles ORDER BY role_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='account.roles' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "account.roles". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "Role" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"Role\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.roles WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Role(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "account.roles" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "Role" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.Role> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"Role\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM account.roles WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Role(), filters); sql.OrderBy("role_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "account.roles". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "Role" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"Role\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.roles WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Role(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "account.roles" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "Role" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.Role> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"Role\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM account.roles WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.Role(), filters); sql.OrderBy("role_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Account.Entities.Role>(this._Catalog, sql); } } }
// 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; #if MS_IO_REDIST namespace Microsoft.IO.Enumeration #else namespace System.IO.Enumeration #endif { /// <summary> /// Provides methods for matching file system names. /// </summary> public static class FileSystemName { // [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression // https://msdn.microsoft.com/en-us/library/ff469270.aspx private static readonly char[] s_wildcardChars = { '\"', '<', '>', '*', '?' }; private static readonly char[] s_simpleWildcardChars = { '*', '?' }; /// <summary> /// Change '*' and '?' to '&lt;', '&gt;' and '"' to match Win32 behavior. For compatibility, Windows /// changes some wildcards to provide a closer match to historical DOS 8.3 filename matching. /// </summary> public static string TranslateWin32Expression(string expression) { if (string.IsNullOrEmpty(expression) || expression == "*" || expression == "*.*") return "*"; bool modified = false; Span<char> stackSpace = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(stackSpace); int length = expression.Length; for (int i = 0; i < length; i++) { char c = expression[i]; switch (c) { case '.': modified = true; if (i >= 1 && i == length - 1 && expression[i - 1] == '*') { sb[sb.Length - 1] = '<'; // DOS_STAR (ends in *.) } else if (i < length - 1 && (expression[i + 1] == '?' || expression[i + 1] == '*')) { sb.Append('\"'); // DOS_DOT } else { sb.Append('.'); } break; case '?': modified = true; sb.Append('>'); // DOS_QM break; default: sb.Append(c); break; } } return modified ? sb.ToString() : expression; } /// <summary> /// Return true if the given expression matches the given name. Supports the following wildcards: /// '*', '?', '&lt;', '&gt;', '"'. The backslash character '\' escapes. /// </summary> /// <param name="expression">The expression to match with, such as "*.foo".</param> /// <param name="name">The name to check against the expression.</param> /// <param name="ignoreCase">True to ignore case (default).</param> /// <remarks> /// This is based off of System.IO.PatternMatcher used in FileSystemWatcher, which is based off /// of RtlIsNameInExpression, which defines the rules for matching DOS wildcards ('*', '?', '&lt;', '&gt;', '"'). /// /// Like PatternMatcher, matching will not line up with Win32 behavior unless you transform the expression /// using <see cref="TranslateWin32Expression(string)"/> /// </remarks> public static bool MatchesWin32Expression(ReadOnlySpan<char> expression, ReadOnlySpan<char> name, bool ignoreCase = true) { return MatchPattern(expression, name, ignoreCase, useExtendedWildcards: true); } /// <summary> /// Return true if the given expression matches the given name. '*' and '?' are wildcards, '\' escapes. /// </summary> public static bool MatchesSimpleExpression(ReadOnlySpan<char> expression, ReadOnlySpan<char> name, bool ignoreCase = true) { return MatchPattern(expression, name, ignoreCase, useExtendedWildcards: false); } // Matching routine description // ============================ // (copied from native impl) // // This routine compares a Dbcs name and an expression and tells the caller // if the name is in the language defined by the expression. The input name // cannot contain wildcards, while the expression may contain wildcards. // // Expression wild cards are evaluated as shown in the nondeterministic // finite automatons below. Note that ~* and ~? are DOS_STAR and DOS_QM. // // ~* is DOS_STAR, ~? is DOS_QM, and ~. is DOS_DOT // // S // <-----< // X | | e Y // X * Y == (0)----->-(1)->-----(2)-----(3) // // S-. // <-----< // X | | e Y // X ~* Y == (0)----->-(1)->-----(2)-----(3) // // X S S Y // X ?? Y == (0)---(1)---(2)---(3)---(4) // // X . . Y // X ~.~. Y == (0)---(1)----(2)------(3)---(4) // | |________| // | ^ | // |_______________| // ^EOF or .^ // // X S-. S-. Y // X ~?~? Y == (0)---(1)-----(2)-----(3)---(4) // | |________| // | ^ | // |_______________| // ^EOF or .^ // // where S is any single character // S-. is any single character except the final . // e is a null character transition // EOF is the end of the name string // // In words: // // * matches 0 or more characters. // ? matches exactly 1 character. // DOS_STAR matches 0 or more characters until encountering and matching // the final . in the name. // DOS_QM matches any single character, or upon encountering a period or // end of name string, advances the expression to the end of the // set of contiguous DOS_QMs. // DOS_DOT matches either a . or zero characters beyond name string. private static bool MatchPattern(ReadOnlySpan<char> expression, ReadOnlySpan<char> name, bool ignoreCase, bool useExtendedWildcards) { // The idea behind the algorithm is pretty simple. We keep track of all possible locations // in the regular expression that are matching the name. When the name has been exhausted, // if one of the locations in the expression is also just exhausted, the name is in the // language defined by the regular expression. if (expression.Length == 0 || name.Length == 0) return false; if (expression[0] == '*') { // Just * matches everything if (expression.Length == 1) return true; ReadOnlySpan<char> expressionEnd = expression.Slice(1); if (expressionEnd.IndexOfAny(useExtendedWildcards ? s_wildcardChars : s_simpleWildcardChars) == -1) { // Handle the special case of a single starting *, which essentially means "ends with" // If the name doesn't have enough characters to match the remaining expression, it can't be a match. if (name.Length < expressionEnd.Length) return false; // See if we end with the expression return name.EndsWith(expressionEnd, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } int nameOffset = 0; int expressionOffset; int priorMatch; int currentMatch; int priorMatchCount; int matchCount = 1; char nameChar = '\0'; char expressionChar; Span<int> temp = stackalloc int[0]; Span<int> currentMatches = stackalloc int[16]; Span<int> priorMatches = stackalloc int[16]; priorMatches[0] = 0; int maxState = expression.Length * 2; int currentState; bool nameFinished = false; // Walk through the name string, picking off characters. We go one // character beyond the end because some wild cards are able to match // zero characters beyond the end of the string. // // With each new name character we determine a new set of states that // match the name so far. We use two arrays that we swap back and forth // for this purpose. One array lists the possible expression states for // all name characters up to but not including the current one, and other // array is used to build up the list of states considering the current // name character as well. The arrays are then switched and the process // repeated. // // There is not a one-to-one correspondence between state number and // offset into the expression. State numbering is not continuous. // This allows a simple conversion between state number and expression // offset. Each character in the expression can represent one or two // states. * and DOS_STAR generate two states: expressionOffset * 2 and // expressionOffset * 2 + 1. All other expression characters can produce // only a single state. Thus expressionOffset = currentState / 2. while (!nameFinished) { if (nameOffset < name.Length) { // Not at the end of the name. Grab the current character and move the offset forward. nameChar = name[nameOffset++]; } else { // At the end of the name. If the expression is exhausted, exit. if (priorMatches[matchCount - 1] == maxState) break; nameFinished = true; } // Now, for each of the previous stored expression matches, see what // we can do with this name character. priorMatch = 0; currentMatch = 0; priorMatchCount = 0; while (priorMatch < matchCount) { // We have to carry on our expression analysis as far as possible for each // character of name, so we loop here until the expression stops matching. expressionOffset = (priorMatches[priorMatch++] + 1) / 2; while (expressionOffset < expression.Length) { currentState = expressionOffset * 2; expressionChar = expression[expressionOffset]; // We may be about to exhaust the local space for matches, // so we have to reallocate if this is the case. if (currentMatch >= currentMatches.Length - 2) { int newSize = currentMatches.Length * 2; temp = new int[newSize]; currentMatches.CopyTo(temp); currentMatches = temp; temp = new int[newSize]; priorMatches.CopyTo(temp); priorMatches = temp; } if (expressionChar == '*') { // '*' matches any character zero or more times. goto MatchZeroOrMore; } else if (useExtendedWildcards && expressionChar == '<') { // '<' (DOS_STAR) matches any character except '.' zero or more times. // If we are at a period, determine if we are allowed to // consume it, i.e. make sure it is not the last one. bool notLastPeriod = false; if (!nameFinished && nameChar == '.') { for (int offset = nameOffset; offset < name.Length; offset++) { if (name[offset] == '.') { notLastPeriod = true; break; } } } if (nameFinished || nameChar != '.' || notLastPeriod) { goto MatchZeroOrMore; } else { // We are at a period. We can only match zero // characters (i.e. the epsilon transition). goto MatchZero; } } else { // The remaining expression characters all match by consuming a character, // so we need to force the expression and state forward. currentState += 2; if (useExtendedWildcards && expressionChar == '>') { // '>' (DOS_QM) is the most complicated. If the name is finished, // we can match zero characters. If this name is a '.', we // don't match, but look at the next expression. Otherwise // we match a single character. if (nameFinished || nameChar == '.') goto NextExpressionCharacter; currentMatches[currentMatch++] = currentState; goto ExpressionFinished; } else if (useExtendedWildcards && expressionChar == '"') { // A '"' (DOS_DOT) can match either a period, or zero characters // beyond the end of name. if (nameFinished) { goto NextExpressionCharacter; } else if (nameChar == '.') { currentMatches[currentMatch++] = currentState; } goto ExpressionFinished; } else { if (expressionChar == '\\') { // Escape character, try to move the expression forward again and match literally. if (++expressionOffset == expression.Length) { currentMatches[currentMatch++] = maxState; goto ExpressionFinished; } currentState = expressionOffset * 2 + 2; expressionChar = expression[expressionOffset]; } // From this point on a name character is required to even // continue, let alone make a match. if (nameFinished) goto ExpressionFinished; if (expressionChar == '?') { // If this expression was a '?' we can match it once. currentMatches[currentMatch++] = currentState; } else if (ignoreCase ? char.ToUpperInvariant(expressionChar) == char.ToUpperInvariant(nameChar) : expressionChar == nameChar) { // Matched a non-wildcard character currentMatches[currentMatch++] = currentState; } goto ExpressionFinished; } } MatchZeroOrMore: currentMatches[currentMatch++] = currentState; MatchZero: currentMatches[currentMatch++] = currentState + 1; NextExpressionCharacter: if (++expressionOffset == expression.Length) currentMatches[currentMatch++] = maxState; } // while (expressionOffset < expression.Length) ExpressionFinished: // Prevent duplication in the destination array. // // Each of the arrays is monotonically increasing and non-duplicating, thus we skip // over any source element in the source array if we just added the same element to // the destination array. This guarantees non-duplication in the destination array. if ((priorMatch < matchCount) && (priorMatchCount < currentMatch)) { while (priorMatchCount < currentMatch) { int previousLength = priorMatches.Length; while ((priorMatch < previousLength) && (priorMatches[priorMatch] < currentMatches[priorMatchCount])) { priorMatch++; } priorMatchCount++; } } } // while (sourceCount < matchesCount) // If we found no matches in the just finished iteration it's time to bail. if (currentMatch == 0) return false; // Swap the meaning the two arrays temp = priorMatches; priorMatches = currentMatches; currentMatches = temp; matchCount = currentMatch; } // while (!nameFinished) currentState = priorMatches[matchCount - 1]; return currentState == maxState; } } }
// <copyright file="DiagonalMatrixTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using MathNet.Numerics.Random; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32 { using Numerics; /// <summary> /// Diagonal matrix tests. /// </summary> public class DiagonalMatrixTests : MatrixTests { /// <summary> /// Setup test matrices. /// </summary> [SetUp] public override void SetupMatrices() { TestData2D = new Dictionary<string, Complex32[,]> { {"Singular3x3", new[,] {{new Complex32(1.0f, 1), Complex32.Zero, Complex32.Zero}, {Complex32.Zero, Complex32.Zero, Complex32.Zero}, {Complex32.Zero, Complex32.Zero, new Complex32(3.0f, 1)}}}, {"Square3x3", new[,] {{new Complex32(-1.1f, 1), Complex32.Zero, Complex32.Zero}, {Complex32.Zero, new Complex32(1.1f, 1), Complex32.Zero}, {Complex32.Zero, Complex32.Zero, new Complex32(6.6f, 1)}}}, {"Square4x4", new[,] {{new Complex32(-1.1f, 1), Complex32.Zero, Complex32.Zero, Complex32.Zero}, {Complex32.Zero, new Complex32(1.1f, 1), Complex32.Zero, Complex32.Zero}, {Complex32.Zero, Complex32.Zero, new Complex32(6.2f, 1), Complex32.Zero}, {Complex32.Zero, Complex32.Zero, Complex32.Zero, new Complex32(-7.7f, 1)}}}, {"Singular4x4", new[,] {{new Complex32(-1.1f, 1), Complex32.Zero, Complex32.Zero, Complex32.Zero}, {Complex32.Zero, new Complex32(-2.2f, 1), Complex32.Zero, Complex32.Zero}, {Complex32.Zero, Complex32.Zero, Complex32.Zero, Complex32.Zero}, {Complex32.Zero, Complex32.Zero, Complex32.Zero, new Complex32(-4.4f, 1)}}}, {"Tall3x2", new[,] {{new Complex32(-1.1f, 1), Complex32.Zero}, {Complex32.Zero, new Complex32(1.1f, 1)}, {Complex32.Zero, Complex32.Zero}}}, {"Wide2x3", new[,] {{new Complex32(-1.1f, 1), Complex32.Zero, Complex32.Zero}, {Complex32.Zero, new Complex32(1.1f, 1), Complex32.Zero}}} }; TestMatrices = new Dictionary<string, Matrix<Complex32>>(); foreach (var name in TestData2D.Keys) { TestMatrices.Add(name, DiagonalMatrix.OfArray(TestData2D[name])); } } /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<Complex32> CreateMatrix(int rows, int columns) { return new DiagonalMatrix(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<Complex32> CreateMatrix(Complex32[,] data) { return DiagonalMatrix.OfArray(data); } /// <summary> /// Can create a matrix from a diagonal array. /// </summary> [Test] public void CanCreateMatrixFromDiagonalArray() { var testData = new Dictionary<string, Matrix<Complex32>> { {"Singular3x3", new DiagonalMatrix(3, 3, new[] {new Complex32(1.0f, 1), Complex32.Zero, new Complex32(3.0f, 1)})}, {"Square3x3", new DiagonalMatrix(3, 3, new[] {new Complex32(-1.1f, 1), new Complex32(1.1f, 1), new Complex32(6.6f, 1)})}, {"Square4x4", new DiagonalMatrix(4, 4, new[] {new Complex32(-1.1f, 1), new Complex32(1.1f, 1), new Complex32(6.2f, 1), new Complex32(-7.7f, 1)})}, {"Tall3x2", new DiagonalMatrix(3, 2, new[] {new Complex32(-1.1f, 1), new Complex32(1.1f, 1)})}, {"Wide2x3", new DiagonalMatrix(2, 3, new[] {new Complex32(-1.1f, 1), new Complex32(1.1f, 1)})}, }; foreach (var name in testData.Keys) { Assert.That(testData[name], Is.EqualTo(TestMatrices[name])); } } /// <summary> /// Matrix from array is a reference. /// </summary> [Test] public void MatrixFrom1DArrayIsReference() { var data = new[] {new Complex32(1.0f, 1), new Complex32(2.0f, 1), new Complex32(3.0f, 1), new Complex32(4.0f, 1), new Complex32(5.0f, 1)}; var matrix = new DiagonalMatrix(5, 5, data); matrix[0, 0] = new Complex32(10.0f, 1); Assert.AreEqual(new Complex32(10.0f, 1), data[0]); } /// <summary> /// Can create a matrix from two-dimensional array. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Square3x3")] [TestCase("Square4x4")] [TestCase("Tall3x2")] [TestCase("Wide2x3")] public void CanCreateMatrixFrom2DArray(string name) { var matrix = DiagonalMatrix.OfArray(TestData2D[name]); for (var i = 0; i < TestData2D[name].GetLength(0); i++) { for (var j = 0; j < TestData2D[name].GetLength(1); j++) { Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]); } } } /// <summary> /// Can create a matrix with uniform values. /// </summary> [Test] public void CanCreateMatrixWithUniformValues() { var matrix = new DiagonalMatrix(10, 10, new Complex32(10.0f, 1)); for (var i = 0; i < matrix.RowCount; i++) { Assert.AreEqual(matrix[i, i], new Complex32(10.0f, 1)); } } /// <summary> /// Can create an identity matrix. /// </summary> [Test] public void CanCreateIdentity() { var matrix = DiagonalMatrix.CreateIdentity(5); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, matrix[i, j]); } } } /// <summary> /// Identity with wrong order throws <c>ArgumentOutOfRangeException</c>. /// </summary> /// <param name="order">The size of the square matrix</param> [TestCase(0)] [TestCase(-1)] public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order) { Assert.That(() => DiagonalMatrix.CreateIdentity(order), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can multiply a matrix with matrix. /// </summary> /// <param name="nameA">Matrix A name.</param> /// <param name="nameB">Matrix B name.</param> public override void CanMultiplyMatrixWithMatrixIntoResult(string nameA, string nameB) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameB]; var matrixC = new SparseMatrix(matrixA.RowCount, matrixB.ColumnCount); matrixA.Multiply(matrixB, matrixC); Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(matrixA.Row(i)*matrixB.Column(j), matrixC[i, j], 15); } } } /// <summary> /// Permute matrix rows throws <c>InvalidOperationException</c>. /// </summary> [Test] public void PermuteMatrixRowsThrowsInvalidOperationException() { var matrixp = DiagonalMatrix.OfArray(TestData2D["Singular3x3"]); var permutation = new Permutation(new[] {2, 0, 1}); Assert.That(() => matrixp.PermuteRows(permutation), Throws.InvalidOperationException); } /// <summary> /// Permute matrix columns throws <c>InvalidOperationException</c>. /// </summary> [Test] public void PermuteMatrixColumnsThrowsInvalidOperationException() { var matrixp = DiagonalMatrix.OfArray(TestData2D["Singular3x3"]); var permutation = new Permutation(new[] {2, 0, 1}); Assert.That(() => matrixp.PermuteColumns(permutation), Throws.InvalidOperationException); } /// <summary> /// Can pointwise divide matrices into a result matrix. /// </summary> public override void CanPointwiseDivideIntoResult() { foreach (var data in TestMatrices.Values) { var other = data.Clone(); var result = data.Clone(); data.PointwiseDivide(other, result); var min = Math.Min(data.RowCount, data.ColumnCount); for (var i = 0; i < min; i++) { Assert.AreEqual(data[i, i]/other[i, i], result[i, i]); } result = data.PointwiseDivide(other); for (var i = 0; i < min; i++) { Assert.AreEqual(data[i, i]/other[i, i], result[i, i]); } } } /// <summary> /// Can compute Frobenius norm. /// </summary> public override void CanComputeFrobeniusNorm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = DenseMatrix.OfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.FrobeniusNorm(), matrix.FrobeniusNorm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.FrobeniusNorm(), matrix.FrobeniusNorm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.FrobeniusNorm(), matrix.FrobeniusNorm(), 14); } /// <summary> /// Can compute Infinity norm. /// </summary> public override void CanComputeInfinityNorm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = DenseMatrix.OfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.InfinityNorm(), matrix.InfinityNorm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.InfinityNorm(), matrix.InfinityNorm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.InfinityNorm(), matrix.InfinityNorm(), 14); } /// <summary> /// Can compute L1 norm. /// </summary> public override void CanComputeL1Norm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = DenseMatrix.OfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L1Norm(), matrix.L1Norm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L1Norm(), matrix.L1Norm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L1Norm(), matrix.L1Norm(), 14); } /// <summary> /// Can compute L2 norm. /// </summary> public override void CanComputeL2Norm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = DenseMatrix.OfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L2Norm(), matrix.L2Norm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L2Norm(), matrix.L2Norm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L2Norm(), matrix.L2Norm(), 14); } /// <summary> /// Can compute determinant. /// </summary> [Test] public void CanComputeDeterminant() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = DenseMatrix.OfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.Determinant(), matrix.Determinant(), 14); matrix = TestMatrices["Square4x4"]; denseMatrix = DenseMatrix.OfArray(TestData2D["Square4x4"]); AssertHelpers.AlmostEqualRelative(denseMatrix.Determinant(), matrix.Determinant(), 14); } /// <summary> /// Determinant of non-square matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void DeterminantNotSquareMatrixThrowsArgumentException() { var matrix = TestMatrices["Tall3x2"]; Assert.That(() => matrix.Determinant(), Throws.ArgumentException); } /// <summary> /// Can check if a matrix is symmetric. /// </summary> [Test] public override void CanCheckIfMatrixIsSymmetric() { var matrix = TestMatrices["Square3x3"]; Assert.IsTrue(matrix.IsSymmetric()); } [Test] public void DenseDiagonalMatrixMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<Complex32>.Build.DiagonalIdentity(3, 3)); var tall = Matrix<Complex32>.Build.Random(8, 3, dist); Assert.IsTrue((tall*Matrix<Complex32>.Build.DiagonalIdentity(3).Multiply(2f)).Equals(tall.Multiply(2f))); Assert.IsTrue((tall*Matrix<Complex32>.Build.Diagonal(3, 5, 2f)).Equals(tall.Multiply(2f).Append(Matrix<Complex32>.Build.Dense(8, 2)))); Assert.IsTrue((tall*Matrix<Complex32>.Build.Diagonal(3, 2, 2f)).Equals(tall.Multiply(2f).SubMatrix(0, 8, 0, 2))); var wide = Matrix<Complex32>.Build.Random(3, 8, dist); Assert.IsTrue((wide*Matrix<Complex32>.Build.DiagonalIdentity(8).Multiply(2f)).Equals(wide.Multiply(2f))); Assert.IsTrue((wide*Matrix<Complex32>.Build.Diagonal(8, 10, 2f)).Equals(wide.Multiply(2f).Append(Matrix<Complex32>.Build.Dense(3, 2)))); Assert.IsTrue((wide*Matrix<Complex32>.Build.Diagonal(8, 2, 2f)).Equals(wide.Multiply(2f).SubMatrix(0, 3, 0, 2))); } [Test] public void DenseDiagonalMatrixTransposeAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<Complex32>.Build.DiagonalIdentity(3, 3)); var tall = Matrix<Complex32>.Build.Random(8, 3, dist); Assert.IsTrue(tall.TransposeAndMultiply(Matrix<Complex32>.Build.DiagonalIdentity(3).Multiply(2f)).Equals(tall.Multiply(2f))); Assert.IsTrue(tall.TransposeAndMultiply(Matrix<Complex32>.Build.Diagonal(5, 3, 2f)).Equals(tall.Multiply(2f).Append(Matrix<Complex32>.Build.Dense(8, 2)))); Assert.IsTrue(tall.TransposeAndMultiply(Matrix<Complex32>.Build.Diagonal(2, 3, 2f)).Equals(tall.Multiply(2f).SubMatrix(0, 8, 0, 2))); var wide = Matrix<Complex32>.Build.Random(3, 8, dist); Assert.IsTrue(wide.TransposeAndMultiply(Matrix<Complex32>.Build.DiagonalIdentity(8).Multiply(2f)).Equals(wide.Multiply(2f))); Assert.IsTrue(wide.TransposeAndMultiply(Matrix<Complex32>.Build.Diagonal(10, 8, 2f)).Equals(wide.Multiply(2f).Append(Matrix<Complex32>.Build.Dense(3, 2)))); Assert.IsTrue(wide.TransposeAndMultiply(Matrix<Complex32>.Build.Diagonal(2, 8, 2f)).Equals(wide.Multiply(2f).SubMatrix(0, 3, 0, 2))); } [Test] public void DenseDiagonalMatrixTransposeThisAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<Complex32>.Build.DiagonalIdentity(3, 3)); var wide = Matrix<Complex32>.Build.Random(3, 8, dist); Assert.IsTrue(wide.TransposeThisAndMultiply(Matrix<Complex32>.Build.DiagonalIdentity(3).Multiply(2f)).Equals(wide.Transpose().Multiply(2f))); Assert.IsTrue(wide.TransposeThisAndMultiply(Matrix<Complex32>.Build.Diagonal(3, 5, 2f)).Equals(wide.Transpose().Multiply(2f).Append(Matrix<Complex32>.Build.Dense(8, 2)))); Assert.IsTrue(wide.TransposeThisAndMultiply(Matrix<Complex32>.Build.Diagonal(3, 2, 2f)).Equals(wide.Transpose().Multiply(2f).SubMatrix(0, 8, 0, 2))); var tall = Matrix<Complex32>.Build.Random(8, 3, dist); Assert.IsTrue(tall.TransposeThisAndMultiply(Matrix<Complex32>.Build.DiagonalIdentity(8).Multiply(2f)).Equals(tall.Transpose().Multiply(2f))); Assert.IsTrue(tall.TransposeThisAndMultiply(Matrix<Complex32>.Build.Diagonal(8, 10, 2f)).Equals(tall.Transpose().Multiply(2f).Append(Matrix<Complex32>.Build.Dense(3, 2)))); Assert.IsTrue(tall.TransposeThisAndMultiply(Matrix<Complex32>.Build.Diagonal(8, 2, 2f)).Equals(tall.Transpose().Multiply(2f).SubMatrix(0, 3, 0, 2))); } [Test] public void DiagonalDenseMatrixMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<Complex32>.Build.DiagonalIdentity(3, 3)); var wide = Matrix<Complex32>.Build.Random(3, 8, dist); Assert.IsTrue((Matrix<Complex32>.Build.DiagonalIdentity(3).Multiply(2f)*wide).Equals(wide.Multiply(2f))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(5, 3, 2f)*wide).Equals(wide.Multiply(2f).Stack(Matrix<Complex32>.Build.Dense(2, 8)))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(2, 3, 2f)*wide).Equals(wide.Multiply(2f).SubMatrix(0, 2, 0, 8))); var tall = Matrix<Complex32>.Build.Random(8, 3, dist); Assert.IsTrue((Matrix<Complex32>.Build.DiagonalIdentity(8).Multiply(2f)*tall).Equals(tall.Multiply(2f))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(10, 8, 2f)*tall).Equals(tall.Multiply(2f).Stack(Matrix<Complex32>.Build.Dense(2, 3)))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(2, 8, 2f)*tall).Equals(tall.Multiply(2f).SubMatrix(0, 2, 0, 3))); } [Test] public void DiagonalDenseMatrixTransposeAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<Complex32>.Build.DiagonalIdentity(3, 3)); var tall = Matrix<Complex32>.Build.Random(8, 3, dist); Assert.IsTrue(Matrix<Complex32>.Build.DiagonalIdentity(3).Multiply(2f).TransposeAndMultiply(tall).Equals(tall.Multiply(2f).Transpose())); Assert.IsTrue(Matrix<Complex32>.Build.Diagonal(5, 3, 2f).TransposeAndMultiply(tall).Equals(tall.Multiply(2f).Append(Matrix<Complex32>.Build.Dense(8, 2)).Transpose())); Assert.IsTrue(Matrix<Complex32>.Build.Diagonal(2, 3, 2f).TransposeAndMultiply(tall).Equals(tall.Multiply(2f).SubMatrix(0, 8, 0, 2).Transpose())); var wide = Matrix<Complex32>.Build.Random(3, 8, dist); Assert.IsTrue(Matrix<Complex32>.Build.DiagonalIdentity(8).Multiply(2f).TransposeAndMultiply(wide).Equals(wide.Multiply(2f).Transpose())); Assert.IsTrue(Matrix<Complex32>.Build.Diagonal(10, 8, 2f).TransposeAndMultiply(wide).Equals(wide.Multiply(2f).Append(Matrix<Complex32>.Build.Dense(3, 2)).Transpose())); Assert.IsTrue(Matrix<Complex32>.Build.Diagonal(2, 8, 2f).TransposeAndMultiply(wide).Equals(wide.Multiply(2f).SubMatrix(0, 3, 0, 2).Transpose())); } [Test] public void DiagonalDenseMatrixTransposeThisAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<Complex32>.Build.DiagonalIdentity(3, 3)); var wide = Matrix<Complex32>.Build.Random(3, 8, dist); Assert.IsTrue((Matrix<Complex32>.Build.DiagonalIdentity(3).Multiply(2f).TransposeThisAndMultiply(wide)).Equals(wide.Multiply(2f))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(3, 5, 2f).TransposeThisAndMultiply(wide)).Equals(wide.Multiply(2f).Stack(Matrix<Complex32>.Build.Dense(2, 8)))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(3, 2, 2f).TransposeThisAndMultiply(wide)).Equals(wide.Multiply(2f).SubMatrix(0, 2, 0, 8))); var tall = Matrix<Complex32>.Build.Random(8, 3, dist); Assert.IsTrue((Matrix<Complex32>.Build.DiagonalIdentity(8).Multiply(2f).TransposeThisAndMultiply(tall)).Equals(tall.Multiply(2f))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(8, 10, 2f).TransposeThisAndMultiply(tall)).Equals(tall.Multiply(2f).Stack(Matrix<Complex32>.Build.Dense(2, 3)))); Assert.IsTrue((Matrix<Complex32>.Build.Diagonal(8, 2, 2f).TransposeThisAndMultiply(tall)).Equals(tall.Multiply(2f).SubMatrix(0, 2, 0, 3))); } } }
//----------------------------------------------------------------------- // <copyright file="WSTrust13RequestSerializer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace System.IdentityModel.Protocols.WSTrust { using System.Collections.Generic; using System.IdentityModel.Tokens; using System.Xml; /// <summary> /// Class for deserializing a WSTrust 1.3 RequestSecurityToken from an XmlReader /// </summary> public class WSTrust13RequestSerializer : WSTrustRequestSerializer { /// <summary> /// Deserializes the RST from the XmlReader to a RequestSecurityToken object. /// </summary> /// <param name="reader">XML reader over the RST</param> /// <param name="context">Current Serialization context.</param> /// <returns>RequestSecurityToken object if the deserialization was successful</returns> /// <exception cref="ArgumentNullException">The reader or context parameter is null</exception> /// <exception cref="WSTrustSerializationException">There was an error parsing the RST</exception> public override RequestSecurityToken ReadXml(XmlReader reader, WSTrustSerializationContext context) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } return WSTrustSerializationHelper.CreateRequest(reader, context, this, WSTrustConstantsAdapter.Trust13); } /// <summary> /// Override of the base class that reads a child element inside the RST /// </summary> /// <param name="reader">Reader pointing at an element to read inside the RST.</param> /// <param name="rst">The RequestSecurityToken element that is being populated from the reader.</param> /// <param name="context">Current Serialization context.</param> /// <exception cref="ArgumentNullException">Either reader or rst or context parameter is null.</exception> /// <exception cref="WSTrustSerializationException">Unable to deserialize the current parameter.</exception> public override void ReadXmlElement(XmlReader reader, RequestSecurityToken rst, WSTrustSerializationContext context) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (rst == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } // special case SecondaryParameters, they cannot be embeded as per WS-Trust 1.3 if (reader.IsStartElement(WSTrust13Constants.ElementNames.SecondaryParameters, WSTrust13Constants.NamespaceURI)) { rst.SecondaryParameters = this.ReadSecondaryParameters(reader, context); return; } if (reader.IsStartElement(WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI)) { rst.KeyWrapAlgorithm = reader.ReadElementContentAsString(); if (!UriUtil.CanCreateValidUri(rst.KeyWrapAlgorithm, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, rst.KeyWrapAlgorithm))); } return; } if (reader.IsStartElement(WSTrust13Constants.ElementNames.ValidateTarget, WSTrust13Constants.NamespaceURI)) { if (!reader.IsEmptyElement) { rst.ValidateTarget = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers); } if (rst.ValidateTarget == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3221))); } return; } WSTrustSerializationHelper.ReadRSTXml(reader, rst, context, WSTrustConstantsAdapter.Trust13); } /// <summary> /// Writes out the supported elements on the request object. Override this method if someone /// has sub-class the RequestSecurityToken class and added more property to it. /// </summary> /// <param name="rst">The request instance</param> /// <param name="writer">The writer to write to</param> /// <param name="context">Current Serialization context.</param> /// <exception cref="ArgumentNullException">Either rst or writer or context parameter is null.</exception> public override void WriteKnownRequestElement(RequestSecurityToken rst, XmlWriter writer, WSTrustSerializationContext context) { if (rst == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst"); } if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } // Write out the exisiting ones WSTrustSerializationHelper.WriteKnownRequestElement(rst, writer, context, this, WSTrustConstantsAdapter.Trust13); // Specific to WS-Trust 13 if (!string.IsNullOrEmpty(rst.KeyWrapAlgorithm)) { if (!UriUtil.CanCreateValidUri(rst.KeyWrapAlgorithm, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, rst.KeyWrapAlgorithm))); } this.WriteXmlElement(writer, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, rst.KeyWrapAlgorithm, rst, context); } if (rst.SecondaryParameters != null) { this.WriteXmlElement(writer, WSTrust13Constants.ElementNames.SecondaryParameters, rst.SecondaryParameters, rst, context); } if (rst.ValidateTarget != null) { this.WriteXmlElement(writer, WSTrust13Constants.ElementNames.ValidateTarget, rst.ValidateTarget, rst, context); } } /// <summary> /// Serializes the given RequestSecurityToken into the XmlWriter /// </summary> /// <param name="request">RequestSecurityToken object to be serialized</param> /// <param name="writer">XML writer to serialize into</param> /// <param name="context">Current Serialization context.</param> /// <exception cref="ArgumentNullException">The request or writer or context parameter is null.</exception> public override void WriteXml(RequestSecurityToken request, XmlWriter writer, WSTrustSerializationContext context) { if (request == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request"); } if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } WSTrustSerializationHelper.WriteRequest(request, writer, context, this, WSTrustConstantsAdapter.Trust13); } /// <summary> /// Override of the Base class method that writes a specific RST parameter to the outgoing stream. /// </summary> /// <param name="writer">Writer to which the </param> /// <param name="elementName">The Local name of the element to be written.</param> /// <param name="elementValue">The value of the element.</param> /// <param name="rst">The entire RST object that is being serialized.</param> /// <param name="context">Current Serialization context.</param> /// <exception cref="ArgumentNullException">Either writer or rst or context is null.</exception> /// <exception cref="ArgumentException">elementName is null or an empty string.</exception> public override void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityToken rst, WSTrustSerializationContext context) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (string.IsNullOrEmpty(elementName)) { throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("elementName"); } if (rst == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } // Write out the WSTrust13 specific elements if (StringComparer.Ordinal.Equals(elementName, WSTrust13Constants.ElementNames.SecondaryParameters)) { RequestSecurityToken secondaryParameters = elementValue as RequestSecurityToken; if (secondaryParameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2064, WSTrust13Constants.ElementNames.SecondaryParameters))); } // WS-Trust 13 spec does not allow this if (secondaryParameters.SecondaryParameters != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2055))); } writer.WriteStartElement(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.SecondaryParameters, WSTrust13Constants.NamespaceURI); // write out the known elements inside the rst.SecondaryParameters this.WriteKnownRequestElement(secondaryParameters, writer, context); // Write the custom elements here from the rst.SecondaryParameters.Elements bag foreach (KeyValuePair<string, object> messageParam in secondaryParameters.Properties) { this.WriteXmlElement(writer, messageParam.Key, messageParam.Value, rst, context); } // close out the SecondaryParameters element writer.WriteEndElement(); return; } if (StringComparer.Ordinal.Equals(elementName, WSTrust13Constants.ElementNames.KeyWrapAlgorithm)) { writer.WriteElementString(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, (string)elementValue); return; } if (StringComparer.Ordinal.Equals(elementName, WSTrust13Constants.ElementNames.ValidateTarget)) { SecurityTokenElement tokenElement = elementValue as SecurityTokenElement; if (tokenElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("elementValue", SR.GetString(SR.ID3222, WSTrust13Constants.ElementNames.ValidateTarget, WSTrust13Constants.NamespaceURI, typeof(SecurityTokenElement), elementValue)); } writer.WriteStartElement(WSTrust13Constants.Prefix, WSTrust13Constants.ElementNames.ValidateTarget, WSTrust13Constants.NamespaceURI); if (tokenElement.SecurityTokenXml != null) { tokenElement.SecurityTokenXml.WriteTo(writer); } else { context.SecurityTokenHandlers.WriteToken(writer, tokenElement.GetSecurityToken()); } writer.WriteEndElement(); return; } WSTrustSerializationHelper.WriteRSTXml(writer, elementName, elementValue, context, WSTrustConstantsAdapter.Trust13); } /// <summary> /// Checks if the given reader is positioned at a RequestSecurityToken element with namespace /// 'http://docs.oasis-open.org/ws-sx/ws-trust/200512' /// </summary> /// <param name="reader">The reader to read from</param> /// <returns> /// 'True' if the reader is positioned at a RequestSecurityToken element with namespace /// 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'. /// </returns> /// <exception cref="ArgumentNullException">The input argument is null.</exception> public override bool CanRead(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } return reader.IsStartElement(WSTrust13Constants.ElementNames.RequestSecurityToken, WSTrust13Constants.NamespaceURI); } /// <summary> /// Special case for reading SecondaryParameters inside a WS-Trust 1.3 RST. The specification states that a SecondaryParameters element /// cannot be inside a SecondaryParameters element. Override this method to provide custom processing. /// </summary> /// <param name="reader">Reader pointing at the SecondaryParameters element inside the RST.</param> /// <param name="context">Current Serialization context.</param> /// <exception cref="ArgumentNullException">Either reader or context parameter is null.</exception> /// <exception cref="WSTrustSerializationException">An inner 'SecondaryParameter' element was found while processing the outer 'SecondaryParameter'.</exception> /// <returns>RequestSecurityToken that contains the SecondaryParameters found in the RST</returns> protected virtual RequestSecurityToken ReadSecondaryParameters( XmlReader reader, WSTrustSerializationContext context) { RequestSecurityToken secondaryParameters = CreateRequestSecurityToken(); if (reader.IsEmptyElement) { reader.Read(); reader.MoveToContent(); return secondaryParameters; } reader.ReadStartElement(); while (reader.IsStartElement()) { if (reader.IsStartElement( WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI)) { secondaryParameters.KeyWrapAlgorithm = reader.ReadElementContentAsString(); if (!UriUtil.CanCreateValidUri(secondaryParameters.KeyWrapAlgorithm, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new WSTrustSerializationException( SR.GetString( SR.ID3135, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, secondaryParameters.KeyWrapAlgorithm))); } } else if (reader.IsStartElement( WSTrust13Constants.ElementNames.SecondaryParameters, WSTrust13Constants.NamespaceURI)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new WSTrustSerializationException(SR.GetString(SR.ID3130))); } else { WSTrustSerializationHelper.ReadRSTXml( reader, secondaryParameters, context, WSTrustConstantsAdapter.GetConstantsAdapter(reader.NamespaceURI) ?? WSTrustConstantsAdapter.TrustFeb2005); } } reader.ReadEndElement(); return secondaryParameters; } } }
using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Web; namespace Cvv.WebUtility.Mvc { public class OnlineHttpRequest : IHttpRequest { private readonly HttpRequest _request; public OnlineHttpRequest(HttpRequest request) { _request = request; } public NameValueCollection ServerVariables { get { return _request.ServerVariables; } } public int TotalBytes { get { return _request.TotalBytes; } } public NameValueCollection Form { get { return _request.Form; } } public NameValueCollection Headers { get { return _request.Headers; } } public string HttpMethod { get { return _request.HttpMethod; } } public Stream InputStream { get { return _request.InputStream; } } public bool IsAuthenticated { get { return _request.IsAuthenticated; } } public HttpCookieCollection Cookies { get { return _request.Cookies; } } public string CurrentExecutionFilePath { get { return _request.CurrentExecutionFilePath; } } public byte[] BinaryRead(int count) { return _request.BinaryRead(count); } public int[] MapImageCoordinates(string imageFieldName) { return _request.MapImageCoordinates(imageFieldName); } public string MapPath(string virtualPath) { return _request.MapPath(virtualPath); } public string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) { return _request.MapPath(virtualPath, baseVirtualDir, allowCrossAppMapping); } public void SaveAs(string filename, bool includeHeaders) { _request.SaveAs(filename, includeHeaders); } public void ValidateInput() { _request.ValidateInput(); } public string[] AcceptTypes { get { return _request.AcceptTypes; } } public string AnonymousID { get { return _request.AnonymousID; } } public string ApplicationPath { get { return _request.ApplicationPath; } } public string AppRelativeCurrentExecutionFilePath { get { return _request.AppRelativeCurrentExecutionFilePath; } } public NameValueCollection QueryString { get { return _request.QueryString; } } public string PhysicalApplicationPath { get { return _request.PhysicalApplicationPath; } } public string PhysicalPath { get { return _request.PhysicalPath; } } public string RawUrl { get { return _request.RawUrl; } } public string RequestType { get { return _request.RequestType; } set { _request.RequestType = value; } } public string FilePath { get { return _request.FilePath; } } public HttpFileCollection Files { get { return _request.Files; } } public Stream Filter { get { return _request.Filter; } set { _request.Filter = value; } } public string PathInfo { get { return _request.PathInfo; } } public bool IsLocal { get { return _request.IsLocal; } } public bool IsSecureConnection { get { return _request.IsSecureConnection; } } public string this[string key] { get { return _request[key]; } } public NameValueCollection Params { get { return _request.Params; } } public HttpBrowserCapabilities Browser { get { return _request.Browser; } set { _request.Browser = value; } } public HttpClientCertificate ClientCertificate { get { return _request.ClientCertificate; } } public Encoding ContentEncoding { get { return _request.ContentEncoding; } set { _request.ContentEncoding = value; } } public int ContentLength { get { return _request.ContentLength; } } public string ContentType { get { return _request.ContentType; } set { _request.ContentType = value; } } public Uri Url { get { return _request.Url; } } public Uri UrlReferrer { get { return _request.UrlReferrer; } } public string Path { get { return _request.Path; } } public string UserHostAddress { get { return _request.UserHostAddress; } } public string UserHostName { get { return _request.UserHostName; } } public string[] UserLanguages { get { return _request.UserLanguages; } } public string UserAgent { get { return _request.UserAgent; } } public bool IsETagEqual(string eTag) { string match = _request.Headers["If-None-Match"]; return match != null && match == ('"' + eTag + '"'); } public bool IsChangedBasedOnTimeStamp(DateTime timeStamp) { string ifModifiedSince = _request.Headers["If-Modified-Since"]; DateTime parsedTimeStamp; if (string.IsNullOrEmpty(ifModifiedSince) || !DateTime.TryParseExact(ifModifiedSince, new string[] { "ddd, dd MMM yyyy HH:mm:ss \"GMT\"", "dddd, dd-MMM-yy HH:mm:ss \"GMT\"", "ddd MM dd HH:mm:ss yyyy", "ddd MM d HH:mm:ss yyyy", }, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal, out parsedTimeStamp)) return true; timeStamp = new DateTime(timeStamp.Year, timeStamp.Month, timeStamp.Day, timeStamp.Hour, timeStamp.Minute, timeStamp.Second); return timeStamp > parsedTimeStamp; } } }
// 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: This is the value class representing a Unicode character ** Char methods until we create this functionality. ** ** ===========================================================*/ using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Char : IComparable, IComparable<Char>, IEquatable<Char>, IConvertible { // // Member Variables // private char m_value; // Do not rename (binary serialization) // // Public Constants // // The maximum character value. public const char MaxValue = (char)0xFFFF; // The minimum character value. public const char MinValue = (char)0x00; // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. private static readonly byte[] s_categoryForLatin1 = { (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027 (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. private static bool IsLatin1(char ch) { return (ch <= '\x00ff'); } // Return true for all characters below or equal U+007f, which is ASCII. private static bool IsAscii(char ch) { return (ch <= '\x007f'); } // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(s_categoryForLatin1[(int)ch]); } // // Private Constants // // // Overriden Instance Methods // // Calculate a hashcode for a 2 byte Unicode character. public override int GetHashCode() { return (int)m_value | ((int)m_value << 16); } // Used for comparing two boxed Char objects. // public override bool Equals(Object obj) { if (!(obj is Char)) { return false; } return (m_value == ((Char)obj).m_value); } [System.Runtime.Versioning.NonVersionable] public bool Equals(Char obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Char)) { throw new ArgumentException(SR.Arg_MustBeChar); } return (m_value - ((Char)value).m_value); } public int CompareTo(Char value) { return (m_value - value); } // Overrides System.Object.ToString. public override String ToString() { return Char.ToString(m_value); } public String ToString(IFormatProvider provider) { return Char.ToString(m_value); } // // Formatting Methods // /*===================================ToString=================================== **This static methods takes a character and returns the String representation of it. ==============================================================================*/ // Provides a string representation of a character. public static string ToString(char c) => string.CreateFromChar(c); public static char Parse(String s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } public static bool TryParse(String s, out Char result) { result = '\0'; if (s == null) { return false; } if (s.Length != 1) { return false; } result = s[0]; return true; } // // Static Methods // /*=================================ISDIGIT====================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. public static bool IsDigit(char c) { if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber); } /*=================================CheckLetter===================================== ** Check if the specified UnicodeCategory belongs to the letter categories. ==============================================================================*/ internal static bool CheckLetter(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.UppercaseLetter): case (UnicodeCategory.LowercaseLetter): case (UnicodeCategory.TitlecaseLetter): case (UnicodeCategory.ModifierLetter): case (UnicodeCategory.OtherLetter): return (true); } return (false); } /*=================================ISLETTER===================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. public static bool IsLetter(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c))); } private static bool IsWhiteSpaceLatin1(char c) { // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. // We use code point comparisons for these characters here as a temporary fix. // U+0009 = <control> HORIZONTAL TAB // U+000a = <control> LINE FEED // U+000b = <control> VERTICAL TAB // U+000c = <contorl> FORM FEED // U+000d = <control> CARRIAGE RETURN // U+0085 = <control> NEXT LINE // U+00a0 = NO-BREAK SPACE return c == ' ' || (uint)(c - '\x0009') <= ('\x000d' - '\x0009') || // (c >= '\x0009' && c <= '\x000d') c == '\x00a0' || c == '\x0085'; } /*===============================ISWHITESPACE=================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return (IsWhiteSpaceLatin1(c)); } return CharUnicodeInfo.IsWhiteSpace(c); } /*===================================IsUpper==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an uppercase character. ==============================================================================*/ // Determines whether a character is upper-case. public static bool IsUpper(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } /*===================================IsLower==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an lowercase character. ==============================================================================*/ // Determines whether a character is lower-case. public static bool IsLower(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } internal static bool CheckPunctuation(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: return (true); } return (false); } /*================================IsPunctuation================================= **Arguments: c -- the characater to be checked. **Returns: True if c is an punctuation mark ==============================================================================*/ // Determines whether a character is a punctuation mark. public static bool IsPunctuation(char c) { if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c))); } /*=================================CheckLetterOrDigit===================================== ** Check if the specified UnicodeCategory belongs to the letter or digit categories. ==============================================================================*/ internal static bool CheckLetterOrDigit(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.DecimalDigitNumber: return (true); } return (false); } // Determines whether a character is a letter or a digit. public static bool IsLetterOrDigit(char c) { if (IsLatin1(c)) { return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c))); } return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c))); } /*===================================ToUpper==================================== ** ==============================================================================*/ // Converts a character to upper-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToUpper(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); return culture.TextInfo.ToUpper(c); } /*=================================TOUPPER====================================== **A wrapper for Char.toUpperCase. Converts character c to its ** **uppercase equivalent. If c is already an uppercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to upper-case for the default culture. // public static char ToUpper(char c) { return CultureInfo.CurrentCulture.TextInfo.ToUpper(c); } // Converts a character to upper-case for invariant culture. public static char ToUpperInvariant(char c) { return CultureInfo.InvariantCulture.TextInfo.ToUpper(c); } /*===================================ToLower==================================== ** ==============================================================================*/ // Converts a character to lower-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToLower(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); return culture.TextInfo.ToLower(c); } /*=================================TOLOWER====================================== **A wrapper for Char.toLowerCase. Converts character c to its ** **lowercase equivalent. If c is already a lowercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to lower-case for the default culture. public static char ToLower(char c) { return CultureInfo.CurrentCulture.TextInfo.ToLower(c); } // Converts a character to lower-case for invariant culture. public static char ToLowerInvariant(char c) { return CultureInfo.InvariantCulture.TextInfo.ToLower(c); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Char; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Boolean")); } char IConvertible.ToChar(IFormatProvider provider) { return m_value; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Single")); } double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Double")); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } public static bool IsControl(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control); } public static bool IsControl(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control); } public static bool IsDigit(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } public static bool IsLetter(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsLetterOrDigit(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index)); } public static bool IsLower(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter); } /*=================================CheckNumber===================================== ** Check if the specified UnicodeCategory belongs to the number categories. ==============================================================================*/ internal static bool CheckNumber(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.DecimalDigitNumber): case (UnicodeCategory.LetterNumber): case (UnicodeCategory.OtherNumber): return (true); } return (false); } public static bool IsNumber(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsNumber(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index))); } //////////////////////////////////////////////////////////////////////// // // IsPunctuation // // Determines if the given character is a punctuation character. // //////////////////////////////////////////////////////////////////////// public static bool IsPunctuation(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index))); } /*================================= CheckSeparator ============================ ** Check if the specified UnicodeCategory belongs to the seprator categories. ==============================================================================*/ internal static bool CheckSeparator(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: return (true); } return (false); } private static bool IsSeparatorLatin1(char c) { // U+00a0 = NO-BREAK SPACE // There is no LineSeparator or ParagraphSeparator in Latin 1 range. return (c == '\x0020' || c == '\x00a0'); } public static bool IsSeparator(char c) { if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSeparator(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsSurrogate(char c) { return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } public static bool IsSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return (IsSurrogate(s[index])); } /*================================= CheckSymbol ============================ ** Check if the specified UnicodeCategory belongs to the symbol categories. ==============================================================================*/ internal static bool CheckSymbol(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.MathSymbol): case (UnicodeCategory.CurrencySymbol): case (UnicodeCategory.ModifierSymbol): case (UnicodeCategory.OtherSymbol): return (true); } return (false); } public static bool IsSymbol(char c) { if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSymbol(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsUpper(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } public static bool IsWhiteSpace(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } if (IsLatin1(s[index])) { return IsWhiteSpaceLatin1(s[index]); } return CharUnicodeInfo.IsWhiteSpace(s, index); } public static UnicodeCategory GetUnicodeCategory(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c)); } return CharUnicodeInfo.GetUnicodeCategory((int)c); } public static UnicodeCategory GetUnicodeCategory(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } if (IsLatin1(s[index])) { return (GetLatin1UnicodeCategory(s[index])); } return CharUnicodeInfo.InternalGetUnicodeCategory(s, index); } public static double GetNumericValue(char c) { return CharUnicodeInfo.GetNumericValue(c); } public static double GetNumericValue(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return CharUnicodeInfo.GetNumericValue(s, index); } /*================================= IsHighSurrogate ============================ ** Check if a char is a high surrogate. ==============================================================================*/ public static bool IsHighSurrogate(char c) { return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END)); } public static bool IsHighSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return (IsHighSurrogate(s[index])); } /*================================= IsLowSurrogate ============================ ** Check if a char is a low surrogate. ==============================================================================*/ public static bool IsLowSurrogate(char c) { return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END)); } public static bool IsLowSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return (IsLowSurrogate(s[index])); } /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ public static bool IsSurrogatePair(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (index + 1 < s.Length) { return (IsSurrogatePair(s[index], s[index + 1])); } return (false); } public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) { return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) && (lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END)); } internal const int UNICODE_PLANE00_END = 0x00ffff; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode. // Plane 16 contains 0x100000 ~ 0x10ffff. internal const int UNICODE_PLANE16_END = 0x10ffff; internal const int HIGH_SURROGATE_START = 0x00d800; internal const int LOW_SURROGATE_END = 0x00dfff; /*================================= ConvertFromUtf32 ============================ ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ public static String ConvertFromUtf32(int utf32) { // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They // are considered as irregular code unit sequence, but they are not illegal. if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) { throw new ArgumentOutOfRangeException(nameof(utf32), SR.ArgumentOutOfRange_InvalidUTF32); } if (utf32 < UNICODE_PLANE01_START) { // This is a BMP character. return (Char.ToString((char)utf32)); } unsafe { // This is a supplementary character. Convert it to a surrogate pair in UTF-16. utf32 -= UNICODE_PLANE01_START; uint surrogate = 0; // allocate 2 chars worth of stack space char* address = (char*)&surrogate; address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START); address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START); return new string(address, 0, 2); } } /*=============================ConvertToUtf32=================================== ** Convert a surrogate pair to UTF32 value ==============================================================================*/ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { if (!IsHighSurrogate(highSurrogate)) { throw new ArgumentOutOfRangeException(nameof(highSurrogate), SR.ArgumentOutOfRange_InvalidHighSurrogate); } if (!IsLowSurrogate(lowSurrogate)) { throw new ArgumentOutOfRangeException(nameof(lowSurrogate), SR.ArgumentOutOfRange_InvalidLowSurrogate); } return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START); } /*=============================ConvertToUtf32=================================== ** Convert a character or a surrogate pair starting at index of the specified string ** to UTF32 value. ** The char pointed by index should be a surrogate pair or a BMP character. ** This method throws if a high-surrogate is not followed by a low surrogate. ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ public static int ConvertToUtf32(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. if (temp1 <= 0x3ff) { // Found a high surrogate. if (index < s.Length - 1) { int temp2 = (int)s[index + 1] - CharUnicodeInfo.LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } else { throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s)); } } else { // Found a high surrogate at the end of the string. throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s)); } } else { // Find a low surrogate at the character pointed by index. throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), nameof(s)); } } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. return ((int)s[index]); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.StorSimple; using Microsoft.WindowsAzure.Management.StorSimple.Models; namespace Microsoft.WindowsAzure.Management.StorSimple { /// <summary> /// All Operations related to Device Failover /// </summary> internal partial class DeviceFailoverOperations : IServiceOperations<StorSimpleManagementClient>, IDeviceFailoverOperations { /// <summary> /// Initializes a new instance of the DeviceFailoverOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DeviceFailoverOperations(StorSimpleManagementClient client) { this._client = client; } private StorSimpleManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient. /// </summary> public StorSimpleManagementClient Client { get { return this._client; } } /// <param name='deviceId'> /// Optional. /// </param> /// <param name='customRequestHeaders'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response model for DataContainerGroups Get call /// </returns> public async Task<DataContainerGroupsGetResponse> ListDCGroupsAsync(string deviceId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListDCGroupsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; if (deviceId != null) { url = url + Uri.EscapeDataString(deviceId); } url = url + "/failoverdatacontainers"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataContainerGroupsGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataContainerGroupsGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dataContainerGroupResponseElement = responseDoc.Element(XName.Get("DataContainerGroupResponse", "http://windowscloudbackup.com/CiS/V2013_03")); if (dataContainerGroupResponseElement != null) { DataContainerGroupResponse dataContainerGroupResponseInstance = new DataContainerGroupResponse(); result.DataContainerGroupResponse = dataContainerGroupResponseInstance; XElement dCGroupsSequenceElement = dataContainerGroupResponseElement.Element(XName.Get("DCGroups", "http://windowscloudbackup.com/CiS/V2013_03")); if (dCGroupsSequenceElement != null) { foreach (XElement dCGroupsElement in dCGroupsSequenceElement.Elements(XName.Get("DataContainerGroup", "http://windowscloudbackup.com/CiS/V2013_03"))) { DataContainerGroup dataContainerGroupInstance = new DataContainerGroup(); dataContainerGroupResponseInstance.DCGroups.Add(dataContainerGroupInstance); XElement dCGroupSequenceElement = dCGroupsElement.Element(XName.Get("DCGroup", "http://windowscloudbackup.com/CiS/V2013_03")); if (dCGroupSequenceElement != null) { foreach (XElement dCGroupElement in dCGroupSequenceElement.Elements(XName.Get("DRDataContainer", "http://windowscloudbackup.com/CiS/V2013_03"))) { DRDataContainer dRDataContainerInstance = new DRDataContainer(); dataContainerGroupInstance.DCGroup.Add(dRDataContainerInstance); XElement instanceIdElement = dCGroupElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement != null) { string instanceIdInstance = instanceIdElement.Value; dRDataContainerInstance.InstanceId = instanceIdInstance; } XElement nameElement = dCGroupElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement != null) { string nameInstance = nameElement.Value; dRDataContainerInstance.Name = nameInstance; } XElement operationInProgressElement = dCGroupElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement != null) { OperationInProgress operationInProgressInstance = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement.Value, true)); dRDataContainerInstance.OperationInProgress = operationInProgressInstance; } XElement cloudTypeElement = dCGroupElement.Element(XName.Get("CloudType", "http://windowscloudbackup.com/CiS/V2013_03")); if (cloudTypeElement != null) { CloudType cloudTypeInstance = StorSimpleManagementClient.ParseCloudType(cloudTypeElement.Value); dRDataContainerInstance.CloudType = cloudTypeInstance; } XElement dataContainerIdElement = dCGroupElement.Element(XName.Get("DataContainerId", "http://windowscloudbackup.com/CiS/V2013_03")); if (dataContainerIdElement != null) { string dataContainerIdInstance = dataContainerIdElement.Value; dRDataContainerInstance.DataContainerId = dataContainerIdInstance; } XElement locationElement = dCGroupElement.Element(XName.Get("Location", "http://windowscloudbackup.com/CiS/V2013_03")); if (locationElement != null) { string locationInstance = locationElement.Value; dRDataContainerInstance.Location = locationInstance; } XElement ownedElement = dCGroupElement.Element(XName.Get("Owned", "http://windowscloudbackup.com/CiS/V2013_03")); if (ownedElement != null) { bool ownedInstance = bool.Parse(ownedElement.Value); dRDataContainerInstance.Owned = ownedInstance; } XElement ownerDeviceIdElement = dCGroupElement.Element(XName.Get("OwnerDeviceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (ownerDeviceIdElement != null) { string ownerDeviceIdInstance = ownerDeviceIdElement.Value; dRDataContainerInstance.OwnerDeviceId = ownerDeviceIdInstance; } XElement volumeListSequenceElement = dCGroupElement.Element(XName.Get("VolumeList", "http://windowscloudbackup.com/CiS/V2013_03")); if (volumeListSequenceElement != null) { foreach (XElement volumeListElement in volumeListSequenceElement.Elements(XName.Get("DRVolume", "http://windowscloudbackup.com/CiS/V2013_03"))) { DRVolume dRVolumeInstance = new DRVolume(); dRDataContainerInstance.VolumeList.Add(dRVolumeInstance); XElement displayNameElement = volumeListElement.Element(XName.Get("DisplayName", "http://windowscloudbackup.com/CiS/V2013_03")); if (displayNameElement != null) { string displayNameInstance = displayNameElement.Value; dRVolumeInstance.DisplayName = displayNameInstance; } XElement sizeElement = volumeListElement.Element(XName.Get("Size", "http://windowscloudbackup.com/CiS/V2013_03")); if (sizeElement != null) { long sizeInstance = long.Parse(sizeElement.Value, CultureInfo.InvariantCulture); dRVolumeInstance.Size = sizeInstance; } XElement snapshotIdElement = volumeListElement.Element(XName.Get("SnapshotId", "http://windowscloudbackup.com/CiS/V2013_03")); if (snapshotIdElement != null) { string snapshotIdInstance = snapshotIdElement.Value; dRVolumeInstance.SnapshotId = snapshotIdInstance; } } } } } XElement ineligibilityMessageElement = dCGroupsElement.Element(XName.Get("IneligibilityMessage", "http://windowscloudbackup.com/CiS/V2013_03")); if (ineligibilityMessageElement != null) { string ineligibilityMessageInstance = ineligibilityMessageElement.Value; dataContainerGroupInstance.IneligibilityMessage = ineligibilityMessageInstance; } XElement isDCGroupEligibleForDRElement = dCGroupsElement.Element(XName.Get("IsDCGroupEligibleForDR", "http://windowscloudbackup.com/CiS/V2013_03")); if (isDCGroupEligibleForDRElement != null) { bool isDCGroupEligibleForDRInstance = bool.Parse(isDCGroupEligibleForDRElement.Value); dataContainerGroupInstance.IsDCGroupEligibleForDR = isDCGroupEligibleForDRInstance; } } } XElement followUpJobIdElement = dataContainerGroupResponseElement.Element(XName.Get("FollowUpJobId", "http://windowscloudbackup.com/CiS/V2013_03")); if (followUpJobIdElement != null) { string followUpJobIdInstance = followUpJobIdElement.Value; dataContainerGroupResponseInstance.FollowUpJobId = followUpJobIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Trigger device failover. /// </summary> /// <param name='deviceId'> /// Required. The device identifier /// </param> /// <param name='drRequest'> /// Required. The details of the device failover request. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// This is the Job Response for all Device Job Related Calls /// </returns> public async Task<JobResponse> TriggerAsync(string deviceId, DeviceFailoverRequest drRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (drRequest == null) { throw new ArgumentNullException("drRequest"); } if (drRequest.DataContainerIds == null) { throw new ArgumentNullException("drRequest.DataContainerIds"); } if (drRequest.TargetDeviceId == null) { throw new ArgumentNullException("drRequest.TargetDeviceId"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("drRequest", drRequest); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "TriggerAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/failover"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement dRRequestV2Element = new XElement(XName.Get("DRRequest_V2", "http://windowscloudbackup.com/CiS/V2013_03")); requestDoc.Add(dRRequestV2Element); XElement cleanupPrimaryElement = new XElement(XName.Get("CleanupPrimary", "http://windowscloudbackup.com/CiS/V2013_03")); cleanupPrimaryElement.Value = drRequest.CleanupPrimary.ToString().ToLower(); dRRequestV2Element.Add(cleanupPrimaryElement); XElement dataContainerIdsSequenceElement = new XElement(XName.Get("DataContainerIds", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string dataContainerIdsItem in drRequest.DataContainerIds) { XElement dataContainerIdsItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); dataContainerIdsItemElement.Value = dataContainerIdsItem; dataContainerIdsSequenceElement.Add(dataContainerIdsItemElement); } dRRequestV2Element.Add(dataContainerIdsSequenceElement); XElement returnWorkflowIdElement = new XElement(XName.Get("ReturnWorkflowId", "http://windowscloudbackup.com/CiS/V2013_03")); returnWorkflowIdElement.Value = drRequest.ReturnWorkflowId.ToString().ToLower(); dRRequestV2Element.Add(returnWorkflowIdElement); XElement targetDeviceIdElement = new XElement(XName.Get("TargetDeviceId", "http://windowscloudbackup.com/CiS/V2013_03")); targetDeviceIdElement.Value = drRequest.TargetDeviceId; dRRequestV2Element.Add(targetDeviceIdElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/")); if (stringElement != null) { string stringInstance = stringElement.Value; result.JobId = stringInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace AjTalk.Tests.Compiler { using System; using System.Collections.Generic; using System.Text; using AjTalk; using AjTalk.Compiler; using AjTalk.Language; using AjTalk.Tests.Language; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class ParserTests { [TestMethod] public void Create() { Parser compiler = new Parser("x ^x"); Assert.IsNotNull(compiler); } [TestMethod] public void CompileMethod() { Machine machine = new Machine(); IClass cls = machine.CreateClass("Rectangle"); cls.DefineInstanceVariable("x"); Parser compiler = new Parser("x ^x"); var method = compiler.CompileInstanceMethod(cls); Assert.IsNotNull(method); Assert.AreEqual("x", method.Name); Assert.IsNotNull(method.ByteCodes); } [TestMethod] public void CompileMethodWithHorizontalBarAsName() { Machine machine = new Machine(); IClass cls = machine.CreateClass("Rectangle"); Parser compiler = new Parser("| aBoolean ^aBoolean"); var method = compiler.CompileInstanceMethod(cls); Assert.IsNotNull(method); Assert.AreEqual("|", method.Name); Assert.IsNotNull(method.ByteCodes); } [TestMethod] public void CompileMethodWithLocals() { Machine machine = new Machine(); IClass cls = machine.CreateClass("Rectangle"); cls.DefineInstanceVariable("x"); Parser compiler = new Parser("x | temp | temp := x. ^temp"); var method = compiler.CompileInstanceMethod(cls); Assert.IsNotNull(method); Assert.AreEqual("x", method.Name); Assert.IsNotNull(method.ByteCodes); } [TestMethod] public void CompileSetMethod() { Machine machine = new Machine(); IClass cls = machine.CreateClass("Rectangle"); cls.DefineInstanceVariable("x"); Parser compiler = new Parser("x: newX x := newX"); var method = compiler.CompileInstanceMethod(cls); Assert.IsNotNull(method); Assert.AreEqual("x:", method.Name); Assert.IsNotNull(method.ByteCodes); } [TestMethod] public void CompileSimpleCommand() { Parser compiler = new Parser("nil invokeWith: 10"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(2, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(6, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSimpleSendToSelf() { Parser compiler = new Parser("self invokeWith: 10"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(2, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(6, block.ByteCodes.Length); Assert.AreEqual(ByteCode.GetSelf, (ByteCode)block.ByteCodes[0]); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileInteger() { Parser compiler = new Parser("1"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(1, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); Assert.AreEqual("GetConstant 1", result[0]); } [TestMethod] public void CompileIntegerWithRadix() { Parser compiler = new Parser("16rFF"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(1, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); Assert.AreEqual("GetConstant 255", result[0]); } [TestMethod] public void CompileCharacter() { Parser compiler = new Parser("$+"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(1, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); Assert.AreEqual("GetConstant +", result[0]); } [TestMethod] public void CompileNegativeInteger() { Parser compiler = new Parser("-1"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(2, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(2, result.Count); Assert.AreEqual("GetConstant 1", result[0]); Assert.AreEqual("Send minus 0", result[1]); } [TestMethod] public void CompileSimpleSum() { Parser compiler = new Parser("1 + 2"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(7, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); Assert.AreEqual("GetConstant 1", result[0]); Assert.AreEqual("GetConstant 2", result[1]); Assert.AreEqual("Send + 1", result[2]); } [TestMethod] public void CompileSimpleAt() { Parser compiler = new Parser("1 @ 2"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(7, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); Assert.AreEqual("GetConstant 1", result[0]); Assert.AreEqual("GetConstant 2", result[1]); Assert.AreEqual("Send @ 1", result[2]); } [TestMethod] public void CompileSimpleRealSum() { Parser compiler = new Parser("1.2 + 3.4"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(3, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(7, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSimpleArithmeticWithParenthesis() { Parser compiler = new Parser("1 * (2 + 3)"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(5, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(12, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileTwoSimpleCommand() { Parser compiler = new Parser("a := 1. b := 2"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(2, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(2, block.NoGlobalNames); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(8, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSimpleCommandWithParenthesis() { Parser compiler = new Parser("a := b with: (anObject class)"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(1, block.NoConstants); Assert.AreEqual(3, block.NoGlobalNames); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(10, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSimpleCommandWithParenthesisAndBang() { Parser compiler = new Parser("a := b with: (anObject !nativeMethod)"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(3, block.NoGlobalNames); Assert.AreEqual(2, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(12, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSimpleCommandWithParenthesisAndBangKeyword() { Parser compiler = new Parser("a := b with: (anObject !nativeMethod: 1)"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(3, block.NoGlobalNames); Assert.AreEqual(3, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(14, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileAndExecuteTwoSimpleCommand() { Parser compiler = new Parser("a := 1. b := 2"); Block block = compiler.CompileBlock(); Machine machine = new Machine(); block.Execute(machine, null); Assert.AreEqual(1, machine.GetGlobalObject("a")); Assert.AreEqual(2, machine.GetGlobalObject("b")); } [TestMethod] public void CompileGlobalVariable() { Parser compiler = new Parser("AClass"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(1, block.NoGlobalNames); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(2, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSubClassDefinition() { Parser compiler = new Parser("nil subclass: #Object"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(2, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(6, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileSubClassDefinitionWithInstances() { Parser compiler = new Parser("nil subclass: #Object instanceVariables: 'a b c'"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(3, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(8, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileTwoCommands() { Parser compiler = new Parser("nil invokeWith: 10. Global := 20"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(3, block.NoConstants); Assert.AreEqual(1, block.NoGlobalNames); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(10, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileTwoCommandsUsingSemicolon() { Parser compiler = new Parser("nil invokeWith: 10; invokeWith: 20"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(3, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(12, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); } [TestMethod] public void CompileBlockWithSourceCode() { string source = "nil invokeWith: 10; invokeWith: 20"; Parser compiler = new Parser(source); Block block = compiler.CompileBlock(); Assert.AreEqual(source, block.SourceCode); } [TestMethod] public void CompileBlock() { Parser compiler = new Parser("nil ifFalse: [self halt]"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(1, block.NoConstants); Assert.AreEqual(0, block.NoLocals); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(11, block.ByteCodes.Length); Assert.AreEqual(0, block.Arity); object constant = block.GetConstant(0); Assert.IsNotNull(constant); Assert.IsInstanceOfType(constant, typeof(Block)); var newblock = (Block)constant; Assert.AreEqual(0, newblock.Arity); Assert.AreEqual(0, newblock.NoLocals); Assert.IsNotNull(newblock.ByteCodes); Assert.AreEqual(4, newblock.ByteCodes.Length); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual("GetNil", result[0]); Assert.AreEqual("JumpIfFalse 8", result[1]); Assert.AreEqual("GetNil", result[2]); Assert.AreEqual("Jump 11", result[3]); Assert.AreEqual("GetBlock { GetSelf; Send halt 0 }", result[4]); } [TestMethod] public void CompileBlockWithParameter() { Parser compiler = new Parser(" :a | a doSomething"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoGlobalNames); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(1, block.NoConstants); Assert.AreEqual(1, block.Arity); Assert.AreEqual("a", block.GetArgumentName(0)); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(5, block.ByteCodes.Length); Assert.AreEqual(1, block.Arity); object constant = block.GetConstant(0); Assert.IsNotNull(constant); Assert.IsInstanceOfType(constant, typeof(string)); Assert.AreEqual("doSomething", constant); } [TestMethod] public void CompileBlockWithParameterWithASpace() { Parser compiler = new Parser(" : a | a doSomething"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoGlobalNames); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(1, block.NoConstants); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(5, block.ByteCodes.Length); Assert.AreEqual(1, block.Arity); object constant = block.GetConstant(0); Assert.IsNotNull(constant); Assert.IsInstanceOfType(constant, typeof(string)); Assert.AreEqual("doSomething", constant); } [TestMethod] public void CompileBlockWithTwoParameters() { Parser compiler = new Parser(" :a :b | a+b"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(0, block.NoGlobalNames); Assert.AreEqual(1, block.NoConstants); Assert.IsNotNull(block.ByteCodes); Assert.AreEqual(7, block.ByteCodes.Length); Assert.AreEqual(2, block.Arity); } [TestMethod] public void ExecuteBlock() { Machine machine = new Machine(); object nil = machine.UndefinedObjectClass; Assert.IsNotNull(nil); Assert.IsInstanceOfType(nil, typeof(IClass)); Parser compiler = new Parser("nil ifNil: [GlobalName := 'foo']"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); block.Execute(machine, null); Assert.IsNotNull(machine.GetGlobalObject("GlobalName")); } [TestMethod] public void ExecuteTrueIfFalse() { Machine machine = new Machine(); Parser compiler = new Parser("true ifFalse: [GlobalName := 'foo']"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); block.Execute(machine, null); Assert.IsNull(machine.GetGlobalObject("GlobalName")); } [TestMethod] public void ExecuteTrueIfTrueIfFalse() { Machine machine = new Machine(); Parser compiler = new Parser("true ifTrue: [GlobalName := 'bar'] ifFalse: [GlobalName := 'foo']"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); block.Execute(machine, null); Assert.AreEqual("bar", machine.GetGlobalObject("GlobalName")); } [TestMethod] public void ExecuteBasicInstSize() { Machine machine = new Machine(); object nil = machine.UndefinedObjectClass; Assert.IsNotNull(nil); Assert.IsInstanceOfType(nil, typeof(IClass)); Parser compiler = new Parser("^UndefinedObject new basicInstSize"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); object result = block.Execute(machine, null); Assert.AreEqual(0, result); } [TestMethod] public void ExecuteBasicInstSizeInRectangle() { Machine machine = new Machine(); IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" }); machine.SetGlobalObject("aRectangle", cls.NewObject()); Parser compiler = new Parser("^aRectangle basicInstSize"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); object result = block.Execute(machine, null); Assert.AreEqual(2, result); } [TestMethod] public void ExecuteBasicInstAt() { Machine machine = new Machine(); IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" }); IObject iobj = (IObject)cls.NewObject(); machine.SetGlobalObject("aRectangle", iobj); iobj[0] = 100; Parser compiler = new Parser("^aRectangle basicInstVarAt: 1"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); object result = block.Execute(machine, null); Assert.AreEqual(100, result); } [TestMethod] public void ExecuteBasicInstVarAtPut() { Machine machine = new Machine(); IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" }); IObject iobj = (IObject)cls.NewObject(); machine.SetGlobalObject("aRectangle", iobj); Parser compiler = new Parser("aRectangle basicInstVarAt: 1 put: 200"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); block.Execute(machine, null); Assert.AreEqual(200, iobj[0]); Assert.IsNull(iobj[1]); } [TestMethod] public void ExecuteNew() { Machine machine = new Machine(); IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, null); cls.DefineClassMethod(new BehaviorDoesNotUnderstandMethod(machine, cls)); machine.SetGlobalObject("Rectangle", cls); Parser compiler = new Parser("^Rectangle new"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); object obj = block.Execute(machine, null); Assert.IsNotNull(obj); Assert.IsInstanceOfType(obj, typeof(IObject)); Assert.AreEqual(cls, ((IObject)obj).Behavior); } [TestMethod] public void ExecuteRedefinedNew() { Machine machine = new Machine(); IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "initialize x := 10. y := 20" }, new string[] { "new ^self basicNew initialize" }); machine.SetGlobalObject("Rectangle", cls); Parser compiler = new Parser("^Rectangle new"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); object obj = block.Execute(machine, null); Assert.IsNotNull(obj); Assert.IsInstanceOfType(obj, typeof(IObject)); Assert.AreEqual(cls, ((IObject)obj).Behavior); IObject iobj = (IObject)obj; Assert.AreEqual(2, iobj.Behavior.NoInstanceVariables); Assert.AreEqual(10, iobj[0]); Assert.AreEqual(20, iobj[1]); } [TestMethod] public void ExecuteBasicNew() { Machine machine = new Machine(); IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, null); machine.SetGlobalObject("Rectangle", cls); Parser compiler = new Parser("^Rectangle basicNew"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); object obj = block.Execute(machine, null); Assert.IsNotNull(obj); Assert.IsInstanceOfType(obj, typeof(IObject)); Assert.AreEqual(cls, ((IObject)obj).Behavior); } [TestMethod] public void CompileMethods() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" }); Assert.IsNotNull(cls); Assert.IsNotNull(cls.GetInstanceMethod("x")); Assert.IsNotNull(cls.GetInstanceMethod("y")); Assert.IsNotNull(cls.GetInstanceMethod("x:")); Assert.IsNotNull(cls.GetInstanceMethod("y:")); } [TestMethod] public void RunMethods() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" }); Assert.IsNotNull(cls); IObject obj = (IObject)cls.NewObject(); cls.GetInstanceMethod("x:").Execute(null, obj, new object[] { 10 }); Assert.AreEqual(10, obj[0]); cls.GetInstanceMethod("y:").Execute(null, obj, new object[] { 20 }); Assert.AreEqual(20, obj[1]); Assert.AreEqual(10, cls.GetInstanceMethod("x").Execute(null, obj, new object[] { })); Assert.AreEqual(20, cls.GetInstanceMethod("y").Execute(null, obj, new object[] { })); } [TestMethod] public void CompileMultiCommandMethod() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "side: newSide x := newSide. y := newSide" }); Assert.IsNotNull(cls); Assert.IsNotNull(cls.GetInstanceMethod("side:")); } [TestMethod] public void CompileMultiCommandMethodWithLocal() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "side: newSide | temp | temp := x. x := temp. y := temp" }); Assert.IsNotNull(cls); Assert.IsNotNull(cls.GetInstanceMethod("side:")); } [TestMethod] public void CompileSameOperator() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "== aRect ^x == aRect x ifTrue: [^y == aRect y] ifFalse: [^false]" }); Assert.IsNotNull(cls); Assert.IsNotNull(cls.GetInstanceMethod("==")); } [TestMethod] public void CompileAndEvaluateInnerBlockWithClosure() { Machine machine = new Machine(); IClass cls = CompileClass( "Adder", new string[] { }, new string[] { "add: aVector | sum | sum := 0. aVector do: [ :x | sum := sum + x ]. ^sum" }); Assert.IsNotNull(cls); IMethod method = cls.GetInstanceMethod("add:"); Assert.IsNotNull(method); IObject obj = (IObject)cls.NewObject(); Assert.AreEqual(6, method.Execute(machine, obj, new object[] { new int[] { 1, 2, 3 } })); } [TestMethod] public void CompileAndEvaluateInnerBlockWithClosureUsingExternalArgument() { Machine machine = new Machine(); IClass cls = CompileClass( "Adder", new string[] { }, new string[] { "add: aVector with: aNumber | sum | sum := 0. aVector do: [ :x | sum := sum + x + aNumber ]. ^sum" }); Assert.IsNotNull(cls); IMethod method = cls.GetInstanceMethod("add:with:"); Assert.IsNotNull(method); IObject obj = (IObject)cls.NewObject(); Assert.AreEqual(9, method.Execute(machine, obj, new object[] { new int[] { 1, 2, 3 }, 1 })); } [TestMethod] public void RunMultiCommandMethod() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "side: newSide x := newSide. y := newSide" }); Assert.IsNotNull(cls); IObject obj = (IObject)cls.NewObject(); cls.GetInstanceMethod("side:").Execute(null, obj, new object[] { 10 }); Assert.AreEqual(10, obj[0]); Assert.AreEqual(10, obj[1]); } [TestMethod] public void RunMultiCommandMethodWithLocal() { IClass cls = CompileClass( "Rectangle", new string[] { "x", "y" }, new string[] { "side: newSide | temp | temp := newSide. x := temp. y := temp" }); Assert.IsNotNull(cls); IObject obj = (IObject)cls.NewObject(); cls.GetInstanceMethod("side:").Execute(null, obj, new object[] { 10 }); Assert.AreEqual(10, obj[0]); Assert.AreEqual(10, obj[1]); } [TestMethod] public void CompileSimpleSetExpression() { Parser parser = new Parser("a := 1"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); Assert.AreEqual(ByteCode.SetGlobalVariable, (ByteCode)result.ByteCodes[2]); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual("SetGlobalVariable a", ops[1]); } [TestMethod] public void CompileBlockWithLocalVariable() { Parser parser = new Parser("|a| a := 1"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual("SetLocal a", ops[1]); } [TestMethod] public void CompileBlockInBrackets() { Parser parser = new Parser("[a := 1]"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual("GetBlock { GetConstant 1; SetGlobalVariable a }", ops[0]); } [TestMethod] public void CompileIntegerArray() { Parser parser = new Parser("#(1 2 3)"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(1, ops.Count); Assert.IsTrue(ops[0].StartsWith("GetConstant ")); } [TestMethod] public void CompileSymbolArray() { Parser parser = new Parser("#(a b c)"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(1, ops.Count); Assert.IsTrue(ops[0].StartsWith("GetConstant ")); } [TestMethod] public void CompileDynamicArray() { Parser parser = new Parser("{a. b. 3}"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(4, ops.Count); Assert.AreEqual("GetGlobalVariable a", ops[0]); Assert.AreEqual("GetGlobalVariable b", ops[1]); Assert.AreEqual("GetConstant 3", ops[2]); Assert.AreEqual("MakeCollection 3", ops[3]); } [TestMethod] public void CompileDynamicArrayWithChainedExpression() { Parser parser = new Parser("{a do: 1; do: 2; yourself. b. 3}"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(11, ops.Count); Assert.AreEqual("GetGlobalVariable a", ops[0]); Assert.AreEqual("GetConstant 1", ops[1]); Assert.AreEqual("Send do: 1", ops[2]); Assert.AreEqual("ChainedSend", ops[3]); Assert.AreEqual("GetConstant 2", ops[4]); Assert.AreEqual("Send do: 1", ops[5]); Assert.AreEqual("ChainedSend", ops[6]); Assert.AreEqual("Send yourself 0", ops[7]); Assert.AreEqual("GetGlobalVariable b", ops[8]); Assert.AreEqual("GetConstant 3", ops[9]); Assert.AreEqual("MakeCollection 3", ops[10]); } [TestMethod] public void CompileSumWithNegativeNumber() { Parser parser = new Parser("-1 + 0"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(4, ops.Count); Assert.AreEqual("GetConstant 1", ops[0]); Assert.AreEqual("Send minus 0", ops[1]); Assert.AreEqual("GetConstant 0", ops[2]); Assert.AreEqual("Send + 1", ops[3]); } [TestMethod] public void CompileSimpleOr() { Parser parser = new Parser("1 | 0"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(3, ops.Count); Assert.AreEqual("GetConstant 1", ops[0]); Assert.AreEqual("GetConstant 0", ops[1]); Assert.AreEqual("Send | 1", ops[2]); } [TestMethod] public void CompileSimpleEqual() { Parser parser = new Parser("1 = 2"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(3, ops.Count); Assert.AreEqual("GetConstant 1", ops[0]); Assert.AreEqual("GetConstant 2", ops[1]); Assert.AreEqual("Send = 1", ops[2]); } [TestMethod] public void CompileSimpleAssingWithEqual() { Parser parser = new Parser("result := value = value"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(4, ops.Count); Assert.AreEqual("GetGlobalVariable value", ops[0]); Assert.AreEqual("GetGlobalVariable value", ops[1]); Assert.AreEqual("Send = 1", ops[2]); Assert.AreEqual("SetGlobalVariable result", ops[3]); } [TestMethod] public void CompileNumericPrimitive() { Parser parser = new Parser("<primitive: 60>"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(1, ops.Count); Assert.AreEqual("Primitive 60", ops[0]); } [TestMethod] public void CompileNumericPrimitiveWithError() { Parser parser = new Parser("<primitive: 60 error:ec>"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(1, ops.Count); Assert.AreEqual("PrimitiveError 60 ec", ops[0]); } [TestMethod] public void CompileNamedPrimitive() { Parser parser = new Parser("<primitive: '' module:''>"); var result = parser.CompileBlock(); Assert.IsNotNull(result); Assert.IsNotNull(result.ByteCodes); BlockDecompiler decompiler = new BlockDecompiler(result); var ops = decompiler.Decompile(); Assert.IsNotNull(ops); Assert.AreEqual(1, ops.Count); Assert.AreEqual("NamedPrimitive \"\" \"\"", ops[0]); } [TestMethod] public void CompileSimpleExpressionInParenthesis() { Parser compiler = new Parser("(1+2)"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(3, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); Assert.AreEqual("GetConstant 1", result[0]); Assert.AreEqual("GetConstant 2", result[1]); Assert.AreEqual("Send + 1", result[2]); } [TestMethod] public void CompileSimpleExpressionInParenthesisUsingYourself() { Parser compiler = new Parser("(1+2;yourself)"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(0, block.NoLocals); Assert.AreEqual(4, block.NoConstants); Assert.AreEqual(0, block.NoGlobalNames); BlockDecompiler decompiler = new BlockDecompiler(block); var result = decompiler.Decompile(); Assert.IsNotNull(result); Assert.AreEqual(5, result.Count); Assert.AreEqual("GetConstant 1", result[0]); Assert.AreEqual("GetConstant 2", result[1]); Assert.AreEqual("Send + 1", result[2]); Assert.AreEqual("ChainedSend", result[3]); Assert.AreEqual("Send yourself 0", result[4]); } [TestMethod] public void CompileGetLocalInBlock() { Parser compiler = new Parser("| env | [env at: #MyGlobal] value"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.IsTrue(block.NoConstants > 0); var result = block.GetConstant(0); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(Block)); var decompiler = new BlockDecompiler((Block)result); var steps = decompiler.Decompile(); Assert.IsTrue(steps.Contains("GetLocal env")); } [TestMethod] public void CompileDottedName() { Parser compiler = new Parser("Smalltalk.MyPackage.MyClass"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.IsTrue(block.NoConstants > 0); var decompiler = new BlockDecompiler(block); var steps = decompiler.Decompile(); Assert.IsNotNull(steps); Assert.AreEqual(5, steps.Count); Assert.AreEqual("GetGlobalVariable Smalltalk", steps[0]); Assert.AreEqual("GetConstant \"MyPackage\"", steps[1]); Assert.AreEqual("Send at: 1", steps[2]); Assert.AreEqual("GetConstant \"MyClass\"", steps[3]); Assert.AreEqual("Send at: 1", steps[4]); } [TestMethod] public void CompileBlockWithDot() { Parser compiler = new Parser("[. 1. 2]"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); } [TestMethod] public void CompileSuperNew() { Parser compiler = new Parser("new super new"); Block block = compiler.CompileInstanceMethod(null); Assert.IsNotNull(block); var decompiler = new BlockDecompiler(block); var steps = decompiler.Decompile(); Assert.IsNotNull(steps); Assert.AreEqual(2, steps.Count); Assert.AreEqual("GetSuper", steps[0]); Assert.AreEqual("Send new 0", steps[1]); } [TestMethod] public void CompileWhileFalse() { Parser compiler = new Parser(":arg | [arg < 3] whileFalse: [arg := arg + 1]"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(13, block.Bytecodes.Length); var decompiler = new BlockDecompiler(block); var steps = decompiler.Decompile(); Assert.IsNotNull(steps); Assert.AreEqual(7, steps.Count); Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 3; Send < 1 }", steps[0]); Assert.AreEqual("Value", steps[1]); Assert.AreEqual("JumpIfTrue 13", steps[2]); Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 1; Send + 1; SetArgument arg }", steps[3]); Assert.AreEqual("Value", steps[4]); Assert.AreEqual("Pop", steps[5]); Assert.AreEqual("Jump 0", steps[6]); } [TestMethod] public void CompileWhileTrue() { Parser compiler = new Parser(":arg | [arg < 3] whileTrue: [arg := arg + 1]"); Block block = compiler.CompileBlock(); Assert.IsNotNull(block); Assert.AreEqual(13, block.Bytecodes.Length); var decompiler = new BlockDecompiler(block); var steps = decompiler.Decompile(); Assert.IsNotNull(steps); Assert.AreEqual(7, steps.Count); Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 3; Send < 1 }", steps[0]); Assert.AreEqual("Value", steps[1]); Assert.AreEqual("JumpIfFalse 13", steps[2]); Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 1; Send + 1; SetArgument arg }", steps[3]); Assert.AreEqual("Value", steps[4]); Assert.AreEqual("Pop", steps[5]); Assert.AreEqual("Jump 0", steps[6]); } internal static IClass CompileClass(string clsname, string[] varnames, string[] methods) { return CompileClass(clsname, varnames, methods, null); } internal static IClass CompileClass(string clsname, string[] varnames, string[] methods, string[] clsmethods) { Machine machine = new Machine(); IClass cls = machine.CreateClass(clsname); if (varnames != null) { foreach (string varname in varnames) { cls.DefineInstanceVariable(varname); } } if (methods != null) { foreach (string method in methods) { Parser compiler = new Parser(method); cls.DefineInstanceMethod(compiler.CompileInstanceMethod(cls)); } } if (clsmethods != null) { foreach (string method in clsmethods) { Parser compiler = new Parser(method); cls.DefineClassMethod(compiler.CompileClassMethod(cls)); } } return cls; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Flavor; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; using IServiceProvider = System.IServiceProvider; namespace Microsoft.PythonTools.Project.Web { [Guid("742BB562-7AEE-4FC7-8CD2-48D66C8CC435")] partial class PythonWebProject : FlavoredProjectBase, IOleCommandTarget, IVsProjectFlavorCfgProvider, IVsProject, IVsFilterAddProjectItemDlg { private readonly IServiceProvider _site; internal IVsProject _innerProject; internal IVsProject3 _innerProject3; private IVsProjectFlavorCfgProvider _innerVsProjectFlavorCfgProvider; private static readonly Guid PythonProjectGuid = new Guid(PythonConstants.ProjectFactoryGuid); private IOleCommandTarget _menuService; private static readonly Guid PublishCmdGuid = new Guid("{1496a755-94de-11d0-8c3f-00c04fc2aae2}"); private static readonly int PublishCmdid = 2006; public PythonWebProject(IServiceProvider site) { _site = site; } #region IVsAggregatableProject /// <summary> /// Do the initialization here (such as loading flavor specific /// information from the project) /// </summary> protected override void InitializeForOuter(string fileName, string location, string name, uint flags, ref Guid guidProject, out bool cancel) { base.InitializeForOuter(fileName, location, name, flags, ref guidProject, out cancel); var proj = _innerVsHierarchy.GetProject(); if (proj != null) { try { dynamic webAppExtender = proj.get_Extender("WebApplication"); if (webAppExtender != null) { webAppExtender.StartWebServerOnDebug = false; } } catch (COMException) { // extender doesn't exist... } } } #endregion protected override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == GuidList.guidOfficeSharePointCmdSet) { for (int i = 0; i < prgCmds.Length; i++) { // Report it as supported so that it's not routed any // further, but disable it and make it invisible. prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE); } return VSConstants.S_OK; } return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } protected override void SetInnerProject(IntPtr innerIUnknown) { var inner = Marshal.GetObjectForIUnknown(innerIUnknown); // The reason why we keep a reference to those is that doing a QI after being // aggregated would do the AddRef on the outer object. _innerVsProjectFlavorCfgProvider = inner as IVsProjectFlavorCfgProvider; _innerProject = inner as IVsProject; _innerProject3 = inner as IVsProject3; _innerVsHierarchy = inner as IVsHierarchy; if (serviceProvider == null) { serviceProvider = _site; } // Now let the base implementation set the inner object base.SetInnerProject(innerIUnknown); // Get access to the menu service used by FlavoredProjectBase. We // need to forward IOleCommandTarget functions to this object, since // we override the FlavoredProjectBase implementation with no way to // call it directory. // (This must run after we called base.SetInnerProject) _menuService = (IOleCommandTarget)((IServiceProvider)this).GetService(typeof(IMenuCommandService)); if (_menuService == null) { throw new InvalidOperationException("Cannot initialize Web project"); } } protected override int GetProperty(uint itemId, int propId, out object property) { switch ((__VSHPROPID2)propId) { case __VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList: { var res = base.GetProperty(itemId, propId, out property); if (ErrorHandler.Succeeded(res)) { var guids = GetGuidsFromList(property as string); guids.RemoveAll(g => CfgSpecificPropertyPagesToRemove.Contains(g)); guids.AddRange(CfgSpecificPropertyPagesToAdd); property = MakeListFromGuids(guids); } return res; } case __VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList: { var res = base.GetProperty(itemId, propId, out property); if (ErrorHandler.Succeeded(res)) { var guids = GetGuidsFromList(property as string); guids.RemoveAll(g => PropertyPagesToRemove.Contains(g)); guids.AddRange(PropertyPagesToAdd); property = MakeListFromGuids(guids); } return res; } } var id8 = (__VSHPROPID8)propId; switch(id8) { case __VSHPROPID8.VSHPROPID_SupportsIconMonikers: property = true; return VSConstants.S_OK; } return base.GetProperty(itemId, propId, out property); } private static Guid[] PropertyPagesToAdd = new[] { new Guid(PythonConstants.WebPropertyPageGuid) }; private static Guid[] CfgSpecificPropertyPagesToAdd = new Guid[0]; private static HashSet<Guid> PropertyPagesToRemove = new HashSet<Guid> { new Guid("{8C0201FE-8ECA-403C-92A3-1BC55F031979}"), // typeof(DeployPropertyPageComClass) new Guid("{ED3B544C-26D8-4348-877B-A1F7BD505ED9}"), // typeof(DatabaseDeployPropertyPageComClass) new Guid("{909D16B3-C8E8-43D1-A2B8-26EA0D4B6B57}"), // Microsoft.VisualStudio.Web.Application.WebPropertyPage new Guid("{379354F2-BBB3-4BA9-AA71-FBE7B0E5EA94}"), // Microsoft.VisualStudio.Web.Application.SilverlightLinksPage }; internal static HashSet<Guid> CfgSpecificPropertyPagesToRemove = new HashSet<Guid> { new Guid("{A553AD0B-2F9E-4BCE-95B3-9A1F7074BC27}"), // Package/Publish Web new Guid("{9AB2347D-948D-4CD2-8DBE-F15F0EF78ED3}"), // Package/Publish SQL }; private static List<Guid> GetGuidsFromList(string guidList) { if (string.IsNullOrEmpty(guidList)) { return new List<Guid>(); } Guid value; return guidList.Split(';') .Select(str => Guid.TryParse(str, out value) ? (Guid?)value : null) .Where(g => g.HasValue) .Select(g => g.Value) .ToList(); } private static string MakeListFromGuids(IEnumerable<Guid> guidList) { return string.Join(";", guidList.Select(g => g.ToString("B"))); } int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == GuidList.guidWebPackgeCmdId) { if (nCmdID == 0x101 /* EnablePublishToWindowsAzureMenuItem*/) { var shell = (IVsShell)((IServiceProvider)this).GetService(typeof(SVsShell)); var webPublishPackageGuid = GuidList.guidWebPackageGuid; IVsPackage package; int res = shell.LoadPackage(ref webPublishPackageGuid, out package); if (!ErrorHandler.Succeeded(res)) { return res; } var cmdTarget = package as IOleCommandTarget; if (cmdTarget != null) { res = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); if (ErrorHandler.Succeeded(res)) { // TODO: Check flag to see if we were notified // about being added as a web role. if (!AddWebRoleSupportFiles()) { VsShellUtilities.ShowMessageBox( this, Strings.AddWebRoleSupportFiles, null, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST ); } } return res; } } } else if (pguidCmdGroup == PublishCmdGuid) { if (nCmdID == PublishCmdid) { // Approximately duplicated in DjangoProject var opts = _site.GetPythonToolsService().SuppressDialogOptions; if (string.IsNullOrEmpty(opts.PublishToAzure30)) { var td = new TaskDialog(_site) { Title = Strings.ProductTitle, MainInstruction = Strings.PublishToAzure30, Content = Strings.PublishToAzure30Message, VerificationText = Strings.DontShowAgain, SelectedVerified = false, AllowCancellation = true, EnableHyperlinks = true }; td.Buttons.Add(TaskDialogButton.OK); td.Buttons.Add(TaskDialogButton.Cancel); if (td.ShowModal() == TaskDialogButton.Cancel) { return VSConstants.S_OK; } if (td.SelectedVerified) { opts.PublishToAzure30 = "true"; opts.Save(); } } } } return _menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } private bool AddWebRoleSupportFiles() { var uiShell = (IVsUIShell)((IServiceProvider)this).GetService(typeof(SVsUIShell)); var emptyGuid = Guid.Empty; var result = new[] { VSADDRESULT.ADDRESULT_Failure }; IntPtr dlgOwner; if (ErrorHandler.Failed(uiShell.GetDialogOwnerHwnd(out dlgOwner))) { dlgOwner = IntPtr.Zero; } var fullTemplate = ((EnvDTE80.Solution2)this.GetDTE().Solution).GetProjectItemTemplate( "AzureCSWebRole.zip", PythonConstants.LanguageName ); return ErrorHandler.Succeeded(_innerProject3.AddItemWithSpecific( (uint)VSConstants.VSITEMID.Root, VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD, "bin", 1, new[] { fullTemplate }, dlgOwner, 0u, ref emptyGuid, string.Empty, ref emptyGuid, result )) && result[0] == VSADDRESULT.ADDRESULT_Success; } int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == GuidList.guidEureka) { for (int i = 0; i < prgCmds.Length; i++) { switch (prgCmds[i].cmdID) { case 0x102: // View in Web Page Inspector from Eureka web tools prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == GuidList.guidVenusCmdId) { for (int i = 0; i < prgCmds.Length; i++) { switch (prgCmds[i].cmdID) { case 0x034: /* add app assembly folder */ case 0x035: /* add app code folder */ case 0x036: /* add global resources */ case 0x037: /* add local resources */ case 0x038: /* add web refs folder */ case 0x039: /* add data folder */ case 0x040: /* add browser folders */ case 0x041: /* theme */ case 0x054: /* package settings */ case 0x055: /* context package settings */ prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == GuidList.guidWebAppCmdId) { for (int i = 0; i < prgCmds.Length; i++) { switch (prgCmds[i].cmdID) { case 0x06A: /* check accessibility */ prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == VSConstants.VSStd2K) { for (int i = 0; i < prgCmds.Length; i++) { switch ((VSConstants.VSStd2KCmdID)prgCmds[i].cmdID) { case VSConstants.VSStd2KCmdID.SETASSTARTPAGE: case VSConstants.VSStd2KCmdID.CHECK_ACCESSIBILITY: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { for (int i = 0; i < prgCmds.Length; i++) { switch ((VSConstants.VSStd97CmdID)prgCmds[i].cmdID) { case VSConstants.VSStd97CmdID.PreviewInBrowser: case VSConstants.VSStd97CmdID.BrowseWith: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } return _menuService.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } #region IVsProjectFlavorCfgProvider Members public int CreateProjectFlavorCfg(IVsCfg pBaseProjectCfg, out IVsProjectFlavorCfg ppFlavorCfg) { // We're flavored with a Web Application project and our normal // project... But we don't want the web application project to // influence our config as that alters our debug launch story. We // control that w/ the web project which is actually just letting // the base Python project handle it. So we keep the base Python // project config here. IVsProjectFlavorCfg webCfg; ErrorHandler.ThrowOnFailure( _innerVsProjectFlavorCfgProvider.CreateProjectFlavorCfg( pBaseProjectCfg, out webCfg ) ); ppFlavorCfg = new PythonWebProjectConfig(pBaseProjectCfg, webCfg); return VSConstants.S_OK; } #endregion #region IVsProject Members int IVsProject.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen, string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult) { return _innerProject.AddItem(itemidLoc, dwAddItemOperation, pszItemName, cFilesToOpen, rgpszFilesToOpen, hwndDlgOwner, pResult); } int IVsProject.GenerateUniqueItemName(uint itemidLoc, string pszExt, string pszSuggestedRoot, out string pbstrItemName) { return _innerProject.GenerateUniqueItemName(itemidLoc, pszExt, pszSuggestedRoot, out pbstrItemName); } int IVsProject.GetItemContext(uint itemid, out VisualStudio.OLE.Interop.IServiceProvider ppSP) { return _innerProject.GetItemContext(itemid, out ppSP); } int IVsProject.GetMkDocument(uint itemid, out string pbstrMkDocument) { return _innerProject.GetMkDocument(itemid, out pbstrMkDocument); } int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid) { return _innerProject.IsDocumentInProject(pszMkDocument, out pfFound, pdwPriority, out pitemid); } int IVsProject.OpenItem(uint itemid, ref Guid rguidLogicalView, IntPtr punkDocDataExisting, out IVsWindowFrame ppWindowFrame) { return _innerProject.OpenItem(itemid, rguidLogicalView, punkDocDataExisting, out ppWindowFrame); } #endregion #region IVsFilterAddProjectItemDlg Members int IVsFilterAddProjectItemDlg.FilterListItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) { pfFilter = 0; return VSConstants.S_OK; } int IVsFilterAddProjectItemDlg.FilterListItemByTemplateFile(ref Guid rguidProjectItemTemplates, string pszTemplateFile, out int pfFilter) { pfFilter = 0; return VSConstants.S_OK; } int IVsFilterAddProjectItemDlg.FilterTreeItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) { pfFilter = 0; return VSConstants.S_OK; } int IVsFilterAddProjectItemDlg.FilterTreeItemByTemplateDir(ref Guid rguidProjectItemTemplates, string pszTemplateDir, out int pfFilter) { // https://pytools.codeplex.com/workitem/1313 // ASP.NET will filter some things out, including .css files, which we don't want it to do. // So we shut that down by not forwarding this to any inner projects, which is fine, because // Python projects don't implement this interface either. pfFilter = 0; return VSConstants.S_OK; } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/logging/v2/logging.proto // Original file comments: // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Logging.V2 { /// <summary> /// Service for ingesting and querying logs. /// </summary> public static partial class LoggingServiceV2 { static readonly string __ServiceName = "google.logging.v2.LoggingServiceV2"; static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.DeleteLogRequest> __Marshaller_DeleteLogRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.DeleteLogRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.WriteLogEntriesRequest> __Marshaller_WriteLogEntriesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.WriteLogEntriesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.WriteLogEntriesResponse> __Marshaller_WriteLogEntriesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.WriteLogEntriesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogEntriesRequest> __Marshaller_ListLogEntriesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogEntriesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogEntriesResponse> __Marshaller_ListLogEntriesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogEntriesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest> __Marshaller_ListMonitoredResourceDescriptorsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse> __Marshaller_ListMonitoredResourceDescriptorsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogsRequest> __Marshaller_ListLogsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogsResponse> __Marshaller_ListLogsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogsResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Logging.V2.DeleteLogRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteLog = new grpc::Method<global::Google.Cloud.Logging.V2.DeleteLogRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteLog", __Marshaller_DeleteLogRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.Logging.V2.WriteLogEntriesRequest, global::Google.Cloud.Logging.V2.WriteLogEntriesResponse> __Method_WriteLogEntries = new grpc::Method<global::Google.Cloud.Logging.V2.WriteLogEntriesRequest, global::Google.Cloud.Logging.V2.WriteLogEntriesResponse>( grpc::MethodType.Unary, __ServiceName, "WriteLogEntries", __Marshaller_WriteLogEntriesRequest, __Marshaller_WriteLogEntriesResponse); static readonly grpc::Method<global::Google.Cloud.Logging.V2.ListLogEntriesRequest, global::Google.Cloud.Logging.V2.ListLogEntriesResponse> __Method_ListLogEntries = new grpc::Method<global::Google.Cloud.Logging.V2.ListLogEntriesRequest, global::Google.Cloud.Logging.V2.ListLogEntriesResponse>( grpc::MethodType.Unary, __ServiceName, "ListLogEntries", __Marshaller_ListLogEntriesRequest, __Marshaller_ListLogEntriesResponse); static readonly grpc::Method<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest, global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse> __Method_ListMonitoredResourceDescriptors = new grpc::Method<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest, global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse>( grpc::MethodType.Unary, __ServiceName, "ListMonitoredResourceDescriptors", __Marshaller_ListMonitoredResourceDescriptorsRequest, __Marshaller_ListMonitoredResourceDescriptorsResponse); static readonly grpc::Method<global::Google.Cloud.Logging.V2.ListLogsRequest, global::Google.Cloud.Logging.V2.ListLogsResponse> __Method_ListLogs = new grpc::Method<global::Google.Cloud.Logging.V2.ListLogsRequest, global::Google.Cloud.Logging.V2.ListLogsResponse>( grpc::MethodType.Unary, __ServiceName, "ListLogs", __Marshaller_ListLogsRequest, __Marshaller_ListLogsResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of LoggingServiceV2</summary> public abstract partial class LoggingServiceV2Base { /// <summary> /// Deletes all the log entries in a log. /// The log reappears if it receives new entries. /// Log entries written shortly before the delete operation might not be /// deleted. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLog(global::Google.Cloud.Logging.V2.DeleteLogRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// ## Log entry resources /// /// Writes log entries to Stackdriver Logging. This API method is the /// only way to send log entries to Stackdriver Logging. This method /// is used, directly or indirectly, by the Stackdriver Logging agent /// (fluentd) and all logging libraries configured to use Stackdriver /// Logging. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.WriteLogEntriesResponse> WriteLogEntries(global::Google.Cloud.Logging.V2.WriteLogEntriesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists log entries. Use this method to retrieve log entries from /// Stackdriver Logging. For ways to export log entries, see /// [Exporting Logs](/logging/docs/export). /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.ListLogEntriesResponse> ListLogEntries(global::Google.Cloud.Logging.V2.ListLogEntriesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists the descriptors for monitored resource types used by Stackdriver /// Logging. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptors(global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists the logs in projects, organizations, folders, or billing accounts. /// Only logs that have entries are listed. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.ListLogsResponse> ListLogs(global::Google.Cloud.Logging.V2.ListLogsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for LoggingServiceV2</summary> public partial class LoggingServiceV2Client : grpc::ClientBase<LoggingServiceV2Client> { /// <summary>Creates a new client for LoggingServiceV2</summary> /// <param name="channel">The channel to use to make remote calls.</param> public LoggingServiceV2Client(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for LoggingServiceV2 that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public LoggingServiceV2Client(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected LoggingServiceV2Client() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected LoggingServiceV2Client(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Deletes all the log entries in a log. /// The log reappears if it receives new entries. /// Log entries written shortly before the delete operation might not be /// deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLog(global::Google.Cloud.Logging.V2.DeleteLogRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteLog(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes all the log entries in a log. /// The log reappears if it receives new entries. /// Log entries written shortly before the delete operation might not be /// deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLog(global::Google.Cloud.Logging.V2.DeleteLogRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteLog, null, options, request); } /// <summary> /// Deletes all the log entries in a log. /// The log reappears if it receives new entries. /// Log entries written shortly before the delete operation might not be /// deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogAsync(global::Google.Cloud.Logging.V2.DeleteLogRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteLogAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes all the log entries in a log. /// The log reappears if it receives new entries. /// Log entries written shortly before the delete operation might not be /// deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogAsync(global::Google.Cloud.Logging.V2.DeleteLogRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteLog, null, options, request); } /// <summary> /// ## Log entry resources /// /// Writes log entries to Stackdriver Logging. This API method is the /// only way to send log entries to Stackdriver Logging. This method /// is used, directly or indirectly, by the Stackdriver Logging agent /// (fluentd) and all logging libraries configured to use Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.WriteLogEntriesResponse WriteLogEntries(global::Google.Cloud.Logging.V2.WriteLogEntriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return WriteLogEntries(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// ## Log entry resources /// /// Writes log entries to Stackdriver Logging. This API method is the /// only way to send log entries to Stackdriver Logging. This method /// is used, directly or indirectly, by the Stackdriver Logging agent /// (fluentd) and all logging libraries configured to use Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.WriteLogEntriesResponse WriteLogEntries(global::Google.Cloud.Logging.V2.WriteLogEntriesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_WriteLogEntries, null, options, request); } /// <summary> /// ## Log entry resources /// /// Writes log entries to Stackdriver Logging. This API method is the /// only way to send log entries to Stackdriver Logging. This method /// is used, directly or indirectly, by the Stackdriver Logging agent /// (fluentd) and all logging libraries configured to use Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.WriteLogEntriesResponse> WriteLogEntriesAsync(global::Google.Cloud.Logging.V2.WriteLogEntriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return WriteLogEntriesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// ## Log entry resources /// /// Writes log entries to Stackdriver Logging. This API method is the /// only way to send log entries to Stackdriver Logging. This method /// is used, directly or indirectly, by the Stackdriver Logging agent /// (fluentd) and all logging libraries configured to use Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.WriteLogEntriesResponse> WriteLogEntriesAsync(global::Google.Cloud.Logging.V2.WriteLogEntriesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_WriteLogEntries, null, options, request); } /// <summary> /// Lists log entries. Use this method to retrieve log entries from /// Stackdriver Logging. For ways to export log entries, see /// [Exporting Logs](/logging/docs/export). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.ListLogEntriesResponse ListLogEntries(global::Google.Cloud.Logging.V2.ListLogEntriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogEntries(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists log entries. Use this method to retrieve log entries from /// Stackdriver Logging. For ways to export log entries, see /// [Exporting Logs](/logging/docs/export). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.ListLogEntriesResponse ListLogEntries(global::Google.Cloud.Logging.V2.ListLogEntriesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListLogEntries, null, options, request); } /// <summary> /// Lists log entries. Use this method to retrieve log entries from /// Stackdriver Logging. For ways to export log entries, see /// [Exporting Logs](/logging/docs/export). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogEntriesResponse> ListLogEntriesAsync(global::Google.Cloud.Logging.V2.ListLogEntriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogEntriesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists log entries. Use this method to retrieve log entries from /// Stackdriver Logging. For ways to export log entries, see /// [Exporting Logs](/logging/docs/export). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogEntriesResponse> ListLogEntriesAsync(global::Google.Cloud.Logging.V2.ListLogEntriesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListLogEntries, null, options, request); } /// <summary> /// Lists the descriptors for monitored resource types used by Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMonitoredResourceDescriptors(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the descriptors for monitored resource types used by Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request); } /// <summary> /// Lists the descriptors for monitored resource types used by Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMonitoredResourceDescriptorsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the descriptors for monitored resource types used by Stackdriver /// Logging. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Cloud.Logging.V2.ListMonitoredResourceDescriptorsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request); } /// <summary> /// Lists the logs in projects, organizations, folders, or billing accounts. /// Only logs that have entries are listed. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.ListLogsResponse ListLogs(global::Google.Cloud.Logging.V2.ListLogsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogs(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the logs in projects, organizations, folders, or billing accounts. /// Only logs that have entries are listed. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Logging.V2.ListLogsResponse ListLogs(global::Google.Cloud.Logging.V2.ListLogsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListLogs, null, options, request); } /// <summary> /// Lists the logs in projects, organizations, folders, or billing accounts. /// Only logs that have entries are listed. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogsResponse> ListLogsAsync(global::Google.Cloud.Logging.V2.ListLogsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the logs in projects, organizations, folders, or billing accounts. /// Only logs that have entries are listed. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogsResponse> ListLogsAsync(global::Google.Cloud.Logging.V2.ListLogsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListLogs, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override LoggingServiceV2Client NewInstance(ClientBaseConfiguration configuration) { return new LoggingServiceV2Client(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(LoggingServiceV2Base serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_DeleteLog, serviceImpl.DeleteLog) .AddMethod(__Method_WriteLogEntries, serviceImpl.WriteLogEntries) .AddMethod(__Method_ListLogEntries, serviceImpl.ListLogEntries) .AddMethod(__Method_ListMonitoredResourceDescriptors, serviceImpl.ListMonitoredResourceDescriptors) .AddMethod(__Method_ListLogs, serviceImpl.ListLogs).Build(); } } } #endregion
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/longrunning/operations.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 Google.Longrunning { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Operations { #region Descriptor public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static Operations() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiNnb29nbGUvbG9uZ3J1bm5pbmcvb3BlcmF0aW9ucy5wcm90bxISZ29vZ2xl", "LmxvbmdydW5uaW5nGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvGhln", "b29nbGUvcHJvdG9idWYvYW55LnByb3RvGhtnb29nbGUvcHJvdG9idWYvZW1w", "dHkucHJvdG8aF2dvb2dsZS9ycGMvc3RhdHVzLnByb3RvIqgBCglPcGVyYXRp", "b24SDAoEbmFtZRgBIAEoCRImCghtZXRhZGF0YRgCIAEoCzIULmdvb2dsZS5w", "cm90b2J1Zi5BbnkSDAoEZG9uZRgDIAEoCBIjCgVlcnJvchgEIAEoCzISLmdv", "b2dsZS5ycGMuU3RhdHVzSAASKAoIcmVzcG9uc2UYBSABKAsyFC5nb29nbGUu", "cHJvdG9idWYuQW55SABCCAoGcmVzdWx0IiMKE0dldE9wZXJhdGlvblJlcXVl", "c3QSDAoEbmFtZRgBIAEoCSJcChVMaXN0T3BlcmF0aW9uc1JlcXVlc3QSDAoE", "bmFtZRgEIAEoCRIOCgZmaWx0ZXIYASABKAkSEQoJcGFnZV9zaXplGAIgASgF", "EhIKCnBhZ2VfdG9rZW4YAyABKAkiZAoWTGlzdE9wZXJhdGlvbnNSZXNwb25z", "ZRIxCgpvcGVyYXRpb25zGAEgAygLMh0uZ29vZ2xlLmxvbmdydW5uaW5nLk9w", "ZXJhdGlvbhIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkiJgoWQ2FuY2VsT3Bl", "cmF0aW9uUmVxdWVzdBIMCgRuYW1lGAEgASgJIiYKFkRlbGV0ZU9wZXJhdGlv", "blJlcXVlc3QSDAoEbmFtZRgBIAEoCTKMBAoKT3BlcmF0aW9ucxJ4CgxHZXRP", "cGVyYXRpb24SJy5nb29nbGUubG9uZ3J1bm5pbmcuR2V0T3BlcmF0aW9uUmVx", "dWVzdBodLmdvb2dsZS5sb25ncnVubmluZy5PcGVyYXRpb24iIILT5JMCGhIY", "L3YxL3tuYW1lPW9wZXJhdGlvbnMvKip9EoYBCg5MaXN0T3BlcmF0aW9ucxIp", "Lmdvb2dsZS5sb25ncnVubmluZy5MaXN0T3BlcmF0aW9uc1JlcXVlc3QaKi5n", "b29nbGUubG9uZ3J1bm5pbmcuTGlzdE9wZXJhdGlvbnNSZXNwb25zZSIdgtPk", "kwIXEhUvdjEve25hbWU9b3BlcmF0aW9uc30SgQEKD0NhbmNlbE9wZXJhdGlv", "bhIqLmdvb2dsZS5sb25ncnVubmluZy5DYW5jZWxPcGVyYXRpb25SZXF1ZXN0", "GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IiqC0+STAiQiHy92MS97bmFtZT1v", "cGVyYXRpb25zLyoqfTpjYW5jZWw6ASoSdwoPRGVsZXRlT3BlcmF0aW9uEiou", "Z29vZ2xlLmxvbmdydW5uaW5nLkRlbGV0ZU9wZXJhdGlvblJlcXVlc3QaFi5n", "b29nbGUucHJvdG9idWYuRW1wdHkiIILT5JMCGioYL3YxL3tuYW1lPW9wZXJh", "dGlvbnMvKip9QisKFmNvbS5nb29nbGUubG9uZ3J1bm5pbmdCD09wZXJhdGlv", "bnNQcm90b1ABYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.Annotations.Descriptor, global::Google.Protobuf.Proto.Any.Descriptor, global::Google.Protobuf.Proto.Empty.Descriptor, global::Google.Rpc.Proto.Status.Descriptor, }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Longrunning.Operation), new[]{ "Name", "Metadata", "Done", "Error", "Response" }, new[]{ "Result" }, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Longrunning.GetOperationRequest), new[]{ "Name" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Longrunning.ListOperationsRequest), new[]{ "Name", "Filter", "PageSize", "PageToken" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Longrunning.ListOperationsResponse), new[]{ "Operations", "NextPageToken" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Longrunning.CancelOperationRequest), new[]{ "Name" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Longrunning.DeleteOperationRequest), new[]{ "Name" }, null, null, null) })); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Operation : pb::IMessage<Operation> { private static readonly pb::MessageParser<Operation> _parser = new pb::MessageParser<Operation>(() => new Operation()); public static pb::MessageParser<Operation> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Longrunning.Proto.Operations.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Operation() { OnConstruction(); } partial void OnConstruction(); public Operation(Operation other) : this() { name_ = other.name_; Metadata = other.metadata_ != null ? other.Metadata.Clone() : null; done_ = other.done_; switch (other.ResultCase) { case ResultOneofCase.Error: Error = other.Error.Clone(); break; case ResultOneofCase.Response: Response = other.Response.Clone(); break; } } public Operation Clone() { return new Operation(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int MetadataFieldNumber = 2; private global::Google.Protobuf.Any metadata_; public global::Google.Protobuf.Any Metadata { get { return metadata_; } set { metadata_ = value; } } public const int DoneFieldNumber = 3; private bool done_; public bool Done { get { return done_; } set { done_ = value; } } public const int ErrorFieldNumber = 4; public global::Google.Rpc.Status Error { get { return resultCase_ == ResultOneofCase.Error ? (global::Google.Rpc.Status) result_ : null; } set { result_ = value; resultCase_ = value == null ? ResultOneofCase.None : ResultOneofCase.Error; } } public const int ResponseFieldNumber = 5; public global::Google.Protobuf.Any Response { get { return resultCase_ == ResultOneofCase.Response ? (global::Google.Protobuf.Any) result_ : null; } set { result_ = value; resultCase_ = value == null ? ResultOneofCase.None : ResultOneofCase.Response; } } private object result_; public enum ResultOneofCase { None = 0, Error = 4, Response = 5, } private ResultOneofCase resultCase_ = ResultOneofCase.None; public ResultOneofCase ResultCase { get { return resultCase_; } } public void ClearResult() { resultCase_ = ResultOneofCase.None; result_ = null; } public override bool Equals(object other) { return Equals(other as Operation); } public bool Equals(Operation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Metadata, other.Metadata)) return false; if (Done != other.Done) return false; if (!object.Equals(Error, other.Error)) return false; if (!object.Equals(Response, other.Response)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (metadata_ != null) hash ^= Metadata.GetHashCode(); if (Done != false) hash ^= Done.GetHashCode(); if (resultCase_ == ResultOneofCase.Error) hash ^= Error.GetHashCode(); if (resultCase_ == ResultOneofCase.Response) hash ^= Response.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (metadata_ != null) { output.WriteRawTag(18); output.WriteMessage(Metadata); } if (Done != false) { output.WriteRawTag(24); output.WriteBool(Done); } if (resultCase_ == ResultOneofCase.Error) { output.WriteRawTag(34); output.WriteMessage(Error); } if (resultCase_ == ResultOneofCase.Response) { output.WriteRawTag(42); output.WriteMessage(Response); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (metadata_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata); } if (Done != false) { size += 1 + 1; } if (resultCase_ == ResultOneofCase.Error) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Error); } if (resultCase_ == ResultOneofCase.Response) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Response); } return size; } public void MergeFrom(Operation other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.metadata_ != null) { if (metadata_ == null) { metadata_ = new global::Google.Protobuf.Any(); } Metadata.MergeFrom(other.Metadata); } if (other.Done != false) { Done = other.Done; } switch (other.ResultCase) { case ResultOneofCase.Error: Error = other.Error; break; case ResultOneofCase.Response: Response = other.Response; break; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (metadata_ == null) { metadata_ = new global::Google.Protobuf.Any(); } input.ReadMessage(metadata_); break; } case 24: { Done = input.ReadBool(); break; } case 34: { global::Google.Rpc.Status subBuilder = new global::Google.Rpc.Status(); if (resultCase_ == ResultOneofCase.Error) { subBuilder.MergeFrom(Error); } input.ReadMessage(subBuilder); Error = subBuilder; break; } case 42: { global::Google.Protobuf.Any subBuilder = new global::Google.Protobuf.Any(); if (resultCase_ == ResultOneofCase.Response) { subBuilder.MergeFrom(Response); } input.ReadMessage(subBuilder); Response = subBuilder; break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class GetOperationRequest : pb::IMessage<GetOperationRequest> { private static readonly pb::MessageParser<GetOperationRequest> _parser = new pb::MessageParser<GetOperationRequest>(() => new GetOperationRequest()); public static pb::MessageParser<GetOperationRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Longrunning.Proto.Operations.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public GetOperationRequest() { OnConstruction(); } partial void OnConstruction(); public GetOperationRequest(GetOperationRequest other) : this() { name_ = other.name_; } public GetOperationRequest Clone() { return new GetOperationRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as GetOperationRequest); } public bool Equals(GetOperationRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(GetOperationRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ListOperationsRequest : pb::IMessage<ListOperationsRequest> { private static readonly pb::MessageParser<ListOperationsRequest> _parser = new pb::MessageParser<ListOperationsRequest>(() => new ListOperationsRequest()); public static pb::MessageParser<ListOperationsRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Longrunning.Proto.Operations.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ListOperationsRequest() { OnConstruction(); } partial void OnConstruction(); public ListOperationsRequest(ListOperationsRequest other) : this() { name_ = other.name_; filter_ = other.filter_; pageSize_ = other.pageSize_; pageToken_ = other.pageToken_; } public ListOperationsRequest Clone() { return new ListOperationsRequest(this); } public const int NameFieldNumber = 4; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int FilterFieldNumber = 1; private string filter_ = ""; public string Filter { get { return filter_; } set { filter_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int PageSizeFieldNumber = 2; private int pageSize_; public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } public const int PageTokenFieldNumber = 3; private string pageToken_ = ""; public string PageToken { get { return pageToken_; } set { pageToken_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as ListOperationsRequest); } public bool Equals(ListOperationsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Filter != other.Filter) return false; if (PageSize != other.PageSize) return false; if (PageToken != other.PageToken) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Filter.Length != 0) hash ^= Filter.GetHashCode(); if (PageSize != 0) hash ^= PageSize.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Filter.Length != 0) { output.WriteRawTag(10); output.WriteString(Filter); } if (PageSize != 0) { output.WriteRawTag(16); output.WriteInt32(PageSize); } if (PageToken.Length != 0) { output.WriteRawTag(26); output.WriteString(PageToken); } if (Name.Length != 0) { output.WriteRawTag(34); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Filter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter); } if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } return size; } public void MergeFrom(ListOperationsRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Filter.Length != 0) { Filter = other.Filter; } if (other.PageSize != 0) { PageSize = other.PageSize; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Filter = input.ReadString(); break; } case 16: { PageSize = input.ReadInt32(); break; } case 26: { PageToken = input.ReadString(); break; } case 34: { Name = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ListOperationsResponse : pb::IMessage<ListOperationsResponse> { private static readonly pb::MessageParser<ListOperationsResponse> _parser = new pb::MessageParser<ListOperationsResponse>(() => new ListOperationsResponse()); public static pb::MessageParser<ListOperationsResponse> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Longrunning.Proto.Operations.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ListOperationsResponse() { OnConstruction(); } partial void OnConstruction(); public ListOperationsResponse(ListOperationsResponse other) : this() { operations_ = other.operations_.Clone(); nextPageToken_ = other.nextPageToken_; } public ListOperationsResponse Clone() { return new ListOperationsResponse(this); } public const int OperationsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Longrunning.Operation> _repeated_operations_codec = pb::FieldCodec.ForMessage(10, global::Google.Longrunning.Operation.Parser); private readonly pbc::RepeatedField<global::Google.Longrunning.Operation> operations_ = new pbc::RepeatedField<global::Google.Longrunning.Operation>(); public pbc::RepeatedField<global::Google.Longrunning.Operation> Operations { get { return operations_; } } public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as ListOperationsResponse); } public bool Equals(ListOperationsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!operations_.Equals(other.operations_)) return false; if (NextPageToken != other.NextPageToken) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= operations_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { operations_.WriteTo(output, _repeated_operations_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } } public int CalculateSize() { int size = 0; size += operations_.CalculateSize(_repeated_operations_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } return size; } public void MergeFrom(ListOperationsResponse other) { if (other == null) { return; } operations_.Add(other.operations_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { operations_.AddEntriesFrom(input, _repeated_operations_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class CancelOperationRequest : pb::IMessage<CancelOperationRequest> { private static readonly pb::MessageParser<CancelOperationRequest> _parser = new pb::MessageParser<CancelOperationRequest>(() => new CancelOperationRequest()); public static pb::MessageParser<CancelOperationRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Longrunning.Proto.Operations.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public CancelOperationRequest() { OnConstruction(); } partial void OnConstruction(); public CancelOperationRequest(CancelOperationRequest other) : this() { name_ = other.name_; } public CancelOperationRequest Clone() { return new CancelOperationRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as CancelOperationRequest); } public bool Equals(CancelOperationRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(CancelOperationRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DeleteOperationRequest : pb::IMessage<DeleteOperationRequest> { private static readonly pb::MessageParser<DeleteOperationRequest> _parser = new pb::MessageParser<DeleteOperationRequest>(() => new DeleteOperationRequest()); public static pb::MessageParser<DeleteOperationRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Longrunning.Proto.Operations.Descriptor.MessageTypes[5]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DeleteOperationRequest() { OnConstruction(); } partial void OnConstruction(); public DeleteOperationRequest(DeleteOperationRequest other) : this() { name_ = other.name_; } public DeleteOperationRequest Clone() { return new DeleteOperationRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as DeleteOperationRequest); } public bool Equals(DeleteOperationRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(DeleteOperationRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
#nullable enable using System; using System.Linq; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameObjects.Components; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.Physics; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Utility; using static Content.Shared.GameObjects.EntitySystems.SharedInteractionSystem; namespace Content.Shared.Physics.Pull { public class PullController : VirtualController { [Dependency] private readonly IEntityManager _entityManager = default!; [Dependency] private readonly IPhysicsManager _physicsManager = default!; private const float DistBeforeStopPull = InteractionRange; private const float StopMoveThreshold = 0.25f; private IPhysicsComponent? _puller; private EntityCoordinates? _movingTo; public IPhysicsComponent? Puller => _puller; public EntityCoordinates? MovingTo { get => _movingTo; set { if (_movingTo == value || ControlledComponent == null) { return; } _movingTo = value; ControlledComponent.WakeBody(); } } private bool PullerMovingTowardsPulled() { if (_puller == null) { return false; } if (ControlledComponent == null) { return false; } if (_puller.LinearVelocity.EqualsApprox(Vector2.Zero)) { return false; } var pullerTransform = _puller.Owner.Transform; var origin = pullerTransform.Coordinates.Position; var velocity = _puller.LinearVelocity.Normalized; var mapId = pullerTransform.MapPosition.MapId; var ray = new CollisionRay(origin, velocity, (int) CollisionGroup.AllMask); bool Predicate(IEntity e) => e != ControlledComponent.Owner; var rayResults = _physicsManager.IntersectRayWithPredicate(mapId, ray, DistBeforeStopPull, Predicate); return rayResults.Any(); } public bool StartPull(IEntity entity) { DebugTools.AssertNotNull(entity); if (!entity.TryGetComponent(out IPhysicsComponent? physics)) { return false; } return StartPull(physics); } public bool StartPull(IPhysicsComponent puller) { DebugTools.AssertNotNull(puller); if (_puller == puller) { return false; } if (ControlledComponent == null) { return false; } var pullAttempt = new PullAttemptMessage(puller, ControlledComponent); puller.Owner.SendMessage(null, pullAttempt); if (pullAttempt.Cancelled) { return false; } ControlledComponent.Owner.SendMessage(null, pullAttempt); if (pullAttempt.Cancelled) { return false; } _puller = puller; var message = new PullStartedMessage(this, _puller, ControlledComponent); _puller.Owner.SendMessage(null, message); ControlledComponent.Owner.SendMessage(null, message); _puller.Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, message); ControlledComponent.WakeBody(); return true; } public bool StopPull() { var oldPuller = _puller; if (oldPuller == null) { return false; } _puller = null; if (ControlledComponent == null) { return false; } var message = new PullStoppedMessage(oldPuller, ControlledComponent); oldPuller.Owner.SendMessage(null, message); ControlledComponent.Owner.SendMessage(null, message); oldPuller.Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, message); ControlledComponent.WakeBody(); ControlledComponent.TryRemoveController<PullController>(); return true; } public bool TryMoveTo(EntityCoordinates from, EntityCoordinates to) { if (_puller == null || ControlledComponent == null) { return false; } if (!_puller.Owner.Transform.Coordinates.InRange(_entityManager, from, InteractionRange)) { return false; } if (!_puller.Owner.Transform.Coordinates.InRange(_entityManager, to, InteractionRange)) { return false; } if (!from.InRange(_entityManager, to, InteractionRange)) { return false; } if (from.Position.EqualsApprox(to.Position)) { return false; } if (!_puller.Owner.Transform.Coordinates.TryDistance(_entityManager, to, out var distance) || Math.Sqrt(distance) > DistBeforeStopPull || Math.Sqrt(distance) < StopMoveThreshold) { return false; } MovingTo = to; return true; } public override void UpdateBeforeProcessing() { if (_puller == null || ControlledComponent == null) { return; } if (!_puller.Owner.IsInSameOrNoContainer(ControlledComponent.Owner)) { StopPull(); return; } var distance = _puller.Owner.Transform.WorldPosition - ControlledComponent.Owner.Transform.WorldPosition; if (distance.Length > DistBeforeStopPull) { StopPull(); } else if (MovingTo.HasValue) { var diff = MovingTo.Value.Position - ControlledComponent.Owner.Transform.Coordinates.Position; LinearVelocity = diff.Normalized * 5; } else { if (PullerMovingTowardsPulled()) { LinearVelocity = Vector2.Zero; return; } var distanceAbs = Vector2.Abs(distance); var totalAabb = _puller.AABB.Size + ControlledComponent.AABB.Size / 2; if (distanceAbs.X < totalAabb.X && distanceAbs.Y < totalAabb.Y) { LinearVelocity = Vector2.Zero; return; } LinearVelocity = distance.Normalized * _puller.LinearVelocity.Length * 1.5f; } } public override void UpdateAfterProcessing() { base.UpdateAfterProcessing(); if (ControlledComponent == null) { MovingTo = null; return; } if (MovingTo != null && ControlledComponent.Owner.Transform.Coordinates.Position.EqualsApprox(MovingTo.Value.Position, 0.01)) { MovingTo = null; } if (LinearVelocity != Vector2.Zero) { var angle = LinearVelocity.ToAngle(); ControlledComponent.Owner.Transform.LocalRotation = angle; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; namespace Microsoft.AspNetCore.Mvc { /// <summary> /// Static class for url helper extension methods. /// </summary> public static class UrlHelperExtensions { /// <summary> /// Generates a URL with a path for an action method. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <returns>The generated URL.</returns> public static string? Action(this IUrlHelper helper) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action( action: null, controller: null, values: null, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> name. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <returns>The generated URL.</returns> public static string? Action(this IUrlHelper helper, string? action) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(action, controller: null, values: null, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> name and route <paramref name="values"/>. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <param name="values">An object that contains route values.</param> /// <returns>The generated URL.</returns> public static string? Action(this IUrlHelper helper, string? action, object? values) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(action, controller: null, values: values, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> and <paramref name="controller"/> names. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <param name="controller">The name of the controller.</param> /// <returns>The generated URL.</returns> public static string? Action(this IUrlHelper helper, string? action, string? controller) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(action, controller, values: null, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> name, <paramref name="controller"/> name, and route <paramref name="values"/>. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <param name="controller">The name of the controller.</param> /// <param name="values">An object that contains route values.</param> /// <returns>The generated URL.</returns> public static string? Action(this IUrlHelper helper, string? action, string? controller, object? values) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(action, controller, values, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> name, <paramref name="controller"/> name, route <paramref name="values"/>, and /// <paramref name="protocol"/> to use. See the remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <param name="controller">The name of the controller.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// This method uses the value of <see cref="HttpRequest.Host"/> to populate the host section of the generated URI. /// Relying on the value of the current request can allow untrusted input to influence the resulting URI unless /// the <c>Host</c> header has been validated. See the deployment documentation for instructions on how to properly /// validate the <c>Host</c> header in your deployment environment. /// </para> /// </remarks> public static string? Action( this IUrlHelper helper, string? action, string? controller, object? values, string? protocol) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(action, controller, values, protocol, host: null, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> name, <paramref name="controller"/> name, route <paramref name="values"/>, /// <paramref name="protocol"/> to use, and <paramref name="host"/> name. /// Generates an absolute URL if the <paramref name="protocol"/> and <paramref name="host"/> are /// non-<c>null</c>. See the remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <param name="controller">The name of the controller.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? Action( this IUrlHelper helper, string? action, string? controller, object? values, string? protocol, string? host) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(action, controller, values, protocol, host, fragment: null); } /// <summary> /// Generates a URL with a path for an action method, which contains the specified /// <paramref name="action"/> name, <paramref name="controller"/> name, route <paramref name="values"/>, /// <paramref name="protocol"/> to use, <paramref name="host"/> name, and <paramref name="fragment"/>. /// Generates an absolute URL if the <paramref name="protocol"/> and <paramref name="host"/> are /// non-<c>null</c>. See the remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method.</param> /// <param name="controller">The name of the controller.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <param name="fragment">The fragment for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? Action( this IUrlHelper helper, string? action, string? controller, object? values, string? protocol, string? host, string? fragment) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.Action(new UrlActionContext() { Action = action, Controller = controller, Host = host, Values = values, Protocol = protocol, Fragment = fragment }); } /// <summary> /// Generates a URL with an absolute path for the specified route <paramref name="values"/>. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="values">An object that contains route values.</param> /// <returns>The generated URL.</returns> public static string? RouteUrl(this IUrlHelper helper, object? values) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.RouteUrl(routeName: null, values: values, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with an absolute path for the specified <paramref name="routeName"/>. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="routeName">The name of the route that is used to generate URL.</param> /// <returns>The generated URL.</returns> public static string? RouteUrl(this IUrlHelper helper, string? routeName) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.RouteUrl(routeName, values: null, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with an absolute path for the specified <paramref name="routeName"/> and route /// <paramref name="values"/>. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="routeName">The name of the route that is used to generate URL.</param> /// <param name="values">An object that contains route values.</param> /// <returns>The generated URL.</returns> public static string? RouteUrl(this IUrlHelper helper, string? routeName, object? values) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.RouteUrl(routeName, values, protocol: null, host: null, fragment: null); } /// <summary> /// Generates a URL with an absolute path for the specified route <paramref name="routeName"/> and route /// <paramref name="values"/>, which contains the specified <paramref name="protocol"/> to use. See the /// remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="routeName">The name of the route that is used to generate URL.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// This method uses the value of <see cref="HttpRequest.Host"/> to populate the host section of the generated URI. /// Relying on the value of the current request can allow untrusted input to influence the resulting URI unless /// the <c>Host</c> header has been validated. See the deployment documentation for instructions on how to properly /// validate the <c>Host</c> header in your deployment environment. /// </para> /// </remarks> public static string? RouteUrl( this IUrlHelper helper, string? routeName, object? values, string? protocol) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.RouteUrl(routeName, values, protocol, host: null, fragment: null); } /// <summary> /// Generates a URL with an absolute path for the specified route <paramref name="routeName"/> and route /// <paramref name="values"/>, which contains the specified <paramref name="protocol"/> to use and /// <paramref name="host"/> name. Generates an absolute URL if /// <see cref="UrlActionContext.Protocol"/> and <see cref="UrlActionContext.Host"/> are non-<c>null</c>. /// See the remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="routeName">The name of the route that is used to generate URL.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? RouteUrl( this IUrlHelper helper, string? routeName, object? values, string? protocol, string? host) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.RouteUrl(routeName, values, protocol, host, fragment: null); } /// <summary> /// Generates a URL with an absolute path for the specified route <paramref name="routeName"/> and route /// <paramref name="values"/>, which contains the specified <paramref name="protocol"/> to use, /// <paramref name="host"/> name and <paramref name="fragment"/>. Generates an absolute URL if /// <see cref="UrlActionContext.Protocol"/> and <see cref="UrlActionContext.Host"/> are non-<c>null</c>. /// See the remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="routeName">The name of the route that is used to generate URL.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <param name="fragment">The fragment for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? RouteUrl( this IUrlHelper helper, string? routeName, object? values, string? protocol, string? host, string? fragment) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } return helper.RouteUrl(new UrlRouteContext() { RouteName = routeName, Values = values, Protocol = protocol, Host = host, Fragment = fragment }); } /// <summary> /// Generates a URL with a relative path for the specified <paramref name="pageName"/>. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <returns>The generated URL.</returns> public static string? Page(this IUrlHelper urlHelper, string? pageName) => Page(urlHelper, pageName, values: null); /// <summary> /// Generates a URL with a relative path for the specified <paramref name="pageName"/>. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <param name="pageHandler">The handler to generate the url for.</param> /// <returns>The generated URL.</returns> public static string? Page(this IUrlHelper urlHelper, string? pageName, string? pageHandler) => Page(urlHelper, pageName, pageHandler, values: null); /// <summary> /// Generates a URL with a relative path for the specified <paramref name="pageName"/>. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <param name="values">An object that contains route values.</param> /// <returns>The generated URL.</returns> public static string? Page(this IUrlHelper urlHelper, string? pageName, object? values) => Page(urlHelper, pageName, pageHandler: null, values: values); /// <summary> /// Generates a URL with a relative path for the specified <paramref name="pageName"/>. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <param name="pageHandler">The handler to generate the url for.</param> /// <param name="values">An object that contains route values.</param> /// <returns>The generated URL.</returns> public static string? Page( this IUrlHelper urlHelper, string? pageName, string? pageHandler, object? values) => Page(urlHelper, pageName, pageHandler, values, protocol: null); /// <summary> /// Generates a URL with an absolute path for the specified <paramref name="pageName"/>. See the remarks section /// for important security information. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <param name="pageHandler">The handler to generate the url for.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// This method uses the value of <see cref="HttpRequest.Host"/> to populate the host section of the generated URI. /// Relying on the value of the current request can allow untrusted input to influence the resulting URI unless /// the <c>Host</c> header has been validated. See the deployment documentation for instructions on how to properly /// validate the <c>Host</c> header in your deployment environment. /// </para> /// </remarks> public static string? Page( this IUrlHelper urlHelper, string? pageName, string? pageHandler, object? values, string? protocol) => Page(urlHelper, pageName, pageHandler, values, protocol, host: null, fragment: null); /// <summary> /// Generates a URL with an absolute path for the specified <paramref name="pageName"/>. See the remarks section for /// important security information. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <param name="pageHandler">The handler to generate the url for.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? Page( this IUrlHelper urlHelper, string? pageName, string? pageHandler, object? values, string? protocol, string? host) => Page(urlHelper, pageName, pageHandler, values, protocol, host, fragment: null); /// <summary> /// Generates a URL with an absolute path for the specified <paramref name="pageName"/>. See the remarks section for /// important security information. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for.</param> /// <param name="pageHandler">The handler to generate the url for.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <param name="fragment">The fragment for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? Page( this IUrlHelper urlHelper, string? pageName, string? pageHandler, object? values, string? protocol, string? host, string? fragment) { if (urlHelper == null) { throw new ArgumentNullException(nameof(urlHelper)); } var routeValues = new RouteValueDictionary(values); var ambientValues = urlHelper.ActionContext.RouteData.Values; UrlHelperBase.NormalizeRouteValuesForPage(urlHelper.ActionContext, pageName, pageHandler, routeValues, ambientValues); return urlHelper.RouteUrl( routeName: null, values: routeValues, protocol: protocol, host: host, fragment: fragment); } /// <summary> /// Generates an absolute URL for an action method, which contains the specified /// <paramref name="action"/> name, <paramref name="controller"/> name, route <paramref name="values"/>, /// <paramref name="protocol"/> to use, <paramref name="host"/> name, and <paramref name="fragment"/>. /// Generates an absolute URL if the <paramref name="protocol"/> and <paramref name="host"/> are /// non-<c>null</c>. See the remarks section for important security information. /// </summary> /// <param name="helper">The <see cref="IUrlHelper"/>.</param> /// <param name="action">The name of the action method. When <see langword="null" />, defaults to the current executing action.</param> /// <param name="controller">The name of the controller. When <see langword="null" />, defaults to the current executing controller.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <param name="fragment">The fragment for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? ActionLink( this IUrlHelper helper, string? action = null, string? controller = null, object? values = null, string? protocol = null, string? host = null, string? fragment = null) { if (helper == null) { throw new ArgumentNullException(nameof(helper)); } var httpContext = helper.ActionContext.HttpContext; if (protocol == null) { protocol = httpContext.Request.Scheme; } if (host == null) { host = httpContext.Request.Host.ToUriComponent(); } return Action(helper, action, controller, values, protocol, host, fragment); } /// <summary> /// Generates an absolute URL for a page, which contains the specified /// <paramref name="pageName"/>, <paramref name="pageHandler"/>, route <paramref name="values"/>, /// <paramref name="protocol"/> to use, <paramref name="host"/> name, and <paramref name="fragment"/>. /// Generates an absolute URL if the <paramref name="protocol"/> and <paramref name="host"/> are /// non-<c>null</c>. See the remarks section for important security information. /// </summary> /// <param name="urlHelper">The <see cref="IUrlHelper"/>.</param> /// <param name="pageName">The page name to generate the url for. When <see langword="null"/>, defaults to the current executing page.</param> /// <param name="pageHandler">The handler to generate the url for. When <see langword="null"/>, defaults to the current executing handler.</param> /// <param name="values">An object that contains route values.</param> /// <param name="protocol">The protocol for the URL, such as "http" or "https".</param> /// <param name="host">The host name for the URL.</param> /// <param name="fragment">The fragment for the URL.</param> /// <returns>The generated URL.</returns> /// <remarks> /// <para> /// The value of <paramref name="host"/> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> public static string? PageLink( this IUrlHelper urlHelper, string? pageName = null, string? pageHandler = null, object? values = null, string? protocol = null, string? host = null, string? fragment = null) { if (urlHelper == null) { throw new ArgumentNullException(nameof(urlHelper)); } var httpContext = urlHelper.ActionContext.HttpContext; if (protocol == null) { protocol = httpContext.Request.Scheme; } if (host == null) { host = httpContext.Request.Host.ToUriComponent(); } return Page(urlHelper, pageName, pageHandler, values, protocol, host, fragment); } } }
// 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.V9.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.V9.Services { /// <summary>Settings for <see cref="LocationViewServiceClient"/> instances.</summary> public sealed partial class LocationViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="LocationViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="LocationViewServiceSettings"/>.</returns> public static LocationViewServiceSettings GetDefault() => new LocationViewServiceSettings(); /// <summary>Constructs a new <see cref="LocationViewServiceSettings"/> object with default settings.</summary> public LocationViewServiceSettings() { } private LocationViewServiceSettings(LocationViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetLocationViewSettings = existing.GetLocationViewSettings; OnCopy(existing); } partial void OnCopy(LocationViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>LocationViewServiceClient.GetLocationView</c> and <c>LocationViewServiceClient.GetLocationViewAsync</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 GetLocationViewSettings { 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="LocationViewServiceSettings"/> object.</returns> public LocationViewServiceSettings Clone() => new LocationViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="LocationViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class LocationViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<LocationViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public LocationViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public LocationViewServiceClientBuilder() { UseJwtAccessWithScopes = LocationViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref LocationViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<LocationViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override LocationViewServiceClient Build() { LocationViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<LocationViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<LocationViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private LocationViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return LocationViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<LocationViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return LocationViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => LocationViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => LocationViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => LocationViewServiceClient.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>LocationViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch location views. /// </remarks> public abstract partial class LocationViewServiceClient { /// <summary> /// The default endpoint for the LocationViewService 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 LocationViewService scopes.</summary> /// <remarks> /// The default LocationViewService 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="LocationViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="LocationViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="LocationViewServiceClient"/>.</returns> public static stt::Task<LocationViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new LocationViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="LocationViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="LocationViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="LocationViewServiceClient"/>.</returns> public static LocationViewServiceClient Create() => new LocationViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="LocationViewServiceClient"/> 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="LocationViewServiceSettings"/>.</param> /// <returns>The created <see cref="LocationViewServiceClient"/>.</returns> internal static LocationViewServiceClient Create(grpccore::CallInvoker callInvoker, LocationViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } LocationViewService.LocationViewServiceClient grpcClient = new LocationViewService.LocationViewServiceClient(callInvoker); return new LocationViewServiceClientImpl(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 LocationViewService client</summary> public virtual LocationViewService.LocationViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested location view 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::LocationView GetLocationView(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested location view 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::LocationView> GetLocationViewAsync(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested location view 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::LocationView> GetLocationViewAsync(GetLocationViewRequest request, st::CancellationToken cancellationToken) => GetLocationViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::LocationView GetLocationView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationView(new GetLocationViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view 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::LocationView> GetLocationViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationViewAsync(new GetLocationViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view 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::LocationView> GetLocationViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetLocationViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::LocationView GetLocationView(gagvr::LocationViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationView(new GetLocationViewRequest { ResourceNameAsLocationViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view 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::LocationView> GetLocationViewAsync(gagvr::LocationViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationViewAsync(new GetLocationViewRequest { ResourceNameAsLocationViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view 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::LocationView> GetLocationViewAsync(gagvr::LocationViewName resourceName, st::CancellationToken cancellationToken) => GetLocationViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>LocationViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch location views. /// </remarks> public sealed partial class LocationViewServiceClientImpl : LocationViewServiceClient { private readonly gaxgrpc::ApiCall<GetLocationViewRequest, gagvr::LocationView> _callGetLocationView; /// <summary> /// Constructs a client wrapper for the LocationViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="LocationViewServiceSettings"/> used within this client.</param> public LocationViewServiceClientImpl(LocationViewService.LocationViewServiceClient grpcClient, LocationViewServiceSettings settings) { GrpcClient = grpcClient; LocationViewServiceSettings effectiveSettings = settings ?? LocationViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetLocationView = clientHelper.BuildApiCall<GetLocationViewRequest, gagvr::LocationView>(grpcClient.GetLocationViewAsync, grpcClient.GetLocationView, effectiveSettings.GetLocationViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetLocationView); Modify_GetLocationViewApiCall(ref _callGetLocationView); 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_GetLocationViewApiCall(ref gaxgrpc::ApiCall<GetLocationViewRequest, gagvr::LocationView> call); partial void OnConstruction(LocationViewService.LocationViewServiceClient grpcClient, LocationViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC LocationViewService client</summary> public override LocationViewService.LocationViewServiceClient GrpcClient { get; } partial void Modify_GetLocationViewRequest(ref GetLocationViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested location view 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::LocationView GetLocationView(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetLocationViewRequest(ref request, ref callSettings); return _callGetLocationView.Sync(request, callSettings); } /// <summary> /// Returns the requested location view 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::LocationView> GetLocationViewAsync(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetLocationViewRequest(ref request, ref callSettings); return _callGetLocationView.Async(request, callSettings); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; 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 Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation connections. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> internal partial class ConnectionOperations : IServiceOperations<AutomationManagementClient>, IConnectionOperations { /// <summary> /// Initializes a new instance of the ConnectionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ConnectionOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create a connection. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// connection operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create or update connection operation. /// </returns> public async Task<ConnectionCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, ConnectionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.ConnectionType == null) { throw new ArgumentNullException("parameters.Properties.ConnectionType"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; url = url + Uri.EscapeDataString(parameters.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject connectionCreateOrUpdateParametersValue = new JObject(); requestDoc = connectionCreateOrUpdateParametersValue; connectionCreateOrUpdateParametersValue["name"] = parameters.Name; JObject propertiesValue = new JObject(); connectionCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.Description != null) { propertiesValue["description"] = parameters.Properties.Description; } JObject connectionTypeValue = new JObject(); propertiesValue["connectionType"] = connectionTypeValue; if (parameters.Properties.ConnectionType.Name != null) { connectionTypeValue["name"] = parameters.Properties.ConnectionType.Name; } if (parameters.Properties.FieldDefinitionValues != null) { if (parameters.Properties.FieldDefinitionValues is ILazyCollection == false || ((ILazyCollection)parameters.Properties.FieldDefinitionValues).IsInitialized) { JObject fieldDefinitionValuesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties.FieldDefinitionValues) { string fieldDefinitionValuesKey = pair.Key; string fieldDefinitionValuesValue = pair.Value; fieldDefinitionValuesDictionary[fieldDefinitionValuesKey] = fieldDefinitionValuesValue; } propertiesValue["fieldDefinitionValues"] = fieldDefinitionValuesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Connection connectionInstance = new Connection(); result.Connection = connectionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); connectionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue2 = propertiesValue2["connectionType"]; if (connectionTypeValue2 != null && connectionTypeValue2.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue2["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey2 = ((string)property.Name); string fieldDefinitionValuesValue2 = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey2, fieldDefinitionValuesValue2); } } JToken creationTimeValue = propertiesValue2["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue2["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete the connection. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionName'> /// Required. The name of connection. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string connectionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (connectionName == null) { throw new ArgumentNullException("connectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("connectionName", connectionName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; url = url + Uri.EscapeDataString(connectionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the connection identified by connection name. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionName'> /// Required. The name of connection. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get connection operation. /// </returns> public async Task<ConnectionGetResponse> GetAsync(string resourceGroupName, string automationAccount, string connectionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (connectionName == null) { throw new ArgumentNullException("connectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("connectionName", connectionName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; url = url + Uri.EscapeDataString(connectionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Connection connectionInstance = new Connection(); result.Connection = connectionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); connectionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue = propertiesValue["connectionType"]; if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey = ((string)property.Name); string fieldDefinitionValuesValue = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue); } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of connections. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list connection operation. /// </returns> public async Task<ConnectionListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Connection connectionInstance = new Connection(); result.Connection.Add(connectionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); connectionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue = propertiesValue["connectionType"]; if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey = ((string)property.Name); string fieldDefinitionValuesValue = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue); } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of connections. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list connection operation. /// </returns> public async Task<ConnectionListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ConnectionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ConnectionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Connection connectionInstance = new Connection(); result.Connection.Add(connectionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); connectionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); connectionInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ConnectionProperties propertiesInstance = new ConnectionProperties(); connectionInstance.Properties = propertiesInstance; JToken connectionTypeValue = propertiesValue["connectionType"]; if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null) { ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty(); propertiesInstance.ConnectionType = connectionTypeInstance; JToken nameValue2 = connectionTypeValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); connectionTypeInstance.Name = nameInstance2; } } JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]); if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in fieldDefinitionValuesSequenceElement) { string fieldDefinitionValuesKey = ((string)property.Name); string fieldDefinitionValuesValue = ((string)property.Value); propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue); } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a connection. (see /// http://aka.ms/azureautomationsdk/connectionoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the patch a connection /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string automationAccount, ConnectionPatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/connections/"; if (parameters.Name != null) { url = url + Uri.EscapeDataString(parameters.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject connectionPatchParametersValue = new JObject(); requestDoc = connectionPatchParametersValue; if (parameters.Name != null) { connectionPatchParametersValue["name"] = parameters.Name; } JObject propertiesValue = new JObject(); connectionPatchParametersValue["properties"] = propertiesValue; if (parameters.Properties.Description != null) { propertiesValue["description"] = parameters.Properties.Description; } if (parameters.Properties.FieldDefinitionValues != null) { if (parameters.Properties.FieldDefinitionValues is ILazyCollection == false || ((ILazyCollection)parameters.Properties.FieldDefinitionValues).IsInitialized) { JObject fieldDefinitionValuesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties.FieldDefinitionValues) { string fieldDefinitionValuesKey = pair.Key; string fieldDefinitionValuesValue = pair.Value; fieldDefinitionValuesDictionary[fieldDefinitionValuesKey] = fieldDefinitionValuesValue; } propertiesValue["fieldDefinitionValues"] = fieldDefinitionValuesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Common; #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ namespace NLog.Targets { using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.IO; using NLog.Config; /// <summary> /// Writes log messages to the console with customizable coloring. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">Documentation on NLog Wiki</seealso> [Target("ColoredConsole")] public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Should logging being paused/stopped because of the race condition bug in Console.Writeline? /// </summary> /// <remarks> /// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. /// See http://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written /// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service /// /// Full error: /// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. /// The I/ O package is not thread safe by default.In multithreaded applications, /// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or /// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. /// /// </remarks> private bool _pauseLogging; private static readonly IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules = new List<ConsoleRowHighlightingRule>() { new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.Red, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.Magenta, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.White, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.DarkGray, ConsoleOutputColor.NoChange), }; /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public ColoredConsoleTarget() { this.WordHighlightingRules = new List<ConsoleWordHighlightingRule>(); this.RowHighlightingRules = new List<ConsoleRowHighlightingRule>(); this.UseDefaultRowHighlightingRules = true; this._pauseLogging = false; this.DetectConsoleAvailable = false; this.OptimizeBufferReuse = true; } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public ColoredConsoleTarget(string name) : this() { this.Name = name; } /// <summary> /// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout). /// </summary> /// <docgen category='Output Options' order='10' /> [DefaultValue(false)] public bool ErrorStream { get; set; } /// <summary> /// Gets or sets a value indicating whether to use default row highlighting rules. /// </summary> /// <remarks> /// The default rules are: /// <table> /// <tr> /// <th>Condition</th> /// <th>Foreground Color</th> /// <th>Background Color</th> /// </tr> /// <tr> /// <td>level == LogLevel.Fatal</td> /// <td>Red</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Error</td> /// <td>Yellow</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Warn</td> /// <td>Magenta</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Info</td> /// <td>White</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Debug</td> /// <td>Gray</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Trace</td> /// <td>DarkGray</td> /// <td>NoChange</td> /// </tr> /// </table> /// </remarks> /// <docgen category='Highlighting Rules' order='9' /> [DefaultValue(true)] public bool UseDefaultRowHighlightingRules { get; set; } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ /// <summary> /// The encoding for writing messages to the <see cref="Console"/>. /// </summary> /// <remarks>Has side effect</remarks> public Encoding Encoding { get { return ConsoleTargetHelper.GetConsoleOutputEncoding(this._encoding, this.IsInitialized, this._pauseLogging); } set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, this.IsInitialized, this._pauseLogging)) _encoding = value; } } private Encoding _encoding; #endif /// <summary> /// Gets or sets a value indicating whether to auto-check if the console is available. /// - Disables console writing if Environment.UserInteractive = False (Windows Service) /// - Disables console writing if Console Standard Input is not available (Non-Console-App) /// </summary> [DefaultValue(false)] public bool DetectConsoleAvailable { get; set; } /// <summary> /// Gets the row highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> [ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")] public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; private set; } /// <summary> /// Gets the word highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='11' /> [ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")] public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; private set; } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { this._pauseLogging = false; if (DetectConsoleAvailable) { string reason; _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason); if (_pauseLogging) { InternalLogger.Info("Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {0}", reason); } } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ if (this._encoding != null && !this._pauseLogging) Console.OutputEncoding = this._encoding; #endif base.InitializeTarget(); if (this.Header != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); this.WriteToOutput(lei, base.RenderLogEvent(this.Header, lei)); } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { if (this.Footer != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); this.WriteToOutput(lei, base.RenderLogEvent(this.Footer, lei)); } base.CloseTarget(); } /// <summary> /// Writes the specified log event to the console highlighting entries /// and words based on a set of defined rules. /// </summary> /// <param name="logEvent">Log event.</param> protected override void Write(LogEventInfo logEvent) { if (_pauseLogging) { //check early for performance return; } this.WriteToOutput(logEvent, base.RenderLogEvent(this.Layout, logEvent)); } private void WriteToOutput(LogEventInfo logEvent, string message) { ConsoleColor oldForegroundColor = Console.ForegroundColor; ConsoleColor oldBackgroundColor = Console.BackgroundColor; bool didChangeForegroundColor = false, didChangeBackgroundColor = false; try { var matchingRule = GetMatchingRowHighlightingRule(logEvent); didChangeForegroundColor = IsColorChange(matchingRule.ForegroundColor, oldForegroundColor); if (didChangeForegroundColor) Console.ForegroundColor = (ConsoleColor)matchingRule.ForegroundColor; didChangeBackgroundColor = IsColorChange(matchingRule.BackgroundColor, oldBackgroundColor); if (didChangeBackgroundColor) Console.BackgroundColor = (ConsoleColor)matchingRule.BackgroundColor; try { var consoleStream = this.ErrorStream ? Console.Error : Console.Out; if (this.WordHighlightingRules.Count == 0) { consoleStream.WriteLine(message); } else { message = message.Replace("\a", "\a\a"); foreach (ConsoleWordHighlightingRule hl in this.WordHighlightingRules) { message = hl.ReplaceWithEscapeSequences(message); } ColorizeEscapeSequences(consoleStream, message, new ColorPair(Console.ForegroundColor, Console.BackgroundColor), new ColorPair(oldForegroundColor, oldBackgroundColor)); consoleStream.WriteLine(); didChangeForegroundColor = didChangeBackgroundColor = true; } } catch (IndexOutOfRangeException ex) { //this is a bug and therefor stopping logging. For docs, see PauseLogging property _pauseLogging = true; InternalLogger.Warn(ex, "An IndexOutOfRangeException has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets"); } catch (ArgumentOutOfRangeException ex) { //this is a bug and therefor stopping logging. For docs, see PauseLogging property _pauseLogging = true; InternalLogger.Warn(ex, "An ArgumentOutOfRangeException has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets"); } } finally { if (didChangeForegroundColor) Console.ForegroundColor = oldForegroundColor; if (didChangeBackgroundColor) Console.BackgroundColor = oldBackgroundColor; } } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent) { foreach (ConsoleRowHighlightingRule rule in this.RowHighlightingRules) { if (rule.CheckCondition(logEvent)) return rule; } if (this.UseDefaultRowHighlightingRules) { foreach (ConsoleRowHighlightingRule rule in DefaultConsoleRowHighlightingRules) { if (rule.CheckCondition(logEvent)) return rule; } } return ConsoleRowHighlightingRule.Default; } private static bool IsColorChange(ConsoleOutputColor targetColor, ConsoleColor oldColor) { return (targetColor != ConsoleOutputColor.NoChange) && ((ConsoleColor)targetColor != oldColor); } private static void ColorizeEscapeSequences( TextWriter output, string message, ColorPair startingColor, ColorPair defaultColor) { var colorStack = new Stack<ColorPair>(); colorStack.Push(startingColor); int p0 = 0; while (p0 < message.Length) { int p1 = p0; while (p1 < message.Length && message[p1] >= 32) { p1++; } // text if (p1 != p0) { output.Write(message.Substring(p0, p1 - p0)); } if (p1 >= message.Length) { p0 = p1; break; } // control characters char c1 = message[p1]; char c2 = (char)0; if (p1 + 1 < message.Length) { c2 = message[p1 + 1]; } if (c1 == '\a' && c2 == '\a') { output.Write('\a'); p0 = p1 + 2; continue; } if (c1 == '\r' || c1 == '\n') { Console.ForegroundColor = defaultColor.ForegroundColor; Console.BackgroundColor = defaultColor.BackgroundColor; output.Write(c1); Console.ForegroundColor = colorStack.Peek().ForegroundColor; Console.BackgroundColor = colorStack.Peek().BackgroundColor; p0 = p1 + 1; continue; } if (c1 == '\a') { if (c2 == 'X') { colorStack.Pop(); Console.ForegroundColor = colorStack.Peek().ForegroundColor; Console.BackgroundColor = colorStack.Peek().BackgroundColor; p0 = p1 + 2; continue; } var foreground = (ConsoleOutputColor)(c2 - 'A'); var background = (ConsoleOutputColor)(message[p1 + 2] - 'A'); if (foreground != ConsoleOutputColor.NoChange) { Console.ForegroundColor = (ConsoleColor)foreground; } if (background != ConsoleOutputColor.NoChange) { Console.BackgroundColor = (ConsoleColor)background; } colorStack.Push(new ColorPair(Console.ForegroundColor, Console.BackgroundColor)); p0 = p1 + 3; continue; } output.Write(c1); p0 = p1 + 1; } if (p0 < message.Length) { output.Write(message.Substring(p0)); } } /// <summary> /// Color pair (foreground and background). /// </summary> internal struct ColorPair { private readonly ConsoleColor _foregroundColor; private readonly ConsoleColor _backgroundColor; internal ColorPair(ConsoleColor foregroundColor, ConsoleColor backgroundColor) { this._foregroundColor = foregroundColor; this._backgroundColor = backgroundColor; } internal ConsoleColor BackgroundColor { get { return this._backgroundColor; } } internal ConsoleColor ForegroundColor { get { return this._foregroundColor; } } } } } #endif
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: $ * $Date: $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Imports using System; using System.Data; using System.Reflection; using IBatisNet.Common; using IBatisNet.Common.Logging; using IBatisNet.DataAccess.Exceptions; #endregion namespace IBatisNet.DataAccess.DaoSessionHandlers { /// <summary> /// An ADO.NET implementation of the DataAccess Session . /// </summary> public class SimpleDaoSession : DaoSession { #region Fields private static readonly ILog _logger = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType ); private DataSource _dataSource = null; private bool _isOpenTransaction = false; private bool _consistent = false; /// <summary> /// Holds value of connection /// </summary> private IDbConnection _connection = null; /// <summary> /// Holds value of transaction /// </summary> private IDbTransaction _transaction = null; #endregion #region Properties /// <summary> /// /// </summary> public override DataSource DataSource { get { return _dataSource; } } /// <summary> /// /// </summary> public override IDbConnection Connection { get { return _connection; } } /// <summary> /// /// </summary> public override IDbTransaction Transaction { get { return _transaction; } } /// <summary> /// Changes the vote for transaction to commit (true) or to abort (false). /// </summary> private bool Consistent { set { _consistent = value; } } #endregion #region Constructor (s) / Destructor /// <summary> /// /// </summary> /// <param name="daoManager"></param> /// <param name="dataSource"></param> public SimpleDaoSession(DaoManager daoManager, DataSource dataSource):base(daoManager) { _dataSource = dataSource; } #endregion #region Methods /// <summary> /// Complete (commit) a transaction /// </summary> /// <remarks> /// Use in 'using' syntax. /// </remarks> public override void Complete() { this.Consistent = true; } /// <summary> /// Opens a database connection. /// </summary> public override void OpenConnection() { this.OpenConnection(_dataSource.ConnectionString); } /// <summary> /// Open a connection, on the specified connection string. /// </summary> /// <param name="connectionString">The connection string</param> public override void OpenConnection(string connectionString) { if (_connection == null) { _connection = _dataSource.Provider.GetConnection(); _connection.ConnectionString = connectionString; try { _connection.Open(); if (_logger.IsDebugEnabled) { _logger.Debug(string.Format("Open Connection \"{0}\" to \"{1}\".", _connection.GetHashCode().ToString(), _dataSource.Provider.Description) ); } } catch(Exception ex) { throw new DataAccessException( string.Format("Unable to open connection to \"{0}\".", _dataSource.Provider.Description), ex ); } } else if (_connection.State != ConnectionState.Open) { try { _connection.Open(); if (_logger.IsDebugEnabled) { _logger.Debug(string.Format("Open Connection \"{0}\" to \"{1}\".", _connection.GetHashCode().ToString(), _dataSource.Provider.Description) ); } } catch(Exception ex) { throw new DataAccessException(string.Format("Unable to open connection to \"{0}\".", _dataSource.Provider.Description), ex ); } } } /// <summary> /// Closes the connection /// </summary> public override void CloseConnection() { if ( (_connection != null) && (_connection.State == ConnectionState.Open) ) { _connection.Close(); if (_logger.IsDebugEnabled) { _logger.Debug(string.Format("Close Connection \"{0}\" to \"{1}\".", _connection.GetHashCode().ToString(), _dataSource.Provider.Description)); } } _connection = null; } /// <summary> /// Begins a transaction. /// </summary> /// <remarks> /// Oepn a connection. /// </remarks> public override void BeginTransaction() { this.BeginTransaction( _dataSource.ConnectionString ); } /// <summary> /// Open a connection and begin a transaction on the specified connection string. /// </summary> /// <param name="connectionString">The connection string</param> public override void BeginTransaction(string connectionString) { if (_connection == null || _connection.State != ConnectionState.Open) { this.OpenConnection( connectionString ); } _transaction = _connection.BeginTransaction(); if (_logger.IsDebugEnabled) { _logger.Debug("Begin Transaction."); } _isOpenTransaction = true; } /// <summary> /// Begins a database transaction /// </summary> /// <param name="openConnection">Open a connection.</param> public override void BeginTransaction(bool openConnection) { if (openConnection) { this.BeginTransaction(); } else { if (_connection == null || _connection.State != ConnectionState.Open) { throw new DataAccessException("SimpleDaoSession could not invoke BeginTransaction(). A Connection must be started. Call OpenConnection() first."); } _transaction = _connection.BeginTransaction(); if (_logger.IsDebugEnabled) { _logger.Debug("Begin Transaction."); } _isOpenTransaction = true; } } /// <summary> /// Begins a transaction at the data source with the specified IsolationLevel value. /// </summary> /// <param name="isolationLevel">The transaction isolation level for this connection.</param> public override void BeginTransaction(IsolationLevel isolationLevel) { this.BeginTransaction( _dataSource.ConnectionString, isolationLevel ); } /// <summary> /// Open a connection and begin a transaction on the specified connection string. /// </summary> /// <param name="connectionString">The connection string</param> /// <param name="isolationLevel">The transaction isolation level for this connection.</param> public override void BeginTransaction(string connectionString, IsolationLevel isolationLevel) { if (_connection == null || _connection.State != ConnectionState.Open) { this.OpenConnection( connectionString ); } _transaction = _connection.BeginTransaction(isolationLevel); if (_logger.IsDebugEnabled) { _logger.Debug("Begin Transaction."); } _isOpenTransaction = true; } /// <summary> /// Begins a transaction on the current connection /// with the specified IsolationLevel value. /// </summary> /// <param name="isolationLevel">The transaction isolation level for this connection.</param> /// <param name="openConnection">Open the connection ?</param> public override void BeginTransaction(bool openConnection, IsolationLevel isolationLevel) { this.BeginTransaction( _dataSource.ConnectionString, openConnection, isolationLevel ); } /// <summary> /// Begins a transaction on the current connection /// with the specified IsolationLevel value. /// </summary> /// <param name="isolationLevel">The transaction isolation level for this connection.</param> /// <param name="connectionString">The connection string</param> /// <param name="openConnection">Open a connection.</param> public override void BeginTransaction(string connectionString, bool openConnection, IsolationLevel isolationLevel) { if (openConnection) { this.BeginTransaction(connectionString, isolationLevel); } else { if (_connection == null || _connection.State != ConnectionState.Open) { throw new DataAccessException("SimpleDaoSession could not invoke StartTransaction(). A Connection must be started. Call OpenConnection() first."); } _transaction = _connection.BeginTransaction(isolationLevel); if (_logger.IsDebugEnabled) { _logger.Debug("Begin Transaction."); } _isOpenTransaction = true; } } /// <summary> /// Commits the database transaction. /// </summary> /// <remarks> /// Will close the connection. /// </remarks> public override void CommitTransaction() { _transaction.Commit(); if (_logger.IsDebugEnabled) { _logger.Debug("Commit Transaction"); } _transaction.Dispose(); _transaction= null; if (_connection.State != ConnectionState.Closed) { CloseConnection(); } } /// <summary> /// Commits the database transaction. /// </summary> /// <param name="closeConnection">Close the connection</param> public override void CommitTransaction(bool closeConnection) { _transaction.Commit(); if (_logger.IsDebugEnabled) { _logger.Debug("Commit Transaction"); } _transaction.Dispose(); _transaction= null; if (closeConnection) { if (_connection.State != ConnectionState.Closed) { CloseConnection(); } } } /// <summary> /// Rolls back a transaction from a pending state. /// </summary> /// <remarks> /// Will close the connection. /// </remarks> public override void RollBackTransaction() { _transaction.Rollback(); if (_logger.IsDebugEnabled) { _logger.Debug("RollBack Transaction"); } _transaction.Dispose(); _transaction = null; if (_connection.State != ConnectionState.Closed) { CloseConnection(); } } /// <summary> /// Rolls back a transaction from a pending state. /// </summary> /// <param name="closeConnection">Close the connection</param> public override void RollBackTransaction(bool closeConnection) { _transaction.Rollback(); if (_logger.IsDebugEnabled) { _logger.Debug("RollBack Transaction"); } _transaction.Dispose(); _transaction = null; if (closeConnection) { if (_connection.State != ConnectionState.Closed) { CloseConnection(); } } } /// <summary> /// /// </summary> /// <param name="commandType"></param> /// <returns></returns> public override IDbCommand CreateCommand(CommandType commandType) { IDbCommand command = null; command = _dataSource.Provider.GetCommand(); // Assign CommandType command.CommandType = commandType; // Assign connection command.Connection = _connection; // Assign transaction if (_transaction != null) { try { command.Transaction = _transaction; } catch {} } // Assign connection timeout if (_connection!= null) { try // MySql provider doesn't suppport it ! { command.CommandTimeout = _connection.ConnectionTimeout; } catch(NotSupportedException e) { _logger.Info(e.Message); } } return command; } /// <summary> /// Create an IDataParameter /// </summary> /// <returns>An IDataParameter.</returns> public override IDataParameter CreateDataParameter() { IDataParameter dataParameter = null; dataParameter = _dataSource.Provider.GetDataParameter(); return dataParameter; } /// <summary> /// /// </summary> /// <returns></returns> public override IDbDataAdapter CreateDataAdapter() { return _dataSource.Provider.GetDataAdapter(); } /// <summary> /// /// </summary> /// <param name="command"></param> /// <returns></returns> public override IDbDataAdapter CreateDataAdapter(IDbCommand command) { IDbDataAdapter dataAdapter = null; dataAdapter = _dataSource.Provider.GetDataAdapter(); dataAdapter.SelectCommand = command; return dataAdapter; } #endregion #region IDisposable Members /// <summary> /// /// </summary> public override void Dispose() { if (_logger.IsDebugEnabled) { _logger.Debug("Dispose DaoSession"); } if (_isOpenTransaction == false) { if (_connection.State != ConnectionState.Closed) { daoManager.CloseConnection(); } } else { if (_consistent) { daoManager.CommitTransaction(); } else { if (_connection.State != ConnectionState.Closed) { daoManager.RollBackTransaction(); } } } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Security.Cryptography { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Threading; using System.Globalization; using System.Runtime.Versioning; using Microsoft.Win32; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public class CryptoConfig { private static volatile Dictionary<string, string> defaultOidHT = null; private static volatile Dictionary<string, object> defaultNameHT = null; private static volatile Dictionary<string, string> machineOidHT = null; private static volatile Dictionary<string, string> machineNameHT = null; private static volatile Dictionary<string, Type> appNameHT = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); private static volatile Dictionary<string, string> appOidHT = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private const string MachineConfigFilename = "machine.config"; private static volatile string version = null; #if FEATURE_CRYPTO private static volatile bool s_fipsAlgorithmPolicy; private static volatile bool s_haveFipsAlgorithmPolicy; /// <summary> /// Determine if the runtime should enforce that only FIPS certified algorithms are created. This /// property returns true if this policy should be enforced, false if any algorithm may be created. /// </summary> public static bool AllowOnlyFipsAlgorithms { [System.Security.SecuritySafeCritical] // auto-generated get { if (!s_haveFipsAlgorithmPolicy) { // // If the user has not disabled FIPS enforcement in a config file, check the CNG settings // on Vista and the FIPS registry key downlevel. // #if !FEATURE_CORECLR if (Utils._GetEnforceFipsPolicySetting()) { if (Environment.OSVersion.Version.Major >= 6) { bool fipsEnabled; uint policyReadStatus = Win32Native.BCryptGetFipsAlgorithmMode(out fipsEnabled); bool readPolicy = policyReadStatus == Win32Native.STATUS_SUCCESS || policyReadStatus == Win32Native.STATUS_OBJECT_NAME_NOT_FOUND; s_fipsAlgorithmPolicy = !readPolicy || fipsEnabled; s_haveFipsAlgorithmPolicy = true; } else { s_fipsAlgorithmPolicy = Utils.ReadLegacyFipsPolicy(); s_haveFipsAlgorithmPolicy = true; } } else #endif // !FEATURE_CORECLR { s_fipsAlgorithmPolicy = false; s_haveFipsAlgorithmPolicy = true; } } return s_fipsAlgorithmPolicy; } } #endif // FEATURE_CRYPTO private static string Version { [System.Security.SecurityCritical] // auto-generated get { if(version == null) version = ((RuntimeType)typeof(CryptoConfig)).GetRuntimeAssembly().GetVersion().ToString(); return version; } } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } private static Dictionary<string, string> DefaultOidHT { get { if (defaultOidHT == null) { Dictionary<string, string> ht = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("SHA", Constants.OID_OIWSEC_SHA1); ht.Add("SHA1", Constants.OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1", Constants.OID_OIWSEC_SHA1); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", Constants.OID_OIWSEC_SHA1); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("System.Security.Cryptography.SHA1Managed", Constants.OID_OIWSEC_SHA1); ht.Add("SHA256", Constants.OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256", Constants.OID_OIWSEC_SHA256); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", Constants.OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Cng", Constants.OID_OIWSEC_SHA256); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("System.Security.Cryptography.SHA256Managed", Constants.OID_OIWSEC_SHA256); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("SHA384", Constants.OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384", Constants.OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", Constants.OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Cng", Constants.OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Managed", Constants.OID_OIWSEC_SHA384); ht.Add("SHA512", Constants.OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512", Constants.OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", Constants.OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Cng", Constants.OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Managed", Constants.OID_OIWSEC_SHA512); ht.Add("RIPEMD160", Constants.OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160", Constants.OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160Managed", Constants.OID_OIWSEC_RIPEMD160); ht.Add("MD5", Constants.OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5", Constants.OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", Constants.OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5Managed", Constants.OID_RSA_MD5); ht.Add("TripleDESKeyWrap", Constants.OID_RSA_SMIMEalgCMS3DESwrap); ht.Add("RC2", Constants.OID_RSA_RC2CBC); ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", Constants.OID_RSA_RC2CBC); ht.Add("DES", Constants.OID_OIWSEC_desCBC); ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", Constants.OID_OIWSEC_desCBC); ht.Add("TripleDES", Constants.OID_RSA_DES_EDE3_CBC); ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", Constants.OID_RSA_DES_EDE3_CBC); #endif // FEATURE_CRYPTO defaultOidHT = ht; } return defaultOidHT; } } private static Dictionary<string, object> DefaultNameHT { get { if (defaultNameHT == null) { Dictionary<string, object> ht = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); #if FEATURE_CRYPTO Type SHA1CryptoServiceProviderType = typeof(System.Security.Cryptography.SHA1CryptoServiceProvider); Type MD5CryptoServiceProviderType = typeof(System.Security.Cryptography.MD5CryptoServiceProvider); Type RIPEMD160ManagedType = typeof(System.Security.Cryptography.RIPEMD160Managed); Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5); Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1); Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384); Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512); Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO Type RSACryptoServiceProviderType = typeof(System.Security.Cryptography.RSACryptoServiceProvider); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO && !FEATURE_CORECLR Type DSACryptoServiceProviderType = typeof(System.Security.Cryptography.DSACryptoServiceProvider); Type DESCryptoServiceProviderType = typeof(System.Security.Cryptography.DESCryptoServiceProvider); Type TripleDESCryptoServiceProviderType = typeof(System.Security.Cryptography.TripleDESCryptoServiceProvider); Type RC2CryptoServiceProviderType = typeof(System.Security.Cryptography.RC2CryptoServiceProvider); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription); Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO Type RNGCryptoServiceProviderType = typeof(System.Security.Cryptography.RNGCryptoServiceProvider); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO // Cryptography algorithms in System.Core are referenced by name rather than type so // that we don't force System.Core to load if we don't need any of its algorithms string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyRef.SystemCore; #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO string AesManagedType = "System.Security.Cryptography.AesManaged, " + AssemblyRef.SystemCore; #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO #if !FEATURE_CORECLR string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyRef.SystemCore; string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyRef.SystemCore; #endif string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyRef.SystemCore; string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyRef.SystemCore; string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyRef.SystemCore; string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyRef.SystemCore; string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyRef.SystemCore; string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyRef.SystemCore; string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyRef.SystemCore; string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyRef.SystemCore; #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO bool fipsOnly = AllowOnlyFipsAlgorithms; object SHA256DefaultType = typeof(SHA256Managed); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO if (fipsOnly) { SHA256DefaultType = SHA256CngType; } object SHA384DefaultType = fipsOnly ? (object)SHA384CngType : (object)typeof(SHA384Managed); object SHA512DefaultType = fipsOnly ? (object)SHA512CngType : (object)typeof(SHA512Managed); // Cryptography algorithms in System.Security string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity; #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // Random number generator ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType); ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO // Hash functions ht.Add("SHA", SHA1CryptoServiceProviderType); ht.Add("SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.SHA1Cng", SHA1CngType); ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType); ht.Add("MD5", MD5CryptoServiceProviderType); ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType); ht.Add("System.Security.Cryptography.MD5Cng", MD5CngType); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("SHA256", SHA256DefaultType); ht.Add("SHA-256", SHA256DefaultType); ht.Add("System.Security.Cryptography.SHA256", SHA256DefaultType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("System.Security.Cryptography.SHA256Cng", SHA256CngType); ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", SHA256CryptoServiceProviderType); ht.Add("SHA384", SHA384DefaultType); ht.Add("SHA-384", SHA384DefaultType); ht.Add("System.Security.Cryptography.SHA384", SHA384DefaultType); ht.Add("System.Security.Cryptography.SHA384Cng", SHA384CngType); ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", SHA384CryptoSerivceProviderType); ht.Add("SHA512", SHA512DefaultType); ht.Add("SHA-512", SHA512DefaultType); ht.Add("System.Security.Cryptography.SHA512", SHA512DefaultType); ht.Add("System.Security.Cryptography.SHA512Cng", SHA512CngType); ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", SHA512CryptoServiceProviderType); ht.Add("RIPEMD160", RIPEMD160ManagedType); ht.Add("RIPEMD-160", RIPEMD160ManagedType); ht.Add("System.Security.Cryptography.RIPEMD160", RIPEMD160ManagedType); ht.Add("System.Security.Cryptography.RIPEMD160Managed", RIPEMD160ManagedType); // Keyed Hash Algorithms #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type); ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("HMACMD5", HMACMD5Type); ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type); ht.Add("HMACRIPEMD160", HMACRIPEMD160Type); ht.Add("System.Security.Cryptography.HMACRIPEMD160", HMACRIPEMD160Type); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("HMACSHA1", HMACSHA1Type); ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type); ht.Add("HMACSHA256", HMACSHA256Type); ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("HMACSHA384", HMACSHA384Type); ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type); ht.Add("HMACSHA512", HMACSHA512Type); ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type); ht.Add("MACTripleDES", MAC3DESType); ht.Add("System.Security.Cryptography.MACTripleDES", MAC3DESType); // Asymmetric algorithms #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO && !FEATURE_CORECLR ht.Add("DSA", DSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType); ht.Add("ECDsa", ECDsaCngType); ht.Add("ECDsaCng", ECDsaCngType); ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType); ht.Add("ECDH", ECDiffieHellmanCngType); ht.Add("ECDiffieHellman", ECDiffieHellmanCngType); ht.Add("ECDiffieHellmanCng", ECDiffieHellmanCngType); ht.Add("System.Security.Cryptography.ECDiffieHellmanCng", ECDiffieHellmanCngType); // Symmetric algorithms ht.Add("DES", DESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType); ht.Add("3DES", TripleDESCryptoServiceProviderType); ht.Add("TripleDES", TripleDESCryptoServiceProviderType); ht.Add("Triple DES", TripleDESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType); ht.Add("RC2", RC2CryptoServiceProviderType); ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("Rijndael", RijndaelManagedType); ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType); // Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("AES", AesCryptoServiceProviderType); ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("AesManaged", AesManagedType); ht.Add("System.Security.Cryptography.AesManaged", AesManagedType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO // Data protectors ht.Add("DpapiDataProtector", DpapiDataProtectorType); ht.Add("System.Security.Cryptography.DpapiDataProtector", DpapiDataProtectorType); // Asymmetric signature descriptions ht.Add("http://www.w3.org/2000/09/xmldsig#dsa-sha1", DSASignatureDescriptionType); ht.Add("System.Security.Cryptography.DSASignatureDescription", DSASignatureDescriptionType); ht.Add("http://www.w3.org/2000/09/xmldsig#rsa-sha1", RSAPKCS1SHA1SignatureDescriptionType); ht.Add("System.Security.Cryptography.RSASignatureDescription", RSAPKCS1SHA1SignatureDescriptionType); // Xml Dsig/Enc Hash algorithms ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType); // Add the other hash algorithms introduced with XML Encryption #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256DefaultType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO && !FEATURE_CORECLR ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512DefaultType); ht.Add("http://www.w3.org/2001/04/xmlenc#ripemd160", RIPEMD160ManagedType); // Xml Encryption symmetric keys ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO // Xml Dsig Transforms // First arg must match the constants defined in System.Security.Cryptography.Xml.SignedXml ht.Add("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", "System.Security.Cryptography.Xml.XmlDsigC14NTransform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", "System.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2001/10/xml-exc-c14n#", "System.Security.Cryptography.Xml.XmlDsigExcC14NTransform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", "System.Security.Cryptography.Xml.XmlDsigExcC14NWithCommentsTransform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2000/09/xmldsig#base64", "System.Security.Cryptography.Xml.XmlDsigBase64Transform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/TR/1999/REC-xpath-19991116", "System.Security.Cryptography.Xml.XmlDsigXPathTransform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/TR/1999/REC-xslt-19991116", "System.Security.Cryptography.Xml.XmlDsigXsltTransform, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2000/09/xmldsig#enveloped-signature", "System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform, " + AssemblyRef.SystemSecurity); // the decryption transform ht.Add("http://www.w3.org/2002/07/decrypt#XML", "System.Security.Cryptography.Xml.XmlDecryptionTransform, " + AssemblyRef.SystemSecurity); // Xml licence transform. ht.Add("urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform", "System.Security.Cryptography.Xml.XmlLicenseTransform, " + AssemblyRef.SystemSecurity); // Xml Dsig KeyInfo // First arg (the key) is formed as elem.NamespaceURI + " " + elem.LocalName ht.Add("http://www.w3.org/2000/09/xmldsig# X509Data", "System.Security.Cryptography.Xml.KeyInfoX509Data, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2000/09/xmldsig# KeyName", "System.Security.Cryptography.Xml.KeyInfoName, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue", "System.Security.Cryptography.Xml.DSAKeyValue, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue", "System.Security.Cryptography.Xml.RSAKeyValue, " + AssemblyRef.SystemSecurity); ht.Add("http://www.w3.org/2000/09/xmldsig# RetrievalMethod", "System.Security.Cryptography.Xml.KeyInfoRetrievalMethod, " + AssemblyRef.SystemSecurity); // Xml EncryptedKey ht.Add("http://www.w3.org/2001/04/xmlenc# EncryptedKey", "System.Security.Cryptography.Xml.KeyInfoEncryptedKey, " + AssemblyRef.SystemSecurity); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/ ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO // Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384DefaultType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160", HMACRIPEMD160Type); #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type); #endif //FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO #if FEATURE_CRYPTO ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type); // X509 Extensions (custom decoders) // Basic Constraints OID value ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyRef.System); ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyRef.System); // Subject Key Identifier OID value ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyRef.System); // Key Usage OID value ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyRef.System); // Enhanced Key Usage OID value ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyRef.System); // X509Chain class can be overridden to use a different chain engine. ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyRef.System); // PKCS9 attributes ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyRef.SystemSecurity); ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyRef.SystemSecurity); ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyRef.SystemSecurity); ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyRef.SystemSecurity); ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyRef.SystemSecurity); #endif // FEATURE_CRYPTO defaultNameHT = ht; } return defaultNameHT; } } [System.Security.SecurityCritical] // auto-generated private static void InitializeConfigInfo() { #if FEATURE_CRYPTO && !FEATURE_CORECLR if (machineNameHT == null) { lock(InternalSyncObject) { if(machineNameHT == null) { ConfigNode cryptoConfig = OpenCryptoConfig(); if (cryptoConfig != null) { foreach (ConfigNode node in cryptoConfig.Children) { if (machineNameHT != null && machineOidHT != null) { break; } else if (machineNameHT == null && String.Compare(node.Name, "cryptoNameMapping", StringComparison.Ordinal) == 0) { machineNameHT = InitializeNameMappings(node); } else if (machineOidHT == null && String.Compare(node.Name, "oidMap", StringComparison.Ordinal) == 0) { machineOidHT = InitializeOidMappings(node); } } } // if we couldn't access the config file, or it didn't contain our config section // just create empty tables so that we don't end up trying to read the file // on every access to InitializeConfigInfo() if (machineNameHT == null) machineNameHT = new Dictionary<string, string>(); if (machineOidHT == null) machineOidHT = new Dictionary<string, string>(); } } } #else if (machineNameHT == null) machineNameHT = new Dictionary<string, string>(); if (machineOidHT == null) machineOidHT = new Dictionary<string, string>(); #endif //FEATURE_CRYPTO } /// <summary> /// Add a set of name -> algorithm mappings to be used for the current AppDomain. These mappings /// take precidense over the built-in mappings and the mappings in machine.config. This API is /// critical to prevent partial trust code from hooking trusted crypto operations. /// </summary> [SecurityCritical] public static void AddAlgorithm(Type algorithm, params string[] names) { if (algorithm == null) throw new ArgumentNullException("algorithm"); if (!algorithm.IsVisible) throw new ArgumentException(Environment.GetResourceString("Cryptography_AlgorithmTypesMustBeVisible"), "algorithm"); if (names == null) throw new ArgumentNullException("names"); Contract.EndContractBlock(); string[] algorithmNames = new string[names.Length]; Array.Copy(names, algorithmNames, algorithmNames.Length); // Pre-check the algorithm names for validity so that we don't add a few of the names and then // throw an exception if we find an invalid name partway through the list. foreach (string name in algorithmNames) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException(Environment.GetResourceString("Cryptography_AddNullOrEmptyName")); } } // Everything looks valid, so we're safe to take the table lock and add the name mappings. lock (InternalSyncObject) { foreach (string name in algorithmNames) { appNameHT[name] = algorithm; } } } [System.Security.SecuritySafeCritical] // auto-generated public static object CreateFromName (string name, params object[] args) { if (name == null) throw new ArgumentNullException("name"); Contract.EndContractBlock(); Type retvalType = null; Object retval; // First we'll do the machine-wide stuff, initializing if necessary InitializeConfigInfo(); // Check to see if we have an applicaiton defined mapping lock (InternalSyncObject) { retvalType = appNameHT.GetValueOrDefault(name); } // If we don't have a application defined mapping, search the machine table if (retvalType == null) { BCLDebug.Assert(machineNameHT != null, "machineNameHT != null"); String retvalTypeString = machineNameHT.GetValueOrDefault(name); if (retvalTypeString != null) { retvalType = Type.GetType(retvalTypeString, false, false); if (retvalType != null && !retvalType.IsVisible) retvalType = null; } } // If we didn't find it in the machine-wide table, look in the default table if (retvalType == null) { // We allow the default table to Types and Strings // Types get used for other stuff in mscorlib.dll // strings get used for delay-loaded stuff like System.Security.dll Object retvalObj = DefaultNameHT.GetValueOrDefault(name); if (retvalObj != null) { if (retvalObj is Type) { retvalType = (Type) retvalObj; } else if (retvalObj is String) { retvalType = Type.GetType((String) retvalObj, false, false); if (retvalType != null && !retvalType.IsVisible) retvalType = null; } } } // Maybe they gave us a classname. if (retvalType == null) { retvalType = Type.GetType(name, false, false); if (retvalType != null && !retvalType.IsVisible) retvalType = null; } // Still null? Then we didn't find it if (retvalType == null) return null; // Perform a CreateInstance by hand so we can check that the // constructor doesn't have a linktime demand attached (which would // be incorrrectly applied against mscorlib otherwise). RuntimeType rtType = retvalType as RuntimeType; if (rtType == null) return null; if (args == null) args = new Object[]{}; // Locate all constructors. MethodBase[] cons = rtType.GetConstructors(Activator.ConstructorDefault); if (cons == null) return null; List<MethodBase> candidates = new List<MethodBase>(); for (int i = 0; i < cons.Length; i ++) { MethodBase con = cons[i]; if (con.GetParameters().Length == args.Length) { candidates.Add(con); } } if (candidates.Count == 0) return null; cons = candidates.ToArray(); // Bind to matching ctor. Object state; RuntimeConstructorInfo rci = Type.DefaultBinder.BindToMethod(Activator.ConstructorDefault, cons, ref args, null, null, null, out state) as RuntimeConstructorInfo; // Check for ctor we don't like (non-existant, delegate or decorated // with declarative linktime demand). if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType)) return null; // Ctor invoke (actually causes the allocation as well). retval = rci.Invoke(Activator.ConstructorDefault, Type.DefaultBinder, args, null); // Reset any parameter re-ordering performed by the binder. if (state != null) Type.DefaultBinder.ReorderArgumentArray(ref args, state); return retval; } public static object CreateFromName (string name) { return CreateFromName(name, null); } /// <summary> /// Add a set of name -> OID mappings to be used for the current AppDomain. These mappings /// take precidense over the built-in mappings and the mappings in machine.config. This API is /// critical to prevent partial trust code from hooking trusted crypto operations. /// </summary> [SecurityCritical] public static void AddOID(string oid, params string[] names) { if (oid == null) throw new ArgumentNullException("oid"); if (names == null) throw new ArgumentNullException("names"); Contract.EndContractBlock(); string[] oidNames = new string[names.Length]; Array.Copy(names, oidNames, oidNames.Length); // Pre-check the input names for validity, so that we don't add a few of the names and throw an // exception if an invalid name is found further down the array. foreach (string name in oidNames) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException(Environment.GetResourceString("Cryptography_AddNullOrEmptyName")); } } // Everything is valid, so we're good to lock the hash table and add the application mappings lock (InternalSyncObject) { foreach (string name in oidNames) { appOidHT[name] = oid; } } } public static string MapNameToOID (string name) { return MapNameToOID(name, OidGroup.AllGroups); } [SecuritySafeCritical] internal static string MapNameToOID(string name, OidGroup oidGroup) { if (name == null) throw new ArgumentNullException("name"); Contract.EndContractBlock(); // First we'll do the machine-wide stuff, initializing if necessary InitializeConfigInfo(); string oid = null; // Check to see if we have an application defined mapping lock (InternalSyncObject) { oid = appOidHT.GetValueOrDefault(name); } // If we didn't find an application defined mapping, search the machine table if (oid == null) oid = machineOidHT.GetValueOrDefault(name); // If we didn't find it in the machine-wide table, look in the default table if (oid == null) oid = DefaultOidHT.GetValueOrDefault(name); #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // Try the CAPI table association if (oid == null) oid = X509Utils.GetOidFromFriendlyName(name, oidGroup); #endif // FEATURE_CRYPTO return oid; } static public byte[] EncodeOID (string str) { if (str == null) { throw new ArgumentNullException("str"); } Contract.EndContractBlock(); char[] sepArray = { '.' }; // valid ASN.1 separators String[] oidString = str.Split(sepArray); uint[] oidNums = new uint[oidString.Length]; for (int i = 0; i < oidString.Length; i++) { oidNums[i] = (uint) Int32.Parse(oidString[i], CultureInfo.InvariantCulture); } // Allocate the array to receive encoded oidNums byte[] encodedOidNums = new byte[oidNums.Length * 5]; // this is guaranteed to be longer than necessary int encodedOidNumsIndex = 0; // Handle the first two oidNums special if (oidNums.Length < 2) { throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_InvalidOID")); } uint firstTwoOidNums = (oidNums[0] * 40) + oidNums[1]; byte[] retval = EncodeSingleOIDNum(firstTwoOidNums); Array.Copy(retval, 0, encodedOidNums, encodedOidNumsIndex, retval.Length); encodedOidNumsIndex += retval.Length; for (int i = 2; i < oidNums.Length; i++) { retval = EncodeSingleOIDNum(oidNums[i]); Buffer.InternalBlockCopy(retval, 0, encodedOidNums, encodedOidNumsIndex, retval.Length); encodedOidNumsIndex += retval.Length; } // final return value is 06 <length> || encodedOidNums if (encodedOidNumsIndex > 0x7f) { throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_Config_EncodedOIDError")); } retval = new byte[ encodedOidNumsIndex + 2]; retval[0] = (byte) 0x06; retval[1] = (byte) encodedOidNumsIndex; Buffer.InternalBlockCopy(encodedOidNums, 0, retval, 2, encodedOidNumsIndex); return retval; } static private byte[] EncodeSingleOIDNum(uint dwValue) { byte[] retval; if ((int)dwValue < 0x80) { retval = new byte[1]; retval[0] = (byte) dwValue; return retval; } else if (dwValue < 0x4000) { retval = new byte[2]; retval[0] = (byte) ((dwValue >> 7) | 0x80); retval[1] = (byte) (dwValue & 0x7f); return retval; } else if (dwValue < 0x200000) { retval = new byte[3]; retval[0] = (byte) ((dwValue >> 14) | 0x80); retval[1] = (byte) ((dwValue >> 7) | 0x80); retval[2] = (byte) (dwValue & 0x7f); return retval; } else if (dwValue < 0x10000000) { retval = new byte[4]; retval[0] = (byte) ((dwValue >> 21) | 0x80); retval[1] = (byte) ((dwValue >> 14) | 0x80); retval[2] = (byte) ((dwValue >> 7) | 0x80); retval[3] = (byte) (dwValue & 0x7f); return retval; } else { retval = new byte[5]; retval[0] = (byte) ((dwValue >> 28) | 0x80); retval[1] = (byte) ((dwValue >> 21) | 0x80); retval[2] = (byte) ((dwValue >> 14) | 0x80); retval[3] = (byte) ((dwValue >> 7) | 0x80); retval[4] = (byte) (dwValue & 0x7f); return retval; } } private static Dictionary<string, string> InitializeNameMappings(ConfigNode nameMappingNode) { Contract.Assert(nameMappingNode != null, "No name mappings"); Contract.Assert(String.Compare(nameMappingNode.Name, "cryptoNameMapping", StringComparison.Ordinal) == 0, "Invalid name mapping root"); Dictionary<string, string> nameMappings = new Dictionary<string, string>(); Dictionary<string, string> typeAliases = new Dictionary<string, string>(); // find the cryptoClases element foreach (ConfigNode node in nameMappingNode.Children) { if (String.Compare(node.Name, "cryptoClasses", StringComparison.Ordinal) == 0) { foreach(ConfigNode cryptoClass in node.Children) { if (String.Compare(cryptoClass.Name, "cryptoClass", StringComparison.Ordinal) == 0) { if (cryptoClass.Attributes.Count > 0) { DictionaryEntry attribute = (DictionaryEntry)cryptoClass.Attributes[0]; typeAliases.Add((string)attribute.Key, (string)attribute.Value); } } } } else if(String.Compare(node.Name, "nameEntry", StringComparison.Ordinal) == 0) { string friendlyName = null; string className = null; foreach(DictionaryEntry attribute in node.Attributes) { if(String.Compare((string)attribute.Key, "name", StringComparison.Ordinal) == 0) friendlyName = (string)attribute.Value; else if(String.Compare((string)attribute.Key, "class", StringComparison.Ordinal) == 0) className = (string)attribute.Value; } if (friendlyName != null && className != null) { string typeName = typeAliases.GetValueOrDefault(className); if (typeName != null) nameMappings.Add(friendlyName, typeName); } } } return nameMappings; } private static Dictionary<string, string> InitializeOidMappings(ConfigNode oidMappingNode) { Contract.Assert(oidMappingNode != null, "No OID mappings"); Contract.Assert(String.Compare(oidMappingNode.Name, "oidMap", StringComparison.Ordinal) == 0, "Invalid OID mapping root"); Dictionary<string, string> oidMap = new Dictionary<string, string>(); foreach (ConfigNode node in oidMappingNode.Children) { if (String.Compare(node.Name, "oidEntry", StringComparison.Ordinal) == 0) { string oidString = null; string friendlyName = null; foreach (DictionaryEntry attribute in node.Attributes) { if (String.Compare((string)attribute.Key, "OID", StringComparison.Ordinal) == 0) oidString = (string)attribute.Value; else if (String.Compare((string)attribute.Key, "name", StringComparison.Ordinal) == 0) friendlyName = (string)attribute.Value; } if ((friendlyName != null) && (oidString != null)) oidMap.Add(friendlyName, oidString); } } return oidMap; } [System.Security.SecurityCritical] // auto-generated private static ConfigNode OpenCryptoConfig() { string machineConfigFile = System.Security.Util.Config.MachineDirectory + MachineConfigFilename; new FileIOPermission(FileIOPermissionAccess.Read, machineConfigFile).Assert(); if (!File.Exists(machineConfigFile)) return null; CodeAccessPermission.RevertAssert(); ConfigTreeParser parser = new ConfigTreeParser(); ConfigNode rootNode = parser.Parse(machineConfigFile, "configuration", true); if (rootNode == null) return null; // now, find the mscorlib tag with our version ConfigNode mscorlibNode = null; foreach (ConfigNode node in rootNode.Children) { bool versionSpecificMscorlib = false; if (String.Compare(node.Name, "mscorlib", StringComparison.Ordinal) == 0) { foreach (DictionaryEntry attribute in node.Attributes) { if (String.Compare((string)attribute.Key, "version", StringComparison.Ordinal) == 0) { versionSpecificMscorlib = true; if (String.Compare((string)attribute.Value, Version, StringComparison.Ordinal) == 0) { mscorlibNode = node; break; } } } // if this mscorlib element did not have a version attribute, then use it if (!versionSpecificMscorlib) mscorlibNode = node; } // use the first matching mscorlib we find if (mscorlibNode != null) break; } if (mscorlibNode == null) return null; // now look for the first crypto settings element foreach (ConfigNode node in mscorlibNode.Children) { if (String.Compare(node.Name, "cryptographySettings", StringComparison.Ordinal) == 0) return node; } return null; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedContextsClientSnippets { /// <summary>Snippet for ListContexts</summary> public void ListContextsRequestObject() { // Snippet: ListContexts(ListContextsRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ListContextsRequest request = new ListContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(request); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsRequestObjectAsync() { // Snippet: ListContextsAsync(ListContextsRequest, CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ListContextsRequest request = new ListContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContexts</summary> public void ListContexts() { // Snippet: ListContexts(string, string, int?, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsAsync() { // Snippet: ListContextsAsync(string, string, int?, CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContexts</summary> public void ListContextsResourceNames() { // Snippet: ListContexts(SessionName, string, int?, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsResourceNamesAsync() { // Snippet: ListContextsAsync(SessionName, string, int?, CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContextRequestObject() { // Snippet: GetContext(GetContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request Context response = contextsClient.GetContext(request); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextRequestObjectAsync() { // Snippet: GetContextAsync(GetContextRequest, CallSettings) // Additional: GetContextAsync(GetContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request Context response = await contextsClient.GetContextAsync(request); // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContext() { // Snippet: GetContext(string, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request Context response = contextsClient.GetContext(name); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextAsync() { // Snippet: GetContextAsync(string, CallSettings) // Additional: GetContextAsync(string, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request Context response = await contextsClient.GetContextAsync(name); // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContextResourceNames() { // Snippet: GetContext(ContextName, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request Context response = contextsClient.GetContext(name); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextResourceNamesAsync() { // Snippet: GetContextAsync(ContextName, CallSettings) // Additional: GetContextAsync(ContextName, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request Context response = await contextsClient.GetContextAsync(name); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContextRequestObject() { // Snippet: CreateContext(CreateContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; // Make the request Context response = contextsClient.CreateContext(request); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextRequestObjectAsync() { // Snippet: CreateContextAsync(CreateContextRequest, CallSettings) // Additional: CreateContextAsync(CreateContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; // Make the request Context response = await contextsClient.CreateContextAsync(request); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContext() { // Snippet: CreateContext(string, Context, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; Context context = new Context(); // Make the request Context response = contextsClient.CreateContext(parent, context); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextAsync() { // Snippet: CreateContextAsync(string, Context, CallSettings) // Additional: CreateContextAsync(string, Context, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; Context context = new Context(); // Make the request Context response = await contextsClient.CreateContextAsync(parent, context); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContextResourceNames() { // Snippet: CreateContext(SessionName, Context, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); Context context = new Context(); // Make the request Context response = contextsClient.CreateContext(parent, context); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextResourceNamesAsync() { // Snippet: CreateContextAsync(SessionName, Context, CallSettings) // Additional: CreateContextAsync(SessionName, Context, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); Context context = new Context(); // Make the request Context response = await contextsClient.CreateContextAsync(parent, context); // End snippet } /// <summary>Snippet for UpdateContext</summary> public void UpdateContextRequestObject() { // Snippet: UpdateContext(UpdateContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new FieldMask(), }; // Make the request Context response = contextsClient.UpdateContext(request); // End snippet } /// <summary>Snippet for UpdateContextAsync</summary> public async Task UpdateContextRequestObjectAsync() { // Snippet: UpdateContextAsync(UpdateContextRequest, CallSettings) // Additional: UpdateContextAsync(UpdateContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new FieldMask(), }; // Make the request Context response = await contextsClient.UpdateContextAsync(request); // End snippet } /// <summary>Snippet for UpdateContext</summary> public void UpdateContext() { // Snippet: UpdateContext(Context, FieldMask, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) Context context = new Context(); FieldMask updateMask = new FieldMask(); // Make the request Context response = contextsClient.UpdateContext(context, updateMask); // End snippet } /// <summary>Snippet for UpdateContextAsync</summary> public async Task UpdateContextAsync() { // Snippet: UpdateContextAsync(Context, FieldMask, CallSettings) // Additional: UpdateContextAsync(Context, FieldMask, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) Context context = new Context(); FieldMask updateMask = new FieldMask(); // Make the request Context response = await contextsClient.UpdateContextAsync(context, updateMask); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContextRequestObject() { // Snippet: DeleteContext(DeleteContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request contextsClient.DeleteContext(request); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextRequestObjectAsync() { // Snippet: DeleteContextAsync(DeleteContextRequest, CallSettings) // Additional: DeleteContextAsync(DeleteContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request await contextsClient.DeleteContextAsync(request); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContext() { // Snippet: DeleteContext(string, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request contextsClient.DeleteContext(name); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextAsync() { // Snippet: DeleteContextAsync(string, CallSettings) // Additional: DeleteContextAsync(string, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request await contextsClient.DeleteContextAsync(name); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContextResourceNames() { // Snippet: DeleteContext(ContextName, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request contextsClient.DeleteContext(name); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextResourceNamesAsync() { // Snippet: DeleteContextAsync(ContextName, CallSettings) // Additional: DeleteContextAsync(ContextName, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request await contextsClient.DeleteContextAsync(name); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContextsRequestObject() { // Snippet: DeleteAllContexts(DeleteAllContextsRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request contextsClient.DeleteAllContexts(request); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsRequestObjectAsync() { // Snippet: DeleteAllContextsAsync(DeleteAllContextsRequest, CallSettings) // Additional: DeleteAllContextsAsync(DeleteAllContextsRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request await contextsClient.DeleteAllContextsAsync(request); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContexts() { // Snippet: DeleteAllContexts(string, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request contextsClient.DeleteAllContexts(parent); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsAsync() { // Snippet: DeleteAllContextsAsync(string, CallSettings) // Additional: DeleteAllContextsAsync(string, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request await contextsClient.DeleteAllContextsAsync(parent); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContextsResourceNames() { // Snippet: DeleteAllContexts(SessionName, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request contextsClient.DeleteAllContexts(parent); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsResourceNamesAsync() { // Snippet: DeleteAllContextsAsync(SessionName, CallSettings) // Additional: DeleteAllContextsAsync(SessionName, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request await contextsClient.DeleteAllContextsAsync(parent); // End snippet } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.IO; using System.ComponentModel; using System.Globalization; using Microsoft.Win32; namespace Microsoft.VisualStudio.Shell { /// <summary> /// This attribute can be used to register information about a project system that supports /// the WAP flavor/sub-type. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] internal class WAProvideProjectFactoryAttribute : RegistrationAttribute { private Type _factoryType; private string _displayProjectFileExtensions = null; private string _name; private string _displayName = null; private string _defaultProjectExtension = null; private string _possibleProjectExtensions = null; private string _projectTemplatesDirectory; private int _sortPriority = 100; private Guid _folderGuid = Guid.Empty; private string _languageVsTemplate; private string _templateGroupIDsVsTemplate; private string _templateIDsVsTemplate; private string _displayProjectTypeVsTemplate; private string _projectSubTypeVsTemplate; private bool _newProjectRequireNewFolderVsTemplate = false; private bool _showOnlySpecifiedTemplatesVsTemplate = false; public WAProvideProjectFactoryAttribute(Type factoryType, string name) { if (factoryType == null) { throw new ArgumentNullException("factoryType"); } _factoryType = factoryType; _name = name; } public WAProvideProjectFactoryAttribute(Type factoryType, string name, string languageVsTemplate, bool showOnlySpecifiedTemplatesVsTemplate, string templateGroupIDsVsTemplate, string templateIDsVsTemplate) { if (factoryType == null) { throw new ArgumentNullException("factoryType"); } _factoryType = factoryType; _name = name; _languageVsTemplate = languageVsTemplate; _templateGroupIDsVsTemplate = templateGroupIDsVsTemplate; _templateIDsVsTemplate = templateIDsVsTemplate; _showOnlySpecifiedTemplatesVsTemplate = showOnlySpecifiedTemplatesVsTemplate; } public string Name { get { return _name; } } public string DisplayName { get { return _displayName; } } public int SortPriority { get { return _sortPriority; } set { _sortPriority = value; } } public Type FactoryType { get { return _factoryType; } } public string DisplayProjectFileExtensions { get { return _displayProjectFileExtensions; } } public string DefaultProjectExtension { get { return _defaultProjectExtension; } } public string PossibleProjectExtensions { get { return _possibleProjectExtensions; } } public string ProjectTemplatesDirectory { get { return _projectTemplatesDirectory; } } public string FolderGuid { get { return _folderGuid.ToString("B"); } set { _folderGuid = new Guid(value); } } public string LanguageVsTemplate { get { return _languageVsTemplate; } set { _languageVsTemplate = value; } } public string DisplayProjectTypeVsTemplate { get { return _displayProjectTypeVsTemplate; } set { _displayProjectTypeVsTemplate = value; } } public string ProjectSubTypeVsTemplate { get { return _projectSubTypeVsTemplate; } set { _projectSubTypeVsTemplate = value; } } public bool NewProjectRequireNewFolderVsTemplate { get { return _newProjectRequireNewFolderVsTemplate; } set { _newProjectRequireNewFolderVsTemplate = value; } } public bool ShowOnlySpecifiedTemplatesVsTemplate { get { return _showOnlySpecifiedTemplatesVsTemplate; } set { _showOnlySpecifiedTemplatesVsTemplate = value; } } public string TemplateGroupIDsVsTemplate { get { return _templateGroupIDsVsTemplate; } set { _templateGroupIDsVsTemplate = value; } } public string TemplateIDsVsTemplate { get { return _templateIDsVsTemplate; } set { _templateIDsVsTemplate = value; } } private string ProjectRegKey { get { return string.Format(CultureInfo.InvariantCulture, "Projects\\{0}", FactoryType.GUID.ToString("B")); } } private string NewPrjTemplateRegKey(RegistrationContext context) { return string.Format(CultureInfo.InvariantCulture, "NewProjectTemplates\\TemplateDirs\\{0}\\/1", context.ComponentType.GUID.ToString("B")); } public override void Register(RegistrationContext context) { //context.Log.WriteLine(SR.GetString(SR.Reg_NotifyProjectFactory, FactoryType.Name)); using (Key projectKey = context.CreateKey(ProjectRegKey)) { projectKey.SetValue(string.Empty, Name); if (_displayName != null) projectKey.SetValue("DisplayName", _displayName); if (_displayProjectFileExtensions != null) projectKey.SetValue("DisplayProjectFileExtensions", _displayProjectFileExtensions); projectKey.SetValue("Package", context.ComponentType.GUID.ToString("B")); if (_defaultProjectExtension != null) projectKey.SetValue("DefaultProjectExtension", _defaultProjectExtension); if (_possibleProjectExtensions != null) projectKey.SetValue("PossibleProjectExtensions", _possibleProjectExtensions); if (_projectTemplatesDirectory != null) { if (!System.IO.Path.IsPathRooted(_projectTemplatesDirectory)) { // If path is not rooted, make it relative to package path _projectTemplatesDirectory = System.IO.Path.Combine(context.ComponentPath, _projectTemplatesDirectory); } projectKey.SetValue("ProjectTemplatesDir", context.EscapePath(_projectTemplatesDirectory)); } // VsTemplate Specific Keys // if (_languageVsTemplate != null) projectKey.SetValue("Language(VsTemplate)", _languageVsTemplate); if (_showOnlySpecifiedTemplatesVsTemplate || _templateGroupIDsVsTemplate != null || _templateIDsVsTemplate != null) { int showOnlySpecifiedTemplatesVsTemplate = _showOnlySpecifiedTemplatesVsTemplate ? 1 : 0; projectKey.SetValue("ShowOnlySpecifiedTemplates(VsTemplate)", showOnlySpecifiedTemplatesVsTemplate); } if (_templateGroupIDsVsTemplate != null) projectKey.SetValue("TemplateGroupIDs(VsTemplate)", _templateGroupIDsVsTemplate); if (_templateIDsVsTemplate != null) projectKey.SetValue("TemplateIDs(VsTemplate)", _templateIDsVsTemplate); if (_displayProjectTypeVsTemplate != null) projectKey.SetValue("DisplayProjectType(VsTemplate)", _displayProjectTypeVsTemplate); if (_projectSubTypeVsTemplate != null) projectKey.SetValue("ProjectSubType(VsTemplate)", _projectSubTypeVsTemplate); if (_newProjectRequireNewFolderVsTemplate) projectKey.SetValue("NewProjectRequireNewFolder(VsTemplate)", (int)1); } } public override void Unregister(RegistrationContext context) { context.RemoveKey(ProjectRegKey); context.RemoveKey(NewPrjTemplateRegKey(context)); } } }
using OpenKh.Engine.Renders; using OpenKh.Kh2; using OpenKh.Kh2.Messages; using OpenKh.Tools.Common.Rendering; using OpenKh.Tools.Kh2TextEditor.Interfaces; using OpenKh.Tools.Kh2TextEditor.Models; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using Xe.Tools; using Xe.Tools.Wpf.Commands; using ColorPickerWPF; using System.Windows.Media; namespace OpenKh.Tools.Kh2TextEditor.ViewModels { public class TextEditorViewModel : BaseNotifyPropertyChanged, ICurrentMessageEncoder, IInvalidateErrorCount { private MessagesModel _messages; private List<Msg.Entry> _msgs; private IMessageEncoder _currentMessageEncoder; private MessageModel _selectedItem; private string _currentText; private string _searchTerm; private RenderingMessageContext textContext; private bool _showErrors; public RelayCommand HandleAddition { get; } public RelayCommand HandleRemoval { get; } public RelayCommand HandleComm { get; } public RelayCommand HandleIcon { get; } public List<Msg.Entry> MessageEntries { get => _msgs; set { _msgs = value; ResetMessagesView(); } } public ISpriteDrawing Drawing { get; } public MessagesModel Messages { get => _messages; set { _messages = value; OnPropertyChanged(); } } public MessageModel SelectedItem { get => _selectedItem; set { _selectedItem = value; _currentText = _selectedItem?.Text; OnPropertyChanged(); OnPropertyChanged(nameof(Text)); } } public string Text { get => _currentText; set { var selectedItem = SelectedItem; if (selectedItem == null) return; _currentText = value; selectedItem.Text = value; OnPropertyChanged(); } } public string SearchTerm { get => _searchTerm; set { _searchTerm = value; PerformFiltering(); } } public RenderingMessageContext TextContext { get => textContext; set { textContext = value; OnPropertyChanged(); if (CurrentMessageEncoder != textContext.Encoder) { CurrentMessageEncoder = textContext.Encoder; } } } public IMessageEncoder CurrentMessageEncoder { get => _currentMessageEncoder; private set { _currentMessageEncoder = value; _messages?.InvalidateText(); OnPropertyChanged(nameof(SelectedItem)); OnPropertyChanged(); } } public bool ShowErrors { get => _showErrors; set { _showErrors = value; PerformFiltering(); } } public int ErrorCount => _messages.Items.Count(x => !x.DoesNotContainErrors); public Visibility AnyErrorVisibility => ErrorCount == 0 ? Visibility.Collapsed : Visibility.Visible; public TextEditorViewModel() { Drawing = new SpriteDrawingDirect3D(); CurrentMessageEncoder = Encoders.InternationalSystem; _messages = new MessagesModel(this, this, new Msg.Entry[] { }); HandleRemoval = new RelayCommand(x => { MessageEntries.RemoveAll(x => x.Id == SelectedItem.Id); ResetMessagesView(); }); HandleAddition = new RelayCommand(x => { int _id = MessageEntries.Max(x => x.Id); MessageEntries.Add(new Msg.Entry() { Id = _id + 1, Data = CurrentMessageEncoder.Encode(MsgSerializer.DeserializeText("FAKE").ToList()) }); ResetMessagesView(); }); HandleComm = new RelayCommand(x => { int _o = Convert.ToInt32(x); switch (_o) { case 0: Text += "{:reset}"; break; case 1: { Color _color; bool _ok = ColorPickerWindow.ShowDialog(out _color); if (_ok) Text += "{:color " + string.Format("#{0}{1}{2}{3}", _color.R.ToString("X2"), _color.G.ToString("X2"), _color.B.ToString("X2"), _color.A.ToString("X2")) + "}"; } break; case 2: Text += "{:scale 16}"; break; case 3: Text += "{:width 100}"; break; case 4: Text += "{:clear}"; break; case 5: Text += "{:position 0,0}"; break; } }); HandleIcon = new RelayCommand(x => { Text += "{:icon " + x + "}"; }); } public void SelectMessage(int id) => SelectedItem = Messages.GetMessage(id); public void InvalidateErrorCount() { if (!_messages.Items.Any(x => !x.DoesNotContainErrors) && ShowErrors) ShowErrors = false; OnPropertyChanged(nameof(ErrorCount)); OnPropertyChanged(nameof(AnyErrorVisibility)); } private void ResetMessagesView() { if (MessageEntries != null) Messages = new MessagesModel(this, this, MessageEntries); } private void PerformFiltering() { if (string.IsNullOrWhiteSpace(_searchTerm)) _messages.Filter(x => Filter(x, FilterNone)); else _messages.Filter(x => Filter(x, FilterTextAndId)); } private bool Filter(MessageModel arg, Func<MessageModel, bool> filter) => FilterError(arg) && filter(arg); private bool FilterError(MessageModel arg) => !ShowErrors || (ShowErrors && arg.DoesNotContainErrors == false); private bool FilterNone(MessageModel arg) => true; private bool FilterTextAndId(MessageModel arg) => arg.Title.ToLower().Contains(SearchTerm.ToLower()); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; namespace SPALM.SPSF.Library { public partial class SelectionForm : Form { List<NameValueItem> nvitems = null; private bool multipleItems = false; private bool groupItems = true; private object selection; public SelectionForm(List<NameValueItem> _nvitems, object _selection, bool grouped) { InitializeComponent(); nvitems = _nvitems; groupItems = grouped; selection = _selection; GenerateTree(); } private void GenerateTree() { treeView.Nodes.Clear(); //if in all items the groups are empty then grouping should be disabled CheckGrouped(); if (selection is NameValueItem) { InitiallySelectedNameValueItem = (NameValueItem)selection; } else if (selection is NameValueItem[]) { multipleItems = true; InitiallySelectedNameValueItems = (NameValueItem[])selection; } if (multipleItems) { treeView.CheckBoxes = true; } if (nvitems != null) { if (groupItems) { //first grouping foreach (NameValueItem nvitem in nvitems) { string key = nvitem.Group; if ((key == null) || (key == "")) { key = "[nogroup]"; } TreeNode groupnode = null; if (!treeView.Nodes.ContainsKey(key)) { //create new group groupnode = new TreeNode(); groupnode.Text = key; groupnode.Name = key; //if(key.Equals(SPSFConstants.ThisSolutionNodeText, StringComparison.InvariantCultureIgnoreCase)){ // groupnode.NodeFont = new Font(treeView.Font, FontStyle.Bold); //} treeView.Nodes.Add(groupnode); } else { groupnode = treeView.Nodes[key]; } if (groupnode != null && !string.IsNullOrEmpty(nvitem.Name) && (!nvitem.Name.StartsWith("$Resources:",StringComparison.InvariantCultureIgnoreCase) || key.Equals(SPSFConstants.ThisSolutionNodeText, StringComparison.InvariantCultureIgnoreCase))) { TreeNode tnode = new TreeNode(); tnode.Text = nvitem.Name; tnode.Tag = nvitem; tnode.ToolTipText = nvitem.Description; groupnode.Nodes.Add(tnode); if (InitiallySelectedNameValueItem != null) { if (nvitem.Value == InitiallySelectedNameValueItem.Value) { groupnode.Expand(); } } if (InitiallySelectedNameValueItems != null) { foreach (NameValueItem nvi in InitiallySelectedNameValueItems) { if (nvi.Value == nvitem.Value) { tnode.Checked = true; groupnode.Expand(); } } } } } } else { foreach (NameValueItem nvitem in nvitems) { //gibt es das item schon auf 1. ebene? if (!NodeExists(nvitem) && !string.IsNullOrEmpty(nvitem.Name) ) /*&& (!nvitem.Name.StartsWith("$Resources:",StringComparison.InvariantCultureIgnoreCase) || key.Equals(SPSFConstants.ThisSolutionNodeText, StringComparison.InvariantCultureIgnoreCase)))*/ { TreeNode tnode = new TreeNode(); tnode.Text = nvitem.Name; tnode.Tag = nvitem; tnode.ToolTipText = nvitem.Description; treeView.Nodes.Add(tnode); } } } } treeView.Sort(); ValidateButtons(); } private void SearchTree() { string searchstring = this.textBox1.Text; if(searchstring != "") { treeView.Nodes.Clear(); searchstring = searchstring.ToUpper(); foreach (NameValueItem nvitem in nvitems) { bool additem = false; if (nvitem.Name != null) { if (nvitem.Name.ToUpper().Contains(searchstring)) { additem = true; } } else if (nvitem.Value != null) { if (nvitem.Value.ToUpper().Contains(searchstring)) { additem = true; } } if (additem) { //gibt es das item schon auf 1. ebene? if (!NodeExists(nvitem)) { TreeNode tnode = new TreeNode(); tnode.Text = nvitem.Name; tnode.Tag = nvitem; tnode.ToolTipText = nvitem.Description; treeView.Nodes.Add(tnode); } } } } treeView.Sort(); } private bool NodeExists(NameValueItem nvitem) { foreach (TreeNode node in treeView.Nodes) { if (node.Tag != null) { if ((((NameValueItem)node.Tag).Name == nvitem.Name) && (((NameValueItem)node.Tag).Value == nvitem.Value)) { return true; } } } return false; } private void CheckGrouped() { bool nonEmptyGroupFound = false; foreach (NameValueItem nvitem in nvitems) { if (nvitem.Group.Trim() != "") { nonEmptyGroupFound = true; } } if (!nonEmptyGroupFound) { groupItems = false; } } public NameValueItem InitiallySelectedNameValueItem = null; public NameValueItem[] InitiallySelectedNameValueItems = null; public NameValueItem SelectedNameValueItem = null; public NameValueItem[] SelectedNameValueItems = new NameValueItem[0]; private void treeView_AfterSelect(object sender, TreeViewEventArgs e) { if (treeView.SelectedNode != null) { if (treeView.SelectedNode.Tag != null) { NameValueItem item = (NameValueItem)treeView.SelectedNode.Tag; selectedValue.Text = item.Value; selectedName.Text = item.Name; selectedDescription.Text = item.Description; selectedGroup.Text = item.Group; } else { selectedValue.Text = ""; selectedName.Text = ""; selectedDescription.Text = ""; selectedGroup.Text = ""; } } ValidateButtons(); } private void FindSelectedNodes(TreeNodeCollection nodes, ArrayList items) { foreach (TreeNode node in nodes) { if (node.Checked) { if (node.Tag != null) { if (node.Tag is NameValueItem) { items.Add(node.Tag); } } } FindSelectedNodes(node.Nodes, items); } } private void ValidateButtons() { buton_ok.Enabled = false; if ((treeView.SelectedNode != null) && (treeView.SelectedNode.Tag != null)) { buton_ok.Enabled = true; } else if (treeView.CheckBoxes) { ArrayList items = new ArrayList(); FindSelectedNodes(treeView.Nodes, items); if (items.Count > 0) { buton_ok.Enabled = true; } } } private void button1_Click(object sender, EventArgs e) { CloseForm(); } private void CloseForm() { if (multipleItems) { ArrayList items = new ArrayList(); FindSelectedNodes(treeView.Nodes, items); SelectedNameValueItems = new NameValueItem[items.Count]; for (int i = 0; i < items.Count; i++) { SelectedNameValueItems[i] = (NameValueItem)items[i]; } } else { if (treeView.SelectedNode != null) { if (treeView.SelectedNode.Tag != null) { SelectedNameValueItem = (NameValueItem)treeView.SelectedNode.Tag; selectedValue.Text = SelectedNameValueItem.Value; selectedName.Text = SelectedNameValueItem.Name; selectedDescription.Text = SelectedNameValueItem.Description; selectedGroup.Text = SelectedNameValueItem.Group; } else { selectedValue.Text = ""; selectedName.Text = ""; selectedDescription.Text = ""; selectedGroup.Text = ""; } } } } private void button3_Click(object sender, EventArgs e) { SearchTree(); ValidateButtons(); } private void button1_Click_1(object sender, EventArgs e) { textBox1.Text = ""; GenerateTree(); ValidateButtons(); } private void treeView_AfterCheck(object sender, TreeViewEventArgs e) { if (e.Node != null) { if (e.Node.Nodes.Count > 0) { foreach(TreeNode childNode in e.Node.Nodes) { childNode.Checked = e.Node.Checked; } } } ValidateButtons(); } private void treeView_DoubleClick(object sender, EventArgs e) { if (buton_ok.Enabled) { CloseForm(); } } private void textBox1_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { SearchTree(); ValidateButtons(); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void panel2_Paint(object sender, PaintEventArgs e) { } } }
// 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 Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExpressionTreeRewriter : ExprVisitorBase { public static Expr Rewrite(Expr expr, ExprFactory expressionFactory, SymbolLoader symbolLoader) { ExpressionTreeRewriter rewriter = new ExpressionTreeRewriter(expressionFactory, symbolLoader); return rewriter.Visit(expr); } private ExprFactory expressionFactory; private SymbolLoader symbolLoader; private ExprBoundLambda currentAnonMeth; private ExprFactory GetExprFactory() { return expressionFactory; } private SymbolLoader GetSymbolLoader() { return symbolLoader; } private ExpressionTreeRewriter(ExprFactory expressionFactory, SymbolLoader symbolLoader) { this.expressionFactory = expressionFactory; this.symbolLoader = symbolLoader; } protected override Expr Dispatch(Expr expr) { Debug.Assert(expr != null); Expr result = base.Dispatch(expr); if (result == expr) { throw Error.InternalCompilerError(); } return result; } ///////////////////////////////////////////////////////////////////////////////// // Statement types. protected override Expr VisitASSIGNMENT(ExprAssignment assignment) { Debug.Assert(assignment != null); // For assignments, we either have a member assignment or an indexed assignment. //Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL()); Expr lhs; if (assignment.LHS is ExprProperty prop) { if (prop.OptionalArguments== null) { // Regular property. lhs = Visit(prop); } else { // Indexed assignment. Here we need to find the instance of the object, create the // PropInfo for the thing, and get the array of expressions that make up the index arguments. // // The LHS becomes Expression.Property(instance, indexerInfo, arguments). Expr instance = Visit(prop.MemberGroup.OptionalObject); Expr propInfo = GetExprFactory().CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats); Expr arguments = GenerateParamsArray( GenerateArgsList(prop.OptionalArguments), PredefinedType.PT_EXPRESSION); lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments); } } else { lhs = Visit(assignment.LHS); } Expr rhs = Visit(assignment.RHS); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } protected override Expr VisitMULTIGET(ExprMultiGet pExpr) { return Visit(pExpr.OptionalMulti.Left); } protected override Expr VisitMULTI(ExprMulti pExpr) { Expr rhs = Visit(pExpr.Operator); Expr lhs = Visit(pExpr.Left); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } ///////////////////////////////////////////////////////////////////////////////// // Expression types. protected override Expr VisitBOUNDLAMBDA(ExprBoundLambda anonmeth) { Debug.Assert(anonmeth != null); ExprBoundLambda prevAnonMeth = currentAnonMeth; currentAnonMeth = anonmeth; MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA); CType delegateType = anonmeth.DelegateType; TypeArray lambdaTypeParams = GetSymbolLoader().getBSymmgr().AllocParams(1, new CType[] { delegateType }); AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION); MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams); Expr createParameters = CreateWraps(anonmeth); Expr body = RewriteLambdaBody(anonmeth); Expr parameters = RewriteLambdaParameters(anonmeth); Expr args = GetExprFactory().CreateList(body, parameters); CType typeRet = GetSymbolLoader().GetTypeManager().SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs); ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); ExprCall call = GetExprFactory().CreateCall(0, typeRet, args, pMemGroup, mwi); Expr callLambda = call; call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA; currentAnonMeth = prevAnonMeth; if (createParameters != null) { callLambda = GetExprFactory().CreateSequence(createParameters, callLambda); } Expr expr = DestroyWraps(anonmeth, callLambda); // If we are already inside an expression tree rewrite and this is an expression tree lambda // then it needs to be quoted. if (currentAnonMeth != null) { expr = GenerateCall(PREDEFMETH.PM_EXPRESSION_QUOTE, expr); } return expr; } protected override Expr VisitCONSTANT(ExprConstant expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } protected override Expr VisitLOCAL(ExprLocal local) { Debug.Assert(local != null); Debug.Assert(!local.Local.isThis); // this is true for all parameters of an expression lambda if (local.Local.wrap != null) { return local.Local.wrap; } Debug.Assert(local.Local.fUsedInAnonMeth); return GetExprFactory().CreateHoistedLocalInExpression(); } protected override Expr VisitFIELD(ExprField expr) { Debug.Assert(expr != null); Expr pObject; if (expr.OptionalObject== null) { pObject = GetExprFactory().CreateNull(); } else { pObject = Visit(expr.OptionalObject); } ExprFieldInfo pFieldInfo = GetExprFactory().CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo); } protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr) { Debug.Assert(expr != null); return GenerateUserDefinedConversion(expr, expr.Argument); } protected override Expr VisitCAST(ExprCast pExpr) { Debug.Assert(pExpr != null); Expr pArgument = pExpr.Argument; // If we have generated an identity cast or reference cast to a base class // we can omit the cast. if (pArgument.Type == pExpr.Type || GetSymbolLoader().IsBaseClassOfClass(pArgument.Type, pExpr.Type) || CConversions.FImpRefConv(GetSymbolLoader(), pArgument.Type, pExpr.Type)) { return Visit(pArgument); } // If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is // a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree. if (pExpr.Type != null && pExpr.Type.isPredefType(PredefinedType.PT_G_EXPRESSION) && pArgument is ExprBoundLambda) { return Visit(pArgument); } Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked()); if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // Propagate the unbox flag to the call for the ExpressionTreeCallRewriter. result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } return result; } protected override Expr VisitCONCAT(ExprConcat expr) { Debug.Assert(expr != null); PREDEFMETH pdm; if (expr.FirstArgument.Type.isPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.isPredefType(PredefinedType.PT_STRING)) { pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2; } else { pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2; } Expr p1 = Visit(expr.FirstArgument); Expr p2 = Visit(expr.SecondArgument); MethodSymbol method = GetPreDefMethod(pdm); Expr methodInfo = GetExprFactory().CreateMethodInfo(method, GetSymbolLoader().GetPredefindType(PredefinedType.PT_STRING), null); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo); } protected override Expr VisitBINOP(ExprBinOp expr) { Debug.Assert(expr != null); if (expr.UserDefinedCallMethod != null) { return GenerateUserDefinedBinaryOperator(expr); } else { return GenerateBuiltInBinaryOperator(expr); } } protected override Expr VisitUNARYOP(ExprUnaryOp pExpr) { Debug.Assert(pExpr != null); if (pExpr.UserDefinedCallMethod != null) { return GenerateUserDefinedUnaryOperator(pExpr); } else { return GenerateBuiltInUnaryOperator(pExpr); } } protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr) { Debug.Assert(pExpr != null); Expr arr = Visit(pExpr.Array); Expr args = GenerateIndexList(pExpr.Index); if (args is ExprList) { Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args); } protected override Expr VisitCALL(ExprCall expr) { Debug.Assert(expr != null); switch (expr.NullableCallLiftKind) { default: break; case NullableCallLiftKind.NullableIntermediateConversion: case NullableCallLiftKind.NullableConversion: case NullableCallLiftKind.NullableConversionConstructor: return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked()); case NullableCallLiftKind.NotLiftedIntermediateConversion: case NullableCallLiftKind.UserDefinedConversion: return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst); } if (expr.MethWithInst.Meth().IsConstructor()) { return GenerateConstructor(expr); } ExprMemberGroup memberGroup = expr.MemberGroup; if (memberGroup.IsDelegate) { return GenerateDelegateInvoke(expr); } Expr pObject; if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject== null) { pObject = GetExprFactory().CreateNull(); } else { pObject = expr.MemberGroup.OptionalObject; // If we have, say, an int? which is the object of a call to ToString // then we do NOT want to generate ((object)i).ToString() because that // will convert a null-valued int? to a null object. Rather what we want // to do is box it to a ValueType and call ValueType.ToString. // // To implement this we say that if the object of the call is an implicit boxing cast // then just generate the object, not the cast. If the cast is explicit in the // source code then it will be an EXPLICITCAST and we will visit it normally. // // It might be better to rewrite the expression tree API so that it // can handle in the general case all implicit boxing conversions. Right now it // requires that all arguments to a call that need to be boxed be explicitly boxed. if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast) { pObject = cast.Argument; } pObject = Visit(pObject); } Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.MethWithInst); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL; Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null); return GenerateCall(pdm, pObject, methodInfo, Params); } protected override Expr VisitPROP(ExprProperty expr) { Debug.Assert(expr != null); Expr pObject; if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject== null) { pObject = GetExprFactory().CreateNull(); } else { pObject = Visit(expr.MemberGroup.OptionalObject); } Expr propInfo = GetExprFactory().CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType()); if (expr.OptionalArguments != null) { // It is an indexer property. Turn it into a virtual method call. Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo); } protected override Expr VisitARRINIT(ExprArrayInit expr) { Debug.Assert(expr != null); // POSSIBLE ERROR: Multi-d should be an error? Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).GetElementType()); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params); } protected override Expr VisitZEROINIT(ExprZeroInit expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } protected override Expr VisitTYPEOF(ExprTypeOf expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } private Expr GenerateDelegateInvoke(ExprCall expr) { Debug.Assert(expr != null); ExprMemberGroup memberGroup = expr.MemberGroup; Debug.Assert(memberGroup.IsDelegate); Expr oldObject = memberGroup.OptionalObject; Debug.Assert(oldObject != null); Expr pObject = Visit(oldObject); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params); } private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break; case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break; case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break; case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR; break; case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND; break; case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break; case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break; case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break; case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break; case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break; case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break; case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break; case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break; case ExpressionKind.Multiply: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY; break; case ExpressionKind.Subtract: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT; break; case ExpressionKind.Add: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD; break; default: throw Error.InternalCompilerError(); } Expr origL = expr.OptionalLeftChild; Expr origR = expr.OptionalRightChild; Debug.Assert(origL != null); Debug.Assert(origR != null); CType typeL = origL.Type; CType typeR = origR.Type; Expr newL = Visit(origL); Expr newR = Visit(origR); bool didEnumConversion = false; CType convertL = null; CType convertR = null; if (typeL.isEnumType()) { // We have already inserted casts if not lifted, so we should never see an enum. Debug.Assert(expr.IsLifted); convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.underlyingEnumType()); typeL = convertL; didEnumConversion = true; } else if (typeL is NullableType nubL && nubL.UnderlyingType.isEnumType()) { Debug.Assert(expr.IsLifted); convertL = GetSymbolLoader().GetTypeManager().GetNullable(nubL.UnderlyingType.underlyingEnumType()); typeL = convertL; didEnumConversion = true; } if (typeR.isEnumType()) { Debug.Assert(expr.IsLifted); convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.underlyingEnumType()); typeR = convertR; didEnumConversion = true; } else if (typeR is NullableType nubR && nubR.UnderlyingType.isEnumType()) { Debug.Assert(expr.IsLifted); convertR = GetSymbolLoader().GetTypeManager().GetNullable(nubR.UnderlyingType.underlyingEnumType()); typeR = convertR; didEnumConversion = true; } if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR) { convertR = typeL; } if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL) { convertL = typeR; } if (convertL != null) { newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL)); } if (convertR != null) { newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR)); } Expr call = GenerateCall(pdm, newL, newR); if (didEnumConversion && expr.Type.StripNubs().isEnumType()) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type)); } return call; } private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.UnaryPlus: return Visit(expr.Child); case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.Negate: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE; break; default: throw Error.InternalCompilerError(); } Expr origOp = expr.Child; return GenerateBuiltInUnaryOperator(pdm, origOp, expr); } private Expr GenerateBuiltInUnaryOperator(PREDEFMETH pdm, Expr pOriginalOperator, Expr pOperator) { Expr op = Visit(pOriginalOperator); bool isNullableEnum = pOriginalOperator.Type is NullableType nub && nub.underlyingType().isEnumType(); if (isNullableEnum) { Debug.Assert(pOperator.Kind == ExpressionKind.BitwiseNot); // The only built-in unary operator defined on nullable enum. CType underlyingType = pOriginalOperator.Type.StripNubs().underlyingEnumType(); CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType); op = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, op, CreateTypeOf(nullableType)); } Expr call = GenerateCall(pdm, op); if (isNullableEnum) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(pOperator.Type)); } return call; } private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break; case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break; case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break; case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break; case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break; case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break; case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break; case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break; case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break; case ExpressionKind.StringEq: case ExpressionKind.StringNotEq: case ExpressionKind.DelegateEq: case ExpressionKind.DelegateNotEq: case ExpressionKind.Eq: case ExpressionKind.NotEq: case ExpressionKind.GreaterThanOrEqual: case ExpressionKind.GreaterThan: case ExpressionKind.LessThanOrEqual: case ExpressionKind.LessThan: return GenerateUserDefinedComparisonOperator(expr); case ExpressionKind.DelegateSubtract: case ExpressionKind.Subtract: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED; break; case ExpressionKind.DelegateAdd: case ExpressionKind.Add: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED; break; case ExpressionKind.Multiply: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } Expr p1 = expr.OptionalLeftChild; Expr p2 = expr.OptionalRightChild; Expr udcall = expr.OptionalUserDefinedCall; if (udcall != null) { Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp); if (udcall is ExprCall ascall) { ExprList args = (ExprList)ascall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = args.OptionalElement; p2 = args.OptionalNextListNode; } else { ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp; Debug.Assert(userLogOp != null); ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = ((ExprWrap)args.OptionalElement).OptionalExpression; p2 = args.OptionalNextListNode; } } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod); Expr call = GenerateCall(pdm, p1, p2, methodInfo); // Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate, // not the operand delegate CType. We must cast to the delegate CType. if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd) { Expr pTypeOf = CreateTypeOf(expr.Type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } return call; } private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; Expr arg = expr.Child; ExprCall call = (ExprCall)expr.OptionalUserDefinedCall; if (call != null) { // Use the actual argument of the call; it may contain user-defined // conversions or be a bound lambda, and that will not be in the original // argument stashed away in the left child of the operator. arg = call.OptionalArguments; } Debug.Assert(arg != null && arg.Kind != ExpressionKind.List); switch (expr.Kind) { case ExpressionKind.True: case ExpressionKind.False: return Visit(call); case ExpressionKind.UnaryPlus: pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED; break; case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.DecimalNegate: case ExpressionKind.Negate: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED; break; case ExpressionKind.Inc: case ExpressionKind.Dec: case ExpressionKind.DecimalInc: case ExpressionKind.DecimalDec: pdm = PREDEFMETH.PM_EXPRESSION_CALL; break; default: throw Error.InternalCompilerError(); } Expr op = Visit(arg); Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod); if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec || expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec) { return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION)); } return GenerateCall(pdm, op, methodInfo); } private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.DelegateEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.DelegateNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break; case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } Expr p1 = expr.OptionalLeftChild; Expr p2 = expr.OptionalRightChild; if (expr.OptionalUserDefinedCall != null) { ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall; ExprList args = (ExprList)udcall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = args.OptionalElement; p2 = args.OptionalNextListNode; } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); Expr lift = GetExprFactory().CreateBoolConstant(false); // We never lift to null in C#. Expr methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod); return GenerateCall(pdm, p1, p2, lift, methodInfo); } private Expr RewriteLambdaBody(ExprBoundLambda anonmeth) { Debug.Assert(anonmeth != null); Debug.Assert(anonmeth.OptionalBody != null); Debug.Assert(anonmeth.OptionalBody.OptionalStatements != null); // There ought to be no way to get an empty statement block successfully converted into an expression tree. Debug.Assert(anonmeth.OptionalBody.OptionalStatements.OptionalNextStatement== null); ExprBlock body = anonmeth.OptionalBody; // The most likely case: if (body.OptionalStatements is ExprReturn ret) { Debug.Assert(ret.OptionalObject != null); return Visit(ret.OptionalObject); } // This can only if it is a void delegate and this is a void expression, such as a call to a void method // or something like Expression<Action<Foo>> e = (Foo f) => f.MyEvent += MyDelegate; throw Error.InternalCompilerError(); } private Expr RewriteLambdaParameters(ExprBoundLambda anonmeth) { Debug.Assert(anonmeth != null); // new ParameterExpression[2] {Parameter(typeof(type1), name1), Parameter(typeof(type2), name2)} Expr paramArrayInitializerArgs = null; Expr paramArrayInitializerArgsTail = paramArrayInitializerArgs; for (Symbol sym = anonmeth.ArgumentScope; sym != null; sym = sym.nextChild) { if (!(sym is LocalVariableSymbol local)) { continue; } if (local.isThis) { continue; } GetExprFactory().AppendItemToList(local.wrap, ref paramArrayInitializerArgs, ref paramArrayInitializerArgsTail); } return GenerateParamsArray(paramArrayInitializerArgs, PredefinedType.PT_PARAMETEREXPRESSION); } private Expr GenerateConversion(Expr arg, CType CType, bool bChecked) { return GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked()); } private Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked) { PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; Expr pTypeOf = CreateTypeOf(pType); return GenerateCall(pdm, pTarget, pTypeOf); } private Expr GenerateValueAccessConversion(Expr pArgument) { Debug.Assert(pArgument != null); CType pStrippedTypeOfArgument = pArgument.Type.StripNubs(); Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr); } private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method) { Expr target = Visit(arg); return GenerateUserDefinedConversion(arg, type, target, method); } private Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method) { // The user-defined explicit conversion from enum? to decimal or decimal? requires // that we convert the enum? to its nullable underlying CType. if (isEnumToDecimalConversion(arg.Type, CType)) { // Special case: If we have enum? to decimal? then we need to emit // a conversion from enum? to its nullable underlying CType first. // This is unfortunate; we ought to reorganize how conversions are // represented in the Expr tree so that this is more transparent. // converting an enum to its underlying CType never fails, so no need to check it. CType underlyingType = arg.Type.StripNubs().underlyingEnumType(); CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType); Expr typeofNubEnum = CreateTypeOf(nullableType); target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum); } // If the methodinfo does not return the target CType AND this is not a lifted conversion // from one value CType to another, then we need to wrap the whole thing in another conversion, // e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate // Convert(Convert(myint, typeof(S?), op_implicit), typeof(S)) CType pMethodReturnType = GetSymbolLoader().GetTypeManager().SubstType(method.Meth().RetType, method.GetType(), method.TypeArgs); bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType))); Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType); Expr methodInfo = GetExprFactory().CreateMethodInfo(method); PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED; Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo); if (fDontLiftReturnType) { return callUserDefinedConversion; } PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; Expr typeofOuter = CreateTypeOf(CType); return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter); } private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument) { Expr pCastCall = pExpr.UserDefinedCall; Expr pCastArgument = pExpr.Argument; Expr pConversionSource; if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type) && IsNullableValueAccess(pCastArgument, pArgument)) { // We have an implicit conversion of nullable CType to the value CType, generate a convert node for it. pConversionSource = GenerateValueAccessConversion(pArgument); } else { ExprCall call = pCastCall as ExprCall; Expr pUDConversion = call?.PConversions; if (pUDConversion != null) { if (pUDConversion is ExprCall convCall) { Expr pUDConversionArgument = convCall.OptionalArguments; if (IsNullableValueAccess(pUDConversionArgument, pArgument)) { pConversionSource = GenerateValueAccessConversion(pArgument); } else { pConversionSource = Visit(pUDConversionArgument); } return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked()); } // This can happen if we have a UD conversion from C to, say, int, // and we have an explicit cast to decimal?. The conversion should // then be bound as two chained user-defined conversions. Debug.Assert(pUDConversion is ExprUserDefinedConversion); // Just recurse. return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument); } pConversionSource = Visit(pCastArgument); } return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod); } private Expr GenerateParameter(string name, CType CType) { GetSymbolLoader().GetPredefindType(PredefinedType.PT_STRING); // force an ensure state ExprConstant nameString = GetExprFactory().CreateStringConstant(name); ExprTypeOf pTypeOf = CreateTypeOf(CType); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString); } private MethodSymbol GetPreDefMethod(PREDEFMETH pdm) { return GetSymbolLoader().getPredefinedMembers().GetMethod(pdm); } private ExprTypeOf CreateTypeOf(CType CType) { return GetExprFactory().CreateTypeOf(CType); } private Expr CreateWraps(ExprBoundLambda anonmeth) { Expr sequence = null; for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild) { if (!(sym is LocalVariableSymbol local)) { continue; } if (local.isThis) { continue; } Debug.Assert(anonmeth.OptionalBody != null); Expr create = GenerateParameter(local.name.Text, local.GetType()); local.wrap = GetExprFactory().CreateWrap(create); Expr save = GetExprFactory().CreateSave(local.wrap); if (sequence == null) { sequence = save; } else { sequence = GetExprFactory().CreateSequence(sequence, save); } } return sequence; } private Expr DestroyWraps(ExprBoundLambda anonmeth, Expr sequence) { for (Symbol sym = anonmeth.ArgumentScope; sym != null; sym = sym.nextChild) { if (!(sym is LocalVariableSymbol local)) { continue; } if (local.isThis) { continue; } Debug.Assert(local.wrap != null); Debug.Assert(anonmeth.OptionalBody != null); Expr freeWrap = GetExprFactory().CreateWrap(local.wrap); sequence = GetExprFactory().CreateReverseSequence(sequence, freeWrap); } return sequence; } private Expr GenerateConstructor(ExprCall expr) { Debug.Assert(expr != null); Debug.Assert(expr.MethWithInst.Meth().IsConstructor()); Expr constructorInfo = GetExprFactory().CreateMethodInfo(expr.MethWithInst); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params); } private Expr GenerateArgsList(Expr oldArgs) { Expr newArgs = null; Expr newArgsTail = newArgs; for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext()) { Expr oldArg = it.Current(); GetExprFactory().AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail); } return newArgs; } private Expr GenerateIndexList(Expr oldIndices) { CType intType = symbolLoader.GetPredefindType(PredefinedType.PT_INT); Expr newIndices = null; Expr newIndicesTail = newIndices; for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext()) { Expr newIndex = it.Current(); if (newIndex.Type != intType) { ExprClass exprType = expressionFactory.CreateClass(intType); newIndex = expressionFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, exprType, newIndex); newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW; } Expr rewrittenIndex = Visit(newIndex); expressionFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail); } return newIndices; } private Expr GenerateConstant(Expr expr) { EXPRFLAG flags = 0; AggregateType pObject = GetSymbolLoader().GetPredefindType(PredefinedType.PT_OBJECT); if (expr.Type is NullType) { ExprTypeOf pTypeOf = CreateTypeOf(pObject); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf); } AggregateType stringType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_STRING); if (expr.Type != stringType) { flags = EXPRFLAG.EXF_BOX; } ExprClass objectType = GetExprFactory().CreateClass(pObject); ExprCast cast = GetExprFactory().CreateCast(flags, objectType, expr); ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2); } private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1) { MethodSymbol method = GetPreDefMethod(pdm); // this should be enforced in an earlier pass and the transform pass should not // be handling this error if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = GetExprFactory().CreateList(arg1, arg2); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = GetExprFactory().CreateList(arg1, arg2, arg3); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = GetExprFactory().CreateList(arg1, arg2, arg3, arg4); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); ExprCall call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt) { int parameterCount = ExpressionIterator.Count(args); AggregateType paramsArrayElementType = GetSymbolLoader().GetPredefindType(pt); ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1, true); ExprConstant paramsArrayArg = GetExprFactory().CreateIntegerConstant(parameterCount); return GetExprFactory().CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount }, parameterCount); } private void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2) { // If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then // we need to ensure that the unlifted actual arguments are promoted to their nullable CType. Debug.Assert(expr != null); Debug.Assert(pp1 != null); Debug.Assert(pp1 != null); Debug.Assert(pp2 != null); Debug.Assert(pp2 != null); MethodSymbol method = expr.UserDefinedCallMethod.Meth(); Expr orig1 = expr.OptionalLeftChild; Expr orig2 = expr.OptionalRightChild; Debug.Assert(orig1 != null && orig2 != null); Expr new1 = pp1; Expr new2 = pp2; CType fptype1 = method.Params[0]; CType fptype2 = method.Params[1]; CType aatype1 = orig1.Type; CType aatype2 = orig2.Type; // Is the operator even a candidate for lifting? if (!(fptype1 is AggregateType fat1) || !fat1.getAggregate().IsValueType() || !(fptype2 is AggregateType fat2) || !fat2.getAggregate().IsValueType()) { return; } CType nubfptype1 = GetSymbolLoader().GetTypeManager().GetNullable(fptype1); CType nubfptype2 = GetSymbolLoader().GetTypeManager().GetNullable(fptype2); // If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1? if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType)) { new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1)); } // If we have X op null, or T1? op T2, or null op T2, lift second arg to T2? if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType)) { new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2)); } pp1 = new1; pp2 = new2; } private bool IsNullableValueType(CType pType) => pType is NullableType && pType.StripNubs() is AggregateType agg && agg.getAggregate().IsValueType(); private bool IsNullableValueAccess(Expr pExpr, Expr pObject) { Debug.Assert(pExpr != null); return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType; } private static bool isEnumToDecimalConversion(CType argtype, CType desttype) => argtype.StripNubs().isEnumType() && desttype.StripNubs().isPredefType(PredefinedType.PT_DECIMAL); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Threading; using Microsoft.Management.Infrastructure; using Dbg = System.Management.Automation.Diagnostics; // // Now define the set of commands for manipulating modules. // namespace Microsoft.PowerShell.Commands { /// <summary> /// Implements a cmdlet that gets the list of loaded modules... /// </summary> [Cmdlet(VerbsCommon.Get, "Module", DefaultParameterSetName = ParameterSet_Loaded, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096696")] [OutputType(typeof(PSModuleInfo))] public sealed class GetModuleCommand : ModuleCmdletBase, IDisposable { #region Cmdlet parameters private const string ParameterSet_Loaded = "Loaded"; private const string ParameterSet_AvailableLocally = "Available"; private const string ParameterSet_AvailableInPsrpSession = "PsSession"; private const string ParameterSet_AvailableInCimSession = "CimSession"; /// <summary> /// This parameter specifies the current pipeline object. /// </summary> [Parameter(ParameterSetName = ParameterSet_Loaded, ValueFromPipeline = true, Position = 0)] [Parameter(ParameterSetName = ParameterSet_AvailableLocally, ValueFromPipeline = true, Position = 0)] [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession, ValueFromPipeline = true, Position = 0)] [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, ValueFromPipeline = true, Position = 0)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public string[] Name { get; set; } /// <summary> /// This parameter specifies the current pipeline object. /// </summary> [Parameter(ParameterSetName = ParameterSet_Loaded, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = ParameterSet_AvailableLocally, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public ModuleSpecification[] FullyQualifiedName { get; set; } /// <summary> /// If specified, all loaded modules should be returned, otherwise only the visible /// modules should be returned. /// </summary> [Parameter(ParameterSetName = ParameterSet_Loaded)] [Parameter(ParameterSetName = ParameterSet_AvailableLocally)] public SwitchParameter All { get; set; } /// <summary> /// If specified, then Get-Module will return the set of available modules... /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableLocally, Mandatory = true)] [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)] [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession)] public SwitchParameter ListAvailable { get; set; } /// <summary> /// If specified, then Get-Module will return the set of available modules which supports the specified PowerShell edition... /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableLocally)] [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)] [ArgumentCompleter(typeof(PSEditionArgumentCompleter))] public string PSEdition { get; set; } /// <summary> /// When set, CompatiblePSEditions checking is disabled for modules in the System32 (Windows PowerShell) module directory. /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableLocally)] [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)] [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession)] public SwitchParameter SkipEditionCheck { get { return (SwitchParameter)BaseSkipEditionCheck; } set { BaseSkipEditionCheck = value; } } /// <summary> /// If specified, then Get-Module refreshes the internal cmdlet analysis cache. /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableLocally)] [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)] [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession)] public SwitchParameter Refresh { get; set; } /// <summary> /// If specified, then Get-Module will attempt to discover PowerShell modules on a remote computer using the specified session. /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession, Mandatory = true)] [ValidateNotNull] public PSSession PSSession { get; set; } /// <summary> /// If specified, then Get-Module will attempt to discover PS-CIM modules on a remote computer using the specified session. /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, Mandatory = true)] [ValidateNotNull] public CimSession CimSession { get; set; } /// <summary> /// For interoperability with 3rd party CIM servers, user can specify custom resource URI. /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, Mandatory = false)] [ValidateNotNull] public Uri CimResourceUri { get; set; } /// <summary> /// For interoperability with 3rd party CIM servers, user can specify custom namespace. /// </summary> [Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, Mandatory = false)] [ValidateNotNullOrEmpty] public string CimNamespace { get; set; } #endregion Cmdlet parameters #region Remote discovery private IEnumerable<PSModuleInfo> GetAvailableViaPsrpSessionCore(string[] moduleNames, Runspace remoteRunspace) { Dbg.Assert(remoteRunspace != null, "Caller should verify remoteRunspace != null"); using (var powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.Runspace = remoteRunspace; powerShell.AddCommand("Get-Module"); powerShell.AddParameter("ListAvailable", true); if (Refresh.IsPresent) { powerShell.AddParameter("Refresh", true); } if (moduleNames != null) { powerShell.AddParameter("Name", moduleNames); } string errorMessageTemplate = string.Format( CultureInfo.InvariantCulture, Modules.RemoteDiscoveryRemotePsrpCommandFailed, "Get-Module"); foreach ( PSObject outputObject in RemoteDiscoveryHelper.InvokePowerShell(powerShell, this, errorMessageTemplate, this.CancellationToken)) { PSModuleInfo moduleInfo = RemoteDiscoveryHelper.RehydratePSModuleInfo(outputObject); yield return moduleInfo; } } } private static PSModuleInfo GetModuleInfoForRemoteModuleWithoutManifest(RemoteDiscoveryHelper.CimModule cimModule) { return new PSModuleInfo(cimModule.ModuleName, null, null); } private PSModuleInfo ConvertCimModuleInfoToPSModuleInfo(RemoteDiscoveryHelper.CimModule cimModule, string computerName) { try { bool containedErrors = false; if (cimModule.MainManifest == null) { return GetModuleInfoForRemoteModuleWithoutManifest(cimModule); } string temporaryModuleManifestPath = Path.Combine( RemoteDiscoveryHelper.GetModulePath(cimModule.ModuleName, null, computerName, this.Context.CurrentRunspace), Path.GetFileName(cimModule.ModuleName)); Hashtable mainData = null; if (!containedErrors) { mainData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable( cimModule.MainManifest, temporaryModuleManifestPath, this, ref containedErrors); if (mainData == null) { return GetModuleInfoForRemoteModuleWithoutManifest(cimModule); } } if (!containedErrors) { mainData = RemoteDiscoveryHelper.RewriteManifest(mainData); } Hashtable localizedData = mainData; // TODO/FIXME - this needs full path support from the provider PSModuleInfo moduleInfo = null; if (!containedErrors) { ImportModuleOptions throwAwayOptions = new ImportModuleOptions(); moduleInfo = LoadModuleManifest( temporaryModuleManifestPath, null, // scriptInfo mainData, localizedData, 0 /* - don't write errors, don't load elements, don't return null on first error */, this.BaseMinimumVersion, this.BaseMaximumVersion, this.BaseRequiredVersion, this.BaseGuid, ref throwAwayOptions, ref containedErrors); } if ((moduleInfo == null) || containedErrors) { moduleInfo = GetModuleInfoForRemoteModuleWithoutManifest(cimModule); } return moduleInfo; } catch (Exception e) { ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, cimModule.ModuleName); this.WriteError(errorRecord); return null; } } private IEnumerable<PSModuleInfo> GetAvailableViaCimSessionCore(IEnumerable<string> moduleNames, CimSession cimSession, Uri resourceUri, string cimNamespace) { IEnumerable<RemoteDiscoveryHelper.CimModule> remoteModules = RemoteDiscoveryHelper.GetCimModules( cimSession, resourceUri, cimNamespace, moduleNames, true /* onlyManifests */, this, this.CancellationToken); IEnumerable<PSModuleInfo> remoteModuleInfos = remoteModules .Select(cimModule => this.ConvertCimModuleInfoToPSModuleInfo(cimModule, cimSession.ComputerName)) .Where(static moduleInfo => moduleInfo != null); return remoteModuleInfos; } #endregion Remote discovery #region Cancellation support private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private CancellationToken CancellationToken { get { return _cancellationTokenSource.Token; } } /// <summary> /// When overridden in the derived class, interrupts currently /// running code within the command. It should interrupt BeginProcessing, /// ProcessRecord, and EndProcessing. /// Default implementation in the base class just returns. /// </summary> protected override void StopProcessing() { _cancellationTokenSource.Cancel(); } #endregion #region IDisposable Members /// <summary> /// Releases resources associated with this object. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases resources associated with this object. /// </summary> private void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _cancellationTokenSource.Dispose(); } _disposed = true; } private bool _disposed; #endregion private void AssertListAvailableMode() { if (!this.ListAvailable.IsPresent) { string errorMessage = Modules.RemoteDiscoveryWorksOnlyInListAvailableMode; ArgumentException argumentException = new ArgumentException(errorMessage); ErrorRecord errorRecord = new ErrorRecord( argumentException, "RemoteDiscoveryWorksOnlyInListAvailableMode", ErrorCategory.InvalidArgument, null); this.ThrowTerminatingError(errorRecord); } } /// <summary> /// Write out the specified modules... /// </summary> protected override void ProcessRecord() { // Name and FullyQualifiedName should not be specified at the same time. // Throw out terminating error if this is the case. if ((Name != null) && (FullyQualifiedName != null)) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Name", "FullyQualifiedName"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "NameAndFullyQualifiedNameCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } // -SkipEditionCheck only makes sense for -ListAvailable (otherwise the module is already loaded) if (SkipEditionCheck && !ListAvailable) { ErrorRecord error = new ErrorRecord( new InvalidOperationException(Modules.SkipEditionCheckNotSupportedWithoutListAvailable), nameof(Modules.SkipEditionCheckNotSupportedWithoutListAvailable), ErrorCategory.InvalidOperation, targetObject: null); ThrowTerminatingError(error); } var strNames = new List<string>(); if (Name != null) { strNames.AddRange(Name); } var moduleSpecTable = new Dictionary<string, ModuleSpecification>(StringComparer.OrdinalIgnoreCase); if (FullyQualifiedName != null) { for (int modSpecIndex = 0; modSpecIndex < FullyQualifiedName.Length; modSpecIndex++) { FullyQualifiedName[modSpecIndex] = FullyQualifiedName[modSpecIndex].WithNormalizedName(Context, SessionState.Path.CurrentLocation.Path); } moduleSpecTable = FullyQualifiedName.ToDictionary(static moduleSpecification => moduleSpecification.Name, StringComparer.OrdinalIgnoreCase); strNames.AddRange(FullyQualifiedName.Select(static spec => spec.Name)); } string[] names = strNames.Count > 0 ? strNames.ToArray() : null; if (ParameterSetName.Equals(ParameterSet_Loaded, StringComparison.OrdinalIgnoreCase)) { AssertNameDoesNotResolveToAPath(names, Modules.ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames, "ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames"); GetLoadedModules(names, moduleSpecTable, this.All); } else if (ParameterSetName.Equals(ParameterSet_AvailableLocally, StringComparison.OrdinalIgnoreCase)) { if (ListAvailable.IsPresent) { GetAvailableLocallyModules(names, moduleSpecTable, this.All); } else { AssertNameDoesNotResolveToAPath(names, Modules.ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames, "ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames"); GetLoadedModules(names, moduleSpecTable, this.All); } } else if (ParameterSetName.Equals(ParameterSet_AvailableInPsrpSession, StringComparison.OrdinalIgnoreCase)) { AssertListAvailableMode(); AssertNameDoesNotResolveToAPath(names, Modules.RemoteDiscoveryWorksOnlyForUnQualifiedNames, "RemoteDiscoveryWorksOnlyForUnQualifiedNames"); GetAvailableViaPsrpSession(names, moduleSpecTable, this.PSSession); } else if (ParameterSetName.Equals(ParameterSet_AvailableInCimSession, StringComparison.OrdinalIgnoreCase)) { AssertListAvailableMode(); AssertNameDoesNotResolveToAPath(names, Modules.RemoteDiscoveryWorksOnlyForUnQualifiedNames, "RemoteDiscoveryWorksOnlyForUnQualifiedNames"); GetAvailableViaCimSession(names, moduleSpecTable, this.CimSession, this.CimResourceUri, this.CimNamespace); } else { Dbg.Assert(false, "Unrecognized parameter set"); } } private void AssertNameDoesNotResolveToAPath(string[] names, string stringFormat, string resourceId) { if (names != null) { foreach (var n in names) { if (n.Contains(StringLiterals.DefaultPathSeparator) || n.Contains(StringLiterals.AlternatePathSeparator)) { string errorMessage = StringUtil.Format(stringFormat, n); var argumentException = new ArgumentException(errorMessage); var errorRecord = new ErrorRecord( argumentException, resourceId, ErrorCategory.InvalidArgument, n); this.ThrowTerminatingError(errorRecord); } } } } private void GetAvailableViaCimSession(IEnumerable<string> names, IDictionary<string, ModuleSpecification> moduleSpecTable, CimSession cimSession, Uri resourceUri, string cimNamespace) { IEnumerable<PSModuleInfo> remoteModules = GetAvailableViaCimSessionCore(names, cimSession, resourceUri, cimNamespace); foreach (PSModuleInfo remoteModule in FilterModulesForEditionAndSpecification(remoteModules, moduleSpecTable)) { RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(remoteModule, cimSession, resourceUri, cimNamespace); this.WriteObject(remoteModule); } } private void GetAvailableViaPsrpSession(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, PSSession session) { IEnumerable<PSModuleInfo> remoteModules = GetAvailableViaPsrpSessionCore(names, session.Runspace); foreach (PSModuleInfo remoteModule in FilterModulesForEditionAndSpecification(remoteModules, moduleSpecTable)) { RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(remoteModule, session); this.WriteObject(remoteModule); } } private void GetAvailableLocallyModules(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, bool all) { IEnumerable<PSModuleInfo> modules = GetModule(names, all, Refresh); foreach (PSModuleInfo module in FilterModulesForEditionAndSpecification(modules, moduleSpecTable)) { var psModule = new PSObject(module); psModule.TypeNames.Insert(0, "ModuleInfoGrouping"); WriteObject(psModule); } } private void GetLoadedModules(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, bool all) { var modulesToWrite = Context.Modules.GetModules(names, all); foreach (PSModuleInfo moduleInfo in FilterModulesForEditionAndSpecification(modulesToWrite, moduleSpecTable)) { WriteObject(moduleInfo); } } /// <summary> /// Filter an enumeration of PowerShell modules based on the required PowerShell edition /// and the module specification constraints set for each module (if any). /// </summary> /// <param name="modules">The modules to filter through.</param> /// <param name="moduleSpecificationTable">Module constraints, keyed by module name, to filter modules of that name by.</param> /// <returns>All modules from the original input that meet both any module edition and module specification constraints provided.</returns> private IEnumerable<PSModuleInfo> FilterModulesForEditionAndSpecification( IEnumerable<PSModuleInfo> modules, IDictionary<string, ModuleSpecification> moduleSpecificationTable) { #if !UNIX // Edition check only applies to Windows System32 module path if (!SkipEditionCheck && ListAvailable && !All) { modules = modules.Where(static module => module.IsConsideredEditionCompatible); } #endif if (!string.IsNullOrEmpty(PSEdition)) { modules = modules.Where(module => module.CompatiblePSEditions.Contains(PSEdition, StringComparer.OrdinalIgnoreCase)); } if (moduleSpecificationTable != null && moduleSpecificationTable.Count > 0) { modules = FilterModulesForSpecificationMatch(modules, moduleSpecificationTable); } return modules; } /// <summary> /// Take an enumeration of modules and only return those that match a specification /// in the given specification table, or have no corresponding entry in the specification table. /// </summary> /// <param name="modules">The modules to filter by specification match.</param> /// <param name="moduleSpecificationTable">The specification lookup table to filter the modules on.</param> /// <returns>The modules that match their corresponding table entry, or which have no table entry.</returns> private static IEnumerable<PSModuleInfo> FilterModulesForSpecificationMatch( IEnumerable<PSModuleInfo> modules, IDictionary<string, ModuleSpecification> moduleSpecificationTable) { Dbg.Assert(moduleSpecificationTable != null, $"Caller to verify that {nameof(moduleSpecificationTable)} is not null"); Dbg.Assert(moduleSpecificationTable.Count != 0, $"Caller to verify that {nameof(moduleSpecificationTable)} is not empty"); foreach (PSModuleInfo module in modules) { IEnumerable<ModuleSpecification> candidateModuleSpecs = GetCandidateModuleSpecs(moduleSpecificationTable, module); // Modules with table entries only get returned if they match them // We skip the name check since modules have already been prefiltered base on the moduleSpec path/name foreach (ModuleSpecification moduleSpec in candidateModuleSpecs) { if (ModuleIntrinsics.IsModuleMatchingModuleSpec(module, moduleSpec, skipNameCheck: true)) { yield return module; } } } } /// <summary> /// Take a dictionary of module specifications and return those that potentially match the module /// passed in as a parameter (checks on names and paths). /// </summary> /// <param name="moduleSpecTable">The module specifications to filter candidates from.</param> /// <param name="module">The module to find candidates for from the module specification table.</param> /// <returns>The module specifications matching the module based on name, path and subpath.</returns> private static IEnumerable<ModuleSpecification> GetCandidateModuleSpecs( IDictionary<string, ModuleSpecification> moduleSpecTable, PSModuleInfo module) { const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; foreach (ModuleSpecification moduleSpec in moduleSpecTable.Values) { WildcardPattern namePattern = WildcardPattern.Get(moduleSpec.Name, options); if (namePattern.IsMatch(module.Name) || moduleSpec.Name == module.Path || module.Path.Contains(moduleSpec.Name)) { yield return moduleSpec; } } } } /// <summary> /// PSEditionArgumentCompleter for PowerShell Edition names. /// </summary> public class PSEditionArgumentCompleter : IArgumentCompleter { /// <summary> /// CompleteArgument. /// </summary> public IEnumerable<CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) { var wordToCompletePattern = WildcardPattern.Get(string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", WildcardOptions.IgnoreCase); foreach (var edition in Utils.AllowedEditionValues) { if (wordToCompletePattern.IsMatch(edition)) { yield return new CompletionResult(edition, edition, CompletionResultType.Text, edition); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using Bond.Protocols; public abstract class SerializerGenerator<R, W> : ISerializerGenerator<R, W> { protected delegate Expression Serialize(IParser parser); readonly Expression<Action<R, W, int>> deferredSerialize; readonly List<Expression<Action<R, W>>> serializeActions = new List<Expression<Action<R, W>>>(); readonly Dictionary<KeyValuePair<IParser, Serialize>, int> serializeIndex = new Dictionary<KeyValuePair<IParser, Serialize>, int>(); readonly Stack<KeyValuePair<IParser, Serialize>> inProgress = new Stack<KeyValuePair<IParser, Serialize>>(); protected SerializerGenerator(Expression<Action<R, W, int>> deferredSerialize) { this.deferredSerialize = deferredSerialize; } public abstract IEnumerable<Expression<Action<R, W>>> Generate(IParser parser); protected IEnumerable<Expression<Action<R, W>>> SerializeActions { get { return serializeActions; } } /// <summary> /// Generate expression provided by Serialize delegate, either as inline expression or a lambda call /// </summary> /// <param name="serialize">Delegate to generate serialization expression</param> /// <param name="parser">Parser used for the source of serialization</param> /// <param name="writer">Writer to use for serialization</param> /// <param name="inline">True if the expression can be inlined</param> /// <remarks> /// Generates lambda calls for recursive schemas to avoid infinitely inlining the same expression. /// Expression is considered the same when both serialize delegate and parser are the same. It is /// caller's responsibility to assure that the pair of serialize delegate and parser can be used /// to identify generated expression. For object serializer, when the parser is ObjectParser, this /// is generally guaranteed by using parser instance per schema type. Transcoding may use a single /// parser instance but different Serialize delegates for each transcoded schema type (e.g. when /// the delegate captures schema metadata). /// </remarks> protected Expression GenerateSerialize(Serialize serialize, IParser parser, ParameterExpression writer, bool inline) { var key = new KeyValuePair<IParser, Serialize>(parser, serialize); inline = inline && inProgress.Count != 0 && !inProgress.Contains(key); Expression body; inProgress.Push(key); if (inline) { body = serialize(parser); if (parser.ReaderParam != parser.ReaderValue && parser.ReaderValue.Type.IsBondStruct()) { body = Expression.Block( new[] { parser.ReaderParam }, Expression.Assign(parser.ReaderParam, Expression.Convert(parser.ReaderValue, parser.ReaderParam.Type)), body); } } else { int index; if (!serializeIndex.TryGetValue(key, out index)) { index = serializeActions.Count; serializeIndex[key] = index; serializeActions.Add(null); serializeActions[index] = Expression.Lambda<Action<R, W>>( serialize(parser), parser.ReaderParam, writer); } body = Expression.Invoke( deferredSerialize, PrunedExpression.Convert(parser.ReaderValue, parser.ReaderParam.Type), writer, Expression.Constant(index)); } inProgress.Pop(); return body; } } internal class SerializerTransform<R, W> : SerializerGenerator<R, W> { delegate Expression SerializeWithSchema(IParser parser, RuntimeSchema schema); static readonly Expression noMetadata = Expression.Constant(null, typeof(Metadata)); readonly RuntimeSchema runtimeSchema; readonly ProtocolWriter<W> writer = new ProtocolWriter<W>(); readonly Dictionary<RuntimeSchema, Serialize> serializeDelegates = new Dictionary<RuntimeSchema, Serialize>(new TypeDefComparer()); readonly bool inlineNested; static readonly bool untaggedWriter = typeof (IUntaggedProtocolReader).IsAssignableFrom(typeof (W).GetAttribute<ReaderAttribute>().ReaderType); static readonly bool binaryWriter = untaggedWriter || typeof(ITaggedProtocolReader).IsAssignableFrom(typeof(W).GetAttribute<ReaderAttribute>().ReaderType); public SerializerTransform(Expression<Action<R, W, int>> deferredSerialize, RuntimeSchema schema, bool inlineNested = true) : base(deferredSerialize) { runtimeSchema = schema; this.inlineNested = inlineNested; } public SerializerTransform(Expression<Action<R, W, int>> deferredSerialize, Type type, bool inlineNested = true) : this(deferredSerialize, Schema.GetRuntimeSchema(type), inlineNested) {} public override IEnumerable<Expression<Action<R, W>>> Generate(IParser parser) { if (runtimeSchema.HasValue) { GenerateSerialize(Struct, parser, runtimeSchema); } else { GenerateSerialize(Struct, parser); } return SerializeActions; } Expression GenerateSerialize(Serialize serialize, IParser parser) { return GenerateSerialize(serialize, parser, writer.Param, inline: false); } Expression GenerateSerialize(SerializeWithSchema serializeWithSchema, IParser parser, RuntimeSchema schema) { Debug.Assert(schema.HasValue); Serialize serialize; if (!serializeDelegates.TryGetValue(schema, out serialize)) { serialize = serializeDelegates[schema] = p => serializeWithSchema(p, schema); } // Transcoding from tagged protocol with runtime schema generates enormous expression tree // and for large schemas JIT fails to compile resulting lambda (InvalidProgramException). // As a workaround we don't inline nested serialize expressions in this case. var inline = !typeof(ITaggedProtocolReader).IsAssignableFrom(parser.ReaderParam.Type); inline = inline && (this.inlineNested || !schema.IsStruct); return GenerateSerialize(serialize, parser, writer.Param, inline); } Expression Struct(IParser parser) { return Struct(parser, RuntimeSchema.Empty); } Expression Struct(IParser parser, RuntimeSchema schema) { return Struct(parser, schema, false); } Expression Struct(IParser parser, RuntimeSchema schema, bool isBase) { var metadata = schema.HasValue ? Expression.Constant(schema.StructDef.metadata) : noMetadata; var baseSchema = schema.HasBase ? schema.GetBaseSchema() : RuntimeSchema.Empty; return parser.Apply(new Transform( Begin: () => isBase ? writer.WriteBaseBegin(metadata) : writer.WriteStructBegin(metadata), End: () => isBase ? writer.WriteBaseEnd() : writer.WriteStructEnd(), Fields: schema.HasValue ? from field in schema.StructDef.fields select new Field( Id: field.id, Value: (fieldParser, fieldType) => Expression.Block( writer.WriteFieldBegin(fieldType, field.id, field.metadata), Value(fieldParser, fieldType, schema.GetFieldSchema(field)), writer.WriteFieldEnd()), Omitted: () => writer.WriteFieldOmitted(field.type.id, field.id, field.metadata)) : null, UnknownField: (fieldParser, fieldType, fieldId) => Expression.Block( writer.WriteFieldBegin(fieldType, fieldId, noMetadata), Value(fieldParser, fieldType), writer.WriteFieldEnd()), Base: baseParser => baseSchema.HasValue ? Struct(baseParser, baseSchema, isBase: true) : Expression.Empty(), UnknownEnd: () => writer.WriteBaseEnd())); } Expression Container(IParser parser) { return Container(parser, RuntimeSchema.Empty); } Expression Container(IParser parser, RuntimeSchema schema) { var expectedValueType = schema.HasValue ? schema.TypeDef.element.id : (BondDataType?)null; return parser.Container(expectedValueType, (valueParser, elementType, next, count) => { var body = ControlExpression.While(next, Expression.Block( writer.WriteItemBegin(), schema.HasValue ? Value(valueParser, elementType, schema.GetElementSchema()) : Value(valueParser, elementType), writer.WriteItemEnd())); var blob = parser.Blob(count); if (blob != null) { body = PrunedExpression.IfThenElse( Expression.Equal(elementType, Expression.Constant(BondDataType.BT_INT8)), writer.WriteBytes(blob), body); // For binary protocols we can write blob directly using protocols's WriteBytes // even if the container is not a blob (blob is BT_LIST of BT_INT8). if (binaryWriter) body = PrunedExpression.IfThenElse( Expression.Equal(elementType, Expression.Constant(BondDataType.BT_UINT8)), writer.WriteBytes(blob), body); } return Expression.Block( writer.WriteContainerBegin(count, elementType), body, writer.WriteContainerEnd()); }); } Expression Map(IParser parser) { return Map(parser, RuntimeSchema.Empty); } Expression Map(IParser parser, RuntimeSchema schema) { var expectedValueType = schema.HasValue ? schema.TypeDef.element.id : (BondDataType?)null; var expectedKeyType = schema.HasValue ? schema.TypeDef.key.id : (BondDataType?)null; return parser.Map(expectedKeyType, expectedValueType, (keyParser, valueParser, keyType, valueType, nextKey, nextValue, count) => Expression.Block( writer.WriteContainerBegin(count, keyType, valueType), ControlExpression.While(nextKey, Expression.Block( writer.WriteItemBegin(), schema.HasValue ? Value(keyParser, keyType, schema.GetKeySchema()) : Value(keyParser, keyType), writer.WriteItemEnd(), nextValue, writer.WriteItemBegin(), schema.HasValue ? Value(valueParser, valueType, schema.GetElementSchema()) : Value(valueParser, valueType), writer.WriteItemEnd())), writer.WriteContainerEnd())); } Expression Value(IParser parser, Expression valueType) { if (parser.IsBonded) { return parser.Bonded(value => writer.WriteBonded(PrunedExpression.Convert(value, typeof(IBonded)))); } var switchCases = new List<DeferredSwitchCase> { PrunedExpression.SwitchCase( () => GenerateSerialize(Container, parser), BondDataType.BT_LIST, BondDataType.BT_SET), PrunedExpression.SwitchCase( () => GenerateSerialize(Map, parser), BondDataType.BT_MAP), PrunedExpression.SwitchCase( () => GenerateSerialize(Struct, parser), BondDataType.BT_STRUCT) }; switchCases.AddRange( from type in new[] { BondDataType.BT_BOOL, BondDataType.BT_UINT8, BondDataType.BT_UINT16, BondDataType.BT_UINT32, BondDataType.BT_UINT64, BondDataType.BT_FLOAT, BondDataType.BT_DOUBLE, BondDataType.BT_STRING, BondDataType.BT_INT8, BondDataType.BT_INT16, BondDataType.BT_INT32, BondDataType.BT_INT64, BondDataType.BT_WSTRING } select PrunedExpression.SwitchCase( () => parser.Scalar(Expression.Constant(type), type, value => writer.Write(value, type)), type)); return PrunedExpression.Switch( valueType, ThrowExpression.InvalidTypeException(valueType), switchCases); } Expression Value(IParser parser, Expression valueType, RuntimeSchema schema) { Debug.Assert(schema.HasValue); if (parser.IsBonded || (untaggedWriter && schema.IsBonded)) return parser.Bonded(value => writer.WriteBonded(PrunedExpression.Convert(value, typeof(IBonded)))); if (schema.IsStruct) return GenerateSerialize(Struct, parser, schema); if (schema.IsMap) return GenerateSerialize(Map, parser, schema); if (schema.IsContainer) return GenerateSerialize(Container, parser, schema); return parser.Scalar(valueType, schema.TypeDef.id, value => writer.Write(value, schema.TypeDef.id)); } } }
using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob.Protocol; using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Core.Executor; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.File; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Storage.Blob { public class CloudBlockBlob : CloudBlob, ICloudBlob, IListBlobItem { public int StreamWriteSizeInBytes { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } internal bool IsStreamWriteSizeModified { get { throw new System.NotImplementedException(); } } public CloudBlockBlob(Uri blobAbsoluteUri) : this(blobAbsoluteUri, (StorageCredentials) null) { throw new System.NotImplementedException(); } public CloudBlockBlob(Uri blobAbsoluteUri, StorageCredentials credentials) : this(blobAbsoluteUri, new DateTimeOffset?(), credentials) { throw new System.NotImplementedException(); } public CloudBlockBlob(Uri blobAbsoluteUri, DateTimeOffset? snapshotTime, StorageCredentials credentials) : this(new StorageUri(blobAbsoluteUri), snapshotTime, credentials) { throw new System.NotImplementedException(); } public CloudBlockBlob(StorageUri blobAbsoluteUri, DateTimeOffset? snapshotTime, StorageCredentials credentials) : base(blobAbsoluteUri, snapshotTime, credentials) { throw new System.NotImplementedException(); } internal CloudBlockBlob(string blobName, DateTimeOffset? snapshotTime, CloudBlobContainer container) : base(blobName, snapshotTime, container) { throw new System.NotImplementedException(); } internal CloudBlockBlob(BlobAttributes attributes, CloudBlobClient serviceClient) : base(attributes, serviceClient) { throw new System.NotImplementedException(); } public virtual Task<CloudBlobStream> OpenWriteAsync() { throw new System.NotImplementedException(); } public virtual Task<CloudBlobStream> OpenWriteAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<CloudBlobStream> OpenWriteAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task UploadFromStreamAsync(Stream source) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, long length) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadTextAsync(string content) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadTextAsync(string content, Encoding encoding, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadTextAsync(string content, Encoding encoding, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> DownloadTextAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> DownloadTextAsync(Encoding encoding, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> DownloadTextAsync(Encoding encoding, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudBlockBlob> CreateSnapshotAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudBlockBlob> CreateSnapshotAsync(IDictionary<string, string> metadata, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudBlockBlob> CreateSnapshotAsync(IDictionary<string, string> metadata, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task PutBlockAsync(string blockId, Stream blockData, string contentMD5) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task PutBlockAsync(string blockId, Stream blockData, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task PutBlockAsync(string blockId, Stream blockData, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task PutBlockListAsync(IEnumerable<string> blockList) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task PutBlockListAsync(IEnumerable<string> blockList, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task PutBlockListAsync(IEnumerable<string> blockList, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<ListBlockItem>> DownloadBlockListAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<ListBlockItem>> DownloadBlockListAsync(BlockListingFilter blockListingFilter, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<ListBlockItem>> DownloadBlockListAsync(BlockListingFilter blockListingFilter, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> StartCopyAsync(CloudBlockBlob source) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> StartCopyAsync(CloudFile source) { throw new System.NotImplementedException(); } public virtual Task<string> StartCopyAsync(CloudBlockBlob source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<string> StartCopyAsync(CloudBlockBlob source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<string> StartCopyAsync(CloudFile source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<string> StartCopyAsync(CloudFile source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task SetStandardBlobTierAsync(StandardBlobTier standardBlobTier) { throw new System.NotImplementedException(); } public virtual Task SetStandardBlobTierAsync(StandardBlobTier standardBlobTier, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task SetStandardBlobTierAsync(StandardBlobTier standardBlobTier, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } internal RESTCommand<CloudBlockBlob> CreateSnapshotImpl(IDictionary<string, string> metadata, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> PutBlobImpl(Stream stream, long? length, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } internal RESTCommand<NullType> PutBlockImpl(Stream source, string blockId, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } internal RESTCommand<NullType> PutBlockListImpl(IEnumerable<PutBlockListItem> blocks, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } internal RESTCommand<IEnumerable<ListBlockItem>> GetBlockListImpl(BlockListingFilter typesOfBlocks, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> SetStandardBlobTierImpl(StandardBlobTier standardBlobTier, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private IEnumerable<Stream> OpenMultiSubStream(Stream wrappedStream, long? length, SemaphoreSlim mutex) { throw new System.NotImplementedException(); } internal void CheckAdjustBlockSize(long? streamLength) { throw new System.NotImplementedException(); } } }
/* **************************************************************************** * * 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 * dlr@microsoft.com. 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. * * * ***************************************************************************/ #if FEATURE_FULL_CONSOLE using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Hosting.Shell { /// <summary> /// Core functionality to implement an interactive console. This should be derived for concrete implementations /// </summary> public abstract class ConsoleHost { private int _exitCode; private ConsoleHostOptionsParser _optionsParser; private ScriptRuntime _runtime; private ScriptEngine _engine; private ConsoleOptions _consoleOptions; private IConsole _console; private CommandLine _commandLine; public ConsoleHostOptions Options { get { return _optionsParser.Options; } } public ScriptRuntimeSetup RuntimeSetup { get { return _optionsParser.RuntimeSetup; } } public ScriptEngine Engine { get { return _engine; } protected set { _engine = value; } } public ScriptRuntime Runtime { get { return _runtime; } protected set { _runtime = value; } } protected int ExitCode { get { return _exitCode; } set { _exitCode = value; } } protected ConsoleHostOptionsParser ConsoleHostOptionsParser { get { return _optionsParser; } set { _optionsParser = value; } } protected IConsole ConsoleIO { get { return _console; } set { _console = value; } } protected CommandLine CommandLine { get { return _commandLine; } } protected ConsoleHost() { } /// <summary> /// Console Host entry-point .exe name. /// </summary> protected virtual string ExeName { get { #if !SILVERLIGHT Assembly entryAssembly = Assembly.GetEntryAssembly(); //Can be null if called from unmanaged code (VS integration scenario) return entryAssembly != null ? entryAssembly.GetName().Name : "ConsoleHost"; #else return "ConsoleHost"; #endif } } #region Customization protected virtual void ParseHostOptions(string[] args) { _optionsParser.Parse(args); } protected virtual ScriptRuntimeSetup CreateRuntimeSetup() { var setup = ScriptRuntimeSetup.ReadConfiguration(); string provider = Provider.AssemblyQualifiedName; if (!setup.LanguageSetups.Any(s => s.TypeName == provider)) { var languageSetup = CreateLanguageSetup(); if (languageSetup != null) { setup.LanguageSetups.Add(languageSetup); } } return setup; } protected virtual LanguageSetup CreateLanguageSetup() { return null; } protected virtual PlatformAdaptationLayer PlatformAdaptationLayer { get { return PlatformAdaptationLayer.Default; } } protected virtual Type Provider { get { return null; } } private string GetLanguageProvider(ScriptRuntimeSetup setup) { var providerType = Provider; if (providerType != null) { return providerType.AssemblyQualifiedName; } if (Options.HasLanguageProvider) { return Options.LanguageProvider; } if (Options.RunFile != null) { string ext = Path.GetExtension(Options.RunFile); foreach (var lang in setup.LanguageSetups) { if (lang.FileExtensions.Any(e => DlrConfiguration.FileExtensionComparer.Equals(e, ext))) { return lang.TypeName; } } } throw new InvalidOptionException("No language specified."); } protected virtual CommandLine CreateCommandLine() { return new CommandLine(); } protected virtual OptionsParser CreateOptionsParser() { return new OptionsParser<ConsoleOptions>(); } protected virtual IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options) { ContractUtils.RequiresNotNull(options, "options"); if (options.TabCompletion) { return CreateSuperConsole(commandLine, options.ColorfulConsole); } else { return new BasicConsole(options.ColorfulConsole); } } // The advanced console functions are in a special non-inlined function so that // dependencies are pulled in only if necessary. [MethodImplAttribute(MethodImplOptions.NoInlining)] private static IConsole CreateSuperConsole(CommandLine commandLine, bool isColorful) { return new SuperConsole(commandLine, isColorful); } #endregion /// <summary> /// Request (from another thread) the console REPL loop to terminate /// </summary> /// <param name="exitCode">The caller can specify the exitCode corresponding to the event triggering /// the termination. This will be returned from CommandLine.Run</param> public virtual void Terminate(int exitCode) { _commandLine.Terminate(exitCode); } /// <summary> /// To be called from entry point. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public virtual int Run(string[] args) { var runtimeSetup = CreateRuntimeSetup(); var options = new ConsoleHostOptions(); _optionsParser = new ConsoleHostOptionsParser(options, runtimeSetup); try { ParseHostOptions(args); } catch (InvalidOptionException e) { Console.Error.WriteLine("Invalid argument: " + e.Message); return _exitCode = 1; } SetEnvironment(); string provider = GetLanguageProvider(runtimeSetup); LanguageSetup languageSetup = null; foreach (var language in runtimeSetup.LanguageSetups) { if (language.TypeName == provider) { languageSetup = language; } } if (languageSetup == null) { // the language doesn't have a setup -> create a default one: languageSetup = new LanguageSetup(Provider.AssemblyQualifiedName, Provider.Name); runtimeSetup.LanguageSetups.Add(languageSetup); } // inserts search paths for all languages (/paths option): InsertSearchPaths(runtimeSetup.Options, Options.SourceUnitSearchPaths); _consoleOptions = ParseOptions(Options.IgnoredArgs.ToArray(), runtimeSetup, languageSetup); if (_consoleOptions == null) { return _exitCode = 1; } _runtime = new ScriptRuntime(runtimeSetup); try { _engine = _runtime.GetEngineByTypeName(provider); } catch (Exception e) { Console.Error.WriteLine(e.Message); return _exitCode = 1; } Execute(); return _exitCode; } protected virtual ConsoleOptions ParseOptions(string/*!*/[]/*!*/ args, ScriptRuntimeSetup/*!*/ runtimeSetup, LanguageSetup/*!*/ languageSetup) { var languageOptionsParser = CreateOptionsParser(); try { languageOptionsParser.Parse(args, runtimeSetup, languageSetup, PlatformAdaptationLayer); } catch (InvalidOptionException e) { ReportInvalidOption(e); return null; } return languageOptionsParser.CommonConsoleOptions; } protected virtual void ReportInvalidOption(InvalidOptionException e) { Console.Error.WriteLine(e.Message); } private static void InsertSearchPaths(IDictionary<string, object> options, ICollection<string> paths) { if (options != null && paths != null && paths.Count > 0) { var existingPaths = new List<string>(LanguageOptions.GetSearchPathsOption(options) ?? (IEnumerable<string>)ArrayUtils.EmptyStrings); existingPaths.InsertRange(0, paths); options["SearchPaths"] = existingPaths; } } #region Printing help protected virtual void PrintHelp() { Console.WriteLine(GetHelp()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected virtual string GetHelp() { StringBuilder sb = new StringBuilder(); string[,] optionsHelp = Options.GetHelp(); sb.AppendLine(String.Format("Usage: {0}.exe [<dlr-options>] [--] [<language-specific-command-line>]", ExeName)); sb.AppendLine(); sb.AppendLine("DLR options (both slash or dash could be used to prefix options):"); ArrayUtils.PrintTable(sb, optionsHelp); sb.AppendLine(); sb.AppendLine("Language specific command line:"); PrintLanguageHelp(sb); sb.AppendLine(); return sb.ToString(); } public void PrintLanguageHelp(StringBuilder output) { ContractUtils.RequiresNotNull(output, "output"); string commandLine, comments; string[,] options, environmentVariables; CreateOptionsParser().GetHelp(out commandLine, out options, out environmentVariables, out comments); // only display language specific options if one or more optinos exists. if (commandLine != null || options != null || environmentVariables != null || comments != null) { if (commandLine != null) { output.AppendLine(commandLine); output.AppendLine(); } if (options != null) { output.AppendLine("Options:"); ArrayUtils.PrintTable(output, options); output.AppendLine(); } if (environmentVariables != null) { output.AppendLine("Environment variables:"); ArrayUtils.PrintTable(output, environmentVariables); output.AppendLine(); } if (comments != null) { output.Append(comments); output.AppendLine(); } output.AppendLine(); } } #endregion private void Execute() { #if !SILVERLIGHT if (_consoleOptions.IsMta) { Thread thread = new Thread(ExecuteInternal); thread.SetApartmentState(ApartmentState.MTA); thread.Start(); thread.Join(); return; } #endif ExecuteInternal(); } protected virtual void ExecuteInternal() { Debug.Assert(_engine != null); if (_consoleOptions.PrintVersion){ PrintVersion(); } if (_consoleOptions.PrintUsage) { PrintUsage(); } if (_consoleOptions.Exit) { _exitCode = 0; return; } switch (Options.RunAction) { case ConsoleHostOptions.Action.None: case ConsoleHostOptions.Action.RunConsole: _exitCode = RunCommandLine(); break; case ConsoleHostOptions.Action.RunFile: _exitCode = RunFile(); break; default: throw Assert.Unreachable; } } private void SetEnvironment() { Debug.Assert(Options.EnvironmentVars != null); #if !SILVERLIGHT foreach (string env in Options.EnvironmentVars) { if (!String.IsNullOrEmpty(env)) { string[] var_def = env.Split('='); System.Environment.SetEnvironmentVariable(var_def[0], (var_def.Length > 1) ? var_def[1] : ""); } } #endif } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private int RunFile() { Debug.Assert(_engine != null); int result = 0; try { return _engine.CreateScriptSourceFromFile(Options.RunFile).ExecuteProgram(); #if !FEATURE_PROCESS } catch (ExitProcessException e) { result = e.ExitCode; #endif } catch (Exception e) { UnhandledException(Engine, e); result = 1; } finally { #if FEATURE_REFEMIT try { Snippets.SaveAndVerifyAssemblies(); } catch (Exception) { result = 1; } #endif } return result; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] private int RunCommandLine() { Debug.Assert(_engine != null); _commandLine = CreateCommandLine(); if (_console == null) { _console = CreateConsole(Engine, _commandLine, _consoleOptions); } int? exitCodeOverride = null; try { if (_consoleOptions.HandleExceptions) { try { _commandLine.Run(Engine, _console, _consoleOptions); } catch (Exception e) { if (CommandLine.IsFatalException(e)) { // Some exceptions are too dangerous to try to catch throw; } UnhandledException(Engine, e); } } else { _commandLine.Run(Engine, _console, _consoleOptions); } } finally { #if FEATURE_REFEMIT try { Snippets.SaveAndVerifyAssemblies(); } catch (Exception) { exitCodeOverride = 1; } #endif } if (exitCodeOverride == null) { return _commandLine.ExitCode; } else { return exitCodeOverride.Value; } } private void PrintUsage() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Usage: {0}.exe ", ExeName); PrintLanguageHelp(sb); Console.Write(sb.ToString()); } protected void PrintVersion() { Console.WriteLine("{0} {1} on {2}", Engine.Setup.DisplayName, Engine.LanguageVersion, GetRuntime()); } private static string GetRuntime() { Type mono = typeof(object).Assembly.GetType("Mono.Runtime"); return mono != null ? (string)mono.GetMethod("GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null) : String.Format(CultureInfo.InvariantCulture, ".NET {0}", Environment.Version); } protected virtual void UnhandledException(ScriptEngine engine, Exception e) { Console.Error.Write("Unhandled exception"); Console.Error.WriteLine(':'); ExceptionOperations es = engine.GetService<ExceptionOperations>(); Console.Error.WriteLine(es.FormatException(e)); } protected static void PrintException(TextWriter output, Exception e) { Debug.Assert(output != null); ContractUtils.RequiresNotNull(e, "e"); while (e != null) { output.WriteLine(e); e = e.InnerException; } } } } #endif
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using System.Text; using Encog.App.Analyst.CSV.Basic; using Encog.Util.CSV; namespace Encog.App.Quant.Indicators { /// <summary> /// Process indicators and generate output. /// </summary> public class ProcessIndicators : BasicCachedFile { /// <value>Get the beginning index.</value> private int BeginningIndex { get { int result = 0; foreach (BaseCachedColumn column in Columns) { if (column is Indicator) { var ind = (Indicator) column; result = Math.Max(ind.BeginningIndex, result); } } return result; } } /// <value>Get the ending index.</value> private int EndingIndex { get { int result = RecordCount - 1; foreach (BaseCachedColumn column in Columns) { if (column is Indicator) { var ind = (Indicator) column; result = Math.Min(ind.EndingIndex, result); } } return result; } } /// <summary> /// Allocate storage. /// </summary> private void AllocateStorage() { foreach (BaseCachedColumn column in Columns) { column.Allocate(RecordCount); } } /// <summary> /// Calculate the indicators. /// </summary> private void CalculateIndicators() { foreach (BaseCachedColumn column in Columns) { if (column.Output) { if (column is Indicator) { var indicator = (Indicator) column; indicator.Calculate(ColumnMapping, RecordCount); } } } } /// <summary> /// Process and write the specified output file. /// </summary> /// <param name="output">The output file.</param> public void Process(FileInfo output) { ValidateAnalyzed(); AllocateStorage(); ReadFile(); CalculateIndicators(); WriteCSV(output); } /// <summary> /// Read the CSV file. /// </summary> private void ReadFile() { ReadCSV csv = null; try { csv = new ReadCSV(InputFilename.ToString(), ExpectInputHeaders, Format); ResetStatus(); int row = 0; while (csv.Next() && !ShouldStop()) { UpdateStatus("Reading data"); foreach (BaseCachedColumn column in Columns) { if (column is FileData) { if (column.Input) { var fd = (FileData) column; String str = csv.Get(fd.Index); double d = Format.Parse(str); fd.Data[row] = d; } } } row++; } } finally { ReportDone("Reading data"); if (csv != null) { csv.Close(); } } } /// <summary> /// Rename a column. /// </summary> /// <param name="index">The column index.</param> /// <param name="newName">The new name.</param> public void RenameColumn(int index, String newName) { ColumnMapping.Remove(Columns[index].Name); Columns[index].Name = newName; ColumnMapping[newName] = Columns[index]; } /// <summary> /// Write the CSV. /// </summary> /// <param name="filename">The target filename.</param> private void WriteCSV(FileInfo filename) { StreamWriter tw = null; try { ResetStatus(); tw = new StreamWriter(filename.Create()); // write the headers if (ExpectInputHeaders) { var line = new StringBuilder(); foreach (BaseCachedColumn column in Columns) { if (column.Output) { if (line.Length > 0) { line.Append(Format.Separator); } line.Append("\""); line.Append(column.Name); line.Append("\""); } } tw.WriteLine(line.ToString()); } // starting and ending index int beginningIndex = BeginningIndex; int endingIndex = EndingIndex; // write the file data for (int row = beginningIndex; row <= endingIndex; row++) { UpdateStatus("Writing data"); var line_0 = new StringBuilder(); foreach (BaseCachedColumn column_1 in Columns) { if (column_1.Output) { if (line_0.Length > 0) { line_0.Append(Format.Separator); } double d = column_1.Data[row]; line_0.Append(Format.Format(d, Precision)); } } tw.WriteLine(line_0.ToString()); } } catch (IOException e) { throw (new QuantError(e)); } finally { if (tw != null) { tw.Close(); } } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Data; namespace System.Windows.Controls { /// <summary> /// A column definition that allows a developer to specify specific /// editing and non-editing templates. /// </summary> public class DataGridTemplateColumn : DataGridColumn { #region Constructors static DataGridTemplateColumn() { CanUserSortProperty.OverrideMetadata( typeof(DataGridTemplateColumn), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceTemplateColumnCanUserSort))); SortMemberPathProperty.OverrideMetadata( typeof(DataGridTemplateColumn), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnTemplateColumnSortMemberPathChanged))); } #endregion #region Auto Sort private static void OnTemplateColumnSortMemberPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DataGridTemplateColumn column = (DataGridTemplateColumn)d; column.CoerceValue(CanUserSortProperty); } private static object OnCoerceTemplateColumnCanUserSort(DependencyObject d, object baseValue) { DataGridTemplateColumn templateColumn = (DataGridTemplateColumn)d; if (string.IsNullOrEmpty(templateColumn.SortMemberPath)) { return false; } return DataGridColumn.OnCoerceCanUserSort(d, baseValue); } #endregion #region Templates /// <summary> /// A template describing how to display data for a cell in this column. /// </summary> public DataTemplate CellTemplate { get { return (DataTemplate)GetValue(CellTemplateProperty); } set { SetValue(CellTemplateProperty, value); } } /// <summary> /// The DependencyProperty representing the CellTemplate property. /// </summary> public static readonly DependencyProperty CellTemplateProperty = DependencyProperty.Register( "CellTemplate", typeof(DataTemplate), typeof(DataGridTemplateColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// A template selector describing how to display data for a cell in this column. /// </summary> public DataTemplateSelector CellTemplateSelector { get { return (DataTemplateSelector)GetValue(CellTemplateSelectorProperty); } set { SetValue(CellTemplateSelectorProperty, value); } } /// <summary> /// The DependencyProperty representing the CellTemplateSelector property. /// </summary> public static readonly DependencyProperty CellTemplateSelectorProperty = DependencyProperty.Register( "CellTemplateSelector", typeof(DataTemplateSelector), typeof(DataGridTemplateColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// A template describing how to display data for a cell /// that is being edited in this column. /// </summary> public DataTemplate CellEditingTemplate { get { return (DataTemplate)GetValue(CellEditingTemplateProperty); } set { SetValue(CellEditingTemplateProperty, value); } } /// <summary> /// The DependencyProperty representing the CellEditingTemplate /// </summary> public static readonly DependencyProperty CellEditingTemplateProperty = DependencyProperty.Register( "CellEditingTemplate", typeof(DataTemplate), typeof(DataGridTemplateColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// A template selector describing how to display data for a cell /// that is being edited in this column. /// </summary> public DataTemplateSelector CellEditingTemplateSelector { get { return (DataTemplateSelector)GetValue(CellEditingTemplateSelectorProperty); } set { SetValue(CellEditingTemplateSelectorProperty, value); } } /// <summary> /// The DependencyProperty representing the CellEditingTemplateSelector /// </summary> public static readonly DependencyProperty CellEditingTemplateSelectorProperty = DependencyProperty.Register( "CellEditingTemplateSelector", typeof(DataTemplateSelector), typeof(DataGridTemplateColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// Returns either the specified CellTemplate[Selector] or CellEditingTemplate[Selector]. /// CellTemplate[Selector] is the fallack if CellEditingTemplate[Selector] is null. /// </summary> /// <param name="isEditing">Whether the editing template is requested.</param> private void ChooseCellTemplateAndSelector(bool isEditing, out DataTemplate template, out DataTemplateSelector templateSelector) { template = null; templateSelector = null; if (isEditing) { template = CellEditingTemplate; templateSelector = CellEditingTemplateSelector; } if (template == null && templateSelector == null) { template = CellTemplate; templateSelector = CellTemplateSelector; } } #endregion #region Visual Tree Generation /// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> /// <param name="isEditing">Whether the editing version is being requested.</param> /// <param name="dataItem">The data item for the cell.</param> /// <param name="cell">The cell container that will receive the tree.</param> private FrameworkElement LoadTemplateContent(bool isEditing, object dataItem, DataGridCell cell) { DataTemplate template; DataTemplateSelector templateSelector; ChooseCellTemplateAndSelector(isEditing, out template, out templateSelector); if (template != null || templateSelector != null) { ContentPresenter contentPresenter = new ContentPresenter(); BindingOperations.SetBinding(contentPresenter, ContentPresenter.ContentProperty, new Binding()); contentPresenter.ContentTemplate = template; contentPresenter.ContentTemplateSelector = templateSelector; return contentPresenter; } return null; } /// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { return LoadTemplateContent(/* isEditing = */ false, dataItem, cell); } /// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return LoadTemplateContent(/* isEditing = */ true, dataItem, cell); } #endregion #region Property Changed Handler /// <summary> /// Override which handles property /// change for template properties /// </summary> /// <param name="element"></param> /// <param name="propertyName"></param> protected internal override void RefreshCellContent(FrameworkElement element, string propertyName) { DataGridCell cell = element as DataGridCell; if (cell != null) { bool isCellEditing = cell.IsEditing; if ((!isCellEditing && ((string.Compare(propertyName, "CellTemplate", StringComparison.Ordinal) == 0) || (string.Compare(propertyName, "CellTemplateSelector", StringComparison.Ordinal) == 0))) || (isCellEditing && ((string.Compare(propertyName, "CellEditingTemplate", StringComparison.Ordinal) == 0) || (string.Compare(propertyName, "CellEditingTemplateSelector", StringComparison.Ordinal) == 0)))) { cell.BuildVisualTree(); return; } } base.RefreshCellContent(element, propertyName); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Configuration; using Orleans.Runtime; namespace Orleans.Messaging { /// <summary> /// The GatewayManager class holds the list of known gateways, as well as maintaining the list of "dead" gateways. /// /// The known list can come from one of two places: the full list may appear in the client configuration object, or /// the config object may contain an IGatewayListProvider delegate. If both appear, then the delegate takes priority. /// </summary> internal class GatewayManager : IGatewayListListener, IDisposable { internal readonly IGatewayListProvider ListProvider; private SafeTimer gatewayRefreshTimer; private readonly Dictionary<Uri, DateTime> knownDead; private IList<Uri> cachedLiveGateways; private DateTime lastRefreshTime; private int roundRobinCounter; private readonly SafeRandom rand; private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private readonly object lockable; private readonly GatewayOptions gatewayOptions; private bool gatewayRefreshCallInitiated; public GatewayManager(GatewayOptions gatewayOptions, IGatewayListProvider gatewayListProvider, ILoggerFactory loggerFactory) { this.gatewayOptions = gatewayOptions; knownDead = new Dictionary<Uri, DateTime>(); rand = new SafeRandom(); logger = loggerFactory.CreateLogger<GatewayManager>(); this.loggerFactory = loggerFactory; lockable = new object(); gatewayRefreshCallInitiated = false; ListProvider = gatewayListProvider; var knownGateways = ListProvider.GetGateways().GetResult(); if (knownGateways.Count == 0) { string gatewayProviderType = gatewayListProvider.GetType().FullName; string err = $"Could not find any gateway in {gatewayProviderType}. Orleans client cannot initialize."; logger.Error(ErrorCode.GatewayManager_NoGateways, err); throw new OrleansException(err); } logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Found {0} knownGateways from Gateway listProvider {1}", knownGateways.Count, Utils.EnumerableToString(knownGateways)); if (ListProvider is IGatewayListObservable) { ((IGatewayListObservable)ListProvider).SubscribeToGatewayNotificationEvents(this); } roundRobinCounter = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : rand.Next(knownGateways.Count); cachedLiveGateways = knownGateways; lastRefreshTime = DateTime.UtcNow; if (ListProvider.IsUpdatable) { gatewayRefreshTimer = new SafeTimer(this.loggerFactory.CreateLogger<SafeTimer>(), RefreshSnapshotLiveGateways_TimerCallback, null, this.gatewayOptions.GatewayListRefreshPeriod, this.gatewayOptions.GatewayListRefreshPeriod); } } public void Stop() { if (gatewayRefreshTimer != null) { Utils.SafeExecute(gatewayRefreshTimer.Dispose, logger); } gatewayRefreshTimer = null; if (ListProvider != null && ListProvider is IGatewayListObservable) { Utils.SafeExecute( () => ((IGatewayListObservable)ListProvider).UnSubscribeFromGatewayNotificationEvents(this), logger); } } public void MarkAsDead(Uri gateway) { lock (lockable) { knownDead[gateway] = DateTime.UtcNow; var copy = cachedLiveGateways.ToList(); copy.Remove(gateway); // swap the reference, don't mutate cachedLiveGateways, so we can access cachedLiveGateways without the lock. cachedLiveGateways = copy; } } public override string ToString() { var sb = new StringBuilder(); sb.Append("GatewayManager: "); lock (lockable) { if (cachedLiveGateways != null) { sb.Append(cachedLiveGateways.Count); sb.Append(" cachedLiveGateways, "); } if (knownDead != null) { sb.Append(knownDead.Count); sb.Append(" known dead gateways."); } } return sb.ToString(); } /// <summary> /// Selects a gateway to use for a new bucket. /// /// Note that if a list provider delegate was given, the delegate is invoked every time this method is called. /// This method performs caching to avoid hammering the ultimate data source. /// /// This implementation does a simple round robin selection. It assumes that the gateway list from the provider /// is in the same order every time. /// </summary> /// <returns></returns> public Uri GetLiveGateway() { IList<Uri> live = GetLiveGateways(); int count = live.Count; if (count > 0) { lock (lockable) { // Round-robin through the known gateways and take the next live one, starting from where we last left off roundRobinCounter = (roundRobinCounter + 1) % count; return live[roundRobinCounter]; } } // If we drop through, then all of the known gateways are presumed dead return null; } public IList<Uri> GetLiveGateways() { // Never takes a lock and returns the cachedLiveGateways list quickly without any operation. // Asynchronously starts gateway refresh only when it is empty. if (cachedLiveGateways.Count == 0) { ExpediteUpdateLiveGatewaysSnapshot(); } return cachedLiveGateways; } internal void ExpediteUpdateLiveGatewaysSnapshot() { // If there is already an expedited refresh call in place, don't call again, until the previous one is finished. // We don't want to issue too many Gateway refresh calls. if (ListProvider == null || !ListProvider.IsUpdatable || gatewayRefreshCallInitiated) return; // Initiate gateway list refresh asynchronously. The Refresh timer will keep ticking regardless. // We don't want to block the client with synchronously Refresh call. // Client's call will fail with "No Gateways found" but we will try to refresh the list quickly. gatewayRefreshCallInitiated = true; var task = Task.Factory.StartNew(() => { RefreshSnapshotLiveGateways_TimerCallback(null); gatewayRefreshCallInitiated = false; }); task.Ignore(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void GatewayListNotification(IEnumerable<Uri> gateways) { try { UpdateLiveGatewaysSnapshot(gateways, ListProvider.MaxStaleness); } catch (Exception exc) { logger.Error(ErrorCode.ProxyClient_GetGateways, "Exception occurred during GatewayListNotification -> UpdateLiveGatewaysSnapshot", exc); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal void RefreshSnapshotLiveGateways_TimerCallback(object context) { try { if (ListProvider == null || !ListProvider.IsUpdatable) return; // the listProvider.GetGateways() is not under lock. var currentKnownGateways = ListProvider.GetGateways().GetResult(); if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Found {0} knownGateways from Gateway listProvider {1}", currentKnownGateways.Count, Utils.EnumerableToString(currentKnownGateways)); } // the next one will grab the lock. UpdateLiveGatewaysSnapshot(currentKnownGateways, ListProvider.MaxStaleness); } catch (Exception exc) { logger.Error(ErrorCode.ProxyClient_GetGateways, "Exception occurred during RefreshSnapshotLiveGateways_TimerCallback -> listProvider.GetGateways()", exc); } } // This function is called asynchronously from gateway refresh timer. private void UpdateLiveGatewaysSnapshot(IEnumerable<Uri> currentKnownGateways, TimeSpan maxStaleness) { // this is a short lock, protecting the access to knownDead and cachedLiveGateways. lock (lockable) { // now take whatever listProvider gave us and exclude those we think are dead. var live = new List<Uri>(); var now = DateTime.UtcNow; var knownGateways = currentKnownGateways as IList<Uri> ?? currentKnownGateways.ToList(); foreach (Uri trial in knownGateways) { // We consider a node to be dead if we recorded it is dead due to socket error // and it was recorded (diedAt) not too long ago (less than maxStaleness ago). // The latter is to cover the case when the Gateway provider returns an outdated list that does not yet reflect the actually recently died Gateway. // If it has passed more than maxStaleness - we assume maxStaleness is the upper bound on Gateway provider freshness. var isDead = false; if (knownDead.TryGetValue(trial, out var diedAt)) { if (now.Subtract(diedAt) < maxStaleness) { isDead = true; } else { // Remove stale entries. knownDead.Remove(trial); } } if (!isDead) { live.Add(trial); } } if (live.Count == 0) { logger.Warn( ErrorCode.GatewayManager_AllGatewaysDead, "All gateways have previously been marked as dead. Clearing the list of dead gateways to expedite reconnection."); live.AddRange(knownGateways); knownDead.Clear(); } // swap cachedLiveGateways pointer in one atomic operation cachedLiveGateways = live; DateTime prevRefresh = lastRefreshTime; lastRefreshTime = now; if (logger.IsEnabled(LogLevel.Information)) { logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Refreshed the live Gateway list. Found {0} gateways from Gateway listProvider: {1}. Picked only known live out of them. Now has {2} live Gateways: {3}. Previous refresh time was = {4}", knownGateways.Count(), Utils.EnumerableToString(knownGateways), cachedLiveGateways.Count, Utils.EnumerableToString(cachedLiveGateways), prevRefresh); } } } public void Dispose() { var timer = gatewayRefreshTimer; if (timer != null) timer.Dispose(); } } }
// 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UnitTests; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class AttributeStringLiteralsShouldParseCorrectlyTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new AttributeStringLiteralsShouldParseCorrectlyAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new AttributeStringLiteralsShouldParseCorrectlyAnalyzer(); } [Fact] public void CA2243_BadAttributeStringLiterals_CSharp() { this.PrintActualDiagnosticsOnFailure = true; VerifyCSharp(@" using System; public sealed class BadAttributeStringLiterals { private sealed class MyLiteralsAttribute : Attribute { private string m_url; private string m_version; private string m_guid; public MyLiteralsAttribute() { } public MyLiteralsAttribute(string url) { m_url = url; } public MyLiteralsAttribute(string url, int dummy1, string thisIsAVersion, int dummy2) { m_url = url; m_version = thisIsAVersion; if (dummy1 > dummy2) // just random stuff to use these arguments m_version = """"; } public string Url { get { return m_url; } set { m_url = value; } } public string Version { get { return m_version; } set { m_version = value; } } public string GUID { get { return m_guid; } set { m_guid = value; } } } [MyLiterals(GUID = ""bad-guid"")] private int x; public BadAttributeStringLiterals() { DoNothing(1); } [MyLiterals(Url = ""bad url"", Version = ""helloworld"")] private void DoNothing( [MyLiterals(""bad url"")] int y) { if (x > 0) DoNothing2(y); } [MyLiterals(""good/url"", 5, ""1.0.bad"", 5)] private void DoNothing2(int y) { this.x = y; } }", CA2243CSharpDefaultResultAt(25, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(29, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.Url", "bad url", "Uri"), CA2243CSharpDefaultResultAt(31, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "url", "bad url", "Uri")); } [Fact] public void CA2243_BadGuids_CSharp() { this.PrintActualDiagnosticsOnFailure = true; VerifyCSharp(@" using System; [GuidAttribute(GUID = ""bad-guid"")] public class ClassWithBadlyFormattedNamedArgumentGuid { } [GuidAttribute(GUID = ""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")] public class ClassWithTooManyDashesNamedArgumentGuid { } [GuidAttribute(GUID = ""{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}"")] public class ClassWithOverflowNamedArgumentGuid { } [GuidAttribute(GUID = """")] public class ClassWithEmptyNamedArgumentGuid { } [GuidAttribute(""bad-guid"")] public class ClassWithBadlyFormattedRequiredArgumentGuid { } [GuidAttribute(""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")] public class ClassWithTooManyDashesRequiredArgumentGuid { } [GuidAttribute(""{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}"")] public class ClassWithOverflowRequiredArgumentGuid { } [GuidAttribute("""")] public class ClassWithEmptyRequiredArgumentGuid { } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class GuidAttribute : Attribute { private string m_guid; public GuidAttribute() { } public GuidAttribute(string ThisIsAGuid) { m_guid = ThisIsAGuid; } public string GUID { get { return m_guid; } set { m_guid = value; } } } ", CA2243CSharpDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(9, 2, "GuidAttribute", "GuidAttribute.GUID", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243CSharpDefaultResultAt(14, 2, "GuidAttribute", "GuidAttribute.GUID", "{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}", "Guid"), CA2243CSharpEmptyResultAt(19, 2, "GuidAttribute", "GuidAttribute.GUID", "Guid"), CA2243CSharpDefaultResultAt(24, 2, "GuidAttribute", "ThisIsAGuid", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(29, 2, "GuidAttribute", "ThisIsAGuid", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243CSharpDefaultResultAt(34, 2, "GuidAttribute", "ThisIsAGuid", "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}", "Guid"), CA2243CSharpEmptyResultAt(39, 2, "GuidAttribute", "ThisIsAGuid", "Guid")); } [Fact] public void CA2243_MiscSymbolsWithBadGuid_CSharp() { this.PrintActualDiagnosticsOnFailure = true; VerifyCSharp(@" using System; [assembly: GuidAttribute(GUID = ""bad-guid"")] public delegate void MiscDelegate([GuidAttribute(GUID = ""bad-guid"")] int p); public class MiscClass<[GuidAttribute(GUID = ""bad-guid"")] U> { public MiscClass<U> this[[GuidAttribute(GUID = ""bad-guid"")] int index] { get { return null; } set { } } public void M<[GuidAttribute(GUID = ""bad-guid"")] T>() { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class GuidAttribute : Attribute { private string m_guid; public GuidAttribute() { } public GuidAttribute(string ThisIsAGuid) { m_guid = ThisIsAGuid; } public string GUID { get { return m_guid; } set { m_guid = value; } } } ", CA2243CSharpDefaultResultAt(4, 12, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(6, 36, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(8, 25, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(10, 31, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(21, 20, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid")); } [Fact] public void CA2243_NoDiagnostics_CSharp() { VerifyCSharp(@" using System; public sealed class GoodAttributeStringLiterals { private sealed class MyLiteralsAttribute : Attribute { private string m_url; private string m_version; private string m_guid; private int m_notAVersion; public MyLiteralsAttribute() { } public MyLiteralsAttribute(string url) { m_url = url; } public MyLiteralsAttribute(string url, int dummy1, string thisIsAVersion, int notAVersion) { m_url = url; m_version = thisIsAVersion; m_notAVersion = notAVersion + dummy1; } public string Url { get { return m_url; } set { m_url = value; } } public string Version { get { return m_version; } set { m_version = value; } } public string GUID { get { return m_guid; } set { m_guid = value; } } public int NotAVersion { get { return m_notAVersion; } set { m_notAVersion = value; } } } [MyLiterals(""good/relative/url"", GUID = ""8fcd093bc1058acf8fcd093bc1058acf"", Version = ""1.4.325.12"")] private int x; public GoodAttributeStringLiterals() { DoNothing(1); } [MyLiterals(GUID = ""{8fcd093b-c105-8acf-8fcd-093bc1058acf}"", Url = ""http://good/absolute/url.htm"")] private void DoNothing( [MyLiterals(""goodurl/"", NotAVersion = 12)] int y) { if (x > 0) DoNothing2(y); } [MyLiterals(""http://good/url"", 5, ""1.0.50823.98"", 5)] private void DoNothing2(int y) { this.x = y; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class UriTemplateAttribute : Attribute { private string m_uriTemplate; public UriTemplateAttribute() { } public UriTemplateAttribute(string uriTemplate) { m_uriTemplate = uriTemplate; } public string UriTemplate { get { return m_uriTemplate; } set { m_uriTemplate = value; } } } public static class ClassWithExceptionForUri { [UriTemplate(UriTemplate=""{0}"")] public static void MethodWithInvalidUriNamedArgumentThatShouldBeIgnored() { } [UriTemplate(UriTemplate = """")] public static void MethodWithEmptyUriNamedArgumentThatShouldBeIgnored() { } [UriTemplate(""{0}"")] public static void MethodWithInvalidUriRequiredArgumentThatShouldBeIgnored() { } [UriTemplate("""")] public static void MethodWithEmptyUriRequiredArgumentThatShouldBeIgnored() { } }"); } [Fact] public void CA2243_BadAttributeStringLiterals_Basic() { this.PrintActualDiagnosticsOnFailure = true; VerifyBasic(@" Imports System Public NotInheritable Class BadAttributeStringLiterals <MyLiterals(GUID:=""bad-guid"")> Private x As Integer Public Sub New() DoNothing(1) End Sub <MyLiterals(Url:=""bad url"", Version:=""helloworld"")> Private Sub DoNothing(<MyLiterals(""bad url"")> y As Integer) If x > 0 Then DoNothing2(y) End If End Sub <MyLiterals(""good/url"", 5, ""1.0.bad"", 5)> Private Sub DoNothing2(y As Integer) Me.x = y End Sub Private NotInheritable Class MyLiteralsAttribute Inherits Attribute Private m_url As String Private m_version As String Private m_guid As String Public Sub New() End Sub Public Sub New(url As String) m_url = url End Sub Public Sub New(url As String, dummy1 As Integer, thisIsAVersion As String, dummy2 As Integer) m_url = url m_version = thisIsAVersion If dummy1 > dummy2 Then ' just random stuff to use these arguments m_version = """" End If End Sub Public Property Url() As String Get Return m_url End Get Set m_url = value End Set End Property Public Property Version() As String Get Return m_version End Get Set m_version = value End Set End Property Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class End Class", CA2243BasicDefaultResultAt(5, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(11, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.Url", "bad url", "Uri"), CA2243BasicDefaultResultAt(12, 28, "BadAttributeStringLiterals.MyLiteralsAttribute", "url", "bad url", "Uri")); } [Fact] public void CA2243_BadGuids_Basic() { this.PrintActualDiagnosticsOnFailure = true; VerifyBasic(@" Imports System <GuidAttribute(GUID := ""bad-guid"")> _ Public Class ClassWithBadlyFormattedNamedArgumentGuid End Class <GuidAttribute(GUID := ""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")> _ Public Class ClassWithTooManyDashesNamedArgumentGuid End Class <GuidAttribute(GUID := ""{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}"")> _ Public Class ClassWithOverflowNamedArgumentGuid End Class <GuidAttribute(GUID := """")> _ Public Class ClassWithEmptyNamedArgumentGuid End Class <GuidAttribute(""bad-guid"")> _ Public Class ClassWithBadlyFormattedRequiredArgumentGuid End Class <GuidAttribute(""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")> _ Public Class ClassWithTooManyDashesRequiredArgumentGuid End Class <GuidAttribute(""{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}"")> _ Public Class ClassWithOverflowRequiredArgumentGuid End Class <GuidAttribute("""")> _ Public Class ClassWithEmptyRequiredArgumentGuid End Class <AttributeUsage(AttributeTargets.All, AllowMultiple := False)> _ Public NotInheritable Class GuidAttribute Inherits Attribute Private m_guid As String Public Sub New() End Sub Public Sub New(ThisIsAGuid As String) m_guid = ThisIsAGuid End Sub Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class ", CA2243BasicDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(8, 2, "GuidAttribute", "GuidAttribute.GUID", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243BasicDefaultResultAt(12, 2, "GuidAttribute", "GuidAttribute.GUID", "{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}", "Guid"), CA2243BasicEmptyResultAt(16, 2, "GuidAttribute", "GuidAttribute.GUID", "Guid"), CA2243BasicDefaultResultAt(20, 2, "GuidAttribute", "ThisIsAGuid", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(24, 2, "GuidAttribute", "ThisIsAGuid", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243BasicDefaultResultAt(28, 2, "GuidAttribute", "ThisIsAGuid", "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}", "Guid"), CA2243BasicEmptyResultAt(32, 2, "GuidAttribute", "ThisIsAGuid", "Guid")); } [Fact] public void CA2243_MiscSymbolsWithBadGuid_Basic() { this.PrintActualDiagnosticsOnFailure = true; VerifyBasic(@" Imports System <Assembly: GuidAttribute(GUID := ""bad-guid"")> Public Delegate Sub MiscDelegate(<GuidAttribute(GUID := ""bad-guid"")> p As Integer) Public Class MiscClass Public Default Property Item(<GuidAttribute(GUID := ""bad-guid"")> index As Integer) As MiscClass Get Return Nothing End Get Set End Set End Property End Class <AttributeUsage(AttributeTargets.All, AllowMultiple := True)> _ Public NotInheritable Class GuidAttribute Inherits Attribute Private m_guid As String Public Sub New() End Sub Public Sub New(ThisIsAGuid As String) m_guid = ThisIsAGuid End Sub Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class ", CA2243BasicDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(6, 35, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(9, 35, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid")); } [Fact] public void CA2243_NoDiagnostics_Basic() { VerifyBasic(@" Imports System Public NotInheritable Class GoodAttributeStringLiterals Private NotInheritable Class MyLiteralsAttribute Inherits Attribute Private m_url As String Private m_version As String Private m_guid As String Private m_notAVersion As Integer Public Sub New() End Sub Public Sub New(url As String) m_url = url End Sub Public Sub New(url As String, dummy1 As Integer, thisIsAVersion As String, notAVersion As Integer) m_url = url m_version = thisIsAVersion m_notAVersion = notAVersion + dummy1 End Sub Public Property Url() As String Get Return m_url End Get Set m_url = Value End Set End Property Public Property Version() As String Get Return m_version End Get Set m_version = Value End Set End Property Public Property GUID() As String Get Return m_guid End Get Set m_guid = Value End Set End Property Public Property NotAVersion() As Integer Get Return m_notAVersion End Get Set m_notAVersion = Value End Set End Property End Class <MyLiterals(""good/relative/url"", GUID:=""8fcd093bc1058acf8fcd093bc1058acf"", Version:=""1.4.325.12"")> Private x As Integer Public Sub New() DoNothing(1) End Sub <MyLiterals(GUID:=""{8fcd093b-c105-8acf-8fcd-093bc1058acf}"", Url:=""http://good/absolute/url.htm"")> Private Sub DoNothing(<MyLiterals(""goodurl/"", NotAVersion:=12)> y As Integer) If x > 0 Then DoNothing2(y) End If End Sub <MyLiterals(""http://good/url"", 5, ""1.0.50823.98"", 5)> Private Sub DoNothing2(y As Integer) Me.x = y End Sub End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=False)> Public NotInheritable Class UriTemplateAttribute Inherits Attribute Private m_uriTemplate As String Public Sub New() End Sub Public Sub New(uriTemplate As String) m_uriTemplate = uriTemplate End Sub Public Property UriTemplate() As String Get Return m_uriTemplate End Get Set m_uriTemplate = Value End Set End Property End Class Public NotInheritable Class ClassWithExceptionForUri Private Sub New() End Sub <UriTemplate(UriTemplate:=""{0}"")> Public Shared Sub MethodWithInvalidUriNamedArgumentThatShouldBeIgnored() End Sub <UriTemplate(UriTemplate:="""")> Public Shared Sub MethodWithEmptyUriNamedArgumentThatShouldBeIgnored() End Sub <UriTemplate(""{0}"")> Public Shared Sub MethodWithInvalidUriRequiredArgumentThatShouldBeIgnored() End Sub <UriTemplate("""")> Public Shared Sub MethodWithEmptyUriRequiredArgumentThatShouldBeIgnored() End Sub End Class "); } private DiagnosticResult CA2243CSharpDefaultResultAt(int line, int column, string arg1, string arg2, string arg3, string arg4) { return GetCSharpResultAt(line, column, AttributeStringLiteralsShouldParseCorrectlyAnalyzer.DefaultRule, arg1, arg2, arg3, arg4); } private DiagnosticResult CA2243CSharpEmptyResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, AttributeStringLiteralsShouldParseCorrectlyAnalyzer.EmptyRule, arg1, arg2, arg3); } private DiagnosticResult CA2243BasicDefaultResultAt(int line, int column, string arg1, string arg2, string arg3, string arg4) { return GetBasicResultAt(line, column, AttributeStringLiteralsShouldParseCorrectlyAnalyzer.DefaultRule, arg1, arg2, arg3, arg4); } private DiagnosticResult CA2243BasicEmptyResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, AttributeStringLiteralsShouldParseCorrectlyAnalyzer.EmptyRule, arg1, arg2, arg3); } } }
namespace android.os { [global::MonoJavaBridge.JavaClass()] public partial class ParcelFileDescriptor : java.lang.Object, Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ParcelFileDescriptor() { InitJNI(); } protected ParcelFileDescriptor(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class AutoCloseInputStream : java.io.FileInputStream { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AutoCloseInputStream() { InitJNI(); } protected AutoCloseInputStream(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _close6634; public override void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.AutoCloseInputStream._close6634); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, global::android.os.ParcelFileDescriptor.AutoCloseInputStream._close6634); } internal static global::MonoJavaBridge.MethodId _AutoCloseInputStream6635; public AutoCloseInputStream(android.os.ParcelFileDescriptor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, global::android.os.ParcelFileDescriptor.AutoCloseInputStream._AutoCloseInputStream6635, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/ParcelFileDescriptor$AutoCloseInputStream")); global::android.os.ParcelFileDescriptor.AutoCloseInputStream._close6634 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, "close", "()V"); global::android.os.ParcelFileDescriptor.AutoCloseInputStream._AutoCloseInputStream6635 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, "<init>", "(Landroid/os/ParcelFileDescriptor;)V"); } } [global::MonoJavaBridge.JavaClass()] public partial class AutoCloseOutputStream : java.io.FileOutputStream { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AutoCloseOutputStream() { InitJNI(); } protected AutoCloseOutputStream(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _close6636; public override void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._close6636); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._close6636); } internal static global::MonoJavaBridge.MethodId _AutoCloseOutputStream6637; public AutoCloseOutputStream(android.os.ParcelFileDescriptor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._AutoCloseOutputStream6637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/ParcelFileDescriptor$AutoCloseOutputStream")); global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._close6636 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, "close", "()V"); global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._AutoCloseOutputStream6637 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, "<init>", "(Landroid/os/ParcelFileDescriptor;)V"); } } internal static global::MonoJavaBridge.MethodId _finalize6638; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._finalize6638); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._finalize6638); } internal static global::MonoJavaBridge.MethodId _toString6639; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._toString6639)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._toString6639)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _close6640; public virtual void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._close6640); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._close6640); } internal static global::MonoJavaBridge.MethodId _open6641; public static global::android.os.ParcelFileDescriptor open(java.io.File arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._open6641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.ParcelFileDescriptor; } internal static global::MonoJavaBridge.MethodId _writeToParcel6642; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._writeToParcel6642, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._writeToParcel6642, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents6643; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._describeContents6643); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._describeContents6643); } internal static global::MonoJavaBridge.MethodId _fromSocket6644; public static global::android.os.ParcelFileDescriptor fromSocket(java.net.Socket arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._fromSocket6644, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.ParcelFileDescriptor; } internal static global::MonoJavaBridge.MethodId _getFileDescriptor6645; public virtual global::java.io.FileDescriptor getFileDescriptor() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._getFileDescriptor6645)) as java.io.FileDescriptor; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._getFileDescriptor6645)) as java.io.FileDescriptor; } internal static global::MonoJavaBridge.MethodId _getStatSize6646; public virtual long getStatSize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor._getStatSize6646); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._getStatSize6646); } internal static global::MonoJavaBridge.MethodId _ParcelFileDescriptor6647; public ParcelFileDescriptor(android.os.ParcelFileDescriptor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._ParcelFileDescriptor6647, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int MODE_WORLD_READABLE { get { return 1; } } public static int MODE_WORLD_WRITEABLE { get { return 2; } } public static int MODE_READ_ONLY { get { return 268435456; } } public static int MODE_WRITE_ONLY { get { return 536870912; } } public static int MODE_READ_WRITE { get { return 805306368; } } public static int MODE_CREATE { get { return 134217728; } } public static int MODE_TRUNCATE { get { return 67108864; } } public static int MODE_APPEND { get { return 33554432; } } internal static global::MonoJavaBridge.FieldId _CREATOR6648; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.os.ParcelFileDescriptor.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/ParcelFileDescriptor")); global::android.os.ParcelFileDescriptor._finalize6638 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "finalize", "()V"); global::android.os.ParcelFileDescriptor._toString6639 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "toString", "()Ljava/lang/String;"); global::android.os.ParcelFileDescriptor._close6640 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "close", "()V"); global::android.os.ParcelFileDescriptor._open6641 = @__env.GetStaticMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "open", "(Ljava/io/File;I)Landroid/os/ParcelFileDescriptor;"); global::android.os.ParcelFileDescriptor._writeToParcel6642 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.os.ParcelFileDescriptor._describeContents6643 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "describeContents", "()I"); global::android.os.ParcelFileDescriptor._fromSocket6644 = @__env.GetStaticMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "fromSocket", "(Ljava/net/Socket;)Landroid/os/ParcelFileDescriptor;"); global::android.os.ParcelFileDescriptor._getFileDescriptor6645 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "getFileDescriptor", "()Ljava/io/FileDescriptor;"); global::android.os.ParcelFileDescriptor._getStatSize6646 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "getStatSize", "()J"); global::android.os.ParcelFileDescriptor._ParcelFileDescriptor6647 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "<init>", "(Landroid/os/ParcelFileDescriptor;)V"); } } }
using System; using UnityEngine; using Flunity.Utils; namespace Flunity.Internal { /// <summary> /// Forms vertex data for rendering scene /// </summary> internal class DrawBatch { private const int INITIAL_QUADS = 64; public int layer = 0; internal Rect? drawRect; private DrawOptions _drawOptions; private Texture2D _currentTexture; private Material _material; private int _renderQueue; private readonly FlashStage _stage; private readonly Mesh _mesh; private Vector3[] _vertices; private Color32[] _colors; private Vector2[] _uv; private Vector2[] _uv2; private int[] _indices; private int _vertexCount; private int _vertexNum; private int _indexCount; private int _indexNum; private Shader _shader; public Shader shader { get { return _shader; } set { if (value == null) throw new ArgumentNullException("value"); _shader = value; _material = new Material(_shader); _material.renderQueue = _renderQueue; } } internal DrawBatch(FlashStage stage, Shader shader, int renderQueue = 0) { _stage = stage; _renderQueue = renderQueue; _drawOptions = new DrawOptions(); _mesh = new Mesh(); _mesh.MarkDynamic(); if (shader != null) this.shader = shader; CreateBuffers(INITIAL_QUADS); Reset(); } private void CreateBuffers(int spriteCount) { _vertexCount = spriteCount * 4; _indexCount = spriteCount * 6; _vertices = new Vector3[_vertexCount]; _colors = new Color32[_vertexCount]; _uv = new Vector2[_vertexCount]; _uv2 = new Vector2[_vertexCount]; _indices = new int[_indexCount]; } public void DrawTriangles(Texture2D texture, VertexData[] vertices) { if (texture != _currentTexture) { Flush(); ApplyTexture(texture); } if (vertices.Length % 3 != 0) throw new Exception("Count of vertices must be divided by 3"); EnsureSize(vertices.Length, vertices.Length); for (var i = 0; i < vertices.Length; i++) { _indices[_indexNum + i] = _vertexNum + i; } AddVertices(vertices); _indexNum += vertices.Length; } public void DrawTriangles(Texture2D texture, VertexData[] vertices, short[] indices) { if (texture != _currentTexture) { Flush(); ApplyTexture(texture); } if (vertices.Length % 3 != 0) throw new Exception("Count of vertices must be divided by 3"); EnsureSize(vertices.Length, indices.Length); for (var i = 0; i < indices.Length; i++) { _indices[_indexNum + i] = _vertexNum + indices[i]; } AddVertices(vertices); _indexNum += indices.Length; } public void DrawQuads(Texture2D texture, QuadCollection quadCollection) { var quads = quadCollection.quads; var quadsCount = quadCollection.quadsCount; for (int i = 0; i < quadsCount; i++) { DrawQuad(texture, ref quads[i]); } } public void DrawQuad(Texture2D texture, ref SpriteQuad quad) { if (texture != _currentTexture) { Flush(); ApplyTexture(texture); } if (drawRect != null) { if (!drawRect.Value.Intersects(quad.GetBounds())) return; } // performance inlining if (_vertexNum + 4 >= _vertexCount || _indexNum + 6 >= _indexCount) EnsureSize(4, 6); _vertices[_vertexNum] = quad.leftTop.position; _vertices[_vertexNum + 1] = quad.rightTop.position; _vertices[_vertexNum + 2] = quad.leftBottom.position; _vertices[_vertexNum + 3] = quad.rightBottom.position; quad.leftTop.color.GetColor(out _colors[_vertexNum + 0]); quad.rightTop.color.GetColor(out _colors[_vertexNum + 1]); quad.leftBottom.color.GetColor(out _colors[_vertexNum + 2]); quad.rightBottom.color.GetColor(out _colors[_vertexNum + 3]); quad.leftTop.color.GetTint(out _uv2[_vertexNum + 0]); quad.rightTop.color.GetTint(out _uv2[_vertexNum + 1]); quad.leftBottom.color.GetTint(out _uv2[_vertexNum + 2]); quad.rightBottom.color.GetTint(out _uv2[_vertexNum + 3]); _uv[_vertexNum] = quad.leftTop.texCoord; _uv[_vertexNum + 1] = quad.rightTop.texCoord; _uv[_vertexNum + 2] = quad.leftBottom.texCoord; _uv[_vertexNum + 3] = quad.rightBottom.texCoord; _indices[_indexNum] = _vertexNum; _indices[_indexNum + 1] = (_vertexNum + 1); _indices[_indexNum + 2] = (_vertexNum + 2); _indices[_indexNum + 3] = (_vertexNum + 1); _indices[_indexNum + 4] = (_vertexNum + 2); _indices[_indexNum + 5] = (_vertexNum + 3); _vertexNum += 4; _indexNum += 6; } public virtual void Flush() { if (_vertexNum == 0) return; if (_indexNum < _indexCount - 1) { _vertices[_vertexNum + 1] = Vector3.zero; _uv[_vertexNum + 1] = Vector2.zero; _colors[_vertexNum + 1] = new Color32(0, 0, 0, 0); _uv2[_vertexNum + 1] = new Vector2(); for (int i = _indexNum + 1; i < _indexCount; i++) { _indices[i] = _vertexNum + 1; } } _vertexCount = _vertexNum; _indexCount = _indexNum; _mesh.Clear(); _mesh.vertices = _vertices; _mesh.colors32 = _colors; _mesh.uv = _uv; _mesh.uv2 = _uv2; _mesh.triangles = _indices; // Debug.Log(_vertices.JoinStrings()); // Debug.Log(_colors.JoinStrings()); // Debug.Log(_uv.JoinStrings()); Graphics.DrawMesh(_mesh, _stage.GetGlobalMatrix(), _material, layer); Reset(); } internal void Reset() { _vertexNum = 0; _indexNum = 0; } private void ApplyTexture(Texture2D texture) { _currentTexture = texture; _material.mainTexture = _currentTexture; _material.SetPass(0); } public void ApplyOptions(DrawOptions drawOptions) { if (drawOptions.EqualsTo(_drawOptions)) return; Flush(); _drawOptions.CopyFrom(drawOptions); // if (_currentEffect != _drawOptions.effect) // { // _currentEffect = _drawOptions.effect; // _currentEffect.CurrentTechnique.Passes[0].Apply(); // } } private void EnsureSize(int verticesCapacity, int indicesCapacity) { var verticesRequired = _vertexNum + verticesCapacity; if (_vertexCount < verticesRequired) { _vertexCount = verticesRequired + 128; Array.Resize(ref _vertices, _vertexCount); Array.Resize(ref _colors, _vertexCount); Array.Resize(ref _uv, _vertexCount); Array.Resize(ref _uv2, _vertexCount); } var inidicesRequired = _indexNum + indicesCapacity; if (_indexCount < inidicesRequired) { _indexCount = inidicesRequired + 192; Array.Resize(ref _indices, _indexCount); } } private void AddVertices(VertexData[] vertices) { Array.Copy(vertices, 0, _indices, _vertexNum, vertices.Length); _vertexNum += vertices.Length; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.LocalisationExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Resources.Localisation.Web; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osuTK; namespace osu.Game.Overlays.BeatmapSet.Scores { public class TopScoreStatisticsSection : CompositeDrawable { private const float margin = 10; private const float top_columns_min_width = 64; private const float bottom_columns_min_width = 45; private readonly FontUsage smallFont = OsuFont.GetFont(size: 16); private readonly FontUsage largeFont = OsuFont.GetFont(size: 22, weight: FontWeight.Light); private readonly TextColumn totalScoreColumn; private readonly TextColumn accuracyColumn; private readonly TextColumn maxComboColumn; private readonly TextColumn ppColumn; private readonly FillFlowContainer<InfoColumn> statisticsColumns; private readonly ModsInfoColumn modsColumn; [Resolved] private ScoreManager scoreManager { get; set; } public TopScoreStatisticsSection() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new FillFlowContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), Children = new Drawable[] { totalScoreColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeadersScoreTotal, largeFont, top_columns_min_width), accuracyColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeadersAccuracy, largeFont, top_columns_min_width), maxComboColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeadersCombo, largeFont, top_columns_min_width) } }, new FillFlowContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), Children = new Drawable[] { statisticsColumns = new FillFlowContainer<InfoColumn> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), }, ppColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeaderspp, smallFont, bottom_columns_min_width), modsColumn = new ModsInfoColumn(), } }, } }; } [BackgroundDependencyLoader] private void load() { if (score != null) totalScoreColumn.Current = scoreManager.GetBindableTotalScoreString(score); } private ScoreInfo score; /// <summary> /// Sets the score to be displayed. /// </summary> public ScoreInfo Score { set { if (score == value) return; score = value; accuracyColumn.Text = value.DisplayAccuracy; maxComboColumn.Text = value.MaxCombo.ToLocalisableString(@"0\x"); ppColumn.Alpha = value.BeatmapInfo?.Status.GrantsPerformancePoints() == true ? 1 : 0; ppColumn.Text = value.PP?.ToLocalisableString(@"N0"); statisticsColumns.ChildrenEnumerable = value.GetStatisticsForDisplay().Select(createStatisticsColumn); modsColumn.Mods = value.Mods; if (scoreManager != null) totalScoreColumn.Current = scoreManager.GetBindableTotalScoreString(value); } } private TextColumn createStatisticsColumn(HitResultDisplayStatistic stat) => new TextColumn(stat.DisplayName, smallFont, bottom_columns_min_width) { Text = stat.MaxCount == null ? stat.Count.ToLocalisableString(@"N0") : (LocalisableString)$"{stat.Count}/{stat.MaxCount}" }; private class InfoColumn : CompositeDrawable { private readonly Box separator; private readonly OsuSpriteText text; public InfoColumn(LocalisableString title, Drawable content, float? minWidth = null) { AutoSizeAxes = Axes.Both; Margin = new MarginPadding { Vertical = 5 }; InternalChild = new GridContainer { AutoSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize, minSize: minWidth ?? 0) }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.Absolute, 2), new Dimension(GridSizeMode.AutoSize) }, Content = new[] { new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold), Text = title.ToUpper(), // 2px padding bottom + 1px vertical to compensate for the additional spacing because of 1.25 line-height in osu-web Padding = new MarginPadding { Top = 1, Bottom = 3 } } }, new Drawable[] { separator = new Box { Anchor = Anchor.TopLeft, RelativeSizeAxes = Axes.X, Height = 2, }, }, new[] { // osu-web has 4px margin here but also uses 0.9 line-height, reducing margin to 2px seems like a good alternative to that content.With(c => c.Margin = new MarginPadding { Top = 2 }) } } }; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { text.Colour = colourProvider.Foreground1; separator.Colour = colourProvider.Background3; } } private class TextColumn : InfoColumn { private readonly SpriteText text; public TextColumn(LocalisableString title, FontUsage font, float? minWidth = null) : this(title, new OsuSpriteText { Font = font }, minWidth) { } private TextColumn(LocalisableString title, SpriteText text, float? minWidth = null) : base(title, text, minWidth) { this.text = text; } public LocalisableString Text { set => text.Text = value; } public Bindable<string> Current { get => text.Current; set => text.Current = value; } } private class ModsInfoColumn : InfoColumn { private readonly FillFlowContainer modsContainer; public ModsInfoColumn() : this(new FillFlowContainer { AutoSizeAxes = Axes.X, Direction = FillDirection.Horizontal, Spacing = new Vector2(1), Height = 18f }) { } private ModsInfoColumn(FillFlowContainer modsContainer) : base(BeatmapsetsStrings.ShowScoreboardHeadersMods, modsContainer) { this.modsContainer = modsContainer; } public IEnumerable<Mod> Mods { set { modsContainer.Clear(); modsContainer.Children = value.Select(mod => new ModIcon(mod) { AutoSizeAxes = Axes.Both, Scale = new Vector2(0.25f), }).ToList(); } } } } }
/* ==================================================================== 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 NPOI.OpenXmlFormats.Spreadsheet; using NUnit.Framework; using NPOI.XSSF.Model; namespace NPOI.XSSF.UserModel.Helpers { /** * Tests for {@link ColumnHelper} * */ [TestFixture] public class TestColumnHelper { [Test] public void TestCleanColumns() { CT_Worksheet worksheet = new CT_Worksheet(); CT_Cols cols1 = worksheet.AddNewCols(); CT_Col col1 = cols1.AddNewCol(); col1.min = (1); col1.max = (1); col1.width = (88); col1.hidden = (true); CT_Col col2 = cols1.AddNewCol(); col2.min = (2); col2.max = (3); CT_Cols cols2 = worksheet.AddNewCols(); CT_Col col4 = cols2.AddNewCol(); col4.min = (13); col4.max = (16384); // Test cleaning cols Assert.AreEqual(2, worksheet.sizeOfColsArray()); int count = countColumns(worksheet); Assert.AreEqual(16375, count); // Clean columns and Test a clean worksheet ColumnHelper helper = new ColumnHelper(worksheet); Assert.AreEqual(1, worksheet.sizeOfColsArray()); count = countColumns(worksheet); Assert.AreEqual(16375, count); // Remember - POI column 0 == OOXML column 1 Assert.AreEqual(88.0, helper.GetColumn(0, false).width, 0.0); Assert.IsTrue(helper.GetColumn(0, false).hidden); Assert.AreEqual(0.0, helper.GetColumn(1, false).width, 0.0); Assert.IsFalse(helper.GetColumn(1, false).hidden); } [Test] public void TestSortColumns() { //CT_Worksheet worksheet = new CT_Worksheet(); //ColumnHelper helper = new ColumnHelper(worksheet); CT_Cols cols1 = new CT_Cols(); CT_Col col1 = cols1.AddNewCol(); col1.min = (1); col1.max = (1); col1.width = (88); col1.hidden = (true); CT_Col col2 = cols1.AddNewCol(); col2.min = (2); col2.max = (3); CT_Col col3 = cols1.AddNewCol(); col3.min = (13); col3.max = (16750); Assert.AreEqual(3, cols1.sizeOfColArray()); CT_Col col4 = cols1.AddNewCol(); col4.min = (8); col4.max = (11); Assert.AreEqual(4, cols1.sizeOfColArray()); CT_Col col5 = cols1.AddNewCol(); col5.min = (4); col5.max = (5); Assert.AreEqual(5, cols1.sizeOfColArray()); CT_Col col6 = cols1.AddNewCol(); col6.min = (8); col6.max = (9); col6.hidden = (true); CT_Col col7 = cols1.AddNewCol(); col7.min = (6); col7.max = (8); col7.width = (17.0); CT_Col col8 = cols1.AddNewCol(); col8.min = (25); col8.max = (27); CT_Col col9 = cols1.AddNewCol(); col9.min = (20); col9.max = (30); Assert.AreEqual(9, cols1.sizeOfColArray()); Assert.AreEqual(20u, cols1.GetColArray(8).min); Assert.AreEqual(30u, cols1.GetColArray(8).max); ColumnHelper.SortColumns(cols1); Assert.AreEqual(9, cols1.sizeOfColArray()); Assert.AreEqual(25u, cols1.GetColArray(8).min); Assert.AreEqual(27u, cols1.GetColArray(8).max); } [Test] public void TestCloneCol() { CT_Worksheet worksheet = new CT_Worksheet(); ColumnHelper helper = new ColumnHelper(worksheet); CT_Cols cols = new CT_Cols(); CT_Col col = new CT_Col(); col.min = (2); col.max = (8); col.hidden = (true); col.width = (13.4); CT_Col newCol = helper.CloneCol(cols, col); Assert.AreEqual(2u, newCol.min); Assert.AreEqual(8u, newCol.max); Assert.IsTrue(newCol.hidden); Assert.AreEqual(13.4, newCol.width, 0.0); } [Test] public void TestAddCleanColIntoCols() { CT_Worksheet worksheet = new CT_Worksheet(); ColumnHelper helper = new ColumnHelper(worksheet); CT_Cols cols1 = new CT_Cols(); CT_Col col1 = cols1.AddNewCol(); col1.min = (1); col1.max = (1); col1.width = (88); col1.hidden = (true); CT_Col col2 = cols1.AddNewCol(); col2.min = (2); col2.max = (3); CT_Col col3 = cols1.AddNewCol(); col3.min = (13); col3.max = (16750); Assert.AreEqual(3, cols1.sizeOfColArray()); CT_Col col4 = cols1.AddNewCol(); col4.min = (8); col4.max = (9); Assert.AreEqual(4, cols1.sizeOfColArray()); CT_Col col5 = new CT_Col(); col5.min = (4); col5.max = (5); helper.AddCleanColIntoCols(cols1, col5); Assert.AreEqual(5, cols1.sizeOfColArray()); CT_Col col6 = new CT_Col(); col6.min = (8); col6.max = (11); col6.hidden = (true); helper.AddCleanColIntoCols(cols1, col6); Assert.AreEqual(6, cols1.sizeOfColArray()); CT_Col col7 = new CT_Col(); col7.min = (6); col7.max = (8); col7.width = (17.0); helper.AddCleanColIntoCols(cols1, col7); Assert.AreEqual(8, cols1.sizeOfColArray()); CT_Col col8 = new CT_Col(); col8.min = (20); col8.max = (30); helper.AddCleanColIntoCols(cols1, col8); Assert.AreEqual(10, cols1.sizeOfColArray()); CT_Col col9 = new CT_Col(); col9.min = (25); col9.max = (27); helper.AddCleanColIntoCols(cols1, col9); // TODO - assert something interesting Assert.AreEqual(12, cols1.col.Count); Assert.AreEqual(1u, cols1.GetColArray(0).min); Assert.AreEqual(16750u, cols1.GetColArray(11).max); } [Test] public void TestColumn() { CT_Worksheet worksheet = new CT_Worksheet(); CT_Cols cols1 = worksheet.AddNewCols(); CT_Col col1 = cols1.AddNewCol(); col1.min = (1); col1.max = (1); col1.width = (88); col1.hidden = (true); CT_Col col2 = cols1.AddNewCol(); col2.min = (2); col2.max = (3); CT_Cols cols2 = worksheet.AddNewCols(); CT_Col col4 = cols2.AddNewCol(); col4.min = (3); col4.max = (6); // Remember - POI column 0 == OOXML column 1 ColumnHelper helper = new ColumnHelper(worksheet); Assert.IsNotNull(helper.GetColumn(0, false)); Assert.IsNotNull(helper.GetColumn(1, false)); Assert.AreEqual(88.0, helper.GetColumn(0, false).width, 0.0); Assert.AreEqual(0.0, helper.GetColumn(1, false).width, 0.0); Assert.IsTrue(helper.GetColumn(0, false).hidden); Assert.IsFalse(helper.GetColumn(1, false).hidden); Assert.IsNull(helper.GetColumn(99, false)); Assert.IsNotNull(helper.GetColumn(5, false)); } [Test] public void TestSetColumnAttributes() { CT_Col col = new CT_Col(); col.width = (12); col.hidden = (true); CT_Col newCol = new CT_Col(); Assert.AreEqual(0.0, newCol.width, 0.0); Assert.IsFalse(newCol.hidden); ColumnHelper helper = new ColumnHelper(new CT_Worksheet()); helper.SetColumnAttributes(col, newCol); Assert.AreEqual(12.0, newCol.width, 0.0); Assert.IsTrue(newCol.hidden); } [Test] public void TestGetOrCreateColumn() { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1"); ColumnHelper columnHelper = sheet.GetColumnHelper(); // Check POI 0 based, OOXML 1 based CT_Col col = columnHelper.GetOrCreateColumn1Based(3, false); Assert.IsNotNull(col); Assert.IsNull(columnHelper.GetColumn(1, false)); Assert.IsNotNull(columnHelper.GetColumn(2, false)); Assert.IsNotNull(columnHelper.GetColumn1Based(3, false)); Assert.IsNull(columnHelper.GetColumn(3, false)); CT_Col col2 = columnHelper.GetOrCreateColumn1Based(30, false); Assert.IsNotNull(col2); Assert.IsNull(columnHelper.GetColumn(28, false)); Assert.IsNotNull(columnHelper.GetColumn(29, false)); Assert.IsNotNull(columnHelper.GetColumn1Based(30, false)); Assert.IsNull(columnHelper.GetColumn(30, false)); } [Test] public void TestGetSetColDefaultStyle() { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); CT_Worksheet ctWorksheet = sheet.GetCTWorksheet(); ColumnHelper columnHelper = sheet.GetColumnHelper(); // POI column 3, OOXML column 4 CT_Col col = columnHelper.GetOrCreateColumn1Based(4, false); Assert.IsNotNull(col); Assert.IsNotNull(columnHelper.GetColumn(3, false)); columnHelper.SetColDefaultStyle(3, 2); Assert.AreEqual(2, columnHelper.GetColDefaultStyle(3)); Assert.AreEqual(-1, columnHelper.GetColDefaultStyle(4)); StylesTable stylesTable = workbook.GetStylesSource(); CT_Xf cellXf = new CT_Xf(); cellXf.fontId = (0); cellXf.fillId = (0); cellXf.borderId = (0); cellXf.numFmtId = (0); cellXf.xfId = (0); stylesTable.PutCellXf(cellXf); CT_Col col_2 = ctWorksheet.GetColsArray(0).AddNewCol(); col_2.min = (10); col_2.max = (12); col_2.style = (1); col_2.styleSpecified = true; Assert.AreEqual(1, columnHelper.GetColDefaultStyle(11)); XSSFCellStyle cellStyle = new XSSFCellStyle(0, 0, stylesTable, null); columnHelper.SetColDefaultStyle(11, cellStyle); Assert.AreEqual(0u, col_2.style); Assert.AreEqual(1, columnHelper.GetColDefaultStyle(10)); } private static int countColumns(CT_Worksheet worksheet) { int count; count = 0; for (int i = 0; i < worksheet.sizeOfColsArray(); i++) { for (int y = 0; y < worksheet.GetColsArray(i).sizeOfColArray(); y++) { for (long k = worksheet.GetColsArray(i).GetColArray(y).min; k <= worksheet .GetColsArray(i).GetColArray(y).max; k++) { count++; } } } return count; } } }
#region Namespaces using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Epi.Collections; using Epi.Windows.Docking; using Epi; using Epi.Fields; #endregion //Namespaces using Epi.Windows.Dialogs; namespace Epi.Windows.Enter.Forms { /// <summary> /// The Data Dictionary form /// </summary> public partial class DataDictionary : DialogBase { #region Private Data Members private new MainForm mainForm; private new View view; private Project project; private DataTable displayTable; private string sortExp = "[Page Position] ASC, [Tab Index] ASC"; private string sortColumnName = ""; #endregion #region Constructors /// <summary> /// Constructor for the class /// </summary> /// <param name="givenView">The View to load check code for</param> /// <param name="givenMainForm">The main form</param> public DataDictionary(View givenView, MainForm givenMainForm) { view = givenView; project = view.Project; mainForm = givenMainForm; Construct(); } private void Construct() { InitializeComponent(); DockManager.FastMoveDraw = false; DockManager.Style = DockVisualStyle.VS2005; Project project = view.GetProject(); Epi.Collections.ViewCollection views = project.Views; viewSelect.Items.AddRange(views.Names.ToArray()); DataSets.TableSchema.TablesDataTable tables = project.Metadata.GetCodeTableList(); foreach (DataRow row in tables) { viewSelect.Items.Add((string)row[ColumnNames.TABLE_NAME]); } viewSelect.SelectedItem = view.Name; viewSelect_SelectedIndexChanged(viewSelect, new EventArgs()); } #endregion //Constructors #region Event Handlers private void btnAsHtml_Click(object sender, EventArgs e) { //string filePath = System.IO.Directory.GetCurrentDirectory().ToString() + "\\dataDictionary.html"; string filePath = System.IO.Path.GetTempPath() + "DataDictionary_" + Guid.NewGuid().ToString("N") + ".html"; if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } System.IO.TextWriter textWriter = System.IO.File.CreateText(filePath); textWriter.WriteLine("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title>"); textWriter.WriteLine("<style type=\"text/css\">"); textWriter.WriteLine("table.dataDictionary { border-width: 1px; border-collapse: collapse; border-color: black; width: 100%;}"); textWriter.WriteLine("table.dataDictionary th { border-width: 1px; border-style: solid; padding: 4px; border-color: black; font-family: Verdana; font-size: x-small; font-weight:bold; background-color:#4a7ac9; color:#FFFFFF;}"); textWriter.WriteLine("table.dataDictionary td { border-width: 1px; border-style: solid; padding: 4px; border-color: black; font-family: Verdana; font-size: x-small; font-weight:normal;}"); textWriter.WriteLine(".styleTitle { font-family: \"Verdana\"; font-size: x-small; font-weight: normal; }"); textWriter.WriteLine("</style>"); textWriter.WriteLine("<br/>"); if (displayTable.TableName.StartsWith("code") == false) { textWriter.WriteLine(string.Format("<span class=\"styleTitle\"><strong>Data Dictionary for View [ {0} ]</strong></span><br />", view.Name)); textWriter.WriteLine(string.Format("<span class=\"styleTitle\">{0}</span><br />", view.FullName)); } textWriter.WriteLine(string.Format("<span class=\"styleTitle\">{0}</span><br />", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString())); textWriter.WriteLine("<br/>"); textWriter.WriteLine("<table class=\"dataDictionary\">"); if (displayTable.TableName.StartsWith("code") == false) { textWriter.WriteLine("<tr><th>Page Position</th><th>Page Name</th><th>Tab Index</th><th>Prompt</th><th>Field Type</th><th>Name</th><th>Variable Type</th><th>Format</th><th>Special Info</th></tr>"); bool highlightRow = false; DataView dataView = new DataView(displayTable); dataView.Sort = sortExp; DataTable sortedTable = dataView.ToTable(); foreach (DataRow row in sortedTable.Rows) { textWriter.WriteLine(string.Format("<tr style=\"background-color: #{0}\">", highlightRow ? "EEEEEE" : "FFFFFF")); textWriter.WriteLine(string.Format("<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td><td>{8}</td>", row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString(), row[5].ToString(), row[6].ToString(), row[7].ToString(), row[8].ToString())); textWriter.WriteLine("</tr>"); highlightRow = !highlightRow; } } else { bool highlightRow = false; DataView dataView = new DataView(displayTable); DataTable table = dataView.ToTable(); textWriter.WriteLine("<tr>"); foreach (DataColumn column in table.Columns) { textWriter.WriteLine("<th>{0}</th>", column.ColumnName); } foreach (DataRow row in table.Rows) { textWriter.WriteLine(string.Format("<tr style=\"background-color: #{0}\">", highlightRow ? "EEEEEE" : "FFFFFF")); object[] itemArray = row.ItemArray; foreach (object obj in itemArray) { textWriter.WriteLine(string.Format("<td>{0}</td>", (string)obj)); } textWriter.WriteLine("</tr>"); highlightRow = !highlightRow; } } textWriter.WriteLine("</table></body></html>"); textWriter.Close(); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = filePath; proc.Start(); } void dataGridView_ColumnHeaderMouseClick(object sender, System.Windows.Forms.DataGridViewCellMouseEventArgs e) { if (dataGridView.SortedColumn != null) { sortColumnName = dataGridView.SortedColumn.Name; string sortOrder = "ASC"; if (dataGridView.SortOrder == System.Windows.Forms.SortOrder.Descending) { sortOrder = "DESC"; } sortExp = string.Format("[{0}] {1}", sortColumnName, sortOrder).Trim(); if (sortColumnName.Equals("Page Position")) { sortExp += string.Format(",[Tab Index] {1}", sortColumnName, sortOrder).Trim(); } } ((BindingSource)this.dataGridView.DataSource).Sort = sortExp; } void dataGridView_CellDoubleClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e) { int rowIndex = ((System.Windows.Forms.DataGridViewCellEventArgs)e).RowIndex; if (rowIndex >= 0) { DataGridViewRow row = ((DataGridView)sender).Rows[rowIndex]; } } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } #endregion private void viewSelect_SelectedIndexChanged(object sender, EventArgs e) { if (viewSelect.SelectedItem == null) return; if (project.Views.Contains((string)viewSelect.SelectedItem)) { view = project.Views[(string)viewSelect.SelectedItem]; displayTable = this.view.Project.Metadata.GetDataDictionary(this.view); foreach(DataColumn column in displayTable.Columns) { column.AllowDBNull = true; } foreach (DataRow dr in displayTable.Rows) { if (dr["Special Info"] is string) { string info = (string)dr["Special Info"]; if (info.Contains("||")) { int index = info.IndexOf("||"); dr["Special Info"] = info.Substring(0, index); } else { dr["Special Info"] = info; } } if (dr["Variable Type"].ToString().ToLowerInvariant() == "unknown") { dr["Variable Type"] = "Text"; } if (dr["Field Type"].ToString().ToLowerInvariant() == "option") { dr["Variable Type"] = "Number"; } else if (dr["Field Type"].ToString().ToLowerInvariant() == "grid") { dr["Variable Type"] = "Data Table"; } if (dr["Field Type"].ToString().ToLowerInvariant() == "image") { dr["Variable Type"] = "Image"; //--2365 Boolean bshouldretainImage = (Boolean)dr[Constants.SHOULDRETAINIMAGESIZE]; if (bshouldretainImage == true) { dr[Constants.SPECIALINFO] = dr[Constants.SPECIALINFO].ToString() + Constants.VARRETAINIMAGESIZE; } //-- } //--2365 Boolean bshouldRepeatLast = false; if (dr[ColumnNames.SHOULD_REPEAT_LAST] != DBNull.Value) { bshouldRepeatLast = (Boolean)dr[ColumnNames.SHOULD_REPEAT_LAST]; if (bshouldRepeatLast == true) { dr[Constants.SPECIALINFO] = dr[Constants.SPECIALINFO].ToString() + Constants.VARREPEATLAST; } } Boolean bIsRequired = false; if (dr[ColumnNames.IS_REQUIRED] != DBNull.Value) { bIsRequired = (Boolean)dr[ColumnNames.IS_REQUIRED]; if (bIsRequired == true) { dr[Constants.SPECIALINFO] = dr[Constants.SPECIALINFO].ToString() + Constants.VARREQUIRED; } } Boolean bIsReadOnly = false; if (dr[ColumnNames.IS_READ_ONLY] != DBNull.Value) { bIsReadOnly = (Boolean)dr[ColumnNames.IS_READ_ONLY]; if (bIsReadOnly == true) { dr[Constants.SPECIALINFO] = dr[Constants.SPECIALINFO] + Constants.VARREADONLY; } } if (dr[ColumnNames.UPPER] != DBNull.Value && dr[ColumnNames.LOWER] != DBNull.Value) { if (dr[ColumnNames.UPPER].ToString().Length > 0 && dr[ColumnNames.LOWER].ToString().Length > 0) { dr[Constants.SPECIALINFO] = dr[Constants.SPECIALINFO] + Constants.VARRANGE + CharLiterals.LEFT_SQUARE_BRACKET + dr[ColumnNames.LOWER].ToString() + CharLiterals.COMMA + dr[ColumnNames.UPPER].ToString() + CharLiterals.RIGHT_SQUARE_BRACKET; } } //---- } //-- 2365 displayTable.Columns.Remove(ColumnNames.IS_REQUIRED); displayTable.Columns.Remove(ColumnNames.SHOULD_REPEAT_LAST); displayTable.Columns.Remove(ColumnNames.IS_READ_ONLY); displayTable.Columns.Remove(Constants.SHOULDRETAINIMAGESIZE); displayTable.Columns.Remove(ColumnNames.UPPER); displayTable.Columns.Remove(ColumnNames.LOWER); //-- ((EnterMainForm)this.mainForm).RunTimeView.EpiInterpreter.Context.ClearState(); ((EnterMainForm)this.mainForm).RunTimeView.EpiInterpreter.Execute(this.view.CheckCode); EpiInfo.Plugin.VariableScope variableScope = EpiInfo.Plugin.VariableScope.Global | EpiInfo.Plugin.VariableScope.Standard | EpiInfo.Plugin.VariableScope.Permanent; List<EpiInfo.Plugin.IVariable> vars = new List<EpiInfo.Plugin.IVariable>(); if (((EnterMainForm)this.mainForm).RunTimeView.EpiInterpreter != null) { vars = ((EnterMainForm)this.mainForm).RunTimeView.EpiInterpreter.Context.GetVariablesInScope(variableScope); } DataRow row; foreach (EpiInfo.Plugin.IVariable var in vars) { if (!(var is Epi.Fields.PredefinedDataField)) { row = displayTable.NewRow(); row["Name"] = var.Name.ToString(); row["Field Type"] = var.VariableScope.ToString(); row["Variable Type"] = var.DataType.ToString(); displayTable.Rows.Add(row); } } BindingSource source = new BindingSource(); source.DataSource = displayTable; source.Sort = sortExp; this.dataGridView.DataSource = source; } else { displayTable = this.view.Project.GetCodeTableData((string)viewSelect.SelectedItem); foreach (DataColumn column in displayTable.Columns) { column.AllowDBNull = true; } BindingSource source = new BindingSource(); source.DataSource = displayTable; this.dataGridView.DataSource = source; } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Linq; using Moq; using Avalonia.Controls.Generators; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Xunit; using System.Collections.ObjectModel; namespace Avalonia.Controls.UnitTests.Presenters { public class CarouselPresenterTests { [Fact] public void Should_Register_With_Host_When_TemplatedParent_Set() { var host = new Mock<IItemsPresenterHost>(); var target = new CarouselPresenter(); target.SetValue(Control.TemplatedParentProperty, host.Object); host.Verify(x => x.RegisterItemsPresenter(target)); } [Fact] public void ApplyTemplate_Should_Create_Panel() { var target = new CarouselPresenter { ItemsPanel = new FuncTemplate<IPanel>(() => new Panel()), }; target.ApplyTemplate(); Assert.IsType<Panel>(target.Panel); } [Fact] public void ItemContainerGenerator_Should_Be_Picked_Up_From_TemplatedControl() { var parent = new TestItemsControl(); var target = new CarouselPresenter { TemplatedParent = parent, }; Assert.IsType<ItemContainerGenerator<TestItem>>(target.ItemContainerGenerator); } [Fact] public void Setting_SelectedIndex_Should_Show_Page() { var target = new CarouselPresenter { Items = new[] { "foo", "bar" }, SelectedIndex = 0, }; target.ApplyTemplate(); Assert.IsType<ContentPresenter>(target.Panel.Children[0]); Assert.Equal("foo", ((ContentPresenter)target.Panel.Children[0]).Content); } [Fact] public void Changing_SelectedIndex_Should_Show_Page() { var target = new CarouselPresenter { Items = new[] { "foo", "bar" }, SelectedIndex = 0, }; target.ApplyTemplate(); target.SelectedIndex = 1; Assert.IsType<ContentPresenter>(target.Panel.Children[0]); Assert.Equal("bar", ((ContentPresenter)target.Panel.Children[0]).Content); } [Fact] public void Should_Remove_NonCurrent_Page_When_IsVirtualized_True() { var target = new CarouselPresenter { Items = new[] { "foo", "bar" }, IsVirtualized = true, SelectedIndex = 0, }; target.ApplyTemplate(); Assert.Single(target.ItemContainerGenerator.Containers); target.SelectedIndex = 1; Assert.Single(target.ItemContainerGenerator.Containers); } [Fact] public void Should_Not_Remove_NonCurrent_Page_When_IsVirtualized_False() { var target = new CarouselPresenter { Items = new[] { "foo", "bar" }, IsVirtualized = false, SelectedIndex = 0, }; target.ApplyTemplate(); Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); target.SelectedIndex = 1; Assert.Equal(2, target.ItemContainerGenerator.Containers.Count()); Assert.Equal(2, target.Panel.Children.Count); target.SelectedIndex = 0; Assert.Equal(2, target.ItemContainerGenerator.Containers.Count()); Assert.Equal(2, target.Panel.Children.Count); } [Fact] public void Should_Remove_Controls_When_IsVirtualized_Is_False() { ObservableCollection<string> items = new ObservableCollection<string>(); var target = new CarouselPresenter { Items = items, SelectedIndex = 0, IsVirtualized = false, }; target.ApplyTemplate(); target.SelectedIndex = 0; items.Add("foo"); target.SelectedIndex = 0; Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); items.Add("bar"); Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); target.SelectedIndex = 1; Assert.Equal(2, target.ItemContainerGenerator.Containers.Count()); Assert.Equal(2, target.Panel.Children.Count); items.Remove(items[0]); Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); items.Remove(items[0]); Assert.Empty(target.ItemContainerGenerator.Containers); Assert.Empty(target.Panel.Children); } [Fact] public void Should_Have_Correct_ItemsContainer_Index() { ObservableCollection<string> items = new ObservableCollection<string>(); var target = new CarouselPresenter { Items = items, SelectedIndex = 0, IsVirtualized = false, }; target.ApplyTemplate(); target.SelectedIndex = 0; items.Add("foo"); target.SelectedIndex = 0; Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); items.Add("bar"); Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); target.SelectedIndex = 1; Assert.Equal(2, target.ItemContainerGenerator.Containers.Count()); Assert.Equal(2, target.Panel.Children.Count); Assert.Equal(0, target.ItemContainerGenerator.Containers.First().Index); items.Remove(items[0]); Assert.Single(target.ItemContainerGenerator.Containers); Assert.Single(target.Panel.Children); Assert.Equal(0, target.ItemContainerGenerator.Containers.First().Index); items.Remove(items[0]); Assert.Empty(target.ItemContainerGenerator.Containers); Assert.Empty(target.Panel.Children); } private class TestItem : ContentControl { } private class TestItemsControl : ItemsControl { protected override IItemContainerGenerator CreateItemContainerGenerator() { return new ItemContainerGenerator<TestItem>(this, TestItem.ContentProperty, null); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client { #if !PCL using Microsoft.Azure.Devices.Client.Common; #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; /// <summary> /// Read-only wrapper for another generic dictionary. /// </summary> /// <typeparam name="TKey">Type to be used for keys.</typeparam> /// <typeparam name="TValue">Type to be used for values</typeparam> #if !WINDOWS_UWP && !PCL [Serializable] #endif [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP && !PCL // WinRT types cannot be generic public #endif class ReadOnlyDictionary45<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary //, IReadOnlyDictionary<TKey, TValue> { readonly IDictionary<TKey, TValue> m_dictionary; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif Object m_syncRoot; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif KeyCollection m_keys; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif ValueCollection m_values; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif IReadOnlyIndicator m_readOnlyIndicator; public ReadOnlyDictionary45(IDictionary<TKey, TValue> dictionary) : this(dictionary, new AlwaysReadOnlyIndicator()) { } internal ReadOnlyDictionary45(IDictionary<TKey, TValue> dictionary, IReadOnlyIndicator readOnlyIndicator) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } Contract.EndContractBlock(); m_dictionary = dictionary; m_readOnlyIndicator = readOnlyIndicator; } protected IDictionary<TKey, TValue> Dictionary { get { return m_dictionary; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (m_keys == null) { m_keys = new KeyCollection(m_dictionary.Keys, this.m_readOnlyIndicator); } return m_keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (m_values == null) { m_values = new ValueCollection(m_dictionary.Values, this.m_readOnlyIndicator); } return m_values; } } #region IDictionary<TKey, TValue> Members public bool ContainsKey(TKey key) { return m_dictionary.ContainsKey(key); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } public bool TryGetValue(TKey key, out TValue value) { return m_dictionary.TryGetValue(key, out value); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } public TValue this[TKey key] { get { return m_dictionary[key]; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add(key, value); } bool IDictionary<TKey, TValue>.Remove(TKey key) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_dictionary.Remove(key); } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return m_dictionary[key]; } set { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary[key] = value; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return m_dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return m_dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { m_dictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add(item); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Clear(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_dictionary.Remove(item); } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return m_dictionary.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_dictionary).GetEnumerator(); } #endregion #region IDictionary Members private static bool IsCompatibleKey(object key) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } return key is TKey; } void IDictionary.Add(object key, object value) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add((TKey)key, (TValue)value); } void IDictionary.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Clear(); } bool IDictionary.Contains(object key) { return IsCompatibleKey(key) && ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { IDictionary d = m_dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); } return new DictionaryEnumerator(m_dictionary); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return Keys; } } void IDictionary.Remove(object key) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Remove((TKey)key); } ICollection IDictionary.Values { get { return Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { return this[(TKey)key]; } return null; } set { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary[(TKey)key] = (TValue)value; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { Fx.Exception.ArgumentNull("array"); } if (array.Rank != 1 || array.GetLowerBound(0) != 0) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } if (index < 0 || index > array.Length) { throw Fx.Exception.ArgumentOutOfRange("index", index, Resources.ValueMustBeNonNegative); } if (array.Length - index < Count) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { m_dictionary.CopyTo(pairs, index); } else { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { foreach (var item in m_dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } } else { object[] objects = array as object[]; if (objects == null) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } try { foreach (var item in m_dictionary) { objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value); } } catch (ArrayTypeMismatchException) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_dictionary as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #if !WINDOWS_UWP && !PCL [Serializable] #endif private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> m_dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) { m_dictionary = dictionary; m_enumerator = m_dictionary.GetEnumerator(); } public DictionaryEntry Entry { get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); } } public object Key { get { return m_enumerator.Current.Key; } } public object Value { get { return m_enumerator.Current.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return m_enumerator.MoveNext(); } public void Reset() { m_enumerator.Reset(); } } #endregion [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP && !PCL [Serializable] #endif public sealed class KeyCollection : ICollection<TKey>, ICollection { private readonly ICollection<TKey> m_collection; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif private Object m_syncRoot; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif private readonly IReadOnlyIndicator m_readOnlyIndicator; internal KeyCollection(ICollection<TKey> collection, IReadOnlyIndicator readOnlyIndicator) { if (collection == null) { throw Fx.Exception.ArgumentNull("collection"); } m_collection = collection; m_readOnlyIndicator = readOnlyIndicator; } #region ICollection<T> Members void ICollection<TKey>.Add(TKey item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Add(item); } void ICollection<TKey>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Clear(); } bool ICollection<TKey>.Contains(TKey item) { return m_collection.Contains(item); } public void CopyTo(TKey[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection<TKey>.Remove(TKey item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_collection.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<TKey> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { throw Fx.Exception.AsError(new NotImplementedException()); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion } [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP && !PCL [Serializable] #endif public sealed class ValueCollection : ICollection<TValue>, ICollection { private readonly ICollection<TValue> m_collection; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif private Object m_syncRoot; #if !WINDOWS_UWP && !PCL [NonSerialized] #endif private readonly IReadOnlyIndicator m_readOnlyIndicator; internal ValueCollection(ICollection<TValue> collection, IReadOnlyIndicator readOnlyIndicator) { if (collection == null) { throw Fx.Exception.ArgumentNull("collection"); } m_collection = collection; m_readOnlyIndicator = readOnlyIndicator; } #region ICollection<T> Members void ICollection<TValue>.Add(TValue item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Add(item); } void ICollection<TValue>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Clear(); } bool ICollection<TValue>.Contains(TValue item) { return m_collection.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection<TValue>.Remove(TValue item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_collection.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<TValue> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { throw Fx.Exception.AsError(new NotImplementedException()); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion ICollection Members } class AlwaysReadOnlyIndicator : IReadOnlyIndicator { public bool IsReadOnly { get { return true; } } } } public interface IReadOnlyIndicator { bool IsReadOnly { get; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; using SLNetworkComm; using libsecondlife; namespace SLeek { public class ChatTextManager { private SleekInstance instance; private SLNetCom netcom; private SecondLife client; private ITextPrinter textPrinter; private List<ChatBufferItem> textBuffer; private bool showTimestamps; public ChatTextManager(SleekInstance instance, ITextPrinter textPrinter) { this.textPrinter = textPrinter; this.textBuffer = new List<ChatBufferItem>(); this.instance = instance; netcom = this.instance.Netcom; client = this.instance.Client; AddNetcomEvents(); showTimestamps = this.instance.Config.CurrentConfig.ChatTimestamps; this.instance.Config.ConfigApplied += new EventHandler<ConfigAppliedEventArgs>(Config_ConfigApplied); } private void Config_ConfigApplied(object sender, ConfigAppliedEventArgs e) { showTimestamps = e.AppliedConfig.ChatTimestamps; ReprintAllText(); } private void AddNetcomEvents() { netcom.ClientLoginStatus += new EventHandler<ClientLoginEventArgs>(netcom_ClientLoginStatus); netcom.ClientLoggedOut += new EventHandler(netcom_ClientLoggedOut); netcom.ClientDisconnected += new EventHandler<ClientDisconnectEventArgs>(netcom_ClientDisconnected); netcom.ChatReceived += new EventHandler<ChatEventArgs>(netcom_ChatReceived); netcom.ChatSent += new EventHandler<ChatSentEventArgs>(netcom_ChatSent); netcom.AlertMessageReceived += new EventHandler<AlertMessageEventArgs>(netcom_AlertMessageReceived); } private void netcom_ChatSent(object sender, ChatSentEventArgs e) { if (e.Channel == 0) return; ProcessOutgoingChat(e); } private void netcom_ClientLoginStatus(object sender, ClientLoginEventArgs e) { if (e.Status == LoginStatus.Success) { ChatBufferItem loggedIn = new ChatBufferItem( DateTime.Now, "Logged into Second Life as " + netcom.LoginOptions.FullName + ".", ChatBufferTextStyle.StatusBlue); ChatBufferItem loginReply = new ChatBufferItem( DateTime.Now, "Login reply: " + e.Message, ChatBufferTextStyle.StatusDarkBlue); ProcessBufferItem(loggedIn, true); ProcessBufferItem(loginReply, true); } else if (e.Status == LoginStatus.Failed) { ChatBufferItem loginError = new ChatBufferItem( DateTime.Now, "Login error: " + e.Message, ChatBufferTextStyle.Error); ProcessBufferItem(loginError, true); } } private void netcom_ClientLoggedOut(object sender, EventArgs e) { ChatBufferItem item = new ChatBufferItem( DateTime.Now, "Logged out of Second Life.\n", ChatBufferTextStyle.StatusBlue); ProcessBufferItem(item, true); } private void netcom_AlertMessageReceived(object sender, AlertMessageEventArgs e) { if (e.Message.ToLower().Contains("autopilot canceled")) return; //workaround the stupid autopilot alerts ChatBufferItem item = new ChatBufferItem( DateTime.Now, "Alert message: " + e.Message, ChatBufferTextStyle.Alert); ProcessBufferItem(item, true); } private void netcom_ClientDisconnected(object sender, ClientDisconnectEventArgs e) { if (e.Type == NetworkManager.DisconnectType.ClientInitiated) return; ChatBufferItem item = new ChatBufferItem( DateTime.Now, "Client disconnected. Message: " + e.Message, ChatBufferTextStyle.Error); ProcessBufferItem(item, true); } private void netcom_ChatReceived(object sender, ChatEventArgs e) { ProcessIncomingChat(e); } public void PrintStartupMessage() { ChatBufferItem title = new ChatBufferItem( DateTime.Now, Properties.Resources.SleekTitle, ChatBufferTextStyle.StartupTitle); ChatBufferItem ready = new ChatBufferItem( DateTime.Now, "Ready.\n", ChatBufferTextStyle.StatusBlue); ProcessBufferItem(title, true); ProcessBufferItem(ready, true); } private void ProcessBufferItem(ChatBufferItem item, bool addToBuffer) { if (addToBuffer) textBuffer.Add(item); if (showTimestamps) { textPrinter.ForeColor = Color.Gray; textPrinter.PrintText(item.Timestamp.ToString("[HH:mm] ")); } switch (item.Style) { case ChatBufferTextStyle.Normal: textPrinter.ForeColor = Color.Black; break; case ChatBufferTextStyle.StatusBlue: textPrinter.ForeColor = Color.Blue; break; case ChatBufferTextStyle.StatusDarkBlue: textPrinter.ForeColor = Color.DarkBlue; break; case ChatBufferTextStyle.LindenChat: textPrinter.ForeColor = Color.DarkGreen; break; case ChatBufferTextStyle.ObjectChat: textPrinter.ForeColor = Color.DarkCyan; break; case ChatBufferTextStyle.StartupTitle: textPrinter.ForeColor = Color.Black; textPrinter.Font = new Font(textPrinter.Font, FontStyle.Bold); break; case ChatBufferTextStyle.Alert: textPrinter.ForeColor = Color.DarkRed; break; case ChatBufferTextStyle.Error: textPrinter.ForeColor = Color.Red; break; } textPrinter.PrintTextLine(item.Text); } //Used only for non-public chat private void ProcessOutgoingChat(ChatSentEventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("(channel "); sb.Append(e.Channel); sb.Append(") You"); switch (e.Type) { case ChatType.Normal: sb.Append(": "); break; case ChatType.Whisper: sb.Append(" whisper: "); break; case ChatType.Shout: sb.Append(" shout: "); break; } sb.Append(e.Message); ChatBufferItem item = new ChatBufferItem( DateTime.Now, sb.ToString(), ChatBufferTextStyle.StatusDarkBlue); ProcessBufferItem(item, true); sb = null; } private void ProcessIncomingChat(ChatEventArgs e) { if (string.IsNullOrEmpty(e.Message)) return; StringBuilder sb = new StringBuilder(); if (e.Message.StartsWith("/me ")) { sb.Append(e.FromName); sb.Append(e.Message.Substring(3)); } else if (e.FromName == netcom.LoginOptions.FullName && e.SourceType == ChatSourceType.Agent) { sb.Append("You"); switch (e.Type) { case ChatType.Normal: sb.Append(": "); break; case ChatType.Whisper: sb.Append(" whisper: "); break; case ChatType.Shout: sb.Append(" shout: "); break; } sb.Append(e.Message); } else { sb.Append(e.FromName); switch (e.Type) { case ChatType.Normal: sb.Append(": "); break; case ChatType.Whisper: sb.Append(" whispers: "); break; case ChatType.Shout: sb.Append(" shouts: "); break; } sb.Append(e.Message); } ChatBufferItem item = new ChatBufferItem(); item.Timestamp = DateTime.Now; item.Text = sb.ToString(); switch (e.SourceType) { case ChatSourceType.Agent: item.Style = (e.FromName.EndsWith("Linden") ? ChatBufferTextStyle.LindenChat : ChatBufferTextStyle.Normal); break; case ChatSourceType.Object: item.Style = ChatBufferTextStyle.ObjectChat; break; } ProcessBufferItem(item, true); sb = null; } public void ReprintAllText() { textPrinter.ClearText(); foreach (ChatBufferItem item in textBuffer) { ProcessBufferItem(item, false); } } public void ClearInternalBuffer() { textBuffer.Clear(); } public ITextPrinter TextPrinter { get { return textPrinter; } set { textPrinter = value; } } } }
using Akka.Actor; using Akka.Util.Internal; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.Plugins; using Neo.SmartContract.Native; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; namespace Neo.Ledger { public class MemoryPool : IReadOnlyCollection<Transaction> { // Allow a reverified transaction to be rebroadcasted if it has been this many block times since last broadcast. private const int BlocksTillRebroadcast = 10; private int RebroadcastMultiplierThreshold => Capacity / 10; private static readonly double MaxMillisecondsToReverifyTx = (double)Blockchain.MillisecondsPerBlock / 3; // These two are not expected to be hit, they are just safegaurds. private static readonly double MaxMillisecondsToReverifyTxPerIdle = (double)Blockchain.MillisecondsPerBlock / 15; private readonly NeoSystem _system; // /// <summary> /// Guarantees consistency of the pool data structures. /// /// Note: The data structures are only modified from the `Blockchain` actor; so operations guaranteed to be /// performed by the blockchain actor do not need to acquire the read lock; they only need the write /// lock for write operations. /// </summary> private readonly ReaderWriterLockSlim _txRwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); /// <summary> /// Store all verified unsorted transactions currently in the pool. /// </summary> private readonly Dictionary<UInt256, PoolItem> _unsortedTransactions = new Dictionary<UInt256, PoolItem>(); /// <summary> /// Stores the verified sorted transactins currently in the pool. /// </summary> private readonly SortedSet<PoolItem> _sortedTransactions = new SortedSet<PoolItem>(); /// <summary> /// Store the unverified transactions currently in the pool. /// /// Transactions in this data structure were valid in some prior block, but may no longer be valid. /// The top ones that could make it into the next block get verified and moved into the verified data structures /// (_unsortedTransactions, and _sortedTransactions) after each block. /// </summary> private readonly Dictionary<UInt256, PoolItem> _unverifiedTransactions = new Dictionary<UInt256, PoolItem>(); private readonly SortedSet<PoolItem> _unverifiedSortedTransactions = new SortedSet<PoolItem>(); // Internal methods to aid in unit testing internal int SortedTxCount => _sortedTransactions.Count; internal int UnverifiedSortedTxCount => _unverifiedSortedTransactions.Count; private int _maxTxPerBlock; private long _feePerByte; /// <summary> /// Total maximum capacity of transactions the pool can hold. /// </summary> public int Capacity { get; } /// <summary> /// Store all verified unsorted transactions' senders' fee currently in the memory pool. /// </summary> public SendersFeeMonitor SendersFeeMonitor = new SendersFeeMonitor(); /// <summary> /// Total count of transactions in the pool. /// </summary> public int Count { get { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.Count + _unverifiedTransactions.Count; } finally { _txRwLock.ExitReadLock(); } } } /// <summary> /// Total count of verified transactions in the pool. /// </summary> public int VerifiedCount => _unsortedTransactions.Count; // read of 32 bit type is atomic (no lock) public int UnVerifiedCount => _unverifiedTransactions.Count; public MemoryPool(NeoSystem system, int capacity) { _system = system; Capacity = capacity; } internal bool LoadPolicy(StoreView snapshot) { _maxTxPerBlock = (int)NativeContract.Policy.GetMaxTransactionsPerBlock(snapshot); long newFeePerByte = NativeContract.Policy.GetFeePerByte(snapshot); bool policyChanged = newFeePerByte > _feePerByte; _feePerByte = newFeePerByte; return policyChanged; } /// <summary> /// Determine whether the pool is holding this transaction and has at some point verified it. /// Note: The pool may not have verified it since the last block was persisted. To get only the /// transactions that have been verified during this block use GetVerifiedTransactions() /// </summary> /// <param name="hash">the transaction hash</param> /// <returns>true if the MemoryPool contain the transaction</returns> public bool ContainsKey(UInt256 hash) { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.ContainsKey(hash) || _unverifiedTransactions.ContainsKey(hash); } finally { _txRwLock.ExitReadLock(); } } public bool TryGetValue(UInt256 hash, out Transaction tx) { _txRwLock.EnterReadLock(); try { bool ret = _unsortedTransactions.TryGetValue(hash, out PoolItem item) || _unverifiedTransactions.TryGetValue(hash, out item); tx = ret ? item.Tx : null; return ret; } finally { _txRwLock.ExitReadLock(); } } // Note: This isn't used in Fill during consensus, fill uses GetSortedVerifiedTransactions() public IEnumerator<Transaction> GetEnumerator() { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.Select(p => p.Value.Tx) .Concat(_unverifiedTransactions.Select(p => p.Value.Tx)) .ToList() .GetEnumerator(); } finally { _txRwLock.ExitReadLock(); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerable<Transaction> GetVerifiedTransactions() { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.Select(p => p.Value.Tx).ToArray(); } finally { _txRwLock.ExitReadLock(); } } public void GetVerifiedAndUnverifiedTransactions(out IEnumerable<Transaction> verifiedTransactions, out IEnumerable<Transaction> unverifiedTransactions) { _txRwLock.EnterReadLock(); try { verifiedTransactions = _sortedTransactions.Reverse().Select(p => p.Tx).ToArray(); unverifiedTransactions = _unverifiedSortedTransactions.Reverse().Select(p => p.Tx).ToArray(); } finally { _txRwLock.ExitReadLock(); } } public IEnumerable<Transaction> GetSortedVerifiedTransactions() { _txRwLock.EnterReadLock(); try { return _sortedTransactions.Reverse().Select(p => p.Tx).ToArray(); } finally { _txRwLock.ExitReadLock(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private PoolItem GetLowestFeeTransaction(SortedSet<PoolItem> verifiedTxSorted, SortedSet<PoolItem> unverifiedTxSorted, out SortedSet<PoolItem> sortedPool) { PoolItem minItem = unverifiedTxSorted.Min; sortedPool = minItem != null ? unverifiedTxSorted : null; PoolItem verifiedMin = verifiedTxSorted.Min; if (verifiedMin == null) return minItem; if (minItem != null && verifiedMin.CompareTo(minItem) >= 0) return minItem; sortedPool = verifiedTxSorted; minItem = verifiedMin; return minItem; } private PoolItem GetLowestFeeTransaction(out Dictionary<UInt256, PoolItem> unsortedTxPool, out SortedSet<PoolItem> sortedPool) { sortedPool = null; try { return GetLowestFeeTransaction(_sortedTransactions, _unverifiedSortedTransactions, out sortedPool); } finally { unsortedTxPool = Object.ReferenceEquals(sortedPool, _unverifiedSortedTransactions) ? _unverifiedTransactions : _unsortedTransactions; } } // Note: this must only be called from a single thread (the Blockchain actor) internal bool CanTransactionFitInPool(Transaction tx) { if (Count < Capacity) return true; return GetLowestFeeTransaction(out _, out _).CompareTo(tx) <= 0; } /// <summary> /// Adds an already verified transaction to the memory pool. /// /// Note: This must only be called from a single thread (the Blockchain actor). To add a transaction to the pool /// tell the Blockchain actor about the transaction. /// </summary> /// <param name="hash"></param> /// <param name="tx"></param> /// <returns></returns> internal bool TryAdd(UInt256 hash, Transaction tx) { var poolItem = new PoolItem(tx); if (_unsortedTransactions.ContainsKey(hash)) return false; List<Transaction> removedTransactions = null; _txRwLock.EnterWriteLock(); try { _unsortedTransactions.Add(hash, poolItem); SendersFeeMonitor.AddSenderFee(tx); _sortedTransactions.Add(poolItem); if (Count > Capacity) removedTransactions = RemoveOverCapacity(); } finally { _txRwLock.ExitWriteLock(); } foreach (IMemoryPoolTxObserverPlugin plugin in Plugin.TxObserverPlugins) { plugin.TransactionAdded(poolItem.Tx); if (removedTransactions != null) plugin.TransactionsRemoved(MemoryPoolTxRemovalReason.CapacityExceeded, removedTransactions); } return _unsortedTransactions.ContainsKey(hash); } private List<Transaction> RemoveOverCapacity() { List<Transaction> removedTransactions = new List<Transaction>(); do { PoolItem minItem = GetLowestFeeTransaction(out var unsortedPool, out var sortedPool); unsortedPool.Remove(minItem.Tx.Hash); sortedPool.Remove(minItem); removedTransactions.Add(minItem.Tx); } while (Count > Capacity); return removedTransactions; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryRemoveVerified(UInt256 hash, out PoolItem item) { if (!_unsortedTransactions.TryGetValue(hash, out item)) return false; _unsortedTransactions.Remove(hash); SendersFeeMonitor.RemoveSenderFee(item.Tx); _sortedTransactions.Remove(item); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryRemoveUnVerified(UInt256 hash, out PoolItem item) { if (!_unverifiedTransactions.TryGetValue(hash, out item)) return false; _unverifiedTransactions.Remove(hash); _unverifiedSortedTransactions.Remove(item); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void InvalidateVerifiedTransactions() { foreach (PoolItem item in _sortedTransactions) { if (_unverifiedTransactions.TryAdd(item.Tx.Hash, item)) _unverifiedSortedTransactions.Add(item); } // Clear the verified transactions now, since they all must be reverified. _unsortedTransactions.Clear(); SendersFeeMonitor = new SendersFeeMonitor(); _sortedTransactions.Clear(); } // Note: this must only be called from a single thread (the Blockchain actor) internal void UpdatePoolForBlockPersisted(Block block, StoreView snapshot) { bool policyChanged = LoadPolicy(snapshot); _txRwLock.EnterWriteLock(); try { // First remove the transactions verified in the block. foreach (Transaction tx in block.Transactions) { if (TryRemoveVerified(tx.Hash, out _)) continue; TryRemoveUnVerified(tx.Hash, out _); } // Add all the previously verified transactions back to the unverified transactions InvalidateVerifiedTransactions(); if (policyChanged) { var tx = new List<Transaction>(); foreach (PoolItem item in _unverifiedSortedTransactions.Reverse()) if (item.Tx.FeePerByte >= _feePerByte) tx.Add(item.Tx); _unverifiedTransactions.Clear(); _unverifiedSortedTransactions.Clear(); if (tx.Count > 0) _system.Blockchain.Tell(tx.ToArray(), ActorRefs.NoSender); } } finally { _txRwLock.ExitWriteLock(); } // If we know about headers of future blocks, no point in verifying transactions from the unverified tx pool // until we get caught up. if (block.Index > 0 && block.Index < Blockchain.Singleton.HeaderHeight || policyChanged) return; ReverifyTransactions(_sortedTransactions, _unverifiedSortedTransactions, _maxTxPerBlock, MaxMillisecondsToReverifyTx, snapshot); } internal void InvalidateAllTransactions() { _txRwLock.EnterWriteLock(); try { InvalidateVerifiedTransactions(); } finally { _txRwLock.ExitWriteLock(); } } private int ReverifyTransactions(SortedSet<PoolItem> verifiedSortedTxPool, SortedSet<PoolItem> unverifiedSortedTxPool, int count, double millisecondsTimeout, StoreView snapshot) { DateTime reverifyCutOffTimeStamp = DateTime.UtcNow.AddMilliseconds(millisecondsTimeout); List<PoolItem> reverifiedItems = new List<PoolItem>(count); List<PoolItem> invalidItems = new List<PoolItem>(); // Since unverifiedSortedTxPool is ordered in an ascending manner, we take from the end. foreach (PoolItem item in unverifiedSortedTxPool.Reverse().Take(count)) { if (item.Tx.Reverify(snapshot, SendersFeeMonitor.GetSenderFee(item.Tx.Sender))) { reverifiedItems.Add(item); SendersFeeMonitor.AddSenderFee(item.Tx); } else // Transaction no longer valid -- it will be removed from unverifiedTxPool. invalidItems.Add(item); if (DateTime.UtcNow > reverifyCutOffTimeStamp) break; } _txRwLock.EnterWriteLock(); try { int blocksTillRebroadcast = BlocksTillRebroadcast; // Increases, proportionally, blocksTillRebroadcast if mempool has more items than threshold bigger RebroadcastMultiplierThreshold if (Count > RebroadcastMultiplierThreshold) blocksTillRebroadcast = blocksTillRebroadcast * Count / RebroadcastMultiplierThreshold; var rebroadcastCutOffTime = DateTime.UtcNow.AddMilliseconds( -Blockchain.MillisecondsPerBlock * blocksTillRebroadcast); foreach (PoolItem item in reverifiedItems) { if (_unsortedTransactions.TryAdd(item.Tx.Hash, item)) { verifiedSortedTxPool.Add(item); if (item.LastBroadcastTimestamp < rebroadcastCutOffTime) { _system.LocalNode.Tell(new LocalNode.RelayDirectly { Inventory = item.Tx }, _system.Blockchain); item.LastBroadcastTimestamp = DateTime.UtcNow; } } else SendersFeeMonitor.RemoveSenderFee(item.Tx); _unverifiedTransactions.Remove(item.Tx.Hash); unverifiedSortedTxPool.Remove(item); } foreach (PoolItem item in invalidItems) { _unverifiedTransactions.Remove(item.Tx.Hash); unverifiedSortedTxPool.Remove(item); } } finally { _txRwLock.ExitWriteLock(); } var invalidTransactions = invalidItems.Select(p => p.Tx).ToArray(); foreach (IMemoryPoolTxObserverPlugin plugin in Plugin.TxObserverPlugins) plugin.TransactionsRemoved(MemoryPoolTxRemovalReason.NoLongerValid, invalidTransactions); return reverifiedItems.Count; } /// <summary> /// Reverify up to a given maximum count of transactions. Verifies less at a time once the max that can be /// persisted per block has been reached. /// /// Note: this must only be called from a single thread (the Blockchain actor) /// </summary> /// <param name="maxToVerify">Max transactions to reverify, the value passed can be >=1</param> /// <param name="snapshot">The snapshot to use for verifying.</param> /// <returns>true if more unsorted messages exist, otherwise false</returns> internal bool ReVerifyTopUnverifiedTransactionsIfNeeded(int maxToVerify, StoreView snapshot) { if (Blockchain.Singleton.Height < Blockchain.Singleton.HeaderHeight) return false; if (_unverifiedSortedTransactions.Count > 0) { int verifyCount = _sortedTransactions.Count > _maxTxPerBlock ? 1 : maxToVerify; ReverifyTransactions(_sortedTransactions, _unverifiedSortedTransactions, verifyCount, MaxMillisecondsToReverifyTxPerIdle, snapshot); } return _unverifiedTransactions.Count > 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 program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in. // It is available from http://www.codeplex.com/hyperAddin #define FEATURE_MANAGED_ETW #if !ES_BUILD_STANDALONE #define FEATURE_ACTIVITYSAMPLING #endif #if ES_BUILD_STANDALONE #define FEATURE_MANAGED_ETW_CHANNELS // #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS #endif #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor; #endif using System; using System.Runtime.InteropServices; using System.Security; using System.Collections.ObjectModel; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; using System.Collections.Generic; using System.Text; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; using System.Collections.Generic; using System.Text; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { public partial class EventSource { private byte[] providerMetadata; /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> public EventSource( string eventSourceName) : this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> public EventSource( string eventSourceName, EventSourceSettings config) : this(eventSourceName, config, null) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// /// Also specify a list of key-value pairs called traits (you must pass an even number of strings). /// The first string is the key and the second is the value. These are not interpreted by EventSource /// itself but may be interprated the listeners. Can be fetched with GetTrait(string). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> /// <param name="traits">A collection of key-value strings (must be an even number).</param> public EventSource( string eventSourceName, EventSourceSettings config, params string[] traits) : this( eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName, config, traits) { if (eventSourceName == null) { throw new ArgumentNullException("eventSourceName"); } Contract.EndContractBlock(); } /// <summary> /// Writes an event with no fields and default options. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> [SecuritySafeCritical] public unsafe void Write(string eventName) { if (eventName == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance); } /// <summary> /// Writes an event with no fields. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> [SecuritySafeCritical] public unsafe void Write(string eventName, EventSourceOptions options) { if (eventName == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, T data) { if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, EventSourceOptions options, T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// This overload is for use with extension methods that wish to efficiently /// forward the options or data parameter without performing an extra copy. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// This overload is meant for clients that need to manipuate the activityId /// and related ActivityId for the event. /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="activityId"> /// The GUID of the activity associated with this event. /// </param> /// <param name="relatedActivityId"> /// The GUID of another activity that is related to this activity, or Guid.Empty /// if there is no related activity. Most commonly, the Start operation of a /// new activity specifies a parent activity as its related activity. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref Guid activityId, ref Guid relatedActivityId, ref T data) { if (!this.IsEnabled()) { return; } fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId) { this.WriteImpl( eventName, ref options, data, pActivity, relatedActivityId == Guid.Empty ? null : pRelated, SimpleEventTypes<T>.Instance); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// This method does a quick check on whether this event is enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> [SecuritySafeCritical] private unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { if (!this.IsEnabled()) { return; } byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// Attention: This API does not check whether the event is enabled or not. /// Please use WriteMultiMerge to avoid spending CPU cycles for events that are /// not enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> [SecuritySafeCritical] private unsafe void WriteMultiMergeInner( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventTypes.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventTypes.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags); if (nameInfo == null) { return; } identity = nameInfo.identity; EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if (!ES_BUILD_PCL && !PROJECTN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); for (int i = 0; i < eventTypes.typeInfos.Length; i++) { var info = eventTypes.typeInfos[i]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i])); } this.WriteEventRaw( eventName, ref descriptor, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); } finally { this.WriteCleanup(pins, pinCount); } } } /// <summary> /// Writes an extended event, where the values of the event have already /// been serialized in "data". /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="data"> /// The previously serialized values to include in the event. Must not be null. /// The number and types of the values must match the number and types of the /// fields described by the eventTypes parameter. /// </param> [SecuritySafeCritical] internal unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, EventData* data) { if (!this.IsEnabled()) { return; } fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } // We make a descriptor for each EventData, and because we morph strings to counted strings // we may have 2 for each arg, so we allocate enough for this. var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); int numDescrs = 3; for (int i = 0; i < eventTypes.typeInfos.Length; i++) { // Until M3, we need to morph strings to a counted representation // When TDH supports null terminated strings, we can remove this. if (eventTypes.typeInfos[i].DataType == typeof(string)) { // Write out the size of the string descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size; descriptors[numDescrs].m_Size = 2; numDescrs++; descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator numDescrs++; } else { descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size; // old conventions for bool is 4 bytes, but meta-data assumes 1. if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool)) descriptors[numDescrs].m_Size = 1; numDescrs++; } } this.WriteEventRaw( eventName, ref descriptor, activityID, childActivityID, numDescrs, (IntPtr)descriptors); } } } [SecuritySafeCritical] private unsafe void WriteImpl( string eventName, ref EventSourceOptions options, object data, Guid* pActivityId, Guid* pRelatedActivityId, TraceLoggingEventTypes eventTypes) { try { fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if (!ES_BUILD_PCL && !PROJECTN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif EventOpcode opcode = (EventOpcode)descriptor.Opcode; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; if (pActivityId == null && pRelatedActivityId == null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relatedActivityId != Guid.Empty) pRelatedActivityId = &relatedActivityId; } try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); var info = eventTypes.typeInfos[0]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data)); this.WriteEventRaw( eventName, ref descriptor, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); // TODO enable filtering for listeners. if (m_Dispatchers != null) { var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data)); WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData); } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(eventName, ex); } finally { this.WriteCleanup(pins, pinCount); } } } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(eventName, ex); } } [SecurityCritical] private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventName = eventName; eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level; eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords; eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode; eventCallbackArgs.m_tags = tags; // Self described events do not have an id attached. We mark it internally with -1. eventCallbackArgs.EventId = -1; if (pActivityId != null) eventCallbackArgs.RelatedActivityId = *pActivityId; if (payload != null) { eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values); eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys); } DispatchToAllListeners(-1, pActivityId, eventCallbackArgs); } #if (!ES_BUILD_PCL && !PROJECTN) [System.Runtime.ConstrainedExecution.ReliabilityContract( System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] #endif [SecurityCritical] [NonEvent] private unsafe void WriteCleanup(GCHandle* pPins, int cPins) { DataCollector.ThreadInstance.Disable(); for (int i = 0; i != cPins; i++) { if (IntPtr.Zero != (IntPtr)pPins[i]) { pPins[i].Free(); } } } private void InitializeProviderMetadata() { if (m_traits != null) { List<byte> traitMetaData = new List<byte>(100); for (int i = 0; i < m_traits.Length - 1; i += 2) { if (m_traits[i].StartsWith("ETW_")) { string etwTrait = m_traits[i].Substring(4); byte traitNum; if (!byte.TryParse(etwTrait, out traitNum)) { if (etwTrait == "GROUP") { traitNum = 1; } else { throw new ArgumentException(Resources.GetResourceString("UnknownEtwTrait", etwTrait), "traits"); } } string value = m_traits[i + 1]; int lenPos = traitMetaData.Count; traitMetaData.Add(0); // Emit size (to be filled in later) traitMetaData.Add(0); traitMetaData.Add(traitNum); // Emit Trait number var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above. traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8)); } } providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0); int startPos = providerMetadata.Length - traitMetaData.Count; foreach (var b in traitMetaData) providerMetadata[startPos++] = b; } else providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0); } private static int AddValueToMetaData(List<byte> metaData, string value) { if (value.Length == 0) return 0; int startPos = metaData.Count; char firstChar = value[0]; if (firstChar == '@') metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1))); else if (firstChar == '{') metaData.AddRange(new Guid(value).ToByteArray()); else if (firstChar == '#') { for (int i = 1; i < value.Length; i++) { if (value[i] != ' ') // Skip spaces between bytes. { if (!(i + 1 < value.Length)) { throw new ArgumentException(Resources.GetResourceString("EvenHexDigits"), "traits"); } metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1]))); i++; } } } else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation). { metaData.AddRange(Encoding.UTF8.GetBytes(value)); } else { throw new ArgumentException(Resources.GetResourceString("IllegalValue", value), "traits"); } return metaData.Count - startPos; } /// <summary> /// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception. /// </summary> private static int HexDigit(char c) { if ('0' <= c && c <= '9') { return (c - '0'); } if ('a' <= c) { c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case } if ('A' <= c && c <= 'F') { return (c - 'A' + 10); } throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits"); } private NameInfo UpdateDescriptor( string name, TraceLoggingEventTypes eventInfo, ref EventSourceOptions options, out EventDescriptor descriptor) { NameInfo nameInfo = null; int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventInfo.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventInfo.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventInfo.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventInfo.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags); identity = nameInfo.identity; } descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); return nameInfo; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel.Jwk; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; #pragma warning disable 1591 namespace IdentityModel.Client; /// <summary> /// Models an OpenID Connect dynamic client registration request. /// </summary> /// <remarks> /// <see href="https://datatracker.ietf.org/doc/html/rfc7591" /> and <see href="https://openid.net/specs/openid-connect-registration-1_0.html" />. /// </remarks> public class DynamicClientRegistrationDocument { /// <summary> /// List of redirection URI strings for use in redirect-based flows such as the authorization code and implicit flows. /// </summary> /// <remarks> /// Clients using flows with redirection must register their redirection URI values. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.RedirectUris)] public ICollection<Uri> RedirectUris { get; set; } = new HashSet<Uri>(); /// <summary> /// List of the OAuth 2.0 response type strings that the client can use at the authorization endpoint. /// </summary> /// <remarks> /// Example: "code" or "token". /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.ResponseTypes)] public ICollection<string> ResponseTypes { get; set; } = new HashSet<string>(); /// <summary> /// List of OAuth 2.0 grant type strings that the client can use at the token endpoint. /// </summary> /// <remarks> /// Example: "authorization_code", "implicit", "password", "client_credentials", "refresh_token". /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.GrantTypes)] public ICollection<string> GrantTypes { get; set; } = new HashSet<string>(); /// <summary> /// Kind of the application. /// </summary> /// <remarks> /// The defined values are "native" or "web". /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.ApplicationType)] public string ApplicationType { get; set; } /// <summary> /// List of strings representing ways to contact people responsible for this client, typically email addresses. /// </summary> /// <remarks> /// The authorization server may make these contact addresses available to end-users for support requests for the client. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.Contacts)] public ICollection<string> Contacts { get; set; } = new HashSet<string>(); /// <summary> /// Human-readable string name of the client to be presented to the end-user during authorization. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.ClientName)] public string ClientName { get; set; } /// <summary> /// Logo for the client. /// </summary> /// <remarks> /// If present, the server should display this image to the end-user during approval. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.LogoUri)] public Uri LogoUri { get; set; } /// <summary> /// Web page providing information about the client. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.ClientUri)] public Uri ClientUri { get; set; } /// <summary> /// Human-readable privacy policy document that describes how the deployment organization /// collects, uses, retains, and discloses personal data. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.PolicyUri)] public Uri PolicyUri { get; set; } /// <summary> /// Human-readable terms of service document for the client that describes a contractual relationship /// between the end-user and the client that the end-user accepts when authorizing the client. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.TosUri)] public Uri TosUri { get; set; } /// <summary> /// JWK Set document which contains the client's public keys. /// </summary> /// <remarks> /// Use of this parameter is preferred over the "jwks" parameter, as it allows for easier key rotation. /// The <see cref="JwksUri"/> and <see cref="Jwks"/> parameters MUST NOT both be present in /// the same request or response. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.JwksUri)] public Uri JwksUri { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.Jwks)] public JsonWebKeySet Jwks { get; set; } /// <summary> /// URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OpenID provider. /// </summary> /// <remarks> /// The URL references a file with a single JSON array of <c>redirect_uri</c> values. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.SectorIdentifierUri)] public Uri SectorIdentifierUri { get; set; } /// <remarks> /// Valid types include "pairwise" and "public". /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.SubjectType)] public string SubjectType { get; set; } /// <summary> /// String containing a space-separated list of scope values that the client can use when requesting access tokens. /// </summary> /// <remarks> /// If omitted, an authorization server may register a client with a default set of scopes. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.Scope)] public string Scope { get; set; } /// <summary> /// A unique identifier string (e.g., a <see cref="System.Guid"/>) assigned by the client developer or software /// publisher used by registration endpoints to identify the client software to be dynamically registered. /// </summary> /// <remarks> /// The value of this field is not intended to be human readable and is usually opaque to the client and authorization server. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.SoftwareId)] public string SoftwareId { get; set; } /// <summary> /// A version identifier string for the client software identified by <see cref="SoftwareId"/>. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.SoftwareVersion)] public string SoftwareVersion { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.IdentityTokenSignedResponseAlgorithm)] public string IdentityTokenSignedResponseAlgorithm { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.IdentityTokenEncryptedResponseAlgorithm)] public string IdentityTokenEncryptedResponseAlgorithm { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.IdentityTokenEncryptedResponseEncryption)] public string IdentityTokenEncryptedResponseEncryption { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.UserinfoSignedResponseAlgorithm)] public string UserinfoSignedResponseAlgorithm { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.UserInfoEncryptedResponseAlgorithm)] public string UserInfoEncryptedResponseAlgorithm { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.UserinfoEncryptedResponseEncryption)] public string UserinfoEncryptedResponseEncryption { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.RequestObjectSigningAlgorithm)] public string RequestObjectSigningAlgorithm { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.RequestObjectEncryptionAlgorithm)] public string RequestObjectEncryptionAlgorithm { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.RequestObjectEncryptionEncryption)] public string RequestObjectEncryptionEncryption { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.TokenEndpointAuthenticationMethod)] public string TokenEndpointAuthenticationMethod { get; set; } [JsonPropertyName(OidcConstants.ClientMetadata.TokenEndpointAuthenticationSigningAlgorithm)] public string TokenEndpointAuthenticationSigningAlgorithm { get; set; } /// <summary> /// Default maximum authentication age. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.DefaultMaxAge)] public int DefaultMaxAge { get; set; } /// <summary> /// Whether the <c>auth_time</c> claim in the id token is required. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.RequireAuthenticationTime)] public bool RequireAuthenticationTime { get; set; } /// <summary> /// Default requested Authentication Context Class Reference values. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.DefaultAcrValues)] public ICollection<string> DefaultAcrValues { get; set; } = new HashSet<string>(); /// <summary> /// URI using the https scheme that a third party can use to initiate a login by the relying party. /// </summary> /// <remarks> /// The URI must accept requests via both GET and POST. /// The client must understand the <c>login_hint</c> and iss parameters and should support the /// <c>target_link_uri</c> parameter. /// </remarks> [JsonPropertyName(OidcConstants.ClientMetadata.InitiateLoginUris)] public Uri InitiateLoginUri { get; set; } /// <summary> /// List of request URI values that are pre-registered by the relying party for use at the OpenID provider. /// </summary> [JsonPropertyName(OidcConstants.ClientMetadata.RequestUris)] public ICollection<Uri> RequestUris { get; set; } = new HashSet<Uri>(); /// <summary> /// Custom client metadata fields to include in the serialization. /// </summary> [JsonExtensionData] public IDictionary<string, object> Extensions { get; } = new Dictionary<string, object>(StringComparer.Ordinal); // Don't serialize empty arrays public bool ShouldSerializeRequestUris() => RequestUris.Any(); public bool ShouldSerializeDefaultAcrValues() => DefaultAcrValues.Any(); public bool ShouldSerializeResponseTypes() => ResponseTypes.Any(); public bool ShouldSerializeGrantTypes() => GrantTypes.Any(); public bool ShouldSerializeContacts() => Contacts.Any(); }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace CallButler.Manager.Controls { public class DataRowEventArgs : EventArgs { public DataRow DataRow = null; public DataRowEventArgs(DataRow dataRow) { DataRow = dataRow; } } public class CallButlerEditDataGrid : CallButlerDataGrid { public event EventHandler<DataRowEventArgs> EditDataRow; public event EventHandler<DataRowEventArgs> DeleteDataRow; private DataGridViewLinkColumn editColumn = null; private DataGridViewLinkColumn deleteColumn = null; private DataGridViewImageColumn rowImageColumn = null; private Image rowImage = null; private bool showEditColumn = true; private bool showDeleteColumn = true; public CallButlerEditDataGrid() { this.MultiSelect = false; } protected override void InitLayout() { base.InitLayout(); if (!DesignMode) { editColumn = new DataGridViewLinkColumn(); editColumn.ActiveLinkColor = Color.RoyalBlue; editColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; editColumn.HeaderText = ""; editColumn.LinkColor = Color.RoyalBlue; editColumn.TrackVisitedState = false; editColumn.UseColumnTextForLinkValue = true; editColumn.LinkBehavior = LinkBehavior.HoverUnderline; editColumn.Text = Properties.LocalizedStrings.Common_Edit; deleteColumn = new DataGridViewLinkColumn(); deleteColumn.ActiveLinkColor = Color.RoyalBlue; deleteColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; deleteColumn.HeaderText = ""; deleteColumn.LinkColor = Color.RoyalBlue; deleteColumn.TrackVisitedState = false; deleteColumn.UseColumnTextForLinkValue = true; deleteColumn.LinkBehavior = LinkBehavior.HoverUnderline; deleteColumn.Text = Properties.LocalizedStrings.Common_Delete; this.Columns.Add(editColumn); this.Columns.Add(deleteColumn); this.ColumnAdded += new DataGridViewColumnEventHandler(CallButlerEditDataGrid_ColumnAdded); } } public bool ShowEditColumn { get { return showEditColumn; } set { showEditColumn = value; if(editColumn != null) editColumn.Visible = value; } } public bool ShowDeleteColumn { get { return showDeleteColumn; } set { showDeleteColumn = value; if(deleteColumn != null) deleteColumn.Visible = value; } } [TypeConverter(typeof(ImageConverter)), DefaultValue(typeof(Image), null), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Image RowImage { get { return rowImage; } set { rowImage = value; if (!DesignMode) { if (rowImage == null && rowImageColumn != null) this.Columns.Remove(rowImageColumn); rowImageColumn = null; if (rowImage != null) { rowImageColumn = new DataGridViewImageColumn(false); rowImageColumn.DisplayIndex = 0; rowImageColumn.Image = rowImage; rowImageColumn.Width = this.RowTemplate.Height; this.Columns.Add(rowImageColumn); } } } } void CallButlerEditDataGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e) { if(rowImageColumn != null) rowImageColumn.DisplayIndex = 0; editColumn.DisplayIndex = this.ColumnCount - 2; deleteColumn.DisplayIndex = this.ColumnCount - 1; } protected override void OnCellContentClick(DataGridViewCellEventArgs e) { if (e.ColumnIndex == editColumn.Index) { if(EditDataRow != null) EditDataRow(this, new DataRowEventArgs(((DataRowView)this.Rows[e.RowIndex].DataBoundItem).Row)); } else if (e.ColumnIndex == deleteColumn.Index) { if (DeleteDataRow != null) DeleteDataRow(this, new DataRowEventArgs(((DataRowView)this.Rows[e.RowIndex].DataBoundItem).Row)); } else { base.OnCellContentClick(e); } } protected override void OnCellDoubleClick(DataGridViewCellEventArgs e) { if (EditDataRow != null && e.RowIndex >= 0 && e.RowIndex < this.Rows.Count) EditDataRow(this, new DataRowEventArgs(((DataRowView)this.Rows[e.RowIndex].DataBoundItem).Row)); base.OnCellDoubleClick(e); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // // The Original Code is DotSpatial // // The Initial Developer of this Original Code is Ted Dunsford. Created in January, 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// A shapefile class that handles the special case where the data type is point /// </summary> public class PointShapefile : Shapefile { /// <summary> /// Creates a new instance of a PointShapefile for in-ram handling only. /// </summary> public PointShapefile() : base(FeatureType.Point, ShapeType.Point) { } /// <summary> /// Creates a new instance of a PointShapefile that is loaded from the supplied fileName. /// </summary> /// <param name="fileName">The string fileName of the polygon shapefile to load</param> public PointShapefile(string fileName) : this() { Open(fileName, null); } /// <summary> /// Opens a shapefile /// </summary> /// <param name="fileName">The string fileName of the point shapefile to load</param> /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param> public void Open(string fileName, IProgressHandler progressHandler) { if (!File.Exists(fileName)) return; Filename = fileName; IndexMode = true; Header = new ShapefileHeader(Filename); switch (Header.ShapeType) { case ShapeType.PointM: CoordinateType = CoordinateType.M; break; case ShapeType.PointZ: CoordinateType = CoordinateType.Z; break; default: CoordinateType = CoordinateType.Regular; break; } Extent = Header.ToExtent(); Name = Path.GetFileNameWithoutExtension(fileName); Attributes.Open(Filename); FillPoints(Filename, progressHandler); ReadProjection(); } // X Y Points: Total Length = 28 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 1 Integer 1 Little // Byte 12 X Double 1 Little // Byte 20 Y Double 1 Little // X Y M Points: Total Length = 36 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 21 Integer 1 Little // Byte 12 X Double 1 Little // Byte 20 Y Double 1 Little // Byte 28 M Double 1 Little // X Y Z M Points: Total Length = 44 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 11 Integer 1 Little // Byte 12 X Double 1 Little // Byte 20 Y Double 1 Little // Byte 28 Z Double 1 Little // Byte 36 M Double 1 Little /// <summary> /// Obtains a typed list of ShapefilePoint structures with double values associated with the various coordinates. /// </summary> /// <param name="fileName">A string fileName</param> /// <param name="progressHandler">Progress handler</param> private void FillPoints(string fileName, IProgressHandler progressHandler) { // Check to ensure the fileName is not null if (fileName == null) { throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", "fileName")); } if (File.Exists(fileName) == false) { throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", fileName)); } // Get the basic header information. // Check to ensure that the fileName is the correct shape type if (Header.ShapeType != ShapeType.Point && Header.ShapeType != ShapeType.PointM && Header.ShapeType != ShapeType.PointZ) { throw new ApplicationException(DataStrings.FileNotPoints_S.Replace("%S", fileName)); } if (new FileInfo(fileName).Length == 100) { // the file is empty so we are done reading return; } // Reading the headers gives us an easier way to track the number of shapes and their overall length etc. List<ShapeHeader> shapeHeaders = ReadIndexFile(fileName); var numShapes = shapeHeaders.Count; var shapeIndices = new List<ShapeRange>(numShapes); int totalPointsCount = 0; var progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName)) { StepPercent = 5 }; using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { for (var shp = 0; shp < numShapes; shp++) { progressMeter.CurrentPercent = (int)(shp * 50.0 / numShapes); reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin); var shape = new ShapeRange(FeatureType.Point, CoordinateType) { RecordNumber = reader.ReadInt32(Endian.BigEndian), ContentLength = reader.ReadInt32(Endian.BigEndian), StartIndex = totalPointsCount, ShapeType = (ShapeType)reader.ReadInt32() }; Debug.Assert(shape.RecordNumber == shp + 1); Debug.Assert(shape.ContentLength == shapeHeaders[shp].ContentLength); if (shape.ShapeType == ShapeType.NullShape) { shape.NumPoints = 0; shape.NumParts = 0; } else { totalPointsCount += 1; shape.NumPoints = 1; shape.NumParts = 1; } shapeIndices.Add(shape); } double[] m = null; double[] z = null; var vert = new double[2 * totalPointsCount]; // X,Y if (Header.ShapeType == ShapeType.PointM || Header.ShapeType == ShapeType.PointZ) { m = new double[totalPointsCount]; } if (Header.ShapeType == ShapeType.PointZ) { z = new double[totalPointsCount]; } int i = 0; for (var shp = 0; shp < numShapes; shp++) { progressMeter.CurrentPercent = (int)(50 + shp * 50.0 / numShapes); var shape = shapeIndices[shp]; if (shape.ShapeType == ShapeType.NullShape) continue; reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin); reader.Seek(3 * 4, SeekOrigin.Current); // Skip first bytes (Record Number, Content Length, Shapetype) // Read X var ind = 4; vert[i * 2] = reader.ReadDouble(); ind += 8; // Read Y vert[i * 2 + 1] = reader.ReadDouble(); ind += 8; // Read Z if (z != null) { z[i] = reader.ReadDouble(); ind += 8; } // Read M if (m != null) { if (shapeHeaders[shp].ByteLength <= ind) { m[i] = double.MinValue; } else { m[i] = reader.ReadDouble(); } } var part = new PartRange(vert, shape.StartIndex, 0, FeatureType.Point) { NumVertices = 1 }; shape.Parts.Add(part); shape.Extent = new Extent(new[] { vert[i * 2], vert[i * 2 + 1], vert[i * 2], vert[i * 2 + 1] }); i++; } Vertex = vert; M = m; Z = z; ShapeIndices = shapeIndices; } progressMeter.Reset(); } /// <inheritdoc /> public override IFeature GetFeature(int index) { IFeature f; if (!IndexMode) { f = Features[index]; } else { f = GetPoint(index); f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0]; } return f; } /// <inheritdoc /> protected override void SetHeaderShapeType() { if (CoordinateType == CoordinateType.Regular) Header.ShapeType = ShapeType.Point; else if (CoordinateType == CoordinateType.M) Header.ShapeType = ShapeType.PointM; else if (CoordinateType == CoordinateType.Z) Header.ShapeType = ShapeType.PointZ; } /// <summary> /// Calculates the ContentLength that is needed to save a shape with the given number of parts and points. /// </summary> /// <param name="header"></param> /// <returns>ContentLength that is needed to save a shape with the given number of parts and points.</returns> private static int GetContentLength(ShapeType header) { int contentLength = 2; //Shape Type switch (header) { case ShapeType.Point: contentLength += 8; // x, y break; case ShapeType.PointM: contentLength += 12; // x, y, m break; case ShapeType.PointZ: contentLength += 16; // x, y, m, z break; } return contentLength; } /// <summary> /// Populates the given streams for the shp and shx file when not in IndexMode. /// </summary> /// <param name="shpStream">Stream that is used to write the shp file.</param> /// <param name="shxStream">Stream that is used to write the shx file.</param> /// <returns>The lengths of the streams in bytes.</returns> private StreamLengthPair PopulateShpAndShxStreamsNotIndexed(Stream shpStream, Stream shxStream) { var progressMeter = new ProgressMeter(ProgressHandler, "Saving (Not Indexed)...", Features.Count); int fid = 0; int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words foreach (IFeature f in Features) { bool isNullShape = false; int contentLength; if (f.Geometry.IsEmpty) { contentLength = 2; isNullShape = true; } else { contentLength = GetContentLength(Header.ShapeType); } shxStream.WriteBe(offset); shxStream.WriteBe(contentLength); shpStream.WriteBe(fid + 1); shpStream.WriteBe(contentLength); if (isNullShape) { shpStream.WriteLe((int)ShapeType.NullShape); // Byte 8 Shape Type 0 Integer 1 Little } else { shpStream.WriteLe((int)Header.ShapeType); // Byte 8 Shape Type Integer 1 Little Coordinate c = f.Geometry.Coordinates[0]; shpStream.WriteLe(c.X); shpStream.WriteLe(c.Y); if (Header.ShapeType == ShapeType.PointZ) { shpStream.WriteLe(c.Z); } if (Header.ShapeType == ShapeType.PointM || Header.ShapeType == ShapeType.PointZ) { shpStream.WriteLe(c.M); } } progressMeter.CurrentValue = fid; fid++; offset += 4; // header bytes offset += contentLength; // adding the content length from each loop calculates the word offset } progressMeter.Reset(); return new StreamLengthPair { ShpLength = offset, ShxLength = 50 + fid * 4 }; } /// <summary> /// Populates the given streams for the shp and shx file when in IndexMode. /// </summary> /// <param name="shpStream">Stream that is used to write the shp file.</param> /// <param name="shxStream">Stream that is used to write the shx file.</param> /// <returns>The lengths of the streams in bytes.</returns> private StreamLengthPair PopulateShpAndShxStreamsIndexed(Stream shpStream, Stream shxStream) { int fid = 0; int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words foreach (ShapeRange shape in ShapeIndices) { int contentLength = shape.ShapeType == ShapeType.NullShape ? 2 : GetContentLength(Header.ShapeType); shxStream.WriteBe(offset); shxStream.WriteBe(contentLength); shpStream.WriteBe(fid + 1); shpStream.WriteBe(contentLength); if (shape.ShapeType == ShapeType.NullShape) { shpStream.WriteLe((int)ShapeType.NullShape); // Byte 8 Shape Type 3 Integer 1 Little } else { shpStream.WriteLe((int)Header.ShapeType); shpStream.WriteLe(Vertex[shape.StartIndex * 2]); shpStream.WriteLe(Vertex[shape.StartIndex * 2 + 1]); if (Z != null) shpStream.WriteLe(Z[shape.StartIndex]); if (M != null) shpStream.WriteLe(M[shape.StartIndex]); } fid++; offset += 4; // header bytes offset += contentLength; // adding the content length from each loop calculates the word offset } return new StreamLengthPair { ShpLength = offset, ShxLength = 50 + fid * 4 }; } /// <inheritdoc /> protected override StreamLengthPair PopulateShpAndShxStreams(Stream shpStream, Stream shxStream, bool indexed) { if (indexed) return PopulateShpAndShxStreamsIndexed(shpStream, shxStream); return PopulateShpAndShxStreamsNotIndexed(shpStream, shxStream); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System; using System.Collections; using System.Collections.Specialized; namespace NUnit.Core { /// <summary> /// TestInfo holds common info about a test. It represents only /// a single test or a suite and contains no references to other /// tests. Since it is informational only, it can easily be passed /// around using .Net remoting. /// /// TestInfo is used directly in all EventListener events and in /// TestResults. It contains an ID, which can be used by a /// runner to locate the actual test. /// /// TestInfo also serves as the base class for TestNode, which /// adds hierarchical information and is used in client code to /// maintain a visible image of the structure of the tests. /// </summary> [Serializable] public class TestInfo : ITest { #region Instance Variables /// <summary> /// TestName that identifies this test /// </summary> private TestName testName; private string testType; private RunState runState; /// <summary> /// Reason for not running the test /// </summary> private string ignoreReason; /// <summary> /// Number of test cases in this test or suite /// </summary> private int testCaseCount; /// <summary> /// True if this is a suite /// </summary> private bool isSuite; /// <summary> /// The test description /// </summary> private string description; /// <summary> /// A list of all the categories assigned to a test /// </summary> private ArrayList categories = new ArrayList(); /// <summary> /// A dictionary of properties, used to add information /// to tests without requiring the class to change. /// </summary> private ListDictionary properties = new ListDictionary(); #endregion #region Constructors /// <summary> /// Construct from an ITest /// </summary> /// <param name="test">Test from which a TestNode is to be constructed</param> public TestInfo( ITest test ) { this.testName = (TestName)test.TestName.Clone(); this.testType = test.TestType; this.runState = test.RunState; this.ignoreReason = test.IgnoreReason; this.description = test.Description; this.isSuite = test.IsSuite; if (test.Categories != null) this.categories.AddRange(test.Categories); if (test.Properties != null) { this.properties = new ListDictionary(); foreach( DictionaryEntry entry in test.Properties ) this.properties.Add( entry.Key, entry.Value ); } this.testCaseCount = test.TestCount; } /// <summary> /// Construct as a parent to multiple tests. /// </summary> /// <param name="testName">The name to use for the new test</param> /// <param name="tests">An array of child tests</param> public TestInfo( TestName testName, ITest[] tests ) { this.testName = testName; this.testType = "Test Project"; this.runState = RunState.Runnable; this.ignoreReason = null; this.description = null; this.isSuite = true; foreach( ITest test in tests ) { this.testCaseCount += test.TestCount; } } #endregion #region Properties /// <summary> /// Gets the completely specified name of the test /// encapsulated in a TestName object. /// </summary> public TestName TestName { get { return testName; } } /// <summary> /// Gets a string representing the kind of test this /// object represents for display purposes. /// </summary> public string TestType { get { return testType; } } /// <summary> /// The test description /// </summary> public string Description { get { return description; } set { description = value; } } /// <summary> /// Gets the RunState for this test /// </summary> public RunState RunState { get { return runState; } set { runState = value; } } /// <summary> /// The reason for ignoring a test /// </summary> public string IgnoreReason { get { return ignoreReason; } set { ignoreReason = value; } } /// <summary> /// Count of test cases in this test. /// </summary> public int TestCount { get { return testCaseCount; } } /// <summary> /// Gets the parent test of this test /// </summary> public virtual ITest Parent { get { return null; } } /// <summary> /// Gets a list of the categories applied to this test /// </summary> public IList Categories { get { return categories; } } /// <summary> /// Gets a list of any child tests /// </summary> public virtual IList Tests { get { return null; } } /// <summary> /// True if this is a suite, false if a test case /// </summary> public bool IsSuite { get { return isSuite; } } /// <summary> /// Gets the Properties dictionary for this test /// </summary> public IDictionary Properties { get { if ( properties == null ) properties = new ListDictionary(); return properties; } } #endregion #region Methods /// <summary> /// Counts the test cases that would be run if this /// test were executed using the provided filter. /// </summary> /// <param name="filter">The filter to apply</param> /// <returns>A count of test cases</returns> public virtual int CountTestCases(ITestFilter filter) { if (filter.IsEmpty) return TestCount; if (!isSuite) return filter.Pass(this) ? 1 : 0; int count = 0; if (filter.Pass(this)) { foreach (ITest test in Tests) { count += test.CountTestCases(filter); } } return count; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia.Rendering; namespace Avalonia.VisualTree { /// <summary> /// Provides extension methods for working with the visual tree. /// </summary> public static class VisualExtensions { /// <summary> /// Calculates the distance from a visual's ancestor. /// </summary> /// <param name="visual">The visual.</param> /// <param name="ancestor">The ancestor visual.</param> /// <returns> /// The number of steps from the visual to the ancestor or -1 if /// <paramref name="visual"/> is not a descendent of <paramref name="ancestor"/>. /// </returns> public static int CalculateDistanceFromAncestor(this IVisual visual, IVisual ancestor) { Contract.Requires<ArgumentNullException>(visual != null); var result = 0; while (visual != null && visual != ancestor) { visual = visual.VisualParent; result++; } return visual != null ? result : -1; } /// <summary> /// Calculates the distance from a visual's root. /// </summary> /// <param name="visual">The visual.</param> /// <returns> /// The number of steps from the visual to the root. /// </returns> public static int CalculateDistanceFromRoot(IVisual visual) { Contract.Requires<ArgumentNullException>(visual != null); var result = 0; visual = visual?.VisualParent; while (visual != null) { visual = visual.VisualParent; result++; } return result; } /// <summary> /// Tries to get the first common ancestor of two visuals. /// </summary> /// <param name="visual">The first visual.</param> /// <param name="target">The second visual.</param> /// <returns>The common ancestor, or null if not found.</returns> public static IVisual FindCommonVisualAncestor(this IVisual visual, IVisual target) { Contract.Requires<ArgumentNullException>(visual != null); if (target is null) { return null; } void GoUpwards(ref IVisual node, int count) { for (int i = 0; i < count; ++i) { node = node.VisualParent; } } // We want to find lowest node first, then make sure that both nodes are at the same height. // By doing that we can sometimes find out that other node is our lowest common ancestor. var firstHeight = CalculateDistanceFromRoot(visual); var secondHeight = CalculateDistanceFromRoot(target); if (firstHeight > secondHeight) { GoUpwards(ref visual, firstHeight - secondHeight); } else { GoUpwards(ref target, secondHeight - firstHeight); } if (visual == target) { return visual; } while (visual != null && target != null) { IVisual firstParent = visual.VisualParent; IVisual secondParent = target.VisualParent; if (firstParent == secondParent) { return firstParent; } visual = visual.VisualParent; target = target.VisualParent; } return null; } /// <summary> /// Enumerates the ancestors of an <see cref="IVisual"/> in the visual tree. /// </summary> /// <param name="visual">The visual.</param> /// <returns>The visual's ancestors.</returns> public static IEnumerable<IVisual> GetVisualAncestors(this IVisual visual) { Contract.Requires<ArgumentNullException>(visual != null); visual = visual.VisualParent; while (visual != null) { yield return visual; visual = visual.VisualParent; } } /// <summary> /// Finds first ancestor of given type. /// </summary> /// <typeparam name="T">Ancestor type.</typeparam> /// <param name="visual">The visual.</param> /// <param name="includeSelf">If given visual should be included in search.</param> /// <returns>First ancestor of given type.</returns> public static T FindAncestorOfType<T>(this IVisual visual, bool includeSelf = false) where T : class { if (visual is null) { return null; } IVisual parent = includeSelf ? visual : visual.VisualParent; while (parent != null) { if (parent is T result) { return result; } parent = parent.VisualParent; } return null; } /// <summary> /// Finds first descendant of given type. /// </summary> /// <typeparam name="T">Descendant type.</typeparam> /// <param name="visual">The visual.</param> /// <param name="includeSelf">If given visual should be included in search.</param> /// <returns>First descendant of given type.</returns> public static T FindDescendantOfType<T>(this IVisual visual, bool includeSelf = false) where T : class { if (visual is null) { return null; } if (includeSelf && visual is T result) { return result; } return FindDescendantOfTypeCore<T>(visual); } /// <summary> /// Enumerates an <see cref="IVisual"/> and its ancestors in the visual tree. /// </summary> /// <param name="visual">The visual.</param> /// <returns>The visual and its ancestors.</returns> public static IEnumerable<IVisual> GetSelfAndVisualAncestors(this IVisual visual) { Contract.Requires<ArgumentNullException>(visual != null); yield return visual; foreach (var ancestor in visual.GetVisualAncestors()) { yield return ancestor; } } /// <summary> /// Gets the first visual in the visual tree whose bounds contain a point. /// </summary> /// <param name="visual">The root visual to test.</param> /// <param name="p">The point.</param> /// <returns>The visual at the requested point.</returns> public static IVisual GetVisualAt(this IVisual visual, Point p) { Contract.Requires<ArgumentNullException>(visual != null); return visual.GetVisualAt(p, x => x.IsVisible); } /// <summary> /// Gets the first visual in the visual tree whose bounds contain a point. /// </summary> /// <param name="visual">The root visual to test.</param> /// <param name="p">The point.</param> /// <param name="filter"> /// A filter predicate. If the predicate returns false then the visual and all its /// children will be excluded from the results. /// </param> /// <returns>The visual at the requested point.</returns> public static IVisual GetVisualAt(this IVisual visual, Point p, Func<IVisual, bool> filter) { Contract.Requires<ArgumentNullException>(visual != null); var root = visual.GetVisualRoot(); var rootPoint = visual.TranslatePoint(p, root); if (rootPoint.HasValue) { return root.Renderer.HitTestFirst(rootPoint.Value, visual, filter); } return null; } /// <summary> /// Enumerates the visible visuals in the visual tree whose bounds contain a point. /// </summary> /// <param name="visual">The root visual to test.</param> /// <param name="p">The point.</param> /// <returns>The visuals at the requested point.</returns> public static IEnumerable<IVisual> GetVisualsAt( this IVisual visual, Point p) { Contract.Requires<ArgumentNullException>(visual != null); return visual.GetVisualsAt(p, x => x.IsVisible); } /// <summary> /// Enumerates the visuals in the visual tree whose bounds contain a point. /// </summary> /// <param name="visual">The root visual to test.</param> /// <param name="p">The point.</param> /// <param name="filter"> /// A filter predicate. If the predicate returns false then the visual and all its /// children will be excluded from the results. /// </param> /// <returns>The visuals at the requested point.</returns> public static IEnumerable<IVisual> GetVisualsAt( this IVisual visual, Point p, Func<IVisual, bool> filter) { Contract.Requires<ArgumentNullException>(visual != null); var root = visual.GetVisualRoot(); var rootPoint = visual.TranslatePoint(p, root); if (rootPoint.HasValue) { return root.Renderer.HitTest(rootPoint.Value, visual, filter); } return Enumerable.Empty<IVisual>(); } /// <summary> /// Enumerates the children of an <see cref="IVisual"/> in the visual tree. /// </summary> /// <param name="visual">The visual.</param> /// <returns>The visual children.</returns> public static IEnumerable<IVisual> GetVisualChildren(this IVisual visual) { return visual.VisualChildren; } /// <summary> /// Enumerates the descendants of an <see cref="IVisual"/> in the visual tree. /// </summary> /// <param name="visual">The visual.</param> /// <returns>The visual's ancestors.</returns> public static IEnumerable<IVisual> GetVisualDescendants(this IVisual visual) { foreach (IVisual child in visual.VisualChildren) { yield return child; foreach (IVisual descendant in child.GetVisualDescendants()) { yield return descendant; } } } /// <summary> /// Enumerates an <see cref="IVisual"/> and its descendants in the visual tree. /// </summary> /// <param name="visual">The visual.</param> /// <returns>The visual and its ancestors.</returns> public static IEnumerable<IVisual> GetSelfAndVisualDescendants(this IVisual visual) { yield return visual; foreach (var ancestor in visual.GetVisualDescendants()) { yield return ancestor; } } /// <summary> /// Gets the visual parent of an <see cref="IVisual"/>. /// </summary> /// <param name="visual">The visual.</param> /// <returns>The parent, or null if the visual is unparented.</returns> public static IVisual GetVisualParent(this IVisual visual) { return visual.VisualParent; } /// <summary> /// Gets the visual parent of an <see cref="IVisual"/>. /// </summary> /// <typeparam name="T">The type of the visual parent.</typeparam> /// <param name="visual">The visual.</param> /// <returns> /// The parent, or null if the visual is unparented or its parent is not of type <typeparamref name="T"/>. /// </returns> public static T GetVisualParent<T>(this IVisual visual) where T : class { return visual.VisualParent as T; } /// <summary> /// Gets the root visual for an <see cref="IVisual"/>. /// </summary> /// <param name="visual">The visual.</param> /// <returns> /// The root visual or null if the visual is not rooted. /// </returns> public static IRenderRoot GetVisualRoot(this IVisual visual) { Contract.Requires<ArgumentNullException>(visual != null); return visual as IRenderRoot ?? visual.VisualRoot; } /// <summary> /// Tests whether an <see cref="IVisual"/> is an ancestor of another visual. /// </summary> /// <param name="visual">The visual.</param> /// <param name="target">The potential descendant.</param> /// <returns> /// True if <paramref name="visual"/> is an ancestor of <paramref name="target"/>; /// otherwise false. /// </returns> public static bool IsVisualAncestorOf(this IVisual visual, IVisual target) { IVisual current = target?.VisualParent; while (current != null) { if (current == visual) { return true; } current = current.VisualParent; } return false; } public static IEnumerable<IVisual> SortByZIndex(this IEnumerable<IVisual> elements) { return elements .Select((element, index) => new ZOrderElement { Element = element, Index = index, ZIndex = element.ZIndex, }) .OrderBy(x => x, null) .Select(x => x.Element); } private static T FindDescendantOfTypeCore<T>(IVisual visual) where T : class { var visualChildren = visual.VisualChildren; var visualChildrenCount = visualChildren.Count; for (var i = 0; i < visualChildrenCount; i++) { IVisual child = visualChildren[i]; if (child is T result) { return result; } var childResult = FindDescendantOfTypeCore<T>(child); if (!(childResult is null)) { return childResult; } } return null; } private class ZOrderElement : IComparable<ZOrderElement> { public IVisual Element { get; set; } public int Index { get; set; } public int ZIndex { get; set; } public int CompareTo(ZOrderElement other) { var z = other.ZIndex - ZIndex; if (z != 0) { return z; } else { return other.Index - Index; } } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public static class PlayerPrefsExtensions { private static int endianDiff1; private static int endianDiff2; private static int idx; private static byte[] byteBlock; enum ArrayType { Float, Int32, Bool, String, Vector2, Vector3, Quaternion } public static void SetBool(string name, bool value) { PlayerPrefs.SetInt(name, value ? 1 : 0); } public static bool GetBool(string name) { return PlayerPrefs.GetInt(name) == 1; } public static bool GetBool(string name, bool defaultValue) { return PlayerPrefs.HasKey(name) ? GetBool(name) : defaultValue; } public static void SetColor(string key, Color color) { PlayerPrefs.SetString(key, "#" + ColorUtility.ToHtmlStringRGB(color)); } public static void SetColor(string key, string color) { PlayerPrefs.SetString(key, color); } public static Color GetColor(string key) { return PlayerPrefs.GetString(key).ToColor(); } public static Color GetColor(string key, Color defaultValue) { return PlayerPrefs.HasKey(key) ? GetColor(key) : defaultValue; } public static Color GetColor(string key, string defaultValue) { return PlayerPrefs.HasKey(key) ? GetColor(key) : defaultValue.ToColor(); } public static long GetLong(string key, long defaultValue) { SplitLong(defaultValue, out var lowBits, out var highBits); lowBits = PlayerPrefs.GetInt(key + "_lowBits", lowBits); highBits = PlayerPrefs.GetInt(key + "_highBits", highBits); // unsigned, to prevent loss of sign bit. ulong ret = (uint) highBits; ret = (ret << 32); return (long) (ret | (uint) lowBits); } public static long GetLong(string key) { var lowBits = PlayerPrefs.GetInt(key + "_lowBits"); var highBits = PlayerPrefs.GetInt(key + "_highBits"); // unsigned, to prevent loss of sign bit. ulong ret = (uint) highBits; ret = (ret << 32); return (long) (ret | (uint) lowBits); } private static void SplitLong(long input, out int lowBits, out int highBits) { // unsigned everything, to prevent loss of sign bit. lowBits = (int) (uint) (ulong) input; highBits = (int) (uint) (input >> 32); } public static void SetLong(string key, long value) { int lowBits, highBits; SplitLong(value, out lowBits, out highBits); PlayerPrefs.SetInt(key + "_lowBits", lowBits); PlayerPrefs.SetInt(key + "_highBits", highBits); } public static bool SetVector2(string key, Vector2 vector) { return SetFloatArray(key, new[] {vector.x, vector.y}); } static Vector2 GetVector2(string key) { var floatArray = GetFloatArray(key); if (floatArray.Length < 2) { return Vector2.zero; } return new Vector2(floatArray[0], floatArray[1]); } public static Vector2 GetVector2(string key, Vector2 defaultValue) { if (PlayerPrefs.HasKey(key)) { return GetVector2(key); } return defaultValue; } public static bool SetVector3(string key, Vector3 vector) { return SetFloatArray(key, new[] {vector.x, vector.y, vector.z}); } public static Vector3 GetVector3(string key) { var floatArray = GetFloatArray(key); if (floatArray.Length < 3) { return Vector3.zero; } return new Vector3(floatArray[0], floatArray[1], floatArray[2]); } public static Vector3 GetVector3(string key, Vector3 defaultValue) { if (PlayerPrefs.HasKey(key)) { return GetVector3(key); } return defaultValue; } public static bool SetQuaternion(string key, Quaternion vector) { return SetFloatArray(key, new[] {vector.x, vector.y, vector.z, vector.w}); } public static Quaternion GetQuaternion(string key) { var floatArray = GetFloatArray(key); if (floatArray.Length < 4) { return Quaternion.identity; } return new Quaternion(floatArray[0], floatArray[1], floatArray[2], floatArray[3]); } public static Quaternion GetQuaternion(string key, Quaternion defaultValue) { if (PlayerPrefs.HasKey(key)) { return GetQuaternion(key); } return defaultValue; } public static bool SetBoolArray(string key, bool[] boolArray) { // Make a byte array that's a multiple of 8 in length, plus 5 bytes to store the number of entries as an int32 (+ identifier) // We have to store the number of entries, since the boolArray length might not be a multiple of 8, so there could be some padded zeroes var bytes = new byte[(boolArray.Length + 7) / 8 + 5]; bytes[0] = Convert.ToByte(ArrayType.Bool); // Identifier var bits = new BitArray(boolArray); bits.CopyTo(bytes, 5); Initialize(); ConvertInt32ToBytes(boolArray.Length, bytes); // The number of entries in the boolArray goes in the first 4 bytes return SaveBytes(key, bytes); } public static bool[] GetBoolArray(string key) { if (!PlayerPrefs.HasKey(key)) return new bool[0]; var bytes = Convert.FromBase64String(PlayerPrefs.GetString(key)); if (bytes.Length < 5) { Debug.LogError("Corrupt preference file for " + key); return new bool[0]; } if ((ArrayType) bytes[0] != ArrayType.Bool) { Debug.LogError(key + " is not a boolean array"); return new bool[0]; } Initialize(); // Make a new bytes array that doesn't include the number of entries + identifier (first 5 bytes) and turn that into a BitArray var bytes2 = new byte[bytes.Length - 5]; Array.Copy(bytes, 5, bytes2, 0, bytes2.Length); var bits = new BitArray(bytes2) {Length = ConvertBytesToInt32(bytes)}; // Get the number of entries from the first 4 bytes after the identifier and resize the BitArray to that length, then convert it to a boolean array var boolArray = new bool[bits.Count]; bits.CopyTo(boolArray, 0); return boolArray; } public static bool[] GetBoolArray(string key, bool defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetBoolArray(key); } var boolArray = new bool[defaultSize]; for (int i = 0; i < defaultSize; i++) { boolArray[i] = defaultValue; } return boolArray; } public static bool SetStringArray(string key, string[] stringArray) { var bytes = new byte[stringArray.Length + 1]; bytes[0] = Convert.ToByte(ArrayType.String); // Identifier Initialize(); // Store the length of each string that's in stringArray, so we can extract the correct strings in GetStringArray for (var i = 0; i < stringArray.Length; i++) { if (stringArray[i] == null) { Debug.LogError("Can't save null entries in the string array when setting " + key); return false; } if (stringArray[i].Length > 255) { Debug.LogError("Strings cannot be longer than 255 characters when setting " + key); return false; } bytes[idx++] = (byte) stringArray[i].Length; } try { PlayerPrefs.SetString(key, Convert.ToBase64String(bytes) + "|" + string.Join("", stringArray)); } catch { return false; } return true; } public static string[] GetStringArray(string key) { if (PlayerPrefs.HasKey(key)) { var completeString = PlayerPrefs.GetString(key); var separatorIndex = completeString.IndexOf("|"[0]); if (separatorIndex < 4) { Debug.LogError("Corrupt preference file for " + key); return new string[0]; } var bytes = Convert.FromBase64String(completeString.Substring(0, separatorIndex)); if ((ArrayType) bytes[0] != ArrayType.String) { Debug.LogError(key + " is not a string array"); return new string[0]; } Initialize(); var numberOfEntries = bytes.Length - 1; var stringArray = new string[numberOfEntries]; var stringIndex = separatorIndex + 1; for (var i = 0; i < numberOfEntries; i++) { int stringLength = bytes[idx++]; if (stringIndex + stringLength > completeString.Length) { Debug.LogError("Corrupt preference file for " + key); return new string[0]; } stringArray[i] = completeString.Substring(stringIndex, stringLength); stringIndex += stringLength; } return stringArray; } return new string[0]; } public static string[] GetStringArray(string key, string defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetStringArray(key); } var stringArray = new string[defaultSize]; for (int i = 0; i < defaultSize; i++) { stringArray[i] = defaultValue; } return stringArray; } public static string[] GetStringArray(string key, string[] defaultArray) { if (PlayerPrefs.HasKey(key)) { return GetStringArray(key); } return defaultArray; } public static bool SetIntArray(string key, int[] intArray) { return SetValue(key, intArray, ArrayType.Int32, 1, ConvertFromInt); } public static bool SetFloatArray(string key, float[] floatArray) { return SetValue(key, floatArray, ArrayType.Float, 1, ConvertFromFloat); } public static bool SetVector2Array(string key, Vector2[] vector2Array) { return SetValue(key, vector2Array, ArrayType.Vector2, 2, ConvertFromVector2); } public static bool SetVector3Array(string key, Vector3[] vector3Array) { return SetValue(key, vector3Array, ArrayType.Vector3, 3, ConvertFromVector3); } public static bool SetQuaternionArray(string key, Quaternion[] quaternionArray) { return SetValue(key, quaternionArray, ArrayType.Quaternion, 4, ConvertFromQuaternion); } private static bool SetValue<T>(string key, T array, ArrayType arrayType, int vectorNumber, Action<T, byte[], int> convert) where T : IList { var bytes = new byte[(4 * array.Count) * vectorNumber + 1]; bytes[0] = Convert.ToByte(arrayType); // Identifier Initialize(); for (var i = 0; i < array.Count; i++) { convert(array, bytes, i); } return SaveBytes(key, bytes); } private static void ConvertFromInt(int[] array, byte[] bytes, int i) { ConvertInt32ToBytes(array[i], bytes); } private static void ConvertFromFloat(float[] array, byte[] bytes, int i) { ConvertFloatToBytes(array[i], bytes); } private static void ConvertFromVector2(Vector2[] array, byte[] bytes, int i) { ConvertFloatToBytes(array[i].x, bytes); ConvertFloatToBytes(array[i].y, bytes); } private static void ConvertFromVector3(Vector3[] array, byte[] bytes, int i) { ConvertFloatToBytes(array[i].x, bytes); ConvertFloatToBytes(array[i].y, bytes); ConvertFloatToBytes(array[i].z, bytes); } private static void ConvertFromQuaternion(Quaternion[] array, byte[] bytes, int i) { ConvertFloatToBytes(array[i].x, bytes); ConvertFloatToBytes(array[i].y, bytes); ConvertFloatToBytes(array[i].z, bytes); ConvertFloatToBytes(array[i].w, bytes); } public static int[] GetIntArray(string key) { var intList = new List<int>(); GetValue(key, intList, ArrayType.Int32, 1, ConvertToInt); return intList.ToArray(); } public static int[] GetIntArray(string key, int defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetIntArray(key); } var intArray = new int[defaultSize]; for (int i = 0; i < defaultSize; i++) { intArray[i] = defaultValue; } return intArray; } public static float[] GetFloatArray(string key) { var floatList = new List<float>(); GetValue(key, floatList, ArrayType.Float, 1, ConvertToFloat); return floatList.ToArray(); } public static float[] GetFloatArray(string key, float defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetFloatArray(key); } var floatArray = new float[defaultSize]; for (int i = 0; i < defaultSize; i++) { floatArray[i] = defaultValue; } return floatArray; } public static Vector2[] GetVector2Array(string key) { var vector2List = new List<Vector2>(); GetValue(key, vector2List, ArrayType.Vector2, 2, ConvertToVector2); return vector2List.ToArray(); } public static Vector2[] GetVector2Array(string key, Vector2 defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetVector2Array(key); } var vector2Array = new Vector2[defaultSize]; for (int i = 0; i < defaultSize; i++) { vector2Array[i] = defaultValue; } return vector2Array; } public static Vector3[] GetVector3Array(string key) { var vector3List = new List<Vector3>(); GetValue(key, vector3List, ArrayType.Vector3, 3, ConvertToVector3); return vector3List.ToArray(); } public static Vector3[] GetVector3Array(string key, Vector3 defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetVector3Array(key); } var vector3Array = new Vector3[defaultSize]; for (int i = 0; i < defaultSize; i++) { vector3Array[i] = defaultValue; } return vector3Array; } public static Quaternion[] GetQuaternionArray(string key) { var quaternionList = new List<Quaternion>(); GetValue(key, quaternionList, ArrayType.Quaternion, 4, ConvertToQuaternion); return quaternionList.ToArray(); } public static Quaternion[] GetQuaternionArray(string key, Quaternion defaultValue, int defaultSize) { if (PlayerPrefs.HasKey(key)) { return GetQuaternionArray(key); } var quaternionArray = new Quaternion[defaultSize]; for (int i = 0; i < defaultSize; i++) { quaternionArray[i] = defaultValue; } return quaternionArray; } private static void GetValue<T>(string key, T list, ArrayType arrayType, int vectorNumber, Action<T, byte[]> convert) where T : IList { if (PlayerPrefs.HasKey(key)) { var bytes = Convert.FromBase64String(PlayerPrefs.GetString(key)); if ((bytes.Length - 1) % (vectorNumber * 4) != 0) { Debug.LogError("Corrupt preference file for " + key); return; } if ((ArrayType) bytes[0] != arrayType) { Debug.LogError(key + " is not a " + arrayType + " array"); return; } Initialize(); var end = (bytes.Length - 1) / (vectorNumber * 4); for (var i = 0; i < end; i++) { convert(list, bytes); } } } private static void ConvertToInt(List<int> list, byte[] bytes) { list.Add(ConvertBytesToInt32(bytes)); } private static void ConvertToFloat(List<float> list, byte[] bytes) { list.Add(ConvertBytesToFloat(bytes)); } private static void ConvertToVector2(List<Vector2> list, byte[] bytes) { list.Add(new Vector2(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes))); } private static void ConvertToVector3(List<Vector3> list, byte[] bytes) { list.Add(new Vector3(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes))); } private static void ConvertToQuaternion(List<Quaternion> list, byte[] bytes) { list.Add(new Quaternion(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes))); } public static void ShowArrayType(string key) { var bytes = Convert.FromBase64String(PlayerPrefs.GetString(key)); if (bytes.Length > 0) { ArrayType arrayType = (ArrayType) bytes[0]; Debug.Log(key + " is a " + arrayType + " array"); } } private static void Initialize() { if (BitConverter.IsLittleEndian) { endianDiff1 = 0; endianDiff2 = 0; } else { endianDiff1 = 3; endianDiff2 = 1; } if (byteBlock == null) { byteBlock = new byte[4]; } idx = 1; } private static bool SaveBytes(string key, byte[] bytes) { try { PlayerPrefs.SetString(key, Convert.ToBase64String(bytes)); } catch { return false; } return true; } private static void ConvertFloatToBytes(float f, byte[] bytes) { byteBlock = BitConverter.GetBytes(f); ConvertTo4Bytes(bytes); } private static float ConvertBytesToFloat(byte[] bytes) { ConvertFrom4Bytes(bytes); return BitConverter.ToSingle(byteBlock, 0); } private static void ConvertInt32ToBytes(int i, byte[] bytes) { byteBlock = BitConverter.GetBytes(i); ConvertTo4Bytes(bytes); } private static int ConvertBytesToInt32(byte[] bytes) { ConvertFrom4Bytes(bytes); return BitConverter.ToInt32(byteBlock, 0); } private static void ConvertTo4Bytes(byte[] bytes) { bytes[idx] = byteBlock[endianDiff1]; bytes[idx + 1] = byteBlock[1 + endianDiff2]; bytes[idx + 2] = byteBlock[2 - endianDiff2]; bytes[idx + 3] = byteBlock[3 - endianDiff1]; idx += 4; } private static void ConvertFrom4Bytes(byte[] bytes) { byteBlock[endianDiff1] = bytes[idx]; byteBlock[1 + endianDiff2] = bytes[idx + 1]; byteBlock[2 - endianDiff2] = bytes[idx + 2]; byteBlock[3 - endianDiff1] = bytes[idx + 3]; idx += 4; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using Microsoft.PackageManagement.Internal.Utility.Platform; namespace Microsoft.PackageManagement.MetaProvider.PowerShell.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Threading; using Microsoft.PackageManagement.Internal.Utility.Extensions; using Microsoft.PackageManagement.Internal.Utility.Platform; using Messages = Microsoft.PackageManagement.MetaProvider.PowerShell.Internal.Resources.Messages; using System.Collections.Concurrent; public class PowerShellProviderBase : IDisposable { private object _lock = new Object(); protected PSModuleInfo _module; private PowerShell _powershell; private ManualResetEvent _reentrancyLock = new ManualResetEvent(true); private readonly Dictionary<string, CommandInfo> _allCommands = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, CommandInfo> _methods = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); public PowerShellProviderBase(PowerShell ps, PSModuleInfo module) { if (module == null) { throw new ArgumentNullException("module"); } _powershell = ps; _module = module; // combine all the cmdinfos we care about // but normalize the keys as we go (remove any '-' '_' chars) foreach (var k in _module.ExportedAliases.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedAliases[k]); } foreach (var k in _module.ExportedCmdlets.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedCmdlets[k]); } foreach (var k in _module.ExportedFunctions.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedFunctions[k]); } } public string ModulePath { get { return _module.Path; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_powershell != null) { _powershell.Dispose(); _powershell = null; } if (_reentrancyLock != null) { _reentrancyLock.Dispose(); _reentrancyLock = null; } _module = null; } } internal CommandInfo GetMethod(string methodName) { return _methods.GetOrAdd(methodName, () => { if (_allCommands.ContainsKey(methodName)) { return _allCommands[methodName]; } // try simple plurals to single if (methodName.EndsWith("s", StringComparison.OrdinalIgnoreCase)) { var meth = methodName.Substring(0, methodName.Length - 1); if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } // try words like Dependencies to Dependency if (methodName.EndsWith("cies", StringComparison.OrdinalIgnoreCase)) { var meth = methodName.Substring(0, methodName.Length - 4) + "cy"; if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } // try IsFoo to Test-IsFoo if (methodName.IndexOf("Is", StringComparison.OrdinalIgnoreCase) == 0) { var meth = "test" + methodName; if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } if (methodName.IndexOf("add", StringComparison.OrdinalIgnoreCase) == 0) { // try it with 'register' instead var result = GetMethod("register" + methodName.Substring(3)); if (result != null) { return result; } } if (methodName.IndexOf("remove", StringComparison.OrdinalIgnoreCase) == 0) { // try it with 'register' instead var result = GetMethod("unregister" + methodName.Substring(6)); if (result != null) { return result; } } // can't find one, return null. return null; }); // hmm, it is possible to get the parameter types to match better when binding. // module.ExportedFunctions.FirstOrDefault().Value.Parameters.Values.First().ParameterType } internal object CallPowerShellWithoutRequest(string method, params object[] args) { var cmdInfo = GetMethod(method); if (cmdInfo == null) { return null; } var result = _powershell.InvokeFunction<object>(cmdInfo.Name, null, null, args); if (result == null) { // failure! throw new Exception(Messages.PowershellScriptFunctionReturnsNull.format(_module.Name, method)); } return result; } // lock is on this instance only internal void ReportErrors(PsRequest request, IEnumerable<ErrorRecord> errors) { foreach (var error in errors) { request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message); if (!string.IsNullOrWhiteSpace(error.Exception.StackTrace)) { // give a debug hint if we have a script stack trace. How nice of us. // the exception stack trace gives better stack than the script stack trace request.Debug(Constants.ScriptStackTrace, error.Exception.StackTrace); } } } private IAsyncResult _stopResult; private object _stopLock = new object(); internal void CancelRequest() { if (!_reentrancyLock.WaitOne(0)) { // it's running right now. #if !CORECLR NativeMethods.OutputDebugString("[Cmdlet:debugging] -- Stopping powershell script."); #endif lock (_stopLock) { if (_stopResult == null) { _stopResult = _powershell.BeginStop(ar => { }, null); } } } } internal object CallPowerShell(PsRequest request, params object[] args) { // the lock ensures that we're not re-entrant into the same powershell runspace lock (_lock) { if (!_reentrancyLock.WaitOne(0)) { // this lock is set to false, meaning we're still in a call **ON THIS THREAD** // this is bad karma -- powershell won't let us call into the runspace again // we're going to throw an error here because this indicates that the currently // running powershell call is calling back into PM, and it has called back // into this provider. That's just bad bad bad. throw new Exception("Reentrancy Violation in powershell module"); } try { // otherwise, this is the first time we've been here during this call. _reentrancyLock.Reset(); _powershell.SetVariable("request", request); _powershell.Streams.ClearStreams(); object finalValue = null; ConcurrentBag<ErrorRecord> errors = new ConcurrentBag<ErrorRecord>(); request.Debug("INVOKING PowerShell Fn {0} with args {1} that has length {2}", request.CommandInfo.Name, String.Join(", ", args), args.Length); var result = _powershell.InvokeFunction<object>(request.CommandInfo.Name, (sender, e) => output_DataAdded(sender, e, request, ref finalValue), (sender, e) => error_DataAdded(sender, e, request, errors), args); if (result == null) { // result is null but it does not mean that the call fails because the command may return nothing request.Debug(Messages.PowershellScriptFunctionReturnsNull.format(_module.Name, request.CommandInfo.Name)); } if (errors.Count > 0) { // report the error if there are any ReportErrors(request, errors); _powershell.Streams.Error.Clear(); } return finalValue; } catch (CmdletInvocationException cie) { var error = cie.ErrorRecord; request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message); } finally { lock (_stopLock) { if (_stopResult != null){ _powershell.EndStop(_stopResult); _stopResult = null; } } _powershell.Clear(); _powershell.SetVariable("request", null); // it's ok if someone else calls into this module now. request.Debug("Done calling powershell", request.CommandInfo.Name, _module.Name); _reentrancyLock.Set(); } return null; } } private void error_DataAdded(object sender, DataAddedEventArgs e, PsRequest request, ConcurrentBag<ErrorRecord> errors) { PSDataCollection<ErrorRecord> errorStream = sender as PSDataCollection<ErrorRecord>; if (errorStream == null) { return; } var error = errorStream[e.Index]; if (error != null) { // add the error so we can report them later errors.Add(error); } } private void output_DataAdded(object sender, DataAddedEventArgs e, PsRequest request, ref object finalValue) { PSDataCollection<PSObject> outputstream = sender as PSDataCollection<PSObject>; if (outputstream == null) { return; } PSObject psObject = outputstream[e.Index]; if (psObject != null) { var value = psObject.ImmediateBaseObject; var y = value as Yieldable; if (y != null) { // yield it to stream the result gradually y.YieldResult(request); } else { finalValue = value; return; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; #if !MSBUILD12 using Microsoft.Build.Construction; #endif using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A workspace that can be populated by opening MSBuild solution and project files. /// </summary> public sealed class MSBuildWorkspace : Workspace { // used to serialize access to public methods private readonly NonReentrantLock _serializationLock = new NonReentrantLock(); private MSBuildProjectLoader _loader; private MSBuildWorkspace( HostServices hostServices, ImmutableDictionary<string, string> properties) : base(hostServices, "MSBuildWorkspace") { _loader = new MSBuildProjectLoader(this, properties); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> public static MSBuildWorkspace Create() { return Create(ImmutableDictionary<string, string>.Empty); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">An optional set of MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties) { return Create(properties, DesktopMefHostServices.DefaultServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (hostServices == null) { throw new ArgumentNullException(nameof(hostServices)); } return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary()); } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties { get { return _loader.Properties; } } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get { return _loader.LoadMetadataForReferencedProjects; } set { _loader.LoadMetadataForReferencedProjects = value; } } /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// An project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get { return _loader.SkipUnrecognizedProjects; } set { _loader.SkipUnrecognizedProjects = value; } } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { _loader.AssociateFileExtensionWithLanguage(projectFileExtension, language); } /// <summary> /// Close the open solution, and reset the workspace to a new empty solution. /// </summary> public void CloseSolution() { using (_serializationLock.DisposableWait()) { this.ClearSolution(); } } private string GetAbsolutePath(string path, string baseDirectoryPath) { return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path); } #region Open Solution & Project /// <summary> /// Open a solution file and all referenced projects. /// </summary> public async Task<Solution> OpenSolutionAsync(string solutionFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } this.ClearSolution(); var solutionInfo = await _loader.LoadSolutionInfoAsync(solutionFilePath, cancellationToken: cancellationToken).ConfigureAwait(false); // construct workspace from loaded project infos this.OnSolutionAdded(solutionInfo); this.UpdateReferencesAfterAdd(); return this.CurrentSolution; } /// <summary> /// Open a project file and all referenced projects. /// </summary> public async Task<Project> OpenProjectAsync(string projectFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } var projects = await _loader.LoadProjectInfoAsync(projectFilePath, GetCurrentProjectMap(), cancellationToken).ConfigureAwait(false); // add projects to solution foreach (var project in projects) { this.OnProjectAdded(project); } this.UpdateReferencesAfterAdd(); return this.CurrentSolution.GetProject(projects[0].Id); } private Dictionary<string, ProjectId> GetCurrentProjectMap() { return this.CurrentSolution.Projects .Where(p => !string.IsNullOrEmpty(p.FilePath)) .ToDictionary(p => p.FilePath, p => p.Id); } #endregion #region Apply Changes public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: return true; default: return false; } } private bool HasProjectFileChanges(ProjectChanges changes) { return changes.GetAddedDocuments().Any() || changes.GetRemovedDocuments().Any() || changes.GetAddedMetadataReferences().Any() || changes.GetRemovedMetadataReferences().Any() || changes.GetAddedProjectReferences().Any() || changes.GetRemovedProjectReferences().Any() || changes.GetAddedAnalyzerReferences().Any() || changes.GetRemovedAnalyzerReferences().Any(); } private IProjectFile _applyChangesProjectFile; public override bool TryApplyChanges(Solution newSolution) { using (_serializationLock.DisposableWait()) { return base.TryApplyChanges(newSolution); } } protected override void ApplyProjectChanges(ProjectChanges projectChanges) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile == null); var project = projectChanges.OldProject ?? projectChanges.NewProject; try { // if we need to modify the project file, load it first. if (this.HasProjectFileChanges(projectChanges)) { var projectPath = project.FilePath; IProjectFileLoader loader; if (_loader.TryGetLoaderFromProjectPath(projectPath, out loader)) { try { _applyChangesProjectFile = loader.LoadProjectFileAsync(projectPath, _loader.Properties, CancellationToken.None).Result; } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } // do normal apply operations base.ApplyProjectChanges(projectChanges); // save project file if (_applyChangesProjectFile != null) { try { _applyChangesProjectFile.Save(); } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } finally { _applyChangesProjectFile = null; } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { Encoding encoding = DetermineEncoding(text, document); this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } private static Encoding DetermineEncoding(SourceText text, Document document) { if (text.Encoding != null) { return text.Encoding; } try { using (ExceptionHelpers.SuppressFailFast()) { using (var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var onDiskText = EncodedStringText.Create(stream); return onDiskText.Encoding; } } } catch (IOException) { } catch (InvalidDataException) { } return null; } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(info.Id.ProjectId); IProjectFileLoader loader; if (_loader.TryGetLoaderFromProjectPath(project.FilePath, out loader)) { var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind); var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) ? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(project.FilePath)); var newDocumentInfo = info.WithName(fileName) .WithFilePath(fullPath) .WithTextLoader(new FileTextLoader(fullPath, text.Encoding)); // add document to project file _applyChangesProjectFile.AddDocument(relativePath); // add to solution this.OnDocumentAdded(newDocumentInfo); // save text to disk if (text != null) { this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8); } } } private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { using (ExceptionHelpers.SuppressFailFast()) { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding)) { newText.Write(writer); } } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { Debug.Assert(_applyChangesProjectFile != null); var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { _applyChangesProjectFile.RemoveDocument(document.FilePath); this.DeleteDocumentFile(document.Id, document.FilePath); this.OnDocumentRemoved(documentId); } } private void DeleteDocumentFile(DocumentId documentId, string fullPath) { try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (NotSupportedException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (UnauthorizedAccessException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.AddMetadataReference(metadataReference, identity); this.OnMetadataReferenceAdded(projectId, metadataReference); } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); } private AssemblyIdentity GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol != null ? symbol.Identity : null; } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases)); } this.OnProjectReferenceAdded(projectId, projectReference); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath); } this.OnProjectReferenceRemoved(projectId, projectReference); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.AddAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceAdded(projectId, analyzerReference); } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } } #endregion }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Runtime.InteropServices; using System.Threading; using log4net; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using PowerShellTools.Common.ServiceManagement.DebuggingContract; using PowerShellTools.DebugEngine.Definitions; using Task = System.Threading.Tasks.Task; using Thread = System.Threading.Thread; using PowerShellTools.Common; namespace PowerShellTools.DebugEngine { /// <summary> /// The core debug engine for PowerShell. /// </summary> /// <remarks> /// This class is repsonsible for all interactions with the Visual Studio debugger. /// </remarks> [ComVisible(true)] [Guid("C7F9F131-53AB-4FD0-8517-E54D124EA393")] public class Engine : IDebugEngine2, IDebugEngineLaunch2 { #region Fields /// <summary> /// This is the engine GUID of the sample engine. It needs to be changed here and in the registration /// when creating a new engine. /// </summary> public const string Id = "{43ACAB74-8226-4920-B489-BFCF05372437}"; // A unique identifier for the program being debugged. //private Guid m_ad7ProgramId; private ManualResetEvent _runspaceSet; private EngineEvents _events; private ScriptProgramNode _node; private List<ScriptBreakpoint> bps = new List<ScriptBreakpoint>(); private static readonly ILog Log = LogManager.GetLogger(typeof(Engine)); #endregion #region Properties public ScriptDebugger Debugger { get { return PowerShellToolsPackage.Debugger; } } private IEnumerable<PendingBreakpoint> _pendingBreakpoints; private uint _uiContextCookie; public IEnumerable<PendingBreakpoint> PendingBreakpoints { get { return _pendingBreakpoints; } set { _pendingBreakpoints = value; _runspaceSet.Set(); } } #endregion public Engine() { _runspaceSet = new ManualResetEvent(false); _uiContextCookie = UiContextUtilities.CreateUiContext(PowerShellTools.Common.Constants.PowerShellDebuggingUiContextGuid); } /// <summary> /// Initiates the execute of the debug engine. /// </summary> /// <remarks> /// The debug engine works in two different ways. The first is by executing a script file. The second /// is by executing a string of text. /// </remarks> public void Execute() { if (!PowerShellToolsPackage.PowerShellHostInitialized) { // TODO: UI Work required to give user inidcation that it is waiting for debugger to get alive. PowerShellToolsPackage.DebuggerReadyEvent.WaitOne(); } if (!_node.IsAttachedProgram) { if (!_runspaceSet.WaitOne()) { throw new Exception("Runspace not set!"); } while (PendingBreakpoints.Count() > bps.Count) { Thread.Sleep(1000); } } Debugger.HostUi.OutputString = _events.OutputString; Debugger.BreakpointManager.BreakpointHit += Debugger_BreakpointHit; Debugger.DebuggingBegin += Debugger_DebuggingBegin; Debugger.DebuggingFinished += Debugger_DebuggingFinished; Debugger.BreakpointManager.BreakpointUpdated += Debugger_BreakpointUpdated; Debugger.DebuggerPaused += Debugger_DebuggerPaused; Debugger.TerminatingException += Debugger_TerminatingException; _node.Debugger = Debugger; if (Debugger.DebuggingService.GetRunspaceAvailability() == RunspaceAvailability.Available) { Debugger.DebuggerBegin(); Debugger.DebuggingService.SetRunspace(Debugger.OverrideExecutionPolicy); Debugger.Execute(_node); } else { Debugger.DebuggerFinished(); } } /// <summary> /// This event occurs when a terminating execption is thrown from the /// PowerShell debugger. /// </summary> /// <remarks> /// This event triggers a Visual Studio Excecption event so that /// Visual Studio displays the exception window accordingly. /// </remarks> /// <param name="sender"></param> /// <param name="e"></param> void Debugger_TerminatingException(object sender, EventArgs<PowerShellRunTerminatingException> e) { if (e.Value.Error != null && e.Value.Error.InvocationInfo != null) { var scriptLocation = new ScriptLocation(e.Value.Error.InvocationInfo.ScriptName, e.Value.Error.InvocationInfo.ScriptLineNumber, 0); //_events.Break(_node); } _events.Exception(_node, new Exception(e.Value.Message)); } /// <summary> /// This event triggers a Visaul Studio OutputString event so that the string /// provided is written to the Output Pane. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Debugger_OutputString(object sender, EventArgs<string> e) { _events.OutputString(e.Value); } /// <summary> /// This event triggers a Visual Stujdio Break event, causing the debugger to /// break. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Debugger_DebuggerPaused(object sender, EventArgs<ScriptLocation> e) { _events.Break(_node); } /// <summary> /// Placeholder for future support on debugging command in REPL window /// This event handler adds or removes breakpoints monitored by Visual Studio. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Debugger_BreakpointUpdated(object sender, DebuggerBreakpointUpdatedEventArgs e) { // TODO: implementaion for future support on debugging command in REPL window } /// <summary> /// This event handler reports to Visual Studio that the debugger has begun /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Debugger_DebuggingBegin(object sender, EventArgs e) { UiContextUtilities.ActivateUiContext(_uiContextCookie); } /// <summary> /// This event handler reports to Visual Studio that the debugger has finished and destroys the program. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Debugger_DebuggingFinished(object sender, EventArgs e) { bps.Clear(); _events.ProgramDestroyed(_node); UiContextUtilities.DeactivateUiContext(_uiContextCookie); } /// <summary> /// This event handler notifies Visual Studio that a breakbpoint has been hit. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Debugger_BreakpointHit(object sender, EventArgs<ScriptBreakpoint> e) { _events.BreakpointHit(e.Value, _node); } #region Implementation of IDebugEngine2 /// <summary> /// Attaches to the specified program nodes. This is the main entry point to debugging. /// </summary> /// <remarks> /// This method is responsible for firing the correct Visual Studio events to begin debugging /// and then to start the actual PowerShell execution. /// </remarks> /// <param name="rgpPrograms">The programs.</param> /// <param name="rgpProgramNodes">The program nodes.</param> /// <param name="celtPrograms">The celt programs.</param> /// <param name="pCallback">The callback.</param> /// <param name="dwReason">The reason.</param> /// <returns></returns> public int Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 pCallback, enum_ATTACH_REASON dwReason) { Log.Debug("Attaching the debug engine."); Guid id; rgpPrograms[0].GetProgramId(out id); if (_node == null) { _node = rgpProgramNodes[0] as ScriptProgramNode; // during remote attach, the program node is put in the programs array if (_node == null) { _node = rgpPrograms[0] as ScriptProgramNode; _node.IsRemoteProgram = true; } _node.IsAttachedProgram = dwReason == enum_ATTACH_REASON.ATTACH_REASON_USER; } _node.Id = id; var publisher = (IDebugProgramPublisher2)new DebugProgramPublisher(); publisher.PublishProgramNode(_node); _events = new EngineEvents(this, pCallback); _events.RunspaceRequest(); _events.EngineCreated(); _events.ProgramCreated(_node); _events.EngineLoaded(); _events.DebugEntryPoint(); Task.Factory.StartNew(Execute); return VSConstants.S_OK; } // Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run. // This is normally called in response to the user clicking on the pause button in the debugger. // When the break is complete, an AsyncBreakComplete event will be sent back to the debugger. int IDebugEngine2.CauseBreak() { return ((IDebugProgram2)this).CauseBreak(); } // Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM, // was received and processed. The only event the sample engine sends in this fashion is Program Destroy. // It responds to that event by shutting down the engine. int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 eventObject) { return VSConstants.S_OK; } // Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to // a location in the debuggee. int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP) { Log.Debug("Engine: CreatePendingBreakPoint"); ppPendingBP = null; var info = new BP_REQUEST_INFO[1]; info[0].bpLocation.bpLocationType = (uint)enum_BP_LOCATION_TYPE.BPLT_FILE_LINE; if (pBPRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_BPLOCATION, info) == VSConstants.S_OK) { var position = (IDebugDocumentPosition2)Marshal.GetObjectForIUnknown(info[0].bpLocation.unionmember2); var start = new TEXT_POSITION[1]; var end = new TEXT_POSITION[1]; string fileName; position.GetRange(start, end); position.GetFileName(out fileName); //VS has a 0 based line\column value. PowerShell starts at 1 var breakpoint = new ScriptBreakpoint( _node, fileName, (int)start[0].dwLine + 1, (int)start[0].dwColumn, _events); ppPendingBP = breakpoint; _events.BreakpointAdded(breakpoint); bps.Add(breakpoint); } return VSConstants.S_OK; } // Informs a DE that the program specified has been atypically terminated and that the DE should // clean up all references to the program and send a program destroy event. int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram) { // Tell the SDM that the engine knows that the program is exiting, and that the // engine will send a program destroy. We do this because the Win32 debug api will always // tell us that the process exited, and otherwise we have a race condition. return (HRESULT.E_PROGRAM_DESTROY_PENDING); } // Gets the GUID of the DE. int IDebugEngine2.GetEngineId(out Guid guidEngine) { guidEngine = new Guid(Id); return VSConstants.S_OK; } // Removes the list of exceptions the IDE has set for a particular run-time architecture or language. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType) { return VSConstants.S_OK; } // Removes the specified exception so it is no longer handled by the debug engine. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException) { // The sample engine will always stop on all exceptions. return VSConstants.S_OK; } // Specifies how the DE should handle a given exception. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.SetException(EXCEPTION_INFO[] pException) { return VSConstants.S_OK; } // Sets the locale of the DE. // This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that // strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented. int IDebugEngine2.SetLocale(ushort wLangID) { return VSConstants.S_OK; } // A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality. // This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric. int IDebugEngine2.SetMetric(string pszMetric, object varValue) { // The sample engine does not need to understand any metric settings. return VSConstants.S_OK; } // Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored // This allows the debugger to tell the engine where that location is. int IDebugEngine2.SetRegistryRoot(string pszRegistryRoot) { // The sample engine does not read settings from the registry. return VSConstants.S_OK; } #endregion #region Implementation of IDebugEngineLaunch2 public int LaunchSuspended(string pszServer, IDebugPort2 pPort, string pszExe, string pszArgs, string pszDir, string bstrEnv, string pszOptions, enum_LAUNCH_FLAGS dwLaunchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 pCallback, out IDebugProcess2 ppProcess) { _runspaceSet.Reset(); if (dwLaunchFlags.HasFlag(enum_LAUNCH_FLAGS.LAUNCH_DEBUG)) { ppProcess = new ScriptDebugProcess(pPort); } else { ppProcess = new ScriptDebugProcess(pPort); } _node = (ppProcess as ScriptDebugProcess).Node; if (pszExe == "Selection") { _node.IsFile = false; _node.FileName = pszOptions; } else { _node.IsFile = true; _node.FileName = pszExe; _node.Arguments = pszArgs; } _events = new EngineEvents(this, pCallback); return VSConstants.S_OK; } // Determines if a process can be terminated. int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) { Log.Debug("Engine: CanTerminateProcess"); return VSConstants.S_OK; } // Resume a process launched by IDebugEngineLaunch2.LaunchSuspended int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process) { if (process is ScriptDebugProcess) { IDebugPort2 port; process.GetPort(out port); var defaultPort = (IDebugDefaultPort2)port; IDebugPortNotify2 notify; defaultPort.GetPortNotify(out notify); notify.AddProgramNode((process as ScriptDebugProcess).Node); return VSConstants.S_OK; } return VSConstants.E_UNEXPECTED; } // This function is used to terminate a process that the SampleEngine launched // The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method. int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process) { Log.Debug("Engine: TerminateProcess"); IDebugPort2 port; process.GetPort(out port); var defaultPort = (IDebugDefaultPort2)port; IDebugPortNotify2 notify; defaultPort.GetPortNotify(out notify); notify.RemoveProgramNode(_node); Debugger.Stop(); return VSConstants.S_OK; } #endregion #region Deprecated interface methods int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs) { Debug.Fail("This function is not called by the debugger"); programs = null; return VSConstants.E_NOTIMPL; } #endregion } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using System.Linq; /// <summary> /// A Job Preparation task to run before any tasks of the job on any given /// compute node. /// </summary> public partial class JobPreparationTask { /// <summary> /// Initializes a new instance of the JobPreparationTask class. /// </summary> public JobPreparationTask() { } /// <summary> /// Initializes a new instance of the JobPreparationTask class. /// </summary> /// <param name="commandLine">The command line of the Job Preparation /// task.</param> /// <param name="id">A string that uniquely identifies the Job /// Preparation task within the job.</param> /// <param name="resourceFiles">A list of files that the Batch service /// will download to the compute node before running the command /// line.</param> /// <param name="environmentSettings">A list of environment variable /// settings for the Job Preparation task.</param> /// <param name="constraints">Constraints that apply to the Job /// Preparation task.</param> /// <param name="waitForSuccess">Whether the Batch service should wait /// for the Job Preparation task to complete successfully before /// scheduling any other tasks of the job on the compute node.</param> /// <param name="userIdentity">The user identity under which the Job /// Preparation task runs.</param> /// <param name="rerunOnNodeRebootAfterSuccess">Whether the Batch /// service should rerun the Job Preparation task after a compute node /// reboots.</param> public JobPreparationTask(string commandLine, string id = default(string), System.Collections.Generic.IList<ResourceFile> resourceFiles = default(System.Collections.Generic.IList<ResourceFile>), System.Collections.Generic.IList<EnvironmentSetting> environmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), TaskConstraints constraints = default(TaskConstraints), bool? waitForSuccess = default(bool?), UserIdentity userIdentity = default(UserIdentity), bool? rerunOnNodeRebootAfterSuccess = default(bool?)) { Id = id; CommandLine = commandLine; ResourceFiles = resourceFiles; EnvironmentSettings = environmentSettings; Constraints = constraints; WaitForSuccess = waitForSuccess; UserIdentity = userIdentity; RerunOnNodeRebootAfterSuccess = rerunOnNodeRebootAfterSuccess; } /// <summary> /// Gets or sets a string that uniquely identifies the Job Preparation /// task within the job. /// </summary> /// <remarks> /// The ID can contain any combination of alphanumeric characters /// including hyphens and underscores and cannot contain more than 64 /// characters. If you do not specify this property, the Batch service /// assigns a default value of 'jobpreparation'. No other task in the /// job can have the same id as the Job Preparation task. If you try to /// submit a task with the same id, the Batch service rejects the /// request with error code TaskIdSameAsJobPreparationTask; if you are /// calling the REST API directly, the HTTP status code is 409 /// (Conflict). /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the command line of the Job Preparation task. /// </summary> /// <remarks> /// The command line does not run under a shell, and therefore cannot /// take advantage of shell features such as environment variable /// expansion. If you want to take advantage of such features, you /// should invoke the shell in the command line, for example using "cmd /// /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "commandLine")] public string CommandLine { get; set; } /// <summary> /// Gets or sets a list of files that the Batch service will download /// to the compute node before running the command line. /// </summary> /// <remarks> /// Files listed under this element are located in the task's working /// directory. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "resourceFiles")] public System.Collections.Generic.IList<ResourceFile> ResourceFiles { get; set; } /// <summary> /// Gets or sets a list of environment variable settings for the Job /// Preparation task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "environmentSettings")] public System.Collections.Generic.IList<EnvironmentSetting> EnvironmentSettings { get; set; } /// <summary> /// Gets or sets constraints that apply to the Job Preparation task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "constraints")] public TaskConstraints Constraints { get; set; } /// <summary> /// Gets or sets whether the Batch service should wait for the Job /// Preparation task to complete successfully before scheduling any /// other tasks of the job on the compute node. /// </summary> /// <remarks> /// If true and the Job Preparation task fails on a compute node, the /// Batch service retries the Job Preparation task up to its maximum /// retry count (as specified in the constraints element). If the task /// has still not completed successfully after all retries, then the /// Batch service will not schedule tasks of the job to the compute /// node. The compute node remains active and eligible to run tasks of /// other jobs. If false, the Batch service will not wait for the Job /// Preparation task to complete. In this case, other tasks of the job /// can start executing on the compute node while the Job Preparation /// task is still running; and even if the Job Preparation task fails, /// new tasks will continue to be scheduled on the node. The default /// value is true. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "waitForSuccess")] public bool? WaitForSuccess { get; set; } /// <summary> /// Gets or sets the user identity under which the Job Preparation task /// runs. /// </summary> /// <remarks> /// If omitted, the task runs as a non-administrative user unique to /// the task. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "userIdentity")] public UserIdentity UserIdentity { get; set; } /// <summary> /// Gets or sets whether the Batch service should rerun the Job /// Preparation task after a compute node reboots. /// </summary> /// <remarks> /// The Job Preparation task is always rerun if a compute node is /// reimaged, or if the Job Preparation task did not complete (e.g. /// because the reboot occurred while the task was running). Therefore, /// you should always write a Job Preparation task to be idempotent and /// to behave correctly if run multiple times. The default value is /// true. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "rerunOnNodeRebootAfterSuccess")] public bool? RerunOnNodeRebootAfterSuccess { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (CommandLine == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "CommandLine"); } if (this.ResourceFiles != null) { foreach (var element in this.ResourceFiles) { if (element != null) { element.Validate(); } } } if (this.EnvironmentSettings != null) { foreach (var element1 in this.EnvironmentSettings) { if (element1 != null) { element1.Validate(); } } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal partial class InlineRenameSession { /// <summary> /// Manages state for open text buffers. /// </summary> internal class OpenTextBufferManager : ForegroundThreadAffinitizedObject { private readonly DynamicReadOnlyRegionQuery _isBufferReadOnly; private readonly InlineRenameSession _session; private readonly ITextBuffer _subjectBuffer; private readonly IEnumerable<Document> _baseDocuments; private readonly ITextBufferFactoryService _textBufferFactoryService; private static readonly object s_propagateSpansEditTag = new object(); private static readonly object s_calculateMergedSpansEditTag = new object(); /// <summary> /// The list of active tracking spans that are updated with the session's replacement text. /// These are also the only spans the user can edit during an inline rename session. /// </summary> private readonly Dictionary<TextSpan, RenameTrackingSpan> _referenceSpanToLinkedRenameSpanMap = new Dictionary<TextSpan, RenameTrackingSpan>(); private readonly List<RenameTrackingSpan> _conflictResolutionRenameTrackingSpans = new List<RenameTrackingSpan>(); private readonly IList<IReadOnlyRegion> _readOnlyRegions = new List<IReadOnlyRegion>(); private readonly IList<IWpfTextView> _textViews = new List<IWpfTextView>(); private TextSpan? _activeSpan; public OpenTextBufferManager( InlineRenameSession session, ITextBuffer subjectBuffer, Workspace workspace, IEnumerable<Document> documents, ITextBufferFactoryService textBufferFactoryService) { _session = session; _subjectBuffer = subjectBuffer; _baseDocuments = documents; _textBufferFactoryService = textBufferFactoryService; _subjectBuffer.ChangedLowPriority += OnTextBufferChanged; foreach (var view in session._textBufferAssociatedViewService.GetAssociatedTextViews(_subjectBuffer)) { ConnectToView(view); } session.UndoManager.CreateStartRenameUndoTransaction(workspace, subjectBuffer, session); _isBufferReadOnly = new DynamicReadOnlyRegionQuery((isEdit) => !_session._isApplyingEdit); UpdateReadOnlyRegions(); } public IWpfTextView ActiveTextview { get { foreach (var view in _textViews) { if (view.HasAggregateFocus) { return view; } } return _textViews.FirstOrDefault(); } } private void UpdateReadOnlyRegions(bool removeOnly = false) { AssertIsForeground(); if (!removeOnly && _session.ReplacementText == string.Empty) { return; } using (var readOnlyEdit = _subjectBuffer.CreateReadOnlyRegionEdit()) { foreach (var oldReadOnlyRegion in _readOnlyRegions) { readOnlyEdit.RemoveReadOnlyRegion(oldReadOnlyRegion); } _readOnlyRegions.Clear(); if (!removeOnly) { // We will compute the new read only regions to be all spans that are not currently in an editable span var editableSpans = GetEditableSpansForSnapshot(_subjectBuffer.CurrentSnapshot); var entireBufferSpan = _subjectBuffer.CurrentSnapshot.GetSnapshotSpanCollection(); var newReadOnlySpans = NormalizedSnapshotSpanCollection.Difference(entireBufferSpan, new NormalizedSnapshotSpanCollection(editableSpans)); foreach (var newReadOnlySpan in newReadOnlySpans) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(newReadOnlySpan, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow, _isBufferReadOnly)); } // The spans we added allow typing at the start and end. We'll add extra // zero-width read-only regions at the start and end of the file to fix this, // but only if we don't have an identifier at the start or end that _would_ let // them type there. if (editableSpans.All(s => s.Start > 0)) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly)); } if (editableSpans.All(s => s.End < _subjectBuffer.CurrentSnapshot.Length)) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(_subjectBuffer.CurrentSnapshot.Length, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly)); } } readOnlyEdit.Apply(); } } private void OnTextViewClosed(object sender, EventArgs e) { var view = sender as IWpfTextView; view.Closed -= OnTextViewClosed; _textViews.Remove(view); if (!_session._dismissed) { _session.Cancel(); } } internal void ConnectToView(IWpfTextView textView) { textView.Closed += OnTextViewClosed; _textViews.Add(textView); } public event Action SpansChanged; private void RaiseSpansChanged() { this.SpansChanged?.Invoke(); } internal IEnumerable<RenameTrackingSpan> GetRenameTrackingSpans() { return _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Concat(_conflictResolutionRenameTrackingSpans); } internal IEnumerable<SnapshotSpan> GetEditableSpansForSnapshot(ITextSnapshot snapshot) { return _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Select(r => r.TrackingSpan.GetSpan(snapshot)); } internal void SetReferenceSpans(IEnumerable<TextSpan> spans) { AssertIsForeground(); if (spans.SetEquals(_referenceSpanToLinkedRenameSpanMap.Keys)) { return; } using (new SelectionTracking(this)) { // Revert any previous edits in case we're removing spans. Undo conflict resolution as well to avoid // handling the various edge cases where a tracking span might not map to the right span in the current snapshot _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: false); _referenceSpanToLinkedRenameSpanMap.Clear(); foreach (var span in spans) { var renameableSpan = _session._renameInfo.GetReferenceEditSpan( new InlineRenameLocation(_baseDocuments.First(), span), CancellationToken.None); var trackingSpan = new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(renameableSpan.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), RenameSpanKind.Reference); _referenceSpanToLinkedRenameSpanMap[span] = trackingSpan; } _activeSpan = _activeSpan.HasValue && spans.Contains(_activeSpan.Value) ? _activeSpan : spans.Where(s => // in tests `ActiveTextview` can be null so don't depend on it ActiveTextview == null || ActiveTextview.GetSpanInView(_subjectBuffer.CurrentSnapshot.GetSpan(s.ToSpan())).Count != 0) // spans were successfully projected .FirstOrNullable(); // filter to spans that have a projection UpdateReadOnlyRegions(); this.ApplyReplacementText(updateSelection: false); } RaiseSpansChanged(); } private void OnTextBufferChanged(object sender, TextContentChangedEventArgs args) { AssertIsForeground(); // This might be an event fired due to our own edit if (args.EditTag == s_propagateSpansEditTag || _session._isApplyingEdit) { return; } using (Logger.LogBlock(FunctionId.Rename_OnTextBufferChanged, CancellationToken.None)) { var trackingSpansAfterEdit = new NormalizedSpanCollection(GetEditableSpansForSnapshot(args.After).Select(ss => (Span)ss)); var spansTouchedInEdit = new NormalizedSpanCollection(args.Changes.Select(c => c.NewSpan)); var intersectionSpans = NormalizedSpanCollection.Intersection(trackingSpansAfterEdit, spansTouchedInEdit); if (intersectionSpans.Count == 0) { // In Razor we sometimes get formatting changes during inline rename that // do not intersect with any of our spans. Ideally this shouldn't happen at // all, but if it does happen we can just ignore it. return; } // Cases with invalid identifiers may cause there to be multiple intersection // spans, but they should still all map to a single tracked rename span (e.g. // renaming "two" to "one two three" may be interpreted as two distinct // additions of "one" and "three"). var boundingIntersectionSpan = Span.FromBounds(intersectionSpans.First().Start, intersectionSpans.Last().End); var trackingSpansTouched = GetEditableSpansForSnapshot(args.After).Where(ss => ss.IntersectsWith(boundingIntersectionSpan)); Contract.Assert(trackingSpansTouched.Count() == 1); var singleTrackingSpanTouched = trackingSpansTouched.Single(); _activeSpan = _referenceSpanToLinkedRenameSpanMap.Where(kvp => kvp.Value.TrackingSpan.GetSpan(args.After).Contains(boundingIntersectionSpan)).Single().Key; _session.UndoManager.OnTextChanged(this.ActiveTextview.Selection, singleTrackingSpanTouched); } } /// <summary> /// This is a work around for a bug in Razor where the projection spans can get out-of-sync with the /// identifiers. When that bug is fixed this helper can be deleted. /// </summary> private bool AreAllReferenceSpansMappable() { // in tests `ActiveTextview` could be null so don't depend on it return ActiveTextview == null || _referenceSpanToLinkedRenameSpanMap.Keys .Select(s => s.ToSpan()) .All(s => s.End <= _subjectBuffer.CurrentSnapshot.Length && // span is valid for the snapshot ActiveTextview.GetSpanInView(_subjectBuffer.CurrentSnapshot.GetSpan(s)).Count != 0); // spans were successfully projected } internal void ApplyReplacementText(bool updateSelection = true) { AssertIsForeground(); if (!AreAllReferenceSpansMappable()) { // don't dynamically update the reference spans for documents with unmappable projections return; } _session.UndoManager.ApplyCurrentState( _subjectBuffer, s_propagateSpansEditTag, _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Select(r => r.TrackingSpan)); if (updateSelection && _activeSpan.HasValue && this.ActiveTextview != null) { var snapshot = _subjectBuffer.CurrentSnapshot; _session.UndoManager.UpdateSelection(this.ActiveTextview, _subjectBuffer, _referenceSpanToLinkedRenameSpanMap[_activeSpan.Value].TrackingSpan); } } internal void Disconnect(bool documentIsClosed, bool rollbackTemporaryEdits) { AssertIsForeground(); // Detach from the buffer; it is important that this is done before we start // undoing transactions, since the undo actions will cause buffer changes. _subjectBuffer.ChangedLowPriority -= OnTextBufferChanged; foreach (var view in _textViews) { view.Closed -= OnTextViewClosed; } // Remove any old read only regions we had UpdateReadOnlyRegions(removeOnly: true); if (rollbackTemporaryEdits && !documentIsClosed) { _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: true); } } internal void ApplyConflictResolutionEdits(IInlineRenameReplacementInfo conflictResolution, IEnumerable<Document> documents, CancellationToken cancellationToken) { AssertIsForeground(); if (!AreAllReferenceSpansMappable()) { // don't dynamically update the reference spans for documents with unmappable projections return; } using (new SelectionTracking(this)) { // 1. Undo any previous edits and update the buffer to resulting document after conflict resolution _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: false); var preMergeSolution = _session._baseSolution; var postMergeSolution = conflictResolution.NewSolution; var diffMergingSession = new LinkedFileDiffMergingSession(preMergeSolution, postMergeSolution, postMergeSolution.GetChanges(preMergeSolution), logSessionInfo: true); var mergeResult = diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var newDocument = mergeResult.MergedSolution.GetDocument(documents.First().Id); var originalDocument = _baseDocuments.Single(d => d.Id == newDocument.Id); var changes = GetTextChangesFromTextDifferencingServiceAsync(originalDocument, newDocument, cancellationToken).WaitAndGetResult(cancellationToken); // TODO: why does the following line hang when uncommented? // newDocument.GetTextChangesAsync(this.baseDocuments.Single(d => d.Id == newDocument.Id), cancellationToken).WaitAndGetResult(cancellationToken).Reverse(); _session.UndoManager.CreateConflictResolutionUndoTransaction(_subjectBuffer, () => { using (var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag)) { foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.Apply(); } }); // 2. We want to update referenceSpanToLinkedRenameSpanMap where spans were affected by conflict resolution. // We also need to add the remaining document edits to conflictResolutionRenameTrackingSpans // so they get classified/tagged correctly in the editor. _conflictResolutionRenameTrackingSpans.Clear(); foreach (var document in documents) { var relevantReplacements = conflictResolution.GetReplacements(document.Id).Where(r => GetRenameSpanKind(r.Kind) != RenameSpanKind.None); if (!relevantReplacements.Any()) { continue; } var bufferContainsLinkedDocuments = documents.Skip(1).Any(); var mergedReplacements = bufferContainsLinkedDocuments ? GetMergedReplacementInfos( relevantReplacements, conflictResolution.NewSolution.GetDocument(document.Id), mergeResult.MergedSolution.GetDocument(document.Id), cancellationToken) : relevantReplacements; // Show merge conflicts comments as unresolvable conflicts, and do not // show any other rename-related spans that overlap a merge conflict comment. var mergeConflictComments = mergeResult.MergeConflictCommentSpans.ContainsKey(document.Id) ? mergeResult.MergeConflictCommentSpans[document.Id] : SpecializedCollections.EmptyEnumerable<TextSpan>(); foreach (var conflict in mergeConflictComments) { // TODO: Add these to the unresolvable conflict counts in the dashboard _conflictResolutionRenameTrackingSpans.Add(new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(conflict.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), RenameSpanKind.UnresolvedConflict)); } foreach (var replacement in mergedReplacements) { var kind = GetRenameSpanKind(replacement.Kind); if (_referenceSpanToLinkedRenameSpanMap.ContainsKey(replacement.OriginalSpan) && kind != RenameSpanKind.Complexified) { var linkedRenameSpan = _session._renameInfo.GetConflictEditSpan( new InlineRenameLocation(newDocument, replacement.NewSpan), _session.ReplacementText, cancellationToken); if (linkedRenameSpan.HasValue) { if (!mergeConflictComments.Any(s => replacement.NewSpan.IntersectsWith(s))) { _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan] = new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan( linkedRenameSpan.Value.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), kind); } } else { // We might not have a renameable span if an alias conflict completely changed the text _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan] = new RenameTrackingSpan( _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan].TrackingSpan, RenameSpanKind.None); if (_activeSpan.HasValue && _activeSpan.Value.IntersectsWith(replacement.OriginalSpan)) { _activeSpan = null; } } } else { if (!mergeConflictComments.Any(s => replacement.NewSpan.IntersectsWith(s))) { _conflictResolutionRenameTrackingSpans.Add(new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(replacement.NewSpan.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), kind)); } } } } UpdateReadOnlyRegions(); // 3. Reset the undo state and notify the taggers. this.ApplyReplacementText(updateSelection: false); RaiseSpansChanged(); } } private static async Task<IEnumerable<TextChange>> GetTextChangesFromTextDifferencingServiceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken = default(CancellationToken)) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, newDocument.Name, cancellationToken)) { if (oldDocument == newDocument) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (newDocument.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } SourceText oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); SourceText newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); if (oldText == newText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var textChanges = newText.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count != 1 || textChanges[0].Span != new TextSpan(0, oldText.Length)) { return textChanges; } var textDiffService = oldDocument.Project.Solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); return await textDiffService.GetTextChangesAsync(oldDocument, newDocument, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private IEnumerable<InlineRenameReplacement> GetMergedReplacementInfos( IEnumerable<InlineRenameReplacement> relevantReplacements, Document preMergeDocument, Document postMergeDocument, CancellationToken cancellationToken) { AssertIsForeground(); var textDiffService = preMergeDocument.Project.Solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); var contentType = preMergeDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType(); // TODO: Track all spans at once ITextBufferCloneService textBufferCloneService = null; SnapshotSpan? snapshotSpanToClone = null; string preMergeDocumentTextString = null; var preMergeDocumentText = preMergeDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var snapshot = preMergeDocumentText.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { textBufferCloneService = preMergeDocument.Project.Solution.Workspace.Services.GetService<ITextBufferCloneService>(); if (textBufferCloneService != null) { snapshotSpanToClone = snapshot.GetFullSpan(); } } if (snapshotSpanToClone == null) { preMergeDocumentTextString = preMergeDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(); } foreach (var replacement in relevantReplacements) { var buffer = snapshotSpanToClone.HasValue ? textBufferCloneService.Clone(snapshotSpanToClone.Value) : _textBufferFactoryService.CreateTextBuffer(preMergeDocumentTextString, contentType); var trackingSpan = buffer.CurrentSnapshot.CreateTrackingSpan(replacement.NewSpan.ToSpan(), SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward); using (var edit = _subjectBuffer.CreateEdit(EditOptions.None, null, s_calculateMergedSpansEditTag)) { foreach (var change in textDiffService.GetTextChangesAsync(preMergeDocument, postMergeDocument, cancellationToken).WaitAndGetResult(cancellationToken)) { buffer.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } yield return new InlineRenameReplacement(replacement.Kind, replacement.OriginalSpan, trackingSpan.GetSpan(buffer.CurrentSnapshot).Span.ToTextSpan()); } } private static RenameSpanKind GetRenameSpanKind(InlineRenameReplacementKind kind) { switch (kind) { case InlineRenameReplacementKind.NoConflict: case InlineRenameReplacementKind.ResolvedReferenceConflict: return RenameSpanKind.Reference; case InlineRenameReplacementKind.ResolvedNonReferenceConflict: return RenameSpanKind.None; case InlineRenameReplacementKind.UnresolvedConflict: return RenameSpanKind.UnresolvedConflict; case InlineRenameReplacementKind.Complexified: return RenameSpanKind.Complexified; default: throw ExceptionUtilities.Unreachable; } } private struct SelectionTracking : IDisposable { private readonly int? _anchor; private readonly int? _active; private readonly TextSpan _anchorSpan; private readonly TextSpan _activeSpan; private readonly OpenTextBufferManager _openTextBufferManager; public SelectionTracking(OpenTextBufferManager openTextBufferManager) { _openTextBufferManager = openTextBufferManager; _anchor = null; _anchorSpan = default(TextSpan); _active = null; _activeSpan = default(TextSpan); var textView = openTextBufferManager.ActiveTextview; if (textView == null) { return; } var selection = textView.Selection; var snapshot = openTextBufferManager._subjectBuffer.CurrentSnapshot; var containingSpans = openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Select(kvp => { // GetSpanInView() can return an empty collection if the tracking span isn't mapped to anything // in the current view, specifically a `@model SomeModelClass` directive in a Razor file. var ss = textView.GetSpanInView(kvp.Value.TrackingSpan.GetSpan(snapshot)).FirstOrDefault(); if (ss != null && (ss.IntersectsWith(selection.ActivePoint.Position) || ss.IntersectsWith(selection.AnchorPoint.Position))) { return Tuple.Create(kvp.Key, ss); } else { return null; } }).WhereNotNull(); foreach (var tuple in containingSpans) { if (tuple.Item2.IntersectsWith(selection.AnchorPoint.Position)) { _anchor = tuple.Item2.End - selection.AnchorPoint.Position; _anchorSpan = tuple.Item1; } if (tuple.Item2.IntersectsWith(selection.ActivePoint.Position)) { _active = tuple.Item2.End - selection.ActivePoint.Position; _activeSpan = tuple.Item1; } } } public void Dispose() { var textView = _openTextBufferManager.ActiveTextview; if (textView == null) { return; } if (_anchor.HasValue || _active.HasValue) { var selection = textView.Selection; var snapshot = _openTextBufferManager._subjectBuffer.CurrentSnapshot; var anchorSpan = _anchorSpan; var anchorPoint = new VirtualSnapshotPoint(textView.TextSnapshot, _anchor.HasValue && _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Keys.Any(s => s.OverlapsWith(anchorSpan)) ? GetNewEndpoint(_anchorSpan) - _anchor.Value : selection.AnchorPoint.Position); var activeSpan = _activeSpan; var activePoint = new VirtualSnapshotPoint(textView.TextSnapshot, _active.HasValue && _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Keys.Any(s => s.OverlapsWith(activeSpan)) ? GetNewEndpoint(_activeSpan) - _active.Value : selection.ActivePoint.Position); textView.SetSelection(anchorPoint, activePoint); } } private SnapshotPoint GetNewEndpoint(TextSpan span) { var snapshot = _openTextBufferManager._subjectBuffer.CurrentSnapshot; var endPoint = _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.ContainsKey(span) ? _openTextBufferManager._referenceSpanToLinkedRenameSpanMap[span].TrackingSpan.GetEndPoint(snapshot) : _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.First(kvp => kvp.Key.OverlapsWith(span)).Value.TrackingSpan.GetEndPoint(snapshot); return _openTextBufferManager.ActiveTextview.BufferGraph.MapUpToBuffer(endPoint, PointTrackingMode.Positive, PositionAffinity.Successor, _openTextBufferManager.ActiveTextview.TextBuffer).Value; } } } } }
// Copyright 2014 Adrian Chlubek. This file is part of GTA Multiplayer IV project. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. using SharpDX; namespace MIVSDK { public enum ClientState { Invalid, Disconnected, Disconnecting, Initializing, Connecting, Connected, Streaming } public enum Commands { Invalid, Connect, Disconnect, UpdateData, PostChatMessage, ServerInfo, GetServerName, InfoPlayerName, Chat_clear, Chat_writeLine, Chat_sendMessage, Player_setPosition, Player_warpIntoVehicle, Player_setHeading, Player_setModel, Player_setVelocity, Player_setHealth, Player_damage, Player_freeze, Player_unfreeze, Player_setVirtualWorld, Player_setVehicleHealth, Player_giveWeapon, Client_JSEval, Client_JSGetValue, Global_setPlayerName, Global_setPlayerModel, Global_setPlayerPedText, Global_createPlayer, Global_removePlayer, Vehicle_setPosition, Vehicle_create, Vehicle_setModel, Vehicle_setVelocity, Vehicle_setOrientation, Vehicle_removePeds, Vehicle_repair, Vehicle_repaint, Vehicle_setVirtualWorld, Vehicle_damage, Vehicle_setHealth, TextView_create, TextView_destroy, TextView_update, TextureView_create, TextureView_destroy, TextureView_update, LineView_create, LineView_destroy, LineView_update, RectangleView_create, RectangleView_destroy, RectangleView_update, Client_setVirtualWorld, Client_setGfxInterval, Client_setBrodcastInterval, Client_setSlowInterval, Client_pauseBroadcast, Client_resumeBroadcast, Client_clearChat, Client_consoleWrite, Client_enableUDPTunnel, Client_ping, Game_fadeScreenIn, Game_fadeScreenOut, Game_showLoadingScreen, Game_hideLoadingScreen, Game_setGravity, Game_setWeather, Game_setGameTime, NPCDialog_show, NPCDialog_hide, NPCDialog_sendResponse, NPC_create, NPC_destroy, NPC_update, NPC_walkTo, NPC_driveTo, NPC_runTo, NPC_followPlayer, NPC_shootAt, NPC_setPosition, NPC_setHeading, NPC_setName, NPC_setModel, NPC_setWeapon, NPC_setImmortal, NPC_enterVehicle, NPC_leaveVehicle, NPC_playAnimation, NPC_setVirtualWorld, Camera_setPosition, Camera_getPosition, Camera_setDirection, Camera_getDirection, Camera_setOrientation, Camera_getOrientation, Camera_setFOV, Camera_getFOV, Camera_lookAt, Camera_reset, Camera_moveSmooth, InternalClient_requestSpawn, InternalClient_finishSpawn, Request_getSelectedPlayer, Request_getCameraPosition, Request_getCameraDirection, Request_isObjectVisible, Request_worldToScreen, Keys_down, Keys_up, } public enum PlayerState { None = 0, IsAiming = 1, IsShooting = 2, IsCrouching = 4, IsJumping = 8, IsRagdoll = 16, IsPassenger1 = 32, IsPassenger2 = 64, IsPassenger3 = 128, } public enum VehicleState { None = 0, IsAccelerating = 1, IsBraking = 2, IsSterringLeft = 4, IsSterringRight = 8, IsAsPassenger = 16, IsEnteringVehicle = 32, IsSprinting = 64, IsClimbing = 128, } public class UpdateDataStruct { public bool client_has_been_set; public float pos_x, pos_y, pos_z, rot_x, rot_y, rot_z, rot_a, vel_x, vel_y, vel_z, camdir_x, camdir_y, camdir_z, heading; public PlayerState state; public long timestamp; public uint vehicle_id; public int vehicle_model, ped_health, vehicle_health, weapon; public VehicleState vstate; public static UpdateDataStruct Zero { get { return new UpdateDataStruct() { pos_x = 0, pos_y = 0, pos_z = 0, rot_x = 0, rot_y = 0, rot_z = 0, rot_a = 0, heading = 0, ped_health = 0, vehicle_health = 0, vehicle_id = 0, vehicle_model = 0, vel_x = 0, vel_y = 0, vel_z = 0, camdir_x = 0, camdir_y = 0, camdir_z = 0, state = PlayerState.None, vstate = VehicleState.None, client_has_been_set = false }; } set { } } public Quaternion getOrientationQuaternion() { return new Quaternion(rot_x, rot_y, rot_z, rot_a); } public Vector3 getPositionVector() { return new Vector3(pos_x, pos_y, pos_z); } public Vector3 getCameraDirection() { return new Vector3(camdir_x, camdir_y, camdir_z); } public Vector3 getVelocityVector() { return new Vector3(vel_x, vel_y, vel_z); } } }
using System; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Reflection; using System.Text; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using log4net; using WaterOneFlowImpl; using WaterOneFlowImpl.v1_0; using VariableParam = WaterOneFlowImpl.VariableParam; using tableSpace = WaterOneFlow.odm.v1_1.VariablesDatasetTableAdapters; namespace WaterOneFlow.odws { using WaterOneFlow.Schema.v1; using WaterOneFlow.odm.v1_1; using UnitsTableAdapter = tableSpace.UnitsTableAdapter; using VariablesTableAdapter = tableSpace.VariablesTableAdapter; using CategoriesTableAdapter = tableSpace.CategoriesTableAdapter; using VariablesRow = WaterOneFlow.odm.v1_1.VariablesDataset.VariablesRow; /// <summary> /// Summary description for ODvariables /// </summary> public class ODvariables { private static readonly ILog log = LogManager.GetLogger(typeof (ODvariables)); /// <summary> /// In order to use this class, an application variable must be set. /// 'ODNetworkID' type=int. /// where the int, is the networkID in the t_network table. /// /// </summary> public ODvariables() { // // TODO: Add constructor logic here // } /// <summary> /// Returns a VariablesDataSet, as defined by VariablesDataSet.xsd /// /// In SDSC code, this variable is loaded once, and is stored in an /// Application, or AppServer variable, and queries are run against the stored dataset. /// Other methods in this class are used to query the dataset. /// /// In order to use this method, an application variable must be set. /// 'ODNetworkID' type=int. /// where the int, is the networkID in the t_network table. /// </summary> /// <returns></returns> public static VariablesDataset GetVariableDataSet() { int networkID; // Could ingore this, and just fill with all try { networkID = Convert.ToInt32( System.Configuration.ConfigurationManager.AppSettings["ODNetworkID"] ); } catch (Exception e) { throw new WaterOneFlowServerException( "Application Setting 'ODNetworkID' is missing, or is not an integer. Please add or correct 'ODNetworkID'."); } return GetVariableDataSet(networkID); } /// <summary> /// Returns a VariablesDataSet, as defined by VariablesDataSet.xsd /// /// In SDSC code, this variable is loaded once, and is stored in an /// Application, or AppServer variable, and queries are run against the stored dataset. /// Other methods in this class are used to query the dataset. /// </summary> /// <param name="networkID"></param> /// <returns></returns> public static VariablesDataset GetVariableDataSet(int networkID) { VariablesDataset ds = new VariablesDataset(); UnitsTableAdapter unitTableAdapter = new UnitsTableAdapter(); VariablesTableAdapter varsTableAdapter = new VariablesTableAdapter(); unitTableAdapter.Connection.ConnectionString = Config.ODDB(); varsTableAdapter.Connection.ConnectionString = Config.ODDB(); try { unitTableAdapter.Fill(ds.Units); varsTableAdapter.Fill(ds.Variables); } catch (Exception e) { log.Fatal("Cannot retrieve units or variables from database" + e.Message); // + unitTableAdapter.Connection.DataSource throw new WaterOneFlowServerException("Cannot retrieve units or variables from database", e); } GetCategories(ds); return ds; } /// <summary> /// Add catagories for each one of the variableID's /// </summary> /// <param name="ds"></param> /// <returns></returns> public static void GetCategories(VariablesDataset ds) { if (ds != null) { CategoriesTableAdapter categoriesTableAdapter = new CategoriesTableAdapter(); ds.Categories.Clear(); //foreach (VariablesRow vRow in ds.Variables.Rows) //{ // categoriesTableAdapter.FillByVariableID(ds.Categories, vRow.VariableID); //} } } public static VariableInfoType[] getVariable(VariableParam vParam, VariablesDataset ds) { List<VariableInfoType> vars = new List<VariableInfoType>(); if (vParam != null) { /* need to use a data view, so the we can set a filter that does not effect the whole dataset DataView has a ToTable method that is uses to create a new DS, and fill * a new VariablesDataset. Typed Datasets are useful ;) */ DataView view = new DataView(); view.Table = ds.Tables["Variables"]; if (vParam.IsId) { view.RowFilter = "VariableID = " + vParam.Code + " "; } else { view.RowFilter = "VariableCode = '" + vParam.Code + "' "; // list of possible options. Allowing any will break the query (aka QualityControlLevelID, etc) String[] options = {"samplemedium", "datatype", "valuetype"}; foreach (string opt in options) { if (vParam.options.ContainsKey(opt)) { if (!String.IsNullOrEmpty(vParam.options[opt])) { String rowFilter = view.RowFilter + " AND " + opt + "='" + vParam.options[opt] + "'"; view.RowFilter = rowFilter; } } } } DataTable v = view.ToTable(); if (v.Rows.Count > 0) { VariablesDataset vtemp = new VariablesDataset(); vtemp.Variables.Merge(v); foreach (VariablesDataset.VariablesRow row in vtemp.Variables.Rows) { VariableInfoType result = rowToVariableInfoType(row, ds ); vars.Add(result); } return vars.ToArray(); } else { return null; } } else { return null; } } public static VariableInfoType[] getVariables(VariableParam[] vParams, VariablesDataset ds) { List<VariableInfoType> vit = new List<VariableInfoType>(); // if there are no variableParameters, return all varaibles if (vParams == null || vParams.Length == 0) { foreach (VariablesDataset.VariablesRow row in ds.Variables.Rows) { VariableInfoType result = rowToVariableInfoType(row, ds ); vit.Add(result); } return vit.ToArray(); } else { foreach (VariableParam vParam in vParams) { VariableInfoType[] vars = getVariable(vParam, ds); if (vars != null) vit.AddRange(vars); } return vit.ToArray(); } } /// <summary> /// Gets the variables. /// used to test the variable datatable. /// </summary> /// <returns></returns> public static VariableInfoType[] GetVariables() { List<VariableInfoType> vars = new List<VariableInfoType>(); VariablesDataset ds = GetVariableDataSet(); foreach (VariablesDataset.VariablesRow row in ds.Variables) { VariableInfoType vit = rowToVariableInfoType(row, ds); vars.Add(vit); } return vars.ToArray(); } /// <summary> /// Returns the variable associated with a variableID /// /// Note: this will only return one value... and only one value. /// </summary> /// <param name="variableID"></param> /// <param name="ds"></param> /// <returns></returns> public static VariableInfoType GetVariableByID(Nullable<int> variableID, VariablesDataset ds) { VariableInfoType[] vit; if (variableID.HasValue) { vit = GetVariablesByID(new int[] {variableID.Value}, ds); } else { vit = GetVariablesByID(new int[] {}, ds); } if (vit == null) { return null; } else { // there should only be one, and only one value with a variable ID. if (vit.Length == 1) { return vit[0]; } else { return vit[0]; // TODO throw error } } } public static VariableInfoType[] GetVariablesByID(int[] variableIDs, VariablesDataset ds) { List<VariableInfoType> vars = new List<VariableInfoType>(); if (variableIDs.Length == 0) { foreach (VariablesDataset.VariablesRow row in ds.Variables.Rows) { VariableInfoType result = rowToVariableInfoType(row, ds ); vars.Add(result); } return vars.ToArray(); } else { StringBuilder sBuilder = new StringBuilder("("); int i = 0; foreach (int s in variableIDs) { if (i > 0) sBuilder.Append(","); sBuilder.Append("'"); sBuilder.Append(s.ToString()); sBuilder.Append("'"); i++; } sBuilder.Append(")"); //DataRow dr = ds.Tables["variables"].Select("variableCode = " + vCode); DataRow[] dr = ds.Tables["variables"].Select("variableID IN " + sBuilder.ToString()); if (dr.Length > 0) { foreach (DataRow row in dr) { VariableInfoType result = rowToVariableInfoType(( VariablesDataset.VariablesRow) row, ds ); vars.Add(result); } return vars.ToArray(); } else { return null; } } } /// <summary> /// Builds a VariableInfoType from a dataset row /// the dataSet is stored in the NWISService variableDataSet. /// Find the rwo you want with the command: /// /// and convert. /// </summary> /// <param name="row"></param> /// <returns></returns> public static VariableInfoType rowToVariableInfoType(VariablesDataset.VariablesRow row, VariablesDataset ds) { units aUnit = null; aUnit = getUnitsElement(row.VariableUnitsID, ds); String vCode = !String.IsNullOrEmpty(row.VariableCode) ? row.VariableCode : null; int vid = row.VariableID; // appSetting['vocabulary'] String vocab = System.Configuration.ConfigurationManager.AppSettings["vocabulary"]; String varName = !String.IsNullOrEmpty(row.VariableName) ? row.VariableName : null; VariableInfoType vt = CuahsiBuilder.CreateVariableInfoType( vid.ToString(), vocab, vCode, varName, null, //variable description aUnit ); // add time support vt.timeSupport = new VariableInfoTypeTimeSupport(); if (row.IsRegular) { vt.timeSupport.isRegular = true; vt.timeSupport.isRegularSpecified = true; vt.timeSupport.timeInterval = Convert.ToInt32(row.TimeSupport); vt.timeSupport.timeIntervalSpecified = true; // this is different that the other "units", so populate by code units tUnit = getUnitsElement(row.TimeUnitsID, ds); if (tUnit != null) { vt.timeSupport.unit = new UnitsType(); vt.timeSupport.unit.UnitID = int.Parse(tUnit.unitsCode); vt.timeSupport.unit.UnitIDSpecified = true; vt.timeSupport.unit.UnitDescription = tUnit.Value; vt.timeSupport.unit.UnitAbbreviation = tUnit.unitsAbbreviation; if (tUnit.unitsTypeSpecified) { // if it's specified in the units, then it's a valid enum vt.timeSupport.unit.UnitType = tUnit.unitsType; vt.timeSupport.unit.UnitTypeSpecified = true; } } } else { vt.timeSupport.isRegular = false; vt.timeSupport.isRegularSpecified = true; } CuahsiBuilder.SetEnumFromText(vt, row, "valueType", typeof (valueTypeEnum)); CuahsiBuilder.SetEnumFromText(vt, row, "sampleMedium", typeof (SampleMediumEnum)); CuahsiBuilder.SetEnumFromText(vt, row, "dataType", typeof (dataTypeEnum)); CuahsiBuilder.SetEnumFromText(vt, row, "generalCategory", typeof (generalCategoryEnum)); // if (!String.IsNullOrEmpty(row.NoDataValue)) { vt.NoDataValue = row.NoDataValue.ToString(); // } return vt; } public static units getUnitsElement(int unitsID, VariablesDataset ds) { DataRow[] dr = ds.Tables["units"].Select("unitsID = " + unitsID); if (dr.Length > 0) { VariablesDataset.UnitsRow row = (VariablesDataset.UnitsRow) dr[0]; string uID = row.UnitsID.ToString(); string unitType = String.IsNullOrEmpty(row.UnitsType) ? null : row.UnitsType; string unitAbbrev = String.IsNullOrEmpty(row.UnitsAbbreviation) ? null : row.UnitsAbbreviation; string unitName = String.IsNullOrEmpty(row.UnitsName) ? null : row.UnitsName; units u = CuahsiBuilder.CreateUnitsElement(null, uID, unitAbbrev, unitName); CuahsiBuilder.SetEnumFromText(u, row, "unitsType", typeof (UnitsTypeEnum)); return u; } else { return null; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using hw.DebugFormatter; using hw.Helper; using JetBrains.Annotations; namespace hw.Debug { /// <summary> Summary description for Tracer. </summary> public static class Tracer { static readonly Writer _writer = new Writer(); public static readonly Dumper Dumper = new Dumper(); [UsedImplicitly] public static bool IsBreakDisabled; /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="sf"> the stack frame where the location is stored </param> /// <param name="tag"> </param> /// <returns> the "FileName(lineNumber,ColNr): tag: " string </returns> public static string FilePosn(this StackFrame sf, FilePositionTag tag) { if(sf.GetFileLineNumber() == 0) return "<nofile> " + tag; return FilePosn(sf.GetFileName(), sf.GetFileLineNumber() - 1, sf.GetFileColumnNumber(), tag); } /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="fileName"> asis </param> /// <param name="lineNumber"> asis </param> /// <param name="columnNumber"> asis </param> /// <param name="tag"> asis </param> /// <returns> the "fileName(lineNumber,columnNumber): tag: " string </returns> public static string FilePosn(string fileName, int lineNumber, int columnNumber, FilePositionTag tag) { var tagText = tag.ToString(); return FilePosn(fileName, lineNumber, columnNumber, tagText); } /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="fileName"> asis </param> /// <param name="lineNumber"> asis </param> /// <param name="columnNumber"> asis </param> /// <param name="tagText"> asis </param> /// <returns> the "fileName(lineNumber,columnNumber): tag: " string </returns> public static string FilePosn(string fileName, int lineNumber, int columnNumber, string tagText) { return fileName + "(" + (lineNumber + 1) + "," + columnNumber + "): " + tagText + ": "; } /// <summary> /// creates a string to inspect a method /// </summary> /// <param name="m"> the method </param> /// <param name="showParam"> controls if parameter list is appended </param> /// <returns> string to inspect a method </returns> public static string DumpMethod(this MethodBase m, bool showParam) { var result = m.DeclaringType.PrettyName() + "."; result += m.Name; if(!showParam) return result; if(m.IsGenericMethod) { result += "<"; result += m.GetGenericArguments().Select(t => t.PrettyName()).Stringify(", "); result += ">"; } result += "("; for(int i = 0, n = m.GetParameters().Length; i < n; i++) { if(i != 0) result += ", "; var p = m.GetParameters()[i]; result += p.ParameterType.PrettyName(); result += " "; result += p.Name; } result += ")"; return result; } /// <summary> /// creates a string to inspect the method call contained in current call stack /// </summary> /// <param name="stackFrameDepth"> the index of stack frame </param> /// <param name="tag"> </param> /// <param name="showParam"> controls if parameter list is appended </param> /// <returns> string to inspect the method call </returns> public static string MethodHeader(FilePositionTag tag = FilePositionTag.Debug, bool showParam = false, int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return FilePosn(sf, tag) + DumpMethod(sf.GetMethod(), showParam); } public static string CallingMethodName(int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return DumpMethod(sf.GetMethod(), false); } [UsedImplicitly] public static string StackTrace(FilePositionTag tag, int stackFrameDepth = 0) { var stackTrace = new StackTrace(true); var result = ""; for(var i = stackFrameDepth + 1; i < stackTrace.FrameCount; i++) { var stackFrame = stackTrace.GetFrame(i); var filePosn = FilePosn(stackFrame, tag) + DumpMethod(stackFrame.GetMethod(), false); result += "\n" + filePosn; } return result; } /// <summary> /// write a line to debug output /// </summary> /// <param name="s"> the text </param> public static void Line(string s) { _writer.ThreadSafeWrite(s, true); } /// <summary> /// write a line to debug output /// </summary> /// <param name="s"> the text </param> public static void LinePart(string s) { _writer.ThreadSafeWrite(s, false); } /// <summary> /// write a line to debug output, flagged with FileName(lineNumber,ColNr): Method (without parameter list) /// </summary> /// <param name="s"> the text </param> /// <param name="flagText"> </param> /// <param name="showParam"></param> /// <param name="stackFrameDepth"> The stack frame depth. </param> public static void FlaggedLine(string s, FilePositionTag flagText = FilePositionTag.Debug, bool showParam = false, int stackFrameDepth = 0) { Line(MethodHeader(flagText, stackFrameDepth: stackFrameDepth + 1, showParam:showParam) + " " + s); } /// <summary> /// generic dump function by use of reflection /// </summary> /// <param name="target"> the object to dump </param> /// <returns> </returns> public static string Dump(object target) { return Dumper.Dump(target); } /// <summary> /// generic dump function by use of reflection /// </summary> /// <param name="target"> the object to dump </param> /// <returns> </returns> public static string DumpData(object target) { if(target == null) return ""; return Dumper.DumpData(target); } /// <summary> /// creates a string to inspect the method call contained in stack. Runtime parameters are dumped too. /// </summary> /// <param name="parameter"> parameter objects list for the frame </param> public static void DumpStaticMethodWithData(params object[] parameter) { var result = DumpMethodWithData("", null, parameter, 1); Line(result); } internal static string DumpMethodWithData(string text, object thisObject, object[] parameter, int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return FilePosn(sf, FilePositionTag.Debug) + (DumpMethod(sf.GetMethod(), true)) + text + DumpMethodWithData(sf.GetMethod(), thisObject, parameter).Indent(); } /// <summary> /// Dumps the data. /// </summary> /// <param name="text"> The text. </param> /// <param name="data"> The data, as name/value pair. </param> /// <param name="stackFrameDepth"> The stack stackFrameDepth. </param> /// <returns> </returns> public static string DumpData(string text, object[] data, int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return FilePosn(sf, FilePositionTag.Debug) + DumpMethod(sf.GetMethod(), true) + text + DumpMethodWithData(null, data).Indent(); } static string DumpMethodWithData(MethodBase m, object o, object[] p) { var result = "\n"; result += "this="; result += Dump(o); result += "\n"; result += DumpMethodWithData(m.GetParameters(), p); return result; } static string DumpMethodWithData(ParameterInfo[] infos, object[] p) { var result = ""; var n = 0; if(infos != null) n = infos.Length; for(var i = 0; i < n; i++) { if(i > 0) result += "\n"; Assert(infos != null); Assert(infos[i] != null); result += infos[i].Name; result += "="; result += Dump(p[i]); } for(var i = n; i < p.Length; i += 2) { result += "\n"; result += (string) p[i]; result += "="; result += Dump(p[i + 1]); } return result; } /// <summary> /// Function used for condition al break /// </summary> /// <param name="cond"> The cond. </param> /// <param name="getText"> The data. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> /// <returns> </returns> [DebuggerHidden] public static void ConditionalBreak(string cond, Func<string> getText = null, int stackFrameDepth = 0) { var result = "Conditional break: " + cond + "\nData: " + (getText == null ? "" : getText()); FlaggedLine(result, stackFrameDepth: stackFrameDepth + 1); TraceBreak(); } /// <summary> /// Check boolean expression /// </summary> /// <param name="b"> /// if set to <c>true</c> [b]. /// </param> /// <param name="getText"> The text. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> [DebuggerHidden] public static void ConditionalBreak(bool b, Func<string> getText = null, int stackFrameDepth = 0) { if(b) ConditionalBreak("", getText, stackFrameDepth + 1); } /// <summary> /// Throws the assertion failed. /// </summary> /// <param name="cond"> The cond. </param> /// <param name="getText"> The data. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> /// created 15.10.2006 18:04 [DebuggerHidden] public static void ThrowAssertionFailed(string cond, Func<string> getText = null, int stackFrameDepth = 0) { var result = AssertionFailed(cond, getText, stackFrameDepth + 1); throw new AssertionFailedException(result); } /// <summary> /// Function used in assertions /// </summary> /// <param name="cond"> The cond. </param> /// <param name="getText"> The data. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> /// <returns> </returns> [DebuggerHidden] public static string AssertionFailed(string cond, Func<string> getText = null, int stackFrameDepth = 0) { var result = "Assertion Failed: " + cond + "\nData: " + (getText == null ? "" : getText()); FlaggedLine(result, stackFrameDepth: stackFrameDepth + 1); AssertionBreak(result); return result; } /// <summary> /// Check boolean expression /// </summary> /// <param name="b"> /// if set to <c>true</c> [b]. /// </param> /// <param name="getText"> The text. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> [DebuggerHidden] [ContractAnnotation("b: false => halt")] public static void Assert(bool b, Func<string> getText = null, int stackFrameDepth = 0) { if(b) return; AssertionFailed("", getText, stackFrameDepth + 1); } [DebuggerHidden] [ContractAnnotation("b: false => halt")] public static void Assert(bool b, string s) { Assert(b, () => s, 1); } sealed class AssertionFailedException : Exception { public AssertionFailedException(string result) : base(result) { } } sealed class BreakException : Exception {} [DebuggerHidden] static void AssertionBreak(string result) { if(!Debugger.IsAttached || IsBreakDisabled) throw new AssertionFailedException(result); Debugger.Break(); } [UsedImplicitly] [DebuggerHidden] public static void TraceBreak() { if(!Debugger.IsAttached) return; if(IsBreakDisabled) throw new BreakException(); Debugger.Break(); } public static int CurrentFrameCount(int stackFrameDepth) { return new StackTrace(true).FrameCount - stackFrameDepth; } [DebuggerHidden] public static void LaunchDebugger() { Debugger.Launch(); } public static void IndentStart() { _writer.IndentStart(); } public static void IndentEnd() { _writer.IndentEnd(); } } public enum FilePositionTag { Debug, Output, Query, Test, Profiler } interface IDumpExceptAttribute { bool IsException(object target); } public abstract class DumpAttributeBase : Attribute {} }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a snapshot. /// </summary> public partial class Snapshot { private string _dataEncryptionKeyId; private string _description; private bool? _encrypted; private string _kmsKeyId; private string _ownerAlias; private string _ownerId; private string _progress; private string _snapshotId; private DateTime? _startTime; private SnapshotState _state; private string _stateMessage; private List<Tag> _tags = new List<Tag>(); private string _volumeId; private int? _volumeSize; /// <summary> /// Gets and sets the property DataEncryptionKeyId. /// <para> /// The data encryption key identifier for the snapshot. This value is a unique identifier /// that corresponds to the data encryption key that was used to encrypt the original /// volume or snapshot copy. Because data encryption keys are inherited by volumes created /// from snapshots, and vice versa, if snapshots share the same data encryption key identifier, /// then they belong to the same volume/snapshot lineage. This parameter is only returned /// by the <a>DescribeSnapshots</a> API operation. /// </para> /// </summary> public string DataEncryptionKeyId { get { return this._dataEncryptionKeyId; } set { this._dataEncryptionKeyId = value; } } // Check to see if DataEncryptionKeyId property is set internal bool IsSetDataEncryptionKeyId() { return this._dataEncryptionKeyId != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description for the snapshot. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property Encrypted. /// <para> /// Indicates whether the snapshot is encrypted. /// </para> /// </summary> public bool Encrypted { get { return this._encrypted.GetValueOrDefault(); } set { this._encrypted = value; } } // Check to see if Encrypted property is set internal bool IsSetEncrypted() { return this._encrypted.HasValue; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The full ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) /// that was used to protect the volume encryption key for the parent volume. /// </para> /// </summary> public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property OwnerAlias. /// <para> /// The AWS account alias (for example, <code>amazon</code>, <code>self</code>) or AWS /// account ID that owns the snapshot. /// </para> /// </summary> public string OwnerAlias { get { return this._ownerAlias; } set { this._ownerAlias = value; } } // Check to see if OwnerAlias property is set internal bool IsSetOwnerAlias() { return this._ownerAlias != null; } /// <summary> /// Gets and sets the property OwnerId. /// <para> /// The AWS account ID of the EBS snapshot owner. /// </para> /// </summary> public string OwnerId { get { return this._ownerId; } set { this._ownerId = value; } } // Check to see if OwnerId property is set internal bool IsSetOwnerId() { return this._ownerId != null; } /// <summary> /// Gets and sets the property Progress. /// <para> /// The progress of the snapshot, as a percentage. /// </para> /// </summary> public string Progress { get { return this._progress; } set { this._progress = value; } } // Check to see if Progress property is set internal bool IsSetProgress() { return this._progress != null; } /// <summary> /// Gets and sets the property SnapshotId. /// <para> /// The ID of the snapshot. Each snapshot receives a unique identifier when it is created. /// </para> /// </summary> public string SnapshotId { get { return this._snapshotId; } set { this._snapshotId = value; } } // Check to see if SnapshotId property is set internal bool IsSetSnapshotId() { return this._snapshotId != null; } /// <summary> /// Gets and sets the property StartTime. /// <para> /// The time stamp when the snapshot was initiated. /// </para> /// </summary> public DateTime StartTime { get { return this._startTime.GetValueOrDefault(); } set { this._startTime = value; } } // Check to see if StartTime property is set internal bool IsSetStartTime() { return this._startTime.HasValue; } /// <summary> /// Gets and sets the property State. /// <para> /// The snapshot state. /// </para> /// </summary> public SnapshotState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property StateMessage. /// <para> /// Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation /// fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions /// are not obtained) this field displays error state details to help you diagnose why /// the error occurred. This parameter is only returned by the <a>DescribeSnapshots</a> /// API operation. /// </para> /// </summary> public string StateMessage { get { return this._stateMessage; } set { this._stateMessage = value; } } // Check to see if StateMessage property is set internal bool IsSetStateMessage() { return this._stateMessage != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the snapshot. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property VolumeId. /// <para> /// The ID of the volume that was used to create the snapshot. /// </para> /// </summary> public string VolumeId { get { return this._volumeId; } set { this._volumeId = value; } } // Check to see if VolumeId property is set internal bool IsSetVolumeId() { return this._volumeId != null; } /// <summary> /// Gets and sets the property VolumeSize. /// <para> /// The size of the volume, in GiB. /// </para> /// </summary> public int VolumeSize { get { return this._volumeSize.GetValueOrDefault(); } set { this._volumeSize = value; } } // Check to see if VolumeSize property is set internal bool IsSetVolumeSize() { return this._volumeSize.HasValue; } } }
using System.Collections; using System.Collections.Generic; using System.Text; using System; using System.IO; [ProtoBuf.ProtoContract] public class SelectUserInfo : ICommand { [ProtoBuf.ProtoContract] public class t_MapUserSculptProto : ICommand { [ProtoBuf.ProtoMember(1)] public uint dwHorseID { get; set; } [ProtoBuf.ProtoMember(2)] public uint dwHeadID { get; set; } [ProtoBuf.ProtoMember(3)] public uint dwBodyID { get; set; } [ProtoBuf.ProtoMember(4)] public uint dwlegsID { get; set; } [ProtoBuf.ProtoMember(5)] public uint dwhandsID { get; set; } [ProtoBuf.ProtoMember(6)] public uint dwfeetsID { get; set; } [ProtoBuf.ProtoMember(7)] public uint dwWeaponID { get; set; } } [ProtoBuf.ProtoMember(1)] public uint id { get; set; } [ProtoBuf.ProtoMember(2)] public string name { get; set; } [ProtoBuf.ProtoMember(3)] public uint type { get; set; } [ProtoBuf.ProtoMember(4)] public uint level { get; set; } [ProtoBuf.ProtoMember(5)] public uint mapid { get; set; } [ProtoBuf.ProtoMember(6)] public string mapName { get; set; } [ProtoBuf.ProtoMember(7)] public uint country { get; set; } [ProtoBuf.ProtoMember(8)] public uint group { get; set; } [ProtoBuf.ProtoMember(9)] public uint face { get; set; } [ProtoBuf.ProtoMember(10)] public uint hair { get; set; } [ProtoBuf.ProtoMember(11)] public string countryName { get; set; } [ProtoBuf.ProtoMember(12)] public uint bitmask { get; set; } [ProtoBuf.ProtoMember(13)] public uint forbidTime { get; set; } [ProtoBuf.ProtoMember(14)] public uint zone_state { get; set; } [ProtoBuf.ProtoMember(15)] public uint target_zone { get; set; } [ProtoBuf.ProtoMember(16)] public uint acceptPK { get; set; } [ProtoBuf.ProtoMember(17)] public t_MapUserSculptProto sculpt { get; set; } [ProtoBuf.ProtoMember(18)] public uint flatZoneID { get; set; } [ProtoBuf.ProtoMember(19)] public uint gameZoneID { get; set; } [ProtoBuf.ProtoMember(20)] public uint activestar { get; set; } } [ProtoBuf.ProtoContract] public class t_stUserInfoUserCmdProto : ICommand { [ProtoBuf.ProtoMember(1)] public uint version { get; set; } [ProtoBuf.ProtoMember(2)] public SelectUserInfo[] userset { get; set; } } [ProtoBuf.ProtoContract] public class t_stCreateSelectUserCmdProto : ICommand { [ProtoBuf.ProtoMember(1)] public uint version { get; set; } [ProtoBuf.ProtoMember(2)] public string strUserName { get; set; } [ProtoBuf.ProtoMember(3)] public uint jobType { get; set; } [ProtoBuf.ProtoMember(4)] public uint charType { get; set; } [ProtoBuf.ProtoMember(5)] public uint country { get; set; } [ProtoBuf.ProtoMember(6)] public uint suitType { get; set; } [ProtoBuf.ProtoMember(7)] public string strPromoterName { get; set; } } public class stSelectUserCmd : stNullUserCmd { public const uint MAX_CHARINFO = 4; public const byte USERINFO_SELECT_USERCMD_PARA = 1; public const byte CREATE_SELECT_USERCMD_PARA = 2; public const byte LOGIN_SELECT_USERCMD_PARA = 3; public const byte DELETE_SELECT_USERCMD_PARA = 4; public const byte CHECKNAME_SELECT_USERCMD_PARA = 5; public const byte RETURN_DELETE_SELECT_USERCMD_PARA = 6; public const byte RQ_GET_NAME_BY_RAND_PARA = 19; public const byte RT_NAME_BY_RAND_PARA = 20; public stSelectUserCmd() { byCmd = SELECT_USERCMD; } public override void serialize(MemoryStream stream) { base.serialize(stream); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); } } public class stUserInfoUserCmd : stSelectUserCmd { public stUserInfoUserCmd() { byParam = USERINFO_SELECT_USERCMD_PARA; size=0; } public override void serialize(MemoryStream stream) { base.serialize(stream); byte[] bsize =BitConverter.GetBytes(size); stream.Write(bsize,0,bsize.Length); stream.Write(data,0,(int)size); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); byte[] bsize=new byte[4]; stream.Read(bsize,0,4); size = BitConverter.ToUInt32(bsize,0); data= new byte[size]; stream.Read(data,0,(int)size); } public uint size; public byte[] data; } public class stCreateSelectUserCmd : stSelectUserCmd { public stCreateSelectUserCmd() { byParam = CREATE_SELECT_USERCMD_PARA; } public override void serialize(MemoryStream stream) { base.serialize(stream); byte[] bsize =BitConverter.GetBytes(size); stream.Write(bsize,0,bsize.Length); stream.Write(data,0,(int)size); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); byte[] bsize=new byte[4]; stream.Read(bsize,0,4); size = BitConverter.ToUInt32(bsize,0); data= new byte[size]; stream.Read(data,0,(int)size); } public uint size; public byte[] data; } public class stLoginSelectUserCmd : stSelectUserCmd { public stLoginSelectUserCmd() { byParam = LOGIN_SELECT_USERCMD_PARA; charNo=0; } public override void serialize(MemoryStream stream) { base.serialize(stream); byte[] bcharNo =BitConverter.GetBytes(charNo); stream.Write(bcharNo,0,bcharNo.Length); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); byte[] bcharNo=new byte[4]; stream.Read(bcharNo,0,4); charNo = BitConverter.ToUInt32(bcharNo,0); } public uint charNo; } public class stDeleteSelectUserCmd : stSelectUserCmd { public stDeleteSelectUserCmd() { byParam = DELETE_SELECT_USERCMD_PARA; charNo=0; } public override void serialize(MemoryStream stream) { base.serialize(stream); byte[] bcharNo =BitConverter.GetBytes(charNo); stream.Write(bcharNo,0,bcharNo.Length); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); byte[] bcharNo=new byte[4]; stream.Read(bcharNo,0,4); charNo = BitConverter.ToUInt32(bcharNo,0); } public uint charNo; } public class stCheckNameSelectUserCmd : stSelectUserCmd { public stCheckNameSelectUserCmd() { byParam = CHECKNAME_SELECT_USERCMD_PARA; err_code=0; } public override void serialize(MemoryStream stream) { base.serialize(stream); stream.Write(name,0,name.Length); stream.WriteByte(err_code); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); stream.Read(name,0,name.Length); err_code=Convert.ToByte(stream.ReadByte()); } public byte[] name=new byte[MAX_NAMESIZE+1]; public byte err_code; } public class stReturnDeleteSelectUserCmd : stSelectUserCmd { public stReturnDeleteSelectUserCmd() { byParam = RETURN_DELETE_SELECT_USERCMD_PARA; err_code=0; } public override void serialize(MemoryStream stream) { base.serialize(stream); stream.Write(name,0,name.Length); stream.WriteByte(err_code); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); stream.Read(name,0,name.Length); err_code=Convert.ToByte(stream.ReadByte()); } public byte[] name=new byte[MAX_NAMESIZE+1]; public byte err_code; } public class rqGetNameByRandUserCmd : stSelectUserCmd { public rqGetNameByRandUserCmd() { byParam = RQ_GET_NAME_BY_RAND_PARA; sex=0; } public override void serialize(MemoryStream stream) { base.serialize(stream); stream.WriteByte(sex); } public override void unserialize(MemoryStream stream) { base.unserialize(stream); sex=Convert.ToByte(stream.ReadByte()); } public byte sex; }
// 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.Collections.Generic; using System.Reflection.TypeLoading; using RuntimeTypeInfo = System.Reflection.TypeLoading.RoType; namespace System.Reflection.Runtime.BindingFlagSupport { /// <summary> /// This class encapsulates the minimum set of arcane desktop CLR policies needed to implement the Get*(BindingFlags) apis. /// In particular, it encapsulates behaviors such as what exactly determines the "visibility" of a property and event, and /// what determines whether and how they are overridden. /// </summary> internal abstract class MemberPolicies<M> where M : MemberInfo { // Subclasses for specific MemberInfo types must override these: // // Returns all of the directly declared members on the given TypeInfo. // public abstract IEnumerable<M> GetDeclaredMembers(TypeInfo typeInfo); // // Returns all of the directly declared members on the given TypeInfo whose name matches filter. If filter is null, // returns all directly declared members. // public abstract IEnumerable<M> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType); // // Policy to decide whether a member is considered "virtual", "virtual new" and what its member visibility is. // (For "visibility", we reuse the MethodAttributes enum since Reflection lacks an element-agnostic enum for this. // Only the MemberAccessMask bits are set.) // public abstract void GetMemberAttributes(M member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot); // // Policy to decide whether "derivedMember" is a virtual override of "baseMember." Used to implement MethodInfo.GetBaseDefinition(), // parent chain traversal for discovering inherited custom attributes, and suppressing lookup results in the Type.Get*() api family. // // Does not consider explicit overrides (methodimpls.) Does not consider "overrides" of interface methods. // public abstract bool ImplicitlyOverrides(M baseMember, M derivedMember); // // Policy to decide how BindingFlags should be reinterpreted for a given member type. // This is overridden for nested types which all match on any combination Instance | Static and are never inherited. // It is also overridden for constructors which are never inherited. // public virtual BindingFlags ModifyBindingFlags(BindingFlags bindingFlags) { return bindingFlags; } // // Policy to decide if BindingFlags is always interpreted as having set DeclaredOnly. // public abstract bool AlwaysTreatAsDeclaredOnly { get; } // // Policy to decide how or if members in more derived types hide same-named members in base types. // Due to desktop compat concerns, the definitions are a bit more arbitrary than we'd like. // public abstract bool IsSuppressedByMoreDerivedMember(M member, M[] priorMembers, int startIndex, int endIndex); // // Policy to decide whether to throw an AmbiguousMatchException on an ambiguous Type.Get*() call. // Does not apply to GetConstructor/GetMethod/GetProperty calls that have a non-null Type[] array passed to it. // // If method returns true, the Get() api will pick the member that's in the most derived type. // If method returns false, the Get() api throws AmbiguousMatchException. // public abstract bool OkToIgnoreAmbiguity(M m1, M m2); // // Helper method for determining whether two methods are signature-compatible. // protected static bool AreNamesAndSignaturesEqual(MethodInfo method1, MethodInfo method2) { if (method1.Name != method2.Name) return false; ParameterInfo[] p1 = method1.GetParametersNoCopy(); ParameterInfo[] p2 = method2.GetParametersNoCopy(); if (p1.Length != p2.Length) return false; bool isGenericMethod1 = method1.IsGenericMethodDefinition; bool isGenericMethod2 = method2.IsGenericMethodDefinition; if (isGenericMethod1 != isGenericMethod2) return false; if (!isGenericMethod1) { for (int i = 0; i < p1.Length; i++) { Type parameterType1 = p1[i].ParameterType; Type parameterType2 = p2[i].ParameterType; if (!(parameterType1.Equals(parameterType2))) { return false; } } } else { if (method1.GetGenericArguments().Length != method2.GetGenericArguments().Length) return false; for (int i = 0; i < p1.Length; i++) { Type parameterType1 = p1[i].ParameterType; Type parameterType2 = p2[i].ParameterType; if (!GenericMethodAwareAreParameterTypesEqual(parameterType1, parameterType2)) { return false; } } } return true; } // // This helper compares the types of the corresponding parameters of two methods to see if one method is signature equivalent to the other. // This is needed when comparing the signatures of two generic methods as Type.Equals() is not up to that job. // private static bool GenericMethodAwareAreParameterTypesEqual(Type t1, Type t2) { // Fast-path - if Reflection has already deemed them equivalent, we can trust its result. if (t1.Equals(t2)) return true; // If we got here, Reflection determined the types not equivalent. Most of the time, that's the result we want. // There is however, one wrinkle. If the type is or embeds a generic method parameter type, Reflection will always report them // non-equivalent, since generic parameter type comparison always compares both the position and the declaring method. For our purposes, though, // we only want to consider the position. // Fast-path: if the types don't embed any generic parameters, we can go ahead and use Reflection's result. if (!(t1.ContainsGenericParameters && t2.ContainsGenericParameters)) return false; if ((t1.IsArray && t2.IsArray) || (t1.IsByRef && t2.IsByRef) || (t1.IsPointer && t2.IsPointer)) { if (t1.IsSZArray() != t2.IsSZArray()) return false; if (t1.IsArray && (t1.GetArrayRank() != t2.GetArrayRank())) return false; return GenericMethodAwareAreParameterTypesEqual(t1.GetElementType(), t2.GetElementType()); } if (t1.IsConstructedGenericType) { // We can use regular old Equals() rather than recursing into GenericMethodAwareAreParameterTypesEqual() since the // generic type definition will always be a plain old named type and won't embed any generic method parameters. if (!(t1.GetGenericTypeDefinition().Equals(t2.GetGenericTypeDefinition()))) return false; Type[] ga1 = t1.GenericTypeArguments; Type[] ga2 = t2.GenericTypeArguments; if (ga1.Length != ga2.Length) return false; for (int i = 0; i < ga1.Length; i++) { if (!GenericMethodAwareAreParameterTypesEqual(ga1[i], ga2[i])) return false; } return true; } if (t1.IsGenericMethodParameter() && t2.IsGenericMethodParameter()) { // A generic method parameter. The DeclaringMethods will be different but we don't care about that - we can assume that // the declaring method will be the method that declared the parameter's whose type we're testing. We only need to // compare the positions. return t1.GenericParameterPosition == t2.GenericParameterPosition; } // If we got here, either t1 and t2 are different flavors of types or they are both simple named types or both generic type parameters. // Either way, we can trust Reflection's result here. return false; } #pragma warning disable CA1810 // explicit static cctor static MemberPolicies() { Type t = typeof(M); if (t.Equals(typeof(FieldInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Field; Default = (MemberPolicies<M>)(object)(new FieldPolicies()); } else if (t.Equals(typeof(MethodInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Method; Default = (MemberPolicies<M>)(object)(new MethodPolicies()); } else if (t.Equals(typeof(ConstructorInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Constructor; Default = (MemberPolicies<M>)(object)(new ConstructorPolicies()); } else if (t.Equals(typeof(PropertyInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Property; ; Default = (MemberPolicies<M>)(object)(new PropertyPolicies()); } else if (t.Equals(typeof(EventInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Event; Default = (MemberPolicies<M>)(object)(new EventPolicies()); } else if (t.Equals(typeof(Type))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.NestedType; Default = (MemberPolicies<M>)(object)(new NestedTypePolicies()); } else { Debug.Fail("Unknown MemberInfo type."); } } #pragma warning restore CA1810 // // This is a singleton class one for each MemberInfo category: Return the appropriate one. // public static readonly MemberPolicies<M> Default; // // This returns a fixed value from 0 to MemberIndex.Count-1 with each possible type of M // being assigned a unique index (see the MemberTypeIndex for possible values). This is useful // for converting a type reference to M to an array index or switch case label. // public static readonly int MemberTypeIndex; } }
using System; using System.Data; using System.Windows.Forms; using bv.common; using bv.common.Core; using bv.common.win; using bv.common.Objects; using bv.winclient.BasePanel; using DevExpress.Utils; using System.Collections; using bv.winclient.Core; using eidss.model.Enums; namespace EIDSS { /// <summary> /// Summary description for ObjectTypeList. /// </summary> public class ObjectTypeList : BaseDetailForm { //private bool configuratorMode=false; private ObjectTypeList_DB typedDBLevel = null; //Hashtable relations=new Hashtable(); private DataView MainView; //private Hashtable checks=new Hashtable(); private static System.Windows.Forms.Control m_Parent = null; private System.Windows.Forms.Label label1; private DevExpress.XtraEditors.LookUpEdit lookUpEdit1; private DevExpress.XtraEditors.SimpleButton simpleButton2; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView2; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn4; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit relationLookUpEdit; private DevExpress.XtraEditors.Repository.RepositoryItemComboBox repositoryItemComboBox1; public ObjectTypeList() { InitializeComponent(); this.AuditObject = new bv.common.Objects.AuditObject((long)EIDSSAuditObject.daoDataAccess, (long)AuditTable.tstObjectAccess); this.PermissionObject = eidss.model.Enums.EIDSSPermissionObject.DataAccess; this.Permissions = new StandardAccessPermissions( PermissionHelper.SelectPermission (eidss.model.Enums.EIDSSPermissionObject.DataAccess), PermissionHelper.SelectPermission (eidss.model.Enums.EIDSSPermissionObject.DataAccess), PermissionHelper.SelectPermission (eidss.model.Enums.EIDSSPermissionObject.DataAccess), PermissionHelper.DeletePermission (eidss.model.Enums.EIDSSPermissionObject.DataAccess), PermissionHelper.ExecutePermission (eidss.model.Enums.EIDSSPermissionObject.DataAccess) ); //this.configuratorMode = eidss.model.Core.EidssUserContext.User.HasPermission(PermissionHelper.InsertPermission(eidss.model.Enums.EIDSSPermissionObject.DataAccess)); this.typedDBLevel = new ObjectTypeList_DB(); this.DbService = this.typedDBLevel; } #region Designer private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ObjectTypeList)); this.label1 = new System.Windows.Forms.Label(); this.lookUpEdit1 = new DevExpress.XtraEditors.LookUpEdit(); this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView2 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn(); this.relationLookUpEdit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemComboBox1 = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox(); ((System.ComponentModel.ISupportInitialize)(this.lookUpEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.relationLookUpEdit)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemComboBox1)).BeginInit(); this.SuspendLayout(); bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(ObjectTypeList), out resources); // Form Is Localizable: True // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // lookUpEdit1 // resources.ApplyResources(this.lookUpEdit1, "lookUpEdit1"); this.lookUpEdit1.Name = "lookUpEdit1"; this.lookUpEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("lookUpEdit1.Properties.Buttons"))))}); this.lookUpEdit1.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo(resources.GetString("lookUpEdit1.Properties.Columns"), resources.GetString("lookUpEdit1.Properties.Columns1"), ((int)(resources.GetObject("lookUpEdit1.Properties.Columns2"))), ((DevExpress.Utils.FormatType)(resources.GetObject("lookUpEdit1.Properties.Columns3"))), resources.GetString("lookUpEdit1.Properties.Columns4"), ((bool)(resources.GetObject("lookUpEdit1.Properties.Columns5"))), ((DevExpress.Utils.HorzAlignment)(resources.GetObject("lookUpEdit1.Properties.Columns6"))), ((DevExpress.Data.ColumnSortOrder)(resources.GetObject("lookUpEdit1.Properties.Columns7"))))}); this.lookUpEdit1.Properties.DisplayMember = "ParentName"; this.lookUpEdit1.Properties.ShowHeader = false; this.lookUpEdit1.Properties.ValueMember = "idfsParentBaseReference"; this.lookUpEdit1.Tag = "{alwayseditable}"; this.lookUpEdit1.EditValueChanged += new System.EventHandler(this.lookUpEdit1_EditValueChanged); // // simpleButton2 // resources.ApplyResources(this.simpleButton2, "simpleButton2"); this.simpleButton2.Image = global::EIDSS_ObjectAccess.Properties.Resources.Permissions__small__67_; this.simpleButton2.Name = "simpleButton2"; this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click); // // gridControl1 // resources.ApplyResources(this.gridControl1, "gridControl1"); this.gridControl1.MainView = this.gridView2; this.gridControl1.Name = "gridControl1"; this.gridControl1.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.repositoryItemComboBox1, this.relationLookUpEdit}); this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView2}); // // gridView2 // this.gridView2.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.gridColumn1, this.gridColumn4}); this.gridView2.GridControl = this.gridControl1; this.gridView2.Name = "gridView2"; this.gridView2.OptionsView.ShowGroupPanel = false; // // gridColumn1 // this.gridColumn1.AppearanceHeader.Font = ((System.Drawing.Font)(resources.GetObject("gridColumn1.AppearanceHeader.Font"))); this.gridColumn1.AppearanceHeader.Options.UseFont = true; resources.ApplyResources(this.gridColumn1, "gridColumn1"); this.gridColumn1.FieldName = "ChildName"; this.gridColumn1.Name = "gridColumn1"; this.gridColumn1.OptionsColumn.AllowEdit = false; this.gridColumn1.OptionsColumn.ReadOnly = true; // // gridColumn4 // this.gridColumn4.AppearanceHeader.Font = ((System.Drawing.Font)(resources.GetObject("gridColumn4.AppearanceHeader.Font"))); this.gridColumn4.AppearanceHeader.Options.UseFont = true; resources.ApplyResources(this.gridColumn4, "gridColumn4"); this.gridColumn4.ColumnEdit = this.relationLookUpEdit; this.gridColumn4.FieldName = "idfsStatus"; this.gridColumn4.Name = "gridColumn4"; // // relationLookUpEdit // resources.ApplyResources(this.relationLookUpEdit, "relationLookUpEdit"); this.relationLookUpEdit.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("relationLookUpEdit.Buttons"))))}); this.relationLookUpEdit.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo(resources.GetString("relationLookUpEdit.Columns"), resources.GetString("relationLookUpEdit.Columns1"))}); this.relationLookUpEdit.DisplayMember = "Name"; this.relationLookUpEdit.Name = "relationLookUpEdit"; this.relationLookUpEdit.ShowHeader = false; this.relationLookUpEdit.ValueMember = "idfsReference"; // // repositoryItemComboBox1 // resources.ApplyResources(this.repositoryItemComboBox1, "repositoryItemComboBox1"); this.repositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("repositoryItemComboBox1.Buttons"))))}); this.repositoryItemComboBox1.Name = "repositoryItemComboBox1"; this.repositoryItemComboBox1.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.DoubleClick; this.repositoryItemComboBox1.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor; // // ObjectTypeList // resources.ApplyResources(this, "$this"); this.Controls.Add(this.gridControl1); this.Controls.Add(this.simpleButton2); this.Controls.Add(this.lookUpEdit1); this.Controls.Add(this.label1); this.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.FormID = "A18"; this.HelpTopicID = "Administration_Configuration"; this.LeftIcon = global::EIDSS_ObjectAccess.Properties.Resources.Data_Access_Types__large__30_1_; this.Name = "ObjectTypeList"; this.ShowDeleteButton = false; this.Status = bv.common.win.FormStatus.Draft; this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.lookUpEdit1, 0); this.Controls.SetChildIndex(this.simpleButton2, 0); this.Controls.SetChildIndex(this.gridControl1, 0); ((System.ComponentModel.ISupportInitialize)(this.lookUpEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.relationLookUpEdit)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemComboBox1)).EndInit(); this.ResumeLayout(false); } #endregion protected override void DefineBinding() { base.DefineBinding(); //this.State = BusinessObjectState.EditObject; Core.LookupBinder.BindBaseRepositoryLookup(relationLookUpEdit, bv.common.db.BaseReferenceType.rftObjectTypeRelation, false); DataTable main=this.baseDataSet.Tables["ObjectTypeTree"]; MainView = new DataView(main); this.gridControl1.DataSource = MainView; //this.relationLookUpEdit.DataSource = baseDataSet.Tables["RelationType"]; Core.LookupBinder.BindBaseLookup(this.lookUpEdit1, this.baseDataSet, null, bv.common.db.BaseReferenceType.rftObjectType, false, false); DataView types = (DataView)this.lookUpEdit1.Properties.DataSource; types.RowFilter = "idfsReference in (10060001, 10060011)"; //Core.LookupBinder.SetDataSource(this.lookUpEdit1, types.DefaultView, "ParentName", "idfsParentBaseReference"); if(types.Count>0) this.lookUpEdit1.EditValue = types[0]["idfsReference"]; } //TODO:(Mike) Check that Object access rights are working //public static void Register(System.Windows.Forms.Control parentControl) //{ // if (BaseFormManager.ArchiveMode) // return; // m_Parent = parentControl; // MenuAction menuAction = new MenuAction(ShowMe, MenuActionManager.Instance, MenuActionManager.Instance.Security, "MenuObjectTypeList", 1020, false, (int)MenuIconsSmall.DataAccessTypes, -1); // menuAction.SelectPermission = PermissionHelper.SelectPermission(EIDSSPermissionObject.DataAccess); //} public static void ShowMe() { object id = null; BaseFormManager.ShowClient(new ObjectTypeList(), m_Parent, ref id); } private void buttonOK_Click(object sender, System.EventArgs e) { base.DoClose(); } private void lookUpEdit1_EditValueChanged(object sender, System.EventArgs e) { if(Utils.IsEmpty(this.lookUpEdit1.EditValue))return; MainView.RowFilter = "idfsParentObjectType=" + this.lookUpEdit1.EditValue.ToString(); } private void simpleButton2_Click(object sender, System.EventArgs e) { if (Utils.IsEmpty(lookUpEdit1.EditValue)) return; ObjectType current= (ObjectType)lookUpEdit1.EditValue; object empty = current; ObjectAccessDetail objectAccessDetail = new ObjectAccessDetail(current); BaseFormManager.ShowModal(objectAccessDetail, FindForm(), ref empty, null, null, 0, 0); } } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com) 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion #region CVS Information /* * $Source$ * $Author: sontek $ * $Date: 2008-04-29 15:51:17 -0700 (Tue, 29 Apr 2008) $ * $Revision: 264 $ */ #endregion using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Collections.Specialized; using System.Xml; using Prebuild.Core.Nodes; namespace Prebuild.Core.Utilities { /// <summary> /// /// </summary> public class Helper { #region Fields private static Stack dirStack; private static Regex varRegex; static bool checkForOSVariables; /// <summary> /// /// </summary> public static bool CheckForOSVariables { get { return checkForOSVariables; } set { checkForOSVariables = value; } } #endregion #region Constructors /// <summary> /// Initializes the <see cref="Helper"/> class. /// </summary> static Helper() { dirStack = new Stack(); //m_VarRegex = new Regex(@"\${(?<var>[\w|_]+)}"); } #endregion #region Properties /// <summary> /// /// </summary> public static Stack DirStack { get { return dirStack; } } /// <summary> /// /// </summary> public static Regex VarRegex { get { return varRegex; } set { varRegex = value; } } #endregion #region Public Methods #region String Parsing #region Inner Classes and Delegates /// <summary> /// /// </summary> public delegate string StringLookup(string key); #endregion /// <summary> /// Gets a collection of StringLocationPair objects that represent the matches /// </summary> /// <param name="target">The target.</param> /// <param name="beforeGroup">The before group.</param> /// <param name="afterGroup">The after group.</param> /// <param name="includeDelimitersInSubstrings">if set to <c>true</c> [include delimiters in substrings].</param> /// <returns></returns> public static StringCollection FindGroups(string target, string beforeGroup, string afterGroup, bool includeDelimitersInSubstrings) { if( beforeGroup == null ) { throw new ArgumentNullException("beforeGroup"); } if( afterGroup == null ) { throw new ArgumentNullException("afterGroup"); } StringCollection results = new StringCollection(); if(target == null || target.Length == 0) { return results; } int beforeMod = 0; int afterMod = 0; if(includeDelimitersInSubstrings) { //be sure to not exlude the delims beforeMod = beforeGroup.Length; afterMod = afterGroup.Length; } int startIndex = 0; while((startIndex = target.IndexOf(beforeGroup,startIndex)) != -1) { int endIndex = target.IndexOf(afterGroup,startIndex);//the index of the char after it if(endIndex == -1) { break; } int length = endIndex - startIndex - beforeGroup.Length;//move to the first char in the string string substring = substring = target.Substring(startIndex + beforeGroup.Length - beforeMod, length - afterMod); results.Add(substring); //results.Add(new StringLocationPair(substring,startIndex)); startIndex = endIndex + 1; //the Interpolate*() methods will not work if expressions are expandded inside expression due to an optimization //so start after endIndex } return results; } /// <summary> /// Replaces the groups. /// </summary> /// <param name="target">The target.</param> /// <param name="beforeGroup">The before group.</param> /// <param name="afterGroup">The after group.</param> /// <param name="lookup">The lookup.</param> /// <returns></returns> public static string ReplaceGroups(string target, string beforeGroup, string afterGroup, StringLookup lookup) { if( target == null ) { throw new ArgumentNullException("target"); } //int targetLength = target.Length; StringCollection strings = FindGroups(target,beforeGroup,afterGroup,false); if( lookup == null ) { throw new ArgumentNullException("lookup"); } foreach(string substring in strings) { target = target.Replace(beforeGroup + substring + afterGroup, lookup(substring) ); } return target; } /// <summary> /// Replaces ${var} statements in a string with the corresonding values as detirmined by the lookup delegate /// </summary> /// <param name="target">The target.</param> /// <param name="lookup">The lookup.</param> /// <returns></returns> public static string InterpolateForVariables(string target, StringLookup lookup) { return ReplaceGroups(target, "${" , "}" , lookup); } /// <summary> /// Replaces ${var} statements in a string with the corresonding environment variable with name var /// </summary> /// <param name="target"></param> /// <returns></returns> public static string InterpolateForEnvironmentVariables(string target) { return InterpolateForVariables(target, new StringLookup(Environment.GetEnvironmentVariable)); } #endregion /// <summary> /// Translates the value. /// </summary> /// <param name="translateType">Type of the translate.</param> /// <param name="translationItem">The translation item.</param> /// <returns></returns> public static object TranslateValue(Type translateType, string translationItem) { if(translationItem == null) { return null; } try { string lowerVal = translationItem.ToLower(); if(translateType == typeof(bool)) { return (lowerVal == "true" || lowerVal == "1" || lowerVal == "y" || lowerVal == "yes" || lowerVal == "on"); } else if(translateType == typeof(int)) { return (Int32.Parse(translationItem)); } else { return translationItem; } } catch(FormatException) { return null; } } /// <summary> /// Deletes if exists. /// </summary> /// <param name="file">The file.</param> /// <returns></returns> public static bool DeleteIfExists(string file) { string resFile = null; try { resFile = ResolvePath(file); } catch(ArgumentException) { return false; } if(!File.Exists(resFile)) { return false; } File.Delete(resFile); return true; } static readonly char seperator = Path.DirectorySeparatorChar; // This little gem was taken from the NeL source, thanks guys! /// <summary> /// Makes a relative path /// </summary> /// <param name="startPath">Path to start from</param> /// <param name="endPath">Path to end at</param> /// <returns>Path that will get from startPath to endPath</returns> public static string MakePathRelativeTo(string startPath, string endPath) { string tmp = NormalizePath(startPath, seperator); string src = NormalizePath(endPath, seperator); string prefix = ""; while(true) { if((String.Compare(tmp, 0, src, 0, tmp.Length) == 0)) { string ret; int size = tmp.Length; if(size == src.Length) { return "./"; } if((src.Length > tmp.Length) && src[tmp.Length - 1] != seperator) { } else { ret = prefix + endPath.Substring(size, endPath.Length - size); ret = ret.Trim(); if(ret[0] == seperator) { ret = "." + ret; } return NormalizePath(ret); } } if(tmp.Length < 2) { break; } int lastPos = tmp.LastIndexOf(seperator, tmp.Length - 2); int prevPos = tmp.IndexOf(seperator); if((lastPos == prevPos) || (lastPos == -1)) { break; } tmp = tmp.Substring(0, lastPos + 1); prefix += ".." + seperator.ToString(); } return endPath; } /// <summary> /// Resolves the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string ResolvePath(string path) { string tmpPath = NormalizePath(path); if(tmpPath.Length < 1) { tmpPath = "."; } tmpPath = Path.GetFullPath(tmpPath); if(!File.Exists(tmpPath) && !Directory.Exists(tmpPath)) { throw new ArgumentException("Path could not be resolved: " + tmpPath); } return tmpPath; } /// <summary> /// Normalizes the path. /// </summary> /// <param name="path">The path.</param> /// <param name="separatorCharacter">The separator character.</param> /// <returns></returns> public static string NormalizePath(string path, char separatorCharacter) { if(path == null || path == "" || path.Length < 1) { return ""; } string tmpPath = path.Replace('\\', '/'); tmpPath = tmpPath.Replace('/', separatorCharacter); return tmpPath; } /// <summary> /// Normalizes the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string NormalizePath(string path) { return NormalizePath(path, Path.DirectorySeparatorChar); } /// <summary> /// Ends the path. /// </summary> /// <param name="path">The path.</param> /// <param name="separatorCharacter">The separator character.</param> /// <returns></returns> public static string EndPath(string path, char separatorCharacter) { if(path == null || path == "" || path.Length < 1) { return ""; } if(!path.EndsWith(separatorCharacter.ToString())) { return (path + separatorCharacter); } return path; } /// <summary> /// Ends the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string EndPath(string path) { return EndPath(path, Path.DirectorySeparatorChar); } /// <summary> /// Makes the file path. /// </summary> /// <param name="path">The path.</param> /// <param name="name">The name.</param> /// <param name="ext">The ext.</param> /// <returns></returns> public static string MakeFilePath(string path, string name, string ext) { string ret = EndPath(NormalizePath(path)); if( name == null ) { throw new ArgumentNullException("name"); } ret += name; if(!name.EndsWith("." + ext)) { ret += "." + ext; } foreach(char c in Path.GetInvalidPathChars()) { ret = ret.Replace(c, '_'); } return ret; } /// <summary> /// Makes the file path. /// </summary> /// <param name="path">The path.</param> /// <param name="name">The name.</param> /// <returns></returns> public static string MakeFilePath(string path, string name) { string ret = EndPath(NormalizePath(path)); if( name == null ) { throw new ArgumentNullException("name"); } ret += name; foreach (char c in Path.GetInvalidPathChars()) { ret = ret.Replace(c, '_'); } return ret; } /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public static string MakeReferencePath(string path) { string ret = EndPath(NormalizePath(path)); foreach (char c in Path.GetInvalidPathChars()) { ret = ret.Replace(c, '_'); } return ret; } /// <summary> /// Sets the current dir. /// </summary> /// <param name="path">The path.</param> public static void SetCurrentDir(string path) { if( path == null ) { throw new ArgumentNullException("path"); } if(path.Length < 1) { return; } Environment.CurrentDirectory = path; } /// <summary> /// Checks the type. /// </summary> /// <param name="typeToCheck">The type to check.</param> /// <param name="attr">The attr.</param> /// <param name="inter">The inter.</param> /// <returns></returns> public static object CheckType(Type typeToCheck, Type attr, Type inter) { if(typeToCheck == null || attr == null) { return null; } object[] attrs = typeToCheck.GetCustomAttributes(attr, false); if(attrs == null || attrs.Length < 1) { return null; } if( inter == null ) { throw new ArgumentNullException("inter"); } if(typeToCheck.GetInterface(inter.FullName) == null) { return null; } return attrs[0]; } /* A bit of overhead for simple group parsing, there are problems with Regex in Mono public static string ParseValue(string val) { if(val == null || val.Length < 1 || !CheckForOSVariables) return val; string tmp = val; Match m = m_VarRegex.Match(val); while(m.Success) { if(m.Groups["var"] == null) continue; Capture c = m.Groups["var"].Captures[0]; if(c == null) continue; string var = c.Value; string envVal = Environment.GetEnvironmentVariable(var); if(envVal == null) envVal = ""; tmp = tmp.Replace("${" + var + "}", envVal); m = m.NextMatch(); } return tmp; }*/ /// <summary> /// Attributes the value. /// </summary> /// <param name="node">The node.</param> /// <param name="attr">The attr.</param> /// <param name="def">The def.</param> /// <returns></returns> public static string AttributeValue(XmlNode node, string attr, string def) { if( node == null ) { throw new ArgumentNullException("node"); } if(node.Attributes[attr] == null) { return def; } string val = node.Attributes[attr].Value; if(!CheckForOSVariables) { return val; } return InterpolateForEnvironmentVariables(val); } /// <summary> /// Parses the boolean. /// </summary> /// <param name="node">The node.</param> /// <param name="attr">The attr.</param> /// <param name="defaultValue">if set to <c>true</c> [default value].</param> /// <returns></returns> public static bool ParseBoolean(XmlNode node, string attr, bool defaultValue) { if( node == null ) { throw new ArgumentNullException("node"); } if(node.Attributes[attr] == null) { return defaultValue; } return bool.Parse(node.Attributes[attr].Value); } /// <summary> /// Enums the attribute value. /// </summary> /// <param name="node">The node.</param> /// <param name="attr">The attr.</param> /// <param name="enumType">Type of the enum.</param> /// <param name="def">The def.</param> /// <returns></returns> public static object EnumAttributeValue(XmlNode node, string attr, Type enumType, object def) { if( def == null ) { throw new ArgumentNullException("def"); } string val = AttributeValue(node, attr, def.ToString()); return Enum.Parse(enumType, val, true); } /// <summary> /// /// </summary> /// <param name="assemblyName"></param> /// <param name="projectType"></param> /// <returns></returns> public static string AssemblyFullName(string assemblyName, ProjectType projectType) { return assemblyName + (projectType == ProjectType.Library ? ".dll" : ".exe"); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using GuildedRose.Web.Areas.HelpPage.ModelDescriptions; using GuildedRose.Web.Areas.HelpPage.Models; namespace GuildedRose.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); } } } }
// 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 ExtractInt32129() { var test = new ExtractScalarTest__ExtractInt32129(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractScalarTest__ExtractInt32129 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ExtractScalarTest__ExtractInt32129 testClass) { var result = Sse41.Extract(_fld, 129); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static ExtractScalarTest__ExtractInt32129() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ExtractScalarTest__ExtractInt32129() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Extract( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Extract( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Extract( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Extract( _clsVar, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse41.Extract(firstOp, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractScalarTest__ExtractInt32129(); var result = Sse41.Extract(test._fld, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Extract(_fld, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Extract(test._fld, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((result[0] != firstOp[1])) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Int32>(Vector128<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) 2004,2005 Jaroslaw Kowalski <jkowalski@users.sourceforge.net> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Threading; using System.Windows.Forms; using System.Text; using System.IO; using System.Collections; using System.Drawing; using NLogViewer.Receivers; using NLogViewer.Configuration; using NLogViewer.UI; using NLogViewer.Events; using System.Collections.Generic; using NLogViewer.Parsers; using System.Xml.Serialization; using System.Xml; namespace NLogViewer { [XmlRoot("parameters")] public class Session : ILogEventProcessor, ILogEventColumns { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private MainForm _mainForm; private TabPage _tabPage; private SessionTabPage _tabPanel; public SessionTabPage TabPanel { get { return _tabPanel; } } private int _columnOrdinalID; private int _columnOrdinalReceivedDate; private int _columnOrdinalLevel; private Hashtable _logger2NodeCache = new Hashtable(); private Hashtable _level2NodeCache = new Hashtable(); private Hashtable _thread2NodeCache = new Hashtable(); private Hashtable _assembly2NodeCache = new Hashtable(); private Hashtable _class2NodeCache = new Hashtable(); private Hashtable _application2NodeCache = new Hashtable(); private Hashtable _machine2NodeCache = new Hashtable(); private Hashtable _file2NodeCache = new Hashtable(); private string _lastEventInfo = "none"; private CyclicBuffer<LogEvent> _bufferedEvents; private List<LogEvent> _newEvents = new List<LogEvent>(); private FastSortedList<LogEvent> _filteredEvents; private bool _haveNewEvents = false; delegate void AddTreeNodeDelegate(TreeNode parentNode, TreeNode childNode); private long _totalEvents = 0; public Session() { } public LogEvent GetDisplayedItemForIndex(int pos) { lock (this) { return _filteredEvents[pos]; } } public void CreateTab(MainForm form) { _mainForm = form; TabPage page = new TabPage(); _tabPage = page; page.ImageIndex = 1; page.Tag = this; SessionTabPage tabPanel = new SessionTabPage(this); tabPanel.Dock = DockStyle.Fill; page.Controls.Add(tabPanel); _tabPanel = tabPanel; page.Text = Name; TabPanel.ReloadColumns(); } public void Start() { Receiver.Start(); } public void Stop() { Receiver.Stop(); } public string StatusText { get { return Receiver.StatusText; } } public TabPage TabPage { get { return _tabPage; } } #if A private void AddTreeNode(TreeNode parentNode, TreeNode childNode) { parentNode.Nodes.Add(childNode); //if (parentNode.Parent == null || parentNode.Parent.Parent == null) // parentNode.Expand(); } #endif private void ProcessNewEvents() { List<LogEvent> logEventsToProcess = null; lock (this) { if (_haveNewEvents) { logEventsToProcess = _newEvents; _newEvents = new List<LogEvent>(); _haveNewEvents = false; } } if (logEventsToProcess != null) { logger.Info("Processing start {0} items.", logEventsToProcess.Count); int t0 = Environment.TickCount; foreach (LogEvent logEvent in logEventsToProcess) { LogEvent removedEvent = _bufferedEvents.AddAndRemoveLast(logEvent); if (removedEvent != null) _filteredEvents.Remove(removedEvent); if (TryFilters(logEvent)) { _filteredEvents.Add(logEvent); } _totalEvents++; for (int i = 0; i < Columns.Count; ++i) { if (Columns[i].Grouping != LogColumnGrouping.None) TabPanel.ApplyGrouping(Columns[i], logEvent[i]); } /* // LogEventAttributeToNode(logEvent["Level"], _levelsTreeNode, _level2NodeCache, (char)0); LogEventAttributeToNode((string)logEvent["Logger"], _loggersTreeNode, _logger2NodeCache, '.'); LogEventAttributeToNode((string)logEvent["SourceAssembly"], _assembliesTreeNode, _assembly2NodeCache, (char)0); TreeNode node = LogEventAttributeToNode((string)logEvent["SourceType"], _classesTreeNode, _class2NodeCache, '.'); // LogEventAttributeToNode(logEvent.SourceMethod, node, LogEventAttributeToNode((string)logEvent["Thread"], _threadsTreeNode, _thread2NodeCache, (char)0); LogEventAttributeToNode((string)logEvent["SourceApplication"], _applicationsTreeNode, _application2NodeCache, (char)0); LogEventAttributeToNode((string)logEvent["SourceMachine"], _machinesTreeNode, _machine2NodeCache, (char)0); LogEventAttributeToNode((string)logEvent["SourceFile"], _filesTreeNode, _file2NodeCache, (char)'\\'); * */ } int t1 = Environment.TickCount; int ips = -1; if (t1 > t0) { ips = 1000 * logEventsToProcess.Count / (t1 - t0); } logger.Info("Processing finished {0} items. Total {1} ips: {2} time: {3}.", _filteredEvents.Count, logEventsToProcess.Count, ips, t1 - t0); TabPanel.listViewLogMessages.VirtualListSize = _filteredEvents.Count; TabPanel.listViewLogMessages.Invalidate(); UpdateStatusBar(); } } private void UpdateStatusBar() { TabPanel.UpdateCounters(_bufferedEvents.Count, _bufferedEvents.Capacity, _filteredEvents.Count, _totalEvents, _lastEventInfo); } public void OnTimer() { ProcessNewEvents(); } private bool TryFilters(LogEvent logEvent) { //if (logEvent.Level == "TRACE") // return false; return true; } private static int _globalEventID = 0; public void Clear() { lock (this) { _bufferedEvents.Clear(); _filteredEvents.Clear(); _haveNewEvents = true; _totalEvents = 0; TabPanel.listViewLogMessages.VirtualListSize = 0; UpdateStatusBar(); } } public void ChangeBufferSize(int newBufferSize) { lock (this) { CyclicBuffer<LogEvent> newEvents = new CyclicBuffer<LogEvent>(newBufferSize); newEvents.CopyTo(newEvents); //if (newBufferSize > _bufferedEvents = newEvents; } } public void ProcessLogEvent(LogEvent logEvent) { logEvent.ID = Interlocked.Increment(ref _globalEventID); logEvent[_columnOrdinalID] = logEvent.ID; logEvent[_columnOrdinalReceivedDate] = DateTime.Now; lock (this) { _newEvents.Add(logEvent); _haveNewEvents = true; } //LogEventAttributeToNode(logEvent.SourceType, _typesTreeNode, _type); } class ItemComparer : IComparer<LogEvent> { private int _column; private bool _ascending; public ItemComparer(int column, bool ascending) { _column = column; _ascending = ascending; } public int Compare(LogEvent x, LogEvent y) { object v1 = x[_column]; object v2 = y[_column]; if (v1 == null) { if (v2 != null) return _ascending ? -1 : 1; } else { if (v2 == null) return _ascending ? 1 : -1; } if (v1 != null) { int result = ((IComparable)v1).CompareTo(v2); if (result != 0) { if (_ascending) return result; else return -result; } } // by default order by ID if (_ascending) return (x.ID - y.ID); else return -(x.ID - y.ID); } } public void DisplayChangeBufferSizeDialog() { using (ChangeBufferSizeDialog dlg = new ChangeBufferSizeDialog()) { dlg.BufferSize = _bufferedEvents.Capacity; if (dlg.ShowDialog(TabPage) == DialogResult.OK) { ChangeBufferSize(dlg.BufferSize); } } } public void UpdateFonts() { TabPanel.UpdateFonts(); } private bool CaptureParametersAndSaveConfig(string fileName) { AppPreferences.RecentSessions.AddToList(fileName); return Save(fileName); } public bool Save(IWin32Window parent) { if (FileName == null) return SaveAs(parent); return CaptureParametersAndSaveConfig(FileName); } public bool SaveAs(IWin32Window parent) { using (SaveFileDialog sfd = new SaveFileDialog()) { sfd.Filter = "NLogViewer Sessions (*.nlv)|*.nlv|All Files (*.*)|*.*"; if (FileName != null) sfd.FileName = FileName; if (sfd.ShowDialog(parent) == DialogResult.OK) { Name = Path.GetFileNameWithoutExtension(sfd.FileName); TabPage.Text = Name; return CaptureParametersAndSaveConfig(sfd.FileName); } } return false; } public void NewSortOrder() { lock (this) { FastSortedList<LogEvent> newFilteredEvents = new FastSortedList<LogEvent>(new ItemComparer(GetOrAllocateOrdinal(OrderBy), SortAscending)); if (_filteredEvents != null) { foreach (LogEvent ev in _filteredEvents) { newFilteredEvents.Add(ev); } } _filteredEvents = newFilteredEvents; } } public bool Close() { if (Receiver.CanStop()) Stop(); if (Dirty) { switch (MessageBox.Show(TabPanel, "Session '" + Name + "' has unsaved changes. Save before exit?", "NLogViewer", MessageBoxButtons.YesNoCancel)) { case DialogResult.Yes: if (!Save(TabPanel)) return false; break; case DialogResult.Cancel: return false; } } _mainForm.RemoveSession(this); return true; } private bool _dirty; [XmlIgnore] public string FileName; [XmlElement("name")] public string Name; [XmlArray("columns")] [XmlArrayItem("column")] public LogColumnCollection Columns = new LogColumnCollection(); [XmlIgnore] public bool Dirty { get { return _dirty; } set { _dirty = value; } } [XmlElement("max-log-entries")] public int MaxLogEntries = 10000; [XmlElement("show-tree")] public bool ShowTree = true; [XmlElement("show-details")] public bool ShowDetails = true; [XmlElement("sort-by")] public string OrderBy = "ID"; [XmlElement("sort-ascending")] public bool SortAscending = false; [XmlElement("receiver-type")] public string ReceiverType; [XmlElement("parser-type")] public string ParserType = "XML"; [XmlArray("loggers")] [XmlArrayItem("logger", typeof(LoggerConfig))] public LoggerConfigCollection Loggers = new LoggerConfigCollection(); private ILogEventReceiver _receiver; [XmlIgnore] public ILogEventReceiver Receiver { get { return _receiver; } set { _receiver = value; } } [XmlIgnore] public ILogEventParser Parser { get { ILogEventReceiverWithParser rp = Receiver as ILogEventReceiverWithParser; if (rp == null) return null; return rp.Parser; } set { ILogEventReceiverWithParser rp = Receiver as ILogEventReceiverWithParser; if (rp != null) rp.Parser = value; } } private StringToLoggerConfigMap _loggerName2LoggerConfig; public LoggerConfig GetLoggerConfig(string loggerName) { lock (this) { if (_loggerName2LoggerConfig == null) { _loggerName2LoggerConfig = new StringToLoggerConfigMap(); } return (LoggerConfig)_loggerName2LoggerConfig[loggerName]; } } public void AddLoggerConfig(LoggerConfig lc) { lock (this) { _loggerName2LoggerConfig[lc.Name] = lc; Loggers.Add(lc); } } public void Resolve() { if (Columns.Count == 0) { Columns.Add(new LogColumn("ID", 120)); Columns.Add(new LogColumn("Received Time", 120, true)); } // initialize the ordinals for (int i = 0; i < Columns.Count; ++i) Columns[i].Ordinal = i; _columnOrdinalID = GetOrAllocateOrdinal("ID"); _columnOrdinalReceivedDate = GetOrAllocateOrdinal("Received Time"); _columnOrdinalLevel = GetOrAllocateOrdinal("Level"); _bufferedEvents = new CyclicBuffer<LogEvent>(MaxLogEntries); NewSortOrder(); Receiver.Connect(this); } private static XmlSerializer _serializer = new XmlSerializer(typeof(Session)); public bool Save(string fileName) { try { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); using (FileStream fs = File.Create(fileName)) { XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.UTF8); xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("nlog-viewer"); _serializer.Serialize(xtw, this, ns); XmlSerializer s1 = new XmlSerializer(Receiver.GetType()); s1.Serialize(xtw, Receiver, ns); if (Receiver is ILogEventReceiverWithParser) { XmlSerializer s2 = new XmlSerializer(Parser.GetType()); s2.Serialize(xtw, Parser, ns); } xtw.WriteEndElement(); xtw.Flush(); FileName = fileName; Dirty = false; } return true; } catch (Exception ex) { MessageBox.Show("ERROR: " + ex.ToString()); return false; } } public static Session Load(string fileName) { //SoapFormatter formatter = new SoapFormatter(); using (FileStream fs = File.OpenRead(fileName)) { XmlTextReader xtr = new XmlTextReader(fs); xtr.ReadStartElement("nlog-viewer"); Session c = (Session)_serializer.Deserialize(xtr); c.FileName = fileName; XmlSerializer s1 = new XmlSerializer(LogReceiverFactory.GetReceiverType(c.ReceiverType)); c.Receiver = (ILogEventReceiver)s1.Deserialize(xtr); if (c.Receiver is ILogEventReceiverWithParser) { XmlSerializer s2 = new XmlSerializer(LogEventParserFactory.GetParserType(c.ParserType)); c.Parser = (ILogEventParser)s2.Deserialize(xtr); } xtr.ReadEndElement(); c.Resolve(); return c; } } public bool ContainsColumn(string name) { foreach (LogColumn lc in Columns) { if (lc.Name == name) return true; } return false; } public int GetOrAllocateOrdinal(string name) { for (int i = 0; i < Columns.Count; ++i) { if (Columns[i].Name == name) return Columns[i].Ordinal; } LogColumn lc = new LogColumn(); lc.Name = name; lc.Visible = Columns.Count < 20; lc.Width = 100; lc.Ordinal = Columns.Count; Columns.Add(lc); if (lc.Visible && TabPanel != null) TabPanel.ReloadColumns(); return lc.Ordinal; } int ILogEventColumns.Count { get { return Columns.Count; } } public LogEvent CreateLogEvent() { return new LogEvent(this); } } }
#region Copyright (c) 2016 Atif Aziz. 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. // #endregion namespace LinqPadless { #region Imports using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using CSharpMinifier; using Mannex.IO; using MoreLinq.Extensions; using NuGet.Versioning; #endregion enum LinqPadQueryLanguage // ReSharper disable UnusedMember.Global { // ReSharper disable InconsistentNaming Unknown, Expression, Statements, Program, VBExpression, VBStatements, VBProgram, FSharpExpression, FSharpProgram, SQL, ESQL, // ReSharper restore InconsistentNaming // ReSharper restore UnusedMember.Global } sealed class LinqPadQuery { readonly Lazy<XElement> _metaElement; readonly Lazy<LinqPadQueryLanguage> _language; readonly Lazy<ReadOnlyCollection<string>> _namespaces; readonly Lazy<ReadOnlyCollection<string>> _namespaceRemovals; readonly Lazy<ReadOnlyCollection<PackageReference>> _packageReferences; readonly Lazy<ReadOnlyCollection<LinqPadQueryReference>> _loads; readonly Lazy<string> _code; public string FilePath { get; } public string Source { get; } public LinqPadQueryLanguage Language => _language.Value; public XElement MetaElement => _metaElement.Value; public IReadOnlyCollection<string> Namespaces => _namespaces.Value; public IReadOnlyCollection<string> NamespaceRemovals => _namespaceRemovals.Value; public IReadOnlyCollection<PackageReference> PackageReferences => _packageReferences.Value; public IReadOnlyCollection<LinqPadQueryReference> Loads => _loads?.Value ?? ZeroLinqPadQueryReferences; public string Code => _code.Value; static readonly IReadOnlyCollection<LinqPadQueryReference> ZeroLinqPadQueryReferences = new LinqPadQueryReference[0]; public static LinqPadQuery Load(string path) => Load(path, parseLoads: true, resolveLoads: true); public static LinqPadQuery Parse(string source, string path) => Parse(source, path, parseLoads: true, resolveLoads: true); public static LinqPadQuery LoadReferencedQuery(string path) => Load(path, parseLoads: true, resolveLoads: false); public static LinqPadQuery ParseReferencedQuery(string source, string path) => Parse(source, path, parseLoads: true, resolveLoads: false); static LinqPadQuery Load(string path, bool parseLoads, bool resolveLoads) => Parse(File.ReadAllText(path), path, parseLoads, resolveLoads); static LinqPadQuery Parse(string source, string path, bool parseLoads, bool resolveLoads) { var eomLineNumber = LinqPad.GetEndOfMetaLineNumber(source); return new LinqPadQuery(path, source, eomLineNumber, parseLoads, resolveLoads); } LinqPadQuery(string filePath, string source, int eomLineNumber, bool parseLoads, bool resolveLoads) { FilePath = filePath; Source = source; _metaElement = Lazy.Create(() => XElement.Parse(source.Lines() .Take(eomLineNumber) .ToDelimitedString(Environment.NewLine))); _code = Lazy.Create(() => source.Lines() .Skip(eomLineNumber) .ToDelimitedString(Environment.NewLine)); _language = Lazy.Create(() => Enum.TryParse((string) MetaElement.Attribute("Kind"), true, out LinqPadQueryLanguage queryKind) ? queryKind : LinqPadQueryLanguage.Unknown); static ReadOnlyCollection<T> ReadOnlyCollection<T>(IEnumerable<T> items) => new ReadOnlyCollection<T>(items.ToList()); _namespaces = Lazy.Create(() => ReadOnlyCollection( from ns in MetaElement.Elements("Namespace") select (string)ns)); _namespaceRemovals = Lazy.Create(() => ReadOnlyCollection( from ns in MetaElement.Elements("RemoveNamespace") select (string)ns)); _packageReferences = Lazy.Create(() => ReadOnlyCollection( from nr in MetaElement.Elements("NuGetReference") let v = (string) nr.Attribute("Version") select new PackageReference((string) nr, string.IsNullOrEmpty(v) ? null : NuGetVersion.Parse(v), (bool?) nr.Attribute("Prerelease") ?? false))); var dirPath = Path.GetDirectoryName(FilePath); _loads = parseLoads switch { true => Lazy.Create(() => ReadOnlyCollection( from t in Scanner.Scan(Code) where t.Kind == TokenKind.PreprocessorDirective select (t.Start.Line, Text: t.Substring(Code)) into t select (t.Line, t.Text, Parts: t.Text.Split2(' ', StringSplitOptions.RemoveEmptyEntries)) into t where t.Parts.Item1 == "#load" select t.Parts.Item2 switch { var p when p.Length > 2 && p[0] == '"' && p[^1] == '"' => (t.Line, Path: p[1..^1]), _ => throw new Exception("Invalid load directive: " + t.Text) } into d select (d.Line, Path: Path.DirectorySeparatorChar == '\\' ? d.Path : d.Path.Replace('\\', Path.DirectorySeparatorChar)) into d select new LinqPadQueryReference(resolveLoads ? ResolvePath(d.Path) : null, d.Path, d.Line))), _ => null, }; string ResolvePath(string pathSpec) { const string dots = "..."; if (!pathSpec.StartsWith(dots, StringComparison.Ordinal)) return Path.GetFullPath(pathSpec, dirPath); var slashPath = pathSpec.AsSpan(dots.Length); if (slashPath.Length < 2) throw InvalidLoadDirectivePathError(pathSpec); var slash = slashPath[0]; if (slash != Path.DirectorySeparatorChar && slash != Path.AltDirectorySeparatorChar) throw InvalidLoadDirectivePathError(pathSpec); var path = slashPath.Slice(1); foreach (var dir in new DirectoryInfo(dirPath).SelfAndParents()) { var testPath = Path.Join(dir.FullName, path); if (File.Exists(testPath)) return testPath; } throw new FileNotFoundException("File not found: " + pathSpec); } static Exception InvalidLoadDirectivePathError(string path) => throw new Exception("Invalid load directive path: " + path); } public bool IsLanguageSupported => Language == LinqPadQueryLanguage.Statements || Language == LinqPadQueryLanguage.Expression || Language == LinqPadQueryLanguage.Program; public override string ToString() => Source; } sealed class LinqPadQueryReference { readonly Lazy<LinqPadQuery> _query; readonly string _path; public LinqPadQueryReference(string path, string loadPath, int lineNumber) { _path = path; LoadPath = loadPath; LineNumber = lineNumber; _query = Lazy.Create(() => LinqPadQuery.LoadReferencedQuery(path)); } public int LineNumber { get; } public string Path => _path ?? throw new InvalidOperationException(); public string LoadPath { get; } public LinqPadQuery GetQuery() => _query.Value; public string Source => GetQuery().Source; public LinqPadQueryLanguage Language => GetQuery().Language; public XElement MetaElement => GetQuery().MetaElement; public IReadOnlyCollection<string> Namespaces => GetQuery().Namespaces; public IReadOnlyCollection<string> NamespaceRemovals => GetQuery().NamespaceRemovals; public IReadOnlyCollection<PackageReference> PackageReferences => GetQuery().PackageReferences; public string Code => GetQuery().Code; public override string ToString() => Source; } static partial class LinqPadQueryExtensions { public static string GetMergedCode(this LinqPadQuery query, bool skipSelf = false) { if (query == null) throw new ArgumentNullException(nameof(query)); using var lq = query.Loads.GetEnumerator(); if (!lq.MoveNext()) return query.Code; var load = lq.Current; var code = new StringBuilder(); var ln = 1; foreach (var line in query.Code.Lines()) { if (load?.LineNumber == ln) { code.AppendLine("//>>> " + line); if (load.Language switch { LinqPadQueryLanguage.Statements => ("RunLoadedStatements(() => {", "})"), LinqPadQueryLanguage.Expression => ("DumpLoadedExpression(", ")"), _ => default } is ({} prologue, {} epilogue)) { code.AppendLine(prologue) .Append("#line 1 \"").Append(load.Path).Append('"').AppendLine() .AppendLine(load.GetQuery().FormatCodeWithLoadDirectivesCommented()) .Append(epilogue).Append(';').AppendLine(); }; code.AppendLine("//<<< " + line); code.Append("#line ").Append(ln + 1).Append(" \"").Append(query.FilePath).Append('"').AppendLine(); load = lq.MoveNext() ? lq.Current : null; } else if (!skipSelf) { code.AppendLine(line); } ln++; } return code.ToString(); } } } namespace LinqPadless { using System; using System.Linq; using static MoreLinq.Extensions.IndexExtension; using static MoreLinq.Extensions.ToDelimitedStringExtension; static partial class LinqPadQueryExtensions { public static string FormatCodeWithLoadDirectivesCommented(this LinqPadQuery query) { if (query.Loads.Count == 0) return query.Code; var lns = query.Loads.Select(e => e.LineNumber).ToHashSet(); return query.Code.Lines() .Index(1) .Select(e => (lns.Contains(e.Key) ? "// " : null) + e.Value) .ToDelimitedString(Environment.NewLine); } public static NotSupportedException ValidateSupported(this LinqPadQuery query) => !query.IsLanguageSupported ? new NotSupportedException("Only LINQPad " + "C# Statements and Expression queries are fully supported " + "and C# Program queries partially in this version.") : null; } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, 2001, 2002 // // File: Vector.cs //------------------------------------------------------------------------------ using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using System.Text; using System.Collections; using System.Globalization; using System.Windows; using System.Windows.Media; using System.Runtime.InteropServices; namespace System.Windows { /// <summary> /// Vector - A value type which defined a vector in terms of X and Y /// </summary> public partial struct Vector { #region Constructors /// <summary> /// Constructor which sets the vector's initial values /// </summary> /// <param name="x"> double - The initial X </param> /// <param name="y"> double - THe initial Y </param> public Vector(double x, double y) { _x = x; _y = y; } #endregion Constructors #region Public Methods /// <summary> /// Length Property - the length of this Vector /// </summary> public double Length { get { return Math.Sqrt(_x*_x + _y*_y); } } /// <summary> /// LengthSquared Property - the squared length of this Vector /// </summary> public double LengthSquared { get { return _x*_x + _y*_y; } } /// <summary> /// Normalize - Updates this Vector to maintain its direction, but to have a length /// of 1. This is equivalent to dividing this Vector by Length /// </summary> public void Normalize() { // Avoid overflow this /= Math.Max(Math.Abs(_x),Math.Abs(_y)); this /= Length; } /// <summary> /// CrossProduct - Returns the cross product: vector1.X*vector2.Y - vector1.Y*vector2.X /// </summary> /// <returns> /// Returns the cross product: vector1.X*vector2.Y - vector1.Y*vector2.X /// </returns> /// <param name="vector1"> The first Vector </param> /// <param name="vector2"> The second Vector </param> public static double CrossProduct(Vector vector1, Vector vector2) { return vector1._x * vector2._y - vector1._y * vector2._x; } /// <summary> /// AngleBetween - the angle between 2 vectors /// </summary> /// <returns> /// Returns the the angle in degrees between vector1 and vector2 /// </returns> /// <param name="vector1"> The first Vector </param> /// <param name="vector2"> The second Vector </param> public static double AngleBetween(Vector vector1, Vector vector2) { double sin = vector1._x * vector2._y - vector2._x * vector1._y; double cos = vector1._x * vector2._x + vector1._y * vector2._y; return Math.Atan2(sin, cos) * (180 / Math.PI); } #endregion Public Methods #region Public Operators /// <summary> /// Operator -Vector (unary negation) /// </summary> public static Vector operator - (Vector vector) { return new Vector(-vector._x,-vector._y); } /// <summary> /// Negates the values of X and Y on this Vector /// </summary> public void Negate() { _x = -_x; _y = -_y; } /// <summary> /// Operator Vector + Vector /// </summary> public static Vector operator + (Vector vector1, Vector vector2) { return new Vector(vector1._x + vector2._x, vector1._y + vector2._y); } /// <summary> /// Add: Vector + Vector /// </summary> public static Vector Add(Vector vector1, Vector vector2) { return new Vector(vector1._x + vector2._x, vector1._y + vector2._y); } /// <summary> /// Operator Vector - Vector /// </summary> public static Vector operator - (Vector vector1, Vector vector2) { return new Vector(vector1._x - vector2._x, vector1._y - vector2._y); } /// <summary> /// Subtract: Vector - Vector /// </summary> public static Vector Subtract(Vector vector1, Vector vector2) { return new Vector(vector1._x - vector2._x, vector1._y - vector2._y); } /// <summary> /// Operator Vector + Point /// </summary> public static Point operator + (Vector vector, Point point) { return new Point(point._x + vector._x, point._y + vector._y); } /// <summary> /// Add: Vector + Point /// </summary> public static Point Add(Vector vector, Point point) { return new Point(point._x + vector._x, point._y + vector._y); } /// <summary> /// Operator Vector * double /// </summary> public static Vector operator * (Vector vector, double scalar) { return new Vector(vector._x * scalar, vector._y * scalar); } /// <summary> /// Multiply: Vector * double /// </summary> public static Vector Multiply(Vector vector, double scalar) { return new Vector(vector._x * scalar, vector._y * scalar); } /// <summary> /// Operator double * Vector /// </summary> public static Vector operator * (double scalar, Vector vector) { return new Vector(vector._x * scalar, vector._y * scalar); } /// <summary> /// Multiply: double * Vector /// </summary> public static Vector Multiply(double scalar, Vector vector) { return new Vector(vector._x * scalar, vector._y * scalar); } /// <summary> /// Operator Vector / double /// </summary> public static Vector operator / (Vector vector, double scalar) { return vector * (1.0 / scalar); } /// <summary> /// Multiply: Vector / double /// </summary> public static Vector Divide(Vector vector, double scalar) { return vector * (1.0 / scalar); } /// <summary> /// Operator Vector * Matrix /// </summary> public static Vector operator * (Vector vector, Matrix matrix) { return matrix.Transform(vector); } /// <summary> /// Multiply: Vector * Matrix /// </summary> public static Vector Multiply(Vector vector, Matrix matrix) { return matrix.Transform(vector); } /// <summary> /// Operator Vector * Vector, interpreted as their dot product /// </summary> public static double operator * (Vector vector1, Vector vector2) { return vector1._x * vector2._x + vector1._y * vector2._y; } /// <summary> /// Multiply - Returns the dot product: vector1.X*vector2.X + vector1.Y*vector2.Y /// </summary> /// <returns> /// Returns the dot product: vector1.X*vector2.X + vector1.Y*vector2.Y /// </returns> /// <param name="vector1"> The first Vector </param> /// <param name="vector2"> The second Vector </param> public static double Multiply(Vector vector1, Vector vector2) { return vector1._x * vector2._x + vector1._y * vector2._y; } /// <summary> /// Determinant - Returns the determinant det(vector1, vector2) /// </summary> /// <returns> /// Returns the determinant: vector1.X*vector2.Y - vector1.Y*vector2.X /// </returns> /// <param name="vector1"> The first Vector </param> /// <param name="vector2"> The second Vector </param> public static double Determinant(Vector vector1, Vector vector2) { return vector1._x * vector2._y - vector1._y * vector2._x; } /// <summary> /// Explicit conversion to Size. Note that since Size cannot contain negative values, /// the resulting size will contains the absolute values of X and Y /// </summary> /// <returns> /// Size - A Size equal to this Vector /// </returns> /// <param name="vector"> Vector - the Vector to convert to a Size </param> public static explicit operator Size(Vector vector) { return new Size(Math.Abs(vector._x), Math.Abs(vector._y)); } /// <summary> /// Explicit conversion to Point /// </summary> /// <returns> /// Point - A Point equal to this Vector /// </returns> /// <param name="vector"> Vector - the Vector to convert to a Point </param> public static explicit operator Point(Vector vector) { return new Point(vector._x, vector._y); } #endregion Public Operators } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileRADIUSBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileRADIUSProfileRADIUSStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStringArray))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))] public partial class LocalLBProfileRADIUS : iControlInterface { public LocalLBProfileRADIUS() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_client //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void add_client( string [] profile_names, string [] [] clients ) { this.Invoke("add_client", new object [] { profile_names, clients}); } public System.IAsyncResult Beginadd_client(string [] profile_names,string [] [] clients, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_client", new object[] { profile_names, clients}, callback, asyncState); } public void Endadd_client(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileRADIUSProfileRADIUSStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileRADIUSProfileRADIUSStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileRADIUSProfileRADIUSStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileRADIUSProfileRADIUSStatistics)(results[0])); } //----------------------------------------------------------------------- // get_client //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStringArray [] get_client( string [] profile_names ) { object [] results = this.Invoke("get_client", new object [] { profile_names}); return ((LocalLBProfileStringArray [])(results[0])); } public System.IAsyncResult Beginget_client(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_client", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileStringArray [] Endget_client(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStringArray [])(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_persist_avp //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_persist_avp( string [] profile_names ) { object [] results = this.Invoke("get_persist_avp", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_persist_avp(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_persist_avp", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_persist_avp(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileRADIUSProfileRADIUSStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileRADIUSProfileRADIUSStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileRADIUSProfileRADIUSStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileRADIUSProfileRADIUSStatistics)(results[0])); } //----------------------------------------------------------------------- // get_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { object [] results = this.Invoke("get_statistics_by_virtual", new object [] { profile_names, virtual_names}); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // remove_client //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void remove_client( string [] profile_names, string [] [] clients ) { this.Invoke("remove_client", new object [] { profile_names, clients}); } public System.IAsyncResult Beginremove_client(string [] profile_names,string [] [] clients, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_client", new object[] { profile_names, clients}, callback, asyncState); } public void Endremove_client(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void reset_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { this.Invoke("reset_statistics_by_virtual", new object [] { profile_names, virtual_names}); } public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_client //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void set_default_client( string [] profile_names ) { this.Invoke("set_default_client", new object [] { profile_names}); } public System.IAsyncResult Beginset_default_client(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_client", new object[] { profile_names}, callback, asyncState); } public void Endset_default_client(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_persist_avp //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileRADIUS", RequestNamespace="urn:iControl:LocalLB/ProfileRADIUS", ResponseNamespace="urn:iControl:LocalLB/ProfileRADIUS")] public void set_persist_avp( string [] profile_names, LocalLBProfileString [] avps ) { this.Invoke("set_persist_avp", new object [] { profile_names, avps}); } public System.IAsyncResult Beginset_persist_avp(string [] profile_names,LocalLBProfileString [] avps, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_persist_avp", new object[] { profile_names, avps}, callback, asyncState); } public void Endset_persist_avp(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileRADIUS.ProfileRADIUSStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileRADIUSProfileRADIUSStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileRADIUS.ProfileRADIUSStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileRADIUSProfileRADIUSStatistics { private LocalLBProfileRADIUSProfileRADIUSStatisticEntry [] statisticsField; public LocalLBProfileRADIUSProfileRADIUSStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
using System; using System.Runtime.InteropServices; using Vanara.InteropServices; namespace Vanara.PInvoke { public static partial class PowrProf { /// <summary>Function class for effective power mode callback.</summary> /// <param name="Mode">Indicates the effective power mode the system is running in</param> /// <param name="Context">User-specified opaque context. This context would have been passed in at registration in PowerRegisterForEffectivePowerModeNotifications.</param> /// <remarks> /// Immediately after registration, this callback will be invoked with the current value of the power setting. If the registration /// occurs while the power setting is changing, you may receive multiple callbacks; the last callback is the most recent update. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-effective_power_mode_callback void // EFFECTIVE_POWER_MODE_CALLBACK( EFFECTIVE_POWER_MODE Mode, VOID *Context ); [PInvokeData("powersetting.h", MSDNShortId = "47DD6801-5120-44D3-9EE4-58CCDB4B933A")] [UnmanagedFunctionPointer(CallingConvention.Winapi)] public delegate void EFFECTIVE_POWER_MODE_CALLBACK(EFFECTIVE_POWER_MODE Mode, IntPtr Context); /// <summary>Flags for <see cref="PowerSettingRegisterNotification"/>.</summary> [PInvokeData("powersetting.h", MSDNShortId = "0fbca717-2367-4407-8094-3eb2b717b59c")] public enum DEVICE_NOTIFY { /// <summary> /// The Recipient parameter is a handle to a service.Use the CreateService or OpenService function to obtain this handle. /// </summary> DEVICE_NOTIFY_SERVICE_HANDLE = 1, /// <summary>The Recipient parameter is a pointer to a callback function to call when the power setting changes.</summary> DEVICE_NOTIFY_CALLBACK = 2, } /// <summary>Indicates the effective power mode the system is running.</summary> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/ne-powersetting-effective_power_mode typedef enum // EFFECTIVE_POWER_MODE { EffectivePowerModeBatterySaver, EffectivePowerModeBetterBattery, EffectivePowerModeBalanced, // EffectivePowerModeHighPerformance, EffectivePowerModeMaxPerformance, EffectivePowerModeInvalid } ; [PInvokeData("powersetting.h", MSDNShortId = "8FA09CC0-99E7-4B05-88A0-2AF406C7B60C")] public enum EFFECTIVE_POWER_MODE { /// <summary>The system is in battery saver mode.</summary> EffectivePowerModeBatterySaver, /// <summary>The system is in the better battery effective power mode.</summary> EffectivePowerModeBetterBattery, /// <summary>The system is in the balanced effective power mode.</summary> EffectivePowerModeBalanced, /// <summary>The system is in the high performance effective power mode.</summary> EffectivePowerModeHighPerformance, /// <summary>The system is in the maximum performance effective power mode.</summary> EffectivePowerModeMaxPerformance, /// <summary>The system is in an invalid effective power mode due to an internal error.</summary> EffectivePowerModeInvalid, } /// <summary>Retrieves the active power scheme and returns a <c>GUID</c> that identifies the scheme.</summary> /// <param name="UserRootPowerKey">This parameter is reserved for future use and must be set to <c>NULL</c>.</param> /// <param name="ActivePolicyGuid"> /// A pointer that receives a pointer to a <c>GUID</c> structure. Use the LocalFree function to free this memory. /// </param> /// <returns>Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed.</returns> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powergetactivescheme DWORD // PowerGetActiveScheme( HKEY UserRootPowerKey, GUID **ActivePolicyGuid ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "cd72562c-8987-40c1-89c7-04a95b5f1fd0")] public static extern Win32Error PowerGetActiveScheme([Optional] HKEY UserRootPowerKey, out SafeLocalHandle ActivePolicyGuid); /// <summary>Retrieves the active power scheme and returns a <c>GUID</c> that identifies the scheme.</summary> /// <param name="ActivePolicyGuid">Receives a <c>GUID</c> structure.</param> /// <returns>Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed.</returns> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powergetactivescheme DWORD // PowerGetActiveScheme( HKEY UserRootPowerKey, GUID **ActivePolicyGuid ); [PInvokeData("powersetting.h", MSDNShortId = "cd72562c-8987-40c1-89c7-04a95b5f1fd0")] public static Win32Error PowerGetActiveScheme(out Guid ActivePolicyGuid) { var err = PowerGetActiveScheme(default, out var h); ActivePolicyGuid = err.Succeeded ? h.ToStructure<Guid>() : default; return err; } /// <summary>Retrieves the AC power value for the specified power setting.</summary> /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to <c>NULL</c>.</param> /// <param name="SchemeGuid">The identifier of the power scheme.</param> /// <param name="SubGroupOfPowerSettingsGuid"> /// <para> /// The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use /// <c>NO_SUBGROUP_GUID</c> to retrieve the setting for the default power scheme. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>NO_SUBGROUP_GUID fea3413e-7e05-4911-9a71-700331f1c294</term> /// <term>Settings in this subgroup are part of the default power scheme.</term> /// </item> /// <item> /// <term>GUID_DISK_SUBGROUP 0012ee47-9041-4b5d-9b77-535fba8b1442</term> /// <term>Settings in this subgroup control power management configuration of the system's hard disk drives.</term> /// </item> /// <item> /// <term>GUID_SYSTEM_BUTTON_SUBGROUP 4f971e89-eebd-4455-a8de-9e59040e7347</term> /// <term>Settings in this subgroup control configuration of the system power buttons.</term> /// </item> /// <item> /// <term>GUID_PROCESSOR_SETTINGS_SUBGROUP 54533251-82be-4824-96c1-47b60b740d00</term> /// <term>Settings in this subgroup control configuration of processor power management features.</term> /// </item> /// <item> /// <term>GUID_VIDEO_SUBGROUP 7516b95f-f776-4464-8c53-06167f40cc99</term> /// <term>Settings in this subgroup control configuration of the video power management features.</term> /// </item> /// <item> /// <term>GUID_BATTERY_SUBGROUP e73a048d-bf27-4f12-9731-8b2076e8891f</term> /// <term>Settings in this subgroup control battery alarm trip points and actions.</term> /// </item> /// <item> /// <term>GUID_SLEEP_SUBGROUP 238C9FA8-0AAD-41ED-83F4-97BE242C8F20</term> /// <term>Settings in this subgroup control system sleep settings.</term> /// </item> /// <item> /// <term>GUID_PCIEXPRESS_SETTINGS_SUBGROUP 501a4d13-42af-4429-9fd1-a8218c268e20</term> /// <term>Settings in this subgroup control PCI Express settings.</term> /// </item> /// </list> /// </param> /// <param name="PowerSettingGuid">The identifier of the power setting.</param> /// <param name="Type"> /// A pointer to a variable that receives the type of data for the value. The possible values are listed in Registry Value Types. /// This parameter can be <c>NULL</c> and the type of data is not returned. /// </param> /// <param name="Buffer"> /// A pointer to a buffer that receives the data value. If this parameter is <c>NULL</c>, the BufferSize parameter receives the /// required buffer size. /// </param> /// <param name="BufferSize"> /// <para>A pointer to a variable that contains the size of the buffer pointed to by the Buffer parameter.</para> /// <para> /// If the Buffer parameter is <c>NULL</c>, the function returns ERROR_SUCCESS and the variable receives the required buffer size. /// </para> /// <para> /// If the specified buffer size is not large enough to hold the requested data, the function returns <c>ERROR_MORE_DATA</c> and the /// variable receives the required buffer size. /// </para> /// </param> /// <returns> /// Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed. If the buffer size /// specified by the BufferSize parameter is too small, <c>ERROR_MORE_DATA</c> will be returned and the <c>DWORD</c> pointed to by /// the BufferSize parameter will be filled in with the required buffer size. /// </returns> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powerreadacvalue DWORD PowerReadACValue( HKEY // RootPowerKey, const GUID *SchemeGuid, const GUID *SubGroupOfPowerSettingsGuid, const GUID *PowerSettingGuid, PULONG Type, LPBYTE // Buffer, LPDWORD BufferSize ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "b0afaf75-72cc-48a3-bbf2-0000cb85f2e2")] public static extern Win32Error PowerReadACValue([Optional] HKEY RootPowerKey, in Guid SchemeGuid, in Guid SubGroupOfPowerSettingsGuid, in Guid PowerSettingGuid, out REG_VALUE_TYPE Type, IntPtr Buffer, ref uint BufferSize); /// <summary>Retrieves the DC power value for the specified power setting.</summary> /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to <c>NULL</c>.</param> /// <param name="SchemeGuid">The identifier of the power scheme.</param> /// <param name="SubGroupOfPowerSettingsGuid"> /// <para> /// The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use /// <c>NO_SUBGROUP_GUID</c> to retrieve the setting for the default power scheme. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>NO_SUBGROUP_GUID fea3413e-7e05-4911-9a71-700331f1c294</term> /// <term>Settings in this subgroup are part of the default power scheme.</term> /// </item> /// <item> /// <term>GUID_DISK_SUBGROUP 0012ee47-9041-4b5d-9b77-535fba8b1442</term> /// <term>Settings in this subgroup control power management configuration of the system's hard disk drives.</term> /// </item> /// <item> /// <term>GUID_SYSTEM_BUTTON_SUBGROUP 4f971e89-eebd-4455-a8de-9e59040e7347</term> /// <term>Settings in this subgroup control configuration of the system power buttons.</term> /// </item> /// <item> /// <term>GUID_PROCESSOR_SETTINGS_SUBGROUP 54533251-82be-4824-96c1-47b60b740d00</term> /// <term>Settings in this subgroup control configuration of processor power management features.</term> /// </item> /// <item> /// <term>GUID_VIDEO_SUBGROUP 7516b95f-f776-4464-8c53-06167f40cc99</term> /// <term>Settings in this subgroup control configuration of the video power management features.</term> /// </item> /// <item> /// <term>GUID_BATTERY_SUBGROUP e73a048d-bf27-4f12-9731-8b2076e8891f</term> /// <term>Settings in this subgroup control battery alarm trip points and actions.</term> /// </item> /// <item> /// <term>GUID_SLEEP_SUBGROUP 238C9FA8-0AAD-41ED-83F4-97BE242C8F20</term> /// <term>Settings in this subgroup control system sleep settings.</term> /// </item> /// <item> /// <term>GUID_PCIEXPRESS_SETTINGS_SUBGROUP 501a4d13-42af-4429-9fd1-a8218c268e20</term> /// <term>Settings in this subgroup control PCI Express settings.</term> /// </item> /// </list> /// </param> /// <param name="PowerSettingGuid">The identifier of the power setting.</param> /// <param name="Type"> /// A pointer to a variable that receives the type of data for the value. The possible values are listed in Registry Value Types. /// This parameter can be <c>NULL</c> and the type of data is not returned. /// </param> /// <param name="Buffer"> /// A pointer to a variable that receives the data value. If this parameter is <c>NULL</c>, the BufferSize parameter receives the /// required buffer size. /// </param> /// <param name="BufferSize"> /// <para>A pointer to a variable that contains the size of the buffer pointed to by the Buffer parameter.</para> /// <para> /// If the Buffer parameter is <c>NULL</c>, the function returns ERROR_SUCCESS and the variable receives the required buffer size. /// </para> /// <para> /// If the specified buffer size is not large enough to hold the requested data, the function returns <c>ERROR_MORE_DATA</c> and the /// variable receives the required buffer size. /// </para> /// </param> /// <returns> /// Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed. If the buffer size /// specified by the BufferSize parameter is too small, <c>ERROR_MORE_DATA</c> will be returned and the <c>DWORD</c> pointed to by /// the BufferSize parameter will be filled in with the required buffer size. /// </returns> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powerreaddcvalue DWORD PowerReadDCValue( HKEY // RootPowerKey, const GUID *SchemeGuid, const GUID *SubGroupOfPowerSettingsGuid, const GUID *PowerSettingGuid, PULONG Type, PUCHAR // Buffer, LPDWORD BufferSize ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "c439c478-e882-41bf-a95a-82d36382174b")] public static extern Win32Error PowerReadDCValue([Optional] HKEY RootPowerKey, in Guid SchemeGuid, in Guid SubGroupOfPowerSettingsGuid, in Guid PowerSettingGuid, out REG_VALUE_TYPE Type, IntPtr Buffer, ref uint BufferSize); /// <summary>Registers a callback to receive effective power mode change notifications.</summary> /// <param name="Version"> /// <para> /// Supplies the maximum effective power mode version the caller understands. If the effective power mode comes from a later /// version, it is reduced to a compatible version that is then passed to the callback. /// </para> /// <para>As of Windows 10, version 1809 the only understood version is EFFECTIVE_POWER_MODE_V1.</para> /// </param> /// <param name="Callback"> /// A pointer to the callback to call when the effective power mode changes. This will also be called once upon registration to /// supply the current mode. If multiple callbacks are registered using this API, those callbacks can be called concurrently. /// </param> /// <param name="Context">Caller-specified opaque context.</param> /// <param name="RegistrationHandle">A handle to the registration. Use this handle to unregister for notifications.</param> /// <returns>Returns S_OK (zero) if the call was successful, and a nonzero value if the call failed.</returns> /// <remarks> /// Immediately after registration, the callback will be invoked with the current value of the power setting. If the registration /// occurs while the power mode is changing, you may receive multiple callbacks; the last callback is the most recent update. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powerregisterforeffectivepowermodenotifications // HRESULT PowerRegisterForEffectivePowerModeNotifications( ULONG Version, EFFECTIVE_POWER_MODE_CALLBACK *Callback, VOID *Context, // VOID **RegistrationHandle ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "3C87643F-A8DA-4230-A216-8F46629BB6FB")] public static extern HRESULT PowerRegisterForEffectivePowerModeNotifications(uint Version, EFFECTIVE_POWER_MODE_CALLBACK Callback, IntPtr Context, out SafeEffectivePowerModeNotificationHandle RegistrationHandle); /// <summary>Sets the active power scheme for the current user.</summary> /// <param name="UserRootPowerKey">This parameter is reserved for future use and must be set to <c>NULL</c>.</param> /// <param name="SchemeGuid">The identifier of the power scheme.</param> /// <returns>Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed.</returns> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powersetactivescheme DWORD // PowerSetActiveScheme( HKEY UserRootPowerKey, const GUID *SchemeGuid ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "e56bc3f4-2141-4be7-8479-12f8d59971af")] public static extern Win32Error PowerSetActiveScheme([Optional] HKEY UserRootPowerKey, in Guid SchemeGuid); /// <summary>Registers to receive notification when a power setting changes.</summary> /// <param name="SettingGuid">A GUID that represents the power setting.</param> /// <param name="Flags"> /// <para>Information about the recipient of the notification. This parameter can be one of the following values:</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>DEVICE_NOTIFY_SERVICE_HANDLE</term> /// <term>The Recipient parameter is a handle to a service.Use the CreateService or OpenService function to obtain this handle.</term> /// </item> /// <item> /// <term>DEVICE_NOTIFY_CALLBACK</term> /// <term>The Recipient parameter is a pointer to a callback function to call when the power setting changes.</term> /// </item> /// </list> /// </param> /// <param name="Recipient">A handle to the recipient of the notifications.</param> /// <param name="RegistrationHandle">A handle to the registration. Use this handle to unregister for notifications.</param> /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> /// <remarks> /// Immediately after registration, the callback will be invoked with the current value of the power setting. If the registration /// occurs while the power setting is changing, you may receive multiple callbacks; the last callback is the most recent update. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powersettingregisternotification DWORD // PowerSettingRegisterNotification( LPCGUID SettingGuid, DWORD Flags, HANDLE Recipient, PHPOWERNOTIFY RegistrationHandle ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "0fbca717-2367-4407-8094-3eb2b717b59c")] public static extern Win32Error PowerSettingRegisterNotification(in Guid SettingGuid, DEVICE_NOTIFY Flags, in DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS Recipient, out SafeHPOWERNOTIFY RegistrationHandle); /// <summary>Cancels a registration to receive notification when a power setting changes.</summary> /// <param name="RegistrationHandle">A handle to a registration obtained by calling the PowerSettingRegisterNotification function.</param> /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powersettingunregisternotification DWORD // PowerSettingUnregisterNotification( HPOWERNOTIFY RegistrationHandle ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "9853c347-4528-43bb-8326-13bcd819b8a6")] public static extern Win32Error PowerSettingUnregisterNotification(HANDLE RegistrationHandle); /// <summary> /// Unregisters from effective power mode change notifications. This function is intended to be called from cleanup code and will /// wait for all callbacks to complete before unregistering. /// </summary> /// <param name="RegistrationHandle"> /// The handle corresponding to a single power mode registration. This handle should have been saved by the caller after the call to /// PowerRegisterForEffectivePowerModeNotifications and passed in here. /// </param> /// <returns>Returns S_OK (zero) if the call was successful, and a nonzero value if the call failed.</returns> /// <remarks> /// Immediately after registration, the callback will be invoked with the current value of the power setting. If the registration /// occurs while the power setting is changing, you may receive multiple callbacks; the last callback is the most recent update. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powerunregisterfromeffectivepowermodenotifications // HRESULT PowerUnregisterFromEffectivePowerModeNotifications( VOID *RegistrationHandle ); [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("powersetting.h", MSDNShortId = "6E9AB09B-B082-406C-8F2D-43BEA04C19E0")] public static extern HRESULT PowerUnregisterFromEffectivePowerModeNotifications(HANDLE RegistrationHandle); /// <summary>Sets the AC value index of the specified power setting.</summary> /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to <c>NULL</c>.</param> /// <param name="SchemeGuid">The identifier of the power scheme.</param> /// <param name="SubGroupOfPowerSettingsGuid"> /// <para> /// The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use /// <c>NO_SUBGROUP_GUID</c> to refer to the default power scheme. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>NO_SUBGROUP_GUIDfea3413e-7e05-4911-9a71-700331f1c294</term> /// <term>Settings in this subgroup are part of the default power scheme.</term> /// </item> /// <item> /// <term>GUID_DISK_SUBGROUP0012ee47-9041-4b5d-9b77-535fba8b1442</term> /// <term>Settings in this subgroup control power management configuration of the system&amp;#39;s hard disk drives.</term> /// </item> /// <item> /// <term>GUID_SYSTEM_BUTTON_SUBGROUP4f971e89-eebd-4455-a8de-9e59040e7347</term> /// <term>Settings in this subgroup control configuration of the system power buttons.</term> /// </item> /// <item> /// <term>GUID_PROCESSOR_SETTINGS_SUBGROUP54533251-82be-4824-96c1-47b60b740d00</term> /// <term>Settings in this subgroup control configuration of processor power management features.</term> /// </item> /// <item> /// <term>GUID_VIDEO_SUBGROUP7516b95f-f776-4464-8c53-06167f40cc99</term> /// <term>Settings in this subgroup control configuration of the video power management features.</term> /// </item> /// <item> /// <term>GUID_BATTERY_SUBGROUPe73a048d-bf27-4f12-9731-8b2076e8891f</term> /// <term>Settings in this subgroup control battery alarm trip points and actions.</term> /// </item> /// <item> /// <term>GUID_SLEEP_SUBGROUP238C9FA8-0AAD-41ED-83F4-97BE242C8F20</term> /// <term>Settings in this subgroup control system sleep settings.</term> /// </item> /// <item> /// <term>GUID_PCIEXPRESS_SETTINGS_SUBGROUP501a4d13-42af-4429-9fd1-a8218c268e20</term> /// <term>Settings in this subgroup control PCI Express settings.</term> /// </item> /// </list> /// </para> /// </param> /// <param name="PowerSettingGuid">The identifier of the power setting.</param> /// <param name="AcValueIndex">The AC value index.</param> /// <returns>Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed.</returns> // DWORD WINAPI PowerWriteACValueIndex( _In_opt_ HKEY RootPowerKey, _In_ const GUID *SchemeGuid, _In_opt_ const GUID // *SubGroupOfPowerSettingsGuid, _In_opt_ const GUID *PowerSettingGuid, _In_ DWORD AcValueIndex); https://msdn.microsoft.com/en-us/library/windows/desktop/aa372765(v=vs.85).aspx [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("Powersetting.h;", MSDNShortId = "aa372765")] public static extern Win32Error PowerWriteACValueIndex([In, Optional] HKEY RootPowerKey, in Guid SchemeGuid, [Optional] in Guid SubGroupOfPowerSettingsGuid, [Optional] in Guid PowerSettingGuid, uint AcValueIndex); /// <summary>Sets the DC index of the specified power setting.</summary> /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to <c>NULL</c>.</param> /// <param name="SchemeGuid">The identifier of the power scheme.</param> /// <param name="SubGroupOfPowerSettingsGuid"> /// <para> /// The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use /// <c>NO_SUBGROUP_GUID</c> to refer to the default power scheme. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>NO_SUBGROUP_GUIDfea3413e-7e05-4911-9a71-700331f1c294</term> /// <term>Settings in this subgroup are part of the default power scheme.</term> /// </item> /// <item> /// <term>GUID_DISK_SUBGROUP0012ee47-9041-4b5d-9b77-535fba8b1442</term> /// <term>Settings in this subgroup control power management configuration of the system&amp;#39;s hard disk drives.</term> /// </item> /// <item> /// <term>GUID_SYSTEM_BUTTON_SUBGROUP4f971e89-eebd-4455-a8de-9e59040e7347</term> /// <term>Settings in this subgroup control configuration of the system power buttons.</term> /// </item> /// <item> /// <term>GUID_PROCESSOR_SETTINGS_SUBGROUP54533251-82be-4824-96c1-47b60b740d00</term> /// <term>Settings in this subgroup control configuration of processor power management features.</term> /// </item> /// <item> /// <term>GUID_VIDEO_SUBGROUP7516b95f-f776-4464-8c53-06167f40cc99</term> /// <term>Settings in this subgroup control configuration of the video power management features.</term> /// </item> /// <item> /// <term>GUID_BATTERY_SUBGROUPe73a048d-bf27-4f12-9731-8b2076e8891f</term> /// <term>Settings in this subgroup control battery alarm trip points and actions.</term> /// </item> /// <item> /// <term>GUID_SLEEP_SUBGROUP238C9FA8-0AAD-41ED-83F4-97BE242C8F20</term> /// <term>Settings in this subgroup control system sleep settings.</term> /// </item> /// <item> /// <term>GUID_PCIEXPRESS_SETTINGS_SUBGROUP501a4d13-42af-4429-9fd1-a8218c268e20</term> /// <term>Settings in this subgroup control PCI Express settings.</term> /// </item> /// </list> /// </para> /// </param> /// <param name="PowerSettingGuid">The identifier of the power setting.</param> /// <param name="DcValueIndex">The DC value index.</param> /// <returns>Returns <c>ERROR_SUCCESS</c> (zero) if the call was successful, and a nonzero value if the call failed.</returns> // DWORD WINAPI PowerWriteDCValueIndex( _In_opt_ HKEY RootPowerKey, _In_ const GUID *SchemeGuid, _In_opt_ const GUID // *SubGroupOfPowerSettingsGuid, _In_opt_ const GUID *PowerSettingGuid, _In_ DWORD DcValueIndex); https://msdn.microsoft.com/en-us/library/windows/desktop/aa372769(v=vs.85).aspx [DllImport(Lib.PowrProf, SetLastError = false, ExactSpelling = true)] [PInvokeData("Powersetting.h;", MSDNShortId = "aa372769")] public static extern Win32Error PowerWriteDCValueIndex([Optional] HKEY RootPowerKey, in Guid SchemeGuid, [Optional] in Guid SubGroupOfPowerSettingsGuid, [Optional] in Guid PowerSettingGuid, uint DcValueIndex); /// <summary> /// Provides a <see cref="SafeHandle"/> for <see cref="PowerRegisterForEffectivePowerModeNotifications"/> that is disposed using <see cref="PowerUnregisterFromEffectivePowerModeNotifications"/>. /// </summary> public class SafeEffectivePowerModeNotificationHandle : SafeHANDLE { /// <summary> /// Initializes a new instance of the <see cref="SafeEffectivePowerModeNotificationHandle"/> class and assigns an existing handle. /// </summary> /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> /// <param name="ownsHandle"> /// <see langword="true"/> to reliably release the handle during the finalization phase; otherwise, <see langword="false"/> (not recommended). /// </param> public SafeEffectivePowerModeNotificationHandle(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } /// <summary>Initializes a new instance of the <see cref="SafeEffectivePowerModeNotificationHandle"/> class.</summary> private SafeEffectivePowerModeNotificationHandle() : base() { } /// <inheritdoc/> protected override bool InternalReleaseHandle() => PowerUnregisterFromEffectivePowerModeNotifications(handle).Succeeded; } /// <summary>Provides a <see cref="SafeHandle"/> for a registered power notification that is disposed using <see cref="PowerSettingUnregisterNotification"/>.</summary> public class SafeHPOWERNOTIFY : SafeHANDLE { /// <summary>Initializes a new instance of the <see cref="SafeHPOWERNOTIFY"/> class and assigns an existing handle.</summary> /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> /// <param name="ownsHandle"> /// <see langword="true"/> to reliably release the handle during the finalization phase; otherwise, <see langword="false"/> (not recommended). /// </param> public SafeHPOWERNOTIFY(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } /// <summary>Initializes a new instance of the <see cref="SafeHPOWERNOTIFY"/> class.</summary> private SafeHPOWERNOTIFY() : base() { } /// <inheritdoc/> protected override bool InternalReleaseHandle() => PowerSettingUnregisterNotification(handle).Succeeded; } } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.Naiad.DataStructures; using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Research.Naiad.Serialization; using System.Threading; using System.Net.Sockets; using Microsoft.Research.Naiad.Scheduling; using System.Net; using System.IO; using Microsoft.Research.Naiad.Runtime.Controlling; using Microsoft.Research.Naiad.Runtime.Networking; namespace Microsoft.Research.Naiad.Dataflow { /// <summary> /// Describes the origin of a message /// </summary> public struct ReturnAddress { /// <summary> /// Process-local thread identifier of the sender /// </summary> public readonly int ThreadIndex; /// <summary> /// Vertex identifier of the sender /// </summary> public readonly int VertexID; /// <summary> /// Process identifier of the sender /// </summary> public readonly int ProcessID; /// <summary> /// Constructs a return address from process and vertex identifiers /// </summary> /// <param name="processId">process identifier</param> /// <param name="vertexId">vertex identifier</param> public ReturnAddress(int processId, int vertexId) { this.VertexID = vertexId; this.ProcessID = processId; this.ThreadIndex = 0; } /// <summary> /// Constructs a return address from process, vertex, thread identifiers /// </summary> /// <param name="processId">process identifier</param> /// <param name="vertexId">vertex identifier</param> /// <param name="threadIndex">thread identifier</param> public ReturnAddress(int processId, int vertexId, int threadIndex) { this.VertexID = vertexId; this.ProcessID = processId; this.ThreadIndex = threadIndex; } } } namespace Microsoft.Research.Naiad.Dataflow.Channels { internal class PostOfficeChannel<S, T> : Cable<S, T> where T : Time<T> { public int ChannelId { get { return channelID; } } private readonly int channelID; private readonly StageOutput<S, T> sendBundle; private readonly StageInput<S, T> recvBundle; private readonly Dictionary<int, Postbox<S, T>> postboxes; private readonly Mailbox<S, T>[] mailboxes; public PostOfficeChannel(StageOutput<S, T> sendBundle, StageInput<S, T> recvBundle, Action<S[], int[], int> routingHashcodeFunction, NetworkChannel networkChannel, int channelId, Channel.Flags flags) { if ((flags & Channel.Flags.SpillOnRecv) == Channel.Flags.SpillOnRecv) throw new Exception("SpillingLocalMailbox not currently supported"); this.sendBundle = sendBundle; this.recvBundle = recvBundle; this.channelID = channelId; var computation = sendBundle.ForStage.InternalComputation; // populate mailboxes; [proxy] destinations for sent messages. this.mailboxes = new Mailbox<S, T>[recvBundle.ForStage.Placement.Count]; foreach (VertexLocation loc in recvBundle.ForStage.Placement) { if (loc.ProcessId == computation.Controller.Configuration.ProcessID) { var postOffice = this.recvBundle.GetPin(loc.VertexId).Vertex.Scheduler.State(computation).PostOffice; var progressBuffer = new Runtime.Progress.ProgressUpdateBuffer<T>(this.ChannelId, this.recvBundle.GetPin(loc.VertexId).Vertex.Scheduler.State(computation).Producer); LocalMailbox<S, T> localMailbox = new LocalMailbox<S, T>(postOffice, this.recvBundle.GetPin(loc.VertexId), channelID, loc.VertexId, progressBuffer); this.mailboxes[loc.VertexId] = localMailbox; postOffice.RegisterMailbox(localMailbox); if (networkChannel != null) networkChannel.RegisterMailbox(localMailbox); } else this.mailboxes[loc.VertexId] = new RemoteMailbox<S, T>(this.channelID, loc.ProcessId, loc.VertexId, sendBundle.ForStage.InternalComputation); } // populate postboxes; collection points for each local worker. this.postboxes = new Dictionary<int, Postbox<S, T>>(); foreach (VertexLocation location in sendBundle.ForStage.Placement) { if (location.ProcessId == sendBundle.ForStage.InternalComputation.Controller.Configuration.ProcessID) { var progressBuffer = new Runtime.Progress.ProgressUpdateBuffer<T>(this.ChannelId, this.sendBundle.GetFiber(location.VertexId).Vertex.Scheduler.State(computation).Producer); // determine type of postbox to use. if (routingHashcodeFunction == null) this.postboxes[location.VertexId] = new NoHashCodePostbox<S, T>(this.channelID, this.sendBundle.GetFiber(location.VertexId), this.recvBundle, this.mailboxes, networkChannel, progressBuffer); else this.postboxes[location.VertexId] = new BufferingPostbox<S, T>(this.channelID, this.sendBundle.GetFiber(location.VertexId), this.recvBundle, this.mailboxes, routingHashcodeFunction, networkChannel, progressBuffer); } } } public override string ToString() { return String.Format("Exchange channel [{0}]: {1} -> {2}", this.channelID, sendBundle, recvBundle); } public Dataflow.Stage SourceStage { get { return this.sendBundle.ForStage; } } public Dataflow.Stage DestinationStage { get { return this.recvBundle.ForStage; } } public SendChannel<S, T> GetSendChannel(int i) { return this.postboxes[i]; } } internal abstract class Postbox<S, T> : SendChannel<S, T> where T : Time<T> { public int ThreadIndex { get { return this.threadindex; } } protected readonly int threadindex; public int VertexID { get { return this.vertexid; } } protected readonly int vertexid; public int ProcessID { get { return this.sender.Vertex.Stage.InternalComputation.Controller.Configuration.ProcessID; } } private readonly int channelID; private readonly VertexOutput<S, T> sender; protected readonly StageInput<S, T> receiverBundle; protected int[] destinations = new int[256]; protected readonly Action<S[], int[], int> routingHashcodesFunction; private readonly NetworkChannel networkChannel; protected readonly ReturnAddress returnAddress; protected readonly Mailbox<S, T>[] mailboxes; protected Runtime.Progress.ProgressUpdateBuffer<T> progressBuffer; public Postbox(int channelID, VertexOutput<S, T> sender, StageInput<S, T> receiverBundle, Mailbox<S, T>[] mailboxes, Action<S[], int[], int> routingHashcodeFunction, NetworkChannel networkChannel, Runtime.Progress.ProgressUpdateBuffer<T> progressBuffer) : this(channelID, sender, receiverBundle, mailboxes, routingHashcodeFunction, networkChannel) { this.progressBuffer = progressBuffer; } public Postbox(int channelID, VertexOutput<S, T> sender, StageInput<S, T> receiverBundle, Mailbox<S, T>[] mailboxes, Action<S[], int[], int> routingHashcodeFunction, NetworkChannel networkChannel) { this.threadindex = sender.Vertex.Scheduler.Index; this.channelID = channelID; this.sender = sender; this.vertexid = sender.Vertex.VertexId; this.receiverBundle = receiverBundle; this.routingHashcodesFunction = routingHashcodeFunction; this.networkChannel = networkChannel; this.mailboxes = mailboxes; this.returnAddress = new ReturnAddress(this.ProcessID, this.vertexid, this.threadindex); } public abstract void Send(Message<S, T> records); /// <summary> /// Flushes the mailboxes and makes sure the scheduler knows about the latest counts /// </summary> public abstract void Flush(); } internal class BufferingPostbox<S, T> : Postbox<S, T> where T : Time<T> { protected readonly Message<S, T>[] Buffers; protected readonly int mask; protected T CurrentTime; protected bool Busy; protected Queue<Message<S, T>> delayedWork = new Queue<Message<S, T>>(); public override void Send(Message<S, T> records) { if (this.Busy) { // copy the message, because it will be recycled by the sender var newMessage = new Message<S, T>(records.time); newMessage.Allocate(AllocationReason.PostOfficeRentrancy); Array.Copy(records.payload, newMessage.payload, records.length); newMessage.length = records.length; this.delayedWork.Enqueue(newMessage); } else { this.Busy = true; this.InternalSend(records); while (this.delayedWork.Count > 0) { var dequeued = this.delayedWork.Dequeue(); this.InternalSend(dequeued); dequeued.Release(AllocationReason.PostOfficeRentrancy); } this.Busy = false; } } private void FlushBuffers() { for (int i = 0; i < this.Buffers.Length; i++) this.FlushBuffer(i); } private void FlushBuffer(int index) { // capture buffer in case of re-entrancy var temp = this.Buffers[index]; this.Buffers[index] = new Message<S, T>(this.CurrentTime); if (!temp.Unallocated) this.mailboxes[index].Send(temp, this.returnAddress); // do not release temp, because the mailbox now owns the message } private void InternalSend(Message<S, T> records) { // if we have data from a different time, we should flush it all... if (!this.CurrentTime.Equals(records.time)) { this.CurrentTime = records.time; this.FlushBuffers(); } // push changes to these counts if (progressBuffer != null) progressBuffer.Update(records.time, records.length); // populate this.hashcodes ... this.ComputeDestinations(records); // buffer each record and ship if full. for (int i = 0; i < records.length; i++) { int destinationVertexID = this.destinations[i]; Debug.Assert(destinationVertexID < this.mailboxes.Length); // if no space allocated, allocate some. if (this.Buffers[destinationVertexID].Unallocated) this.Buffers[destinationVertexID].Allocate(AllocationReason.PostOfficeChannel); this.Buffers[destinationVertexID].payload[this.Buffers[destinationVertexID].length++] = records.payload[i]; // if the buffer is now full, ship if off and replace with an unallocated one. if (this.Buffers[destinationVertexID].length == this.Buffers[destinationVertexID].payload.Length) this.FlushBuffer(destinationVertexID); } } private void ComputeDestinations(Message<S, T> records) { if (this.routingHashcodesFunction == null) { var destination = this.vertexid % this.mailboxes.Length; for (int i = 0; i < records.length; i++) this.destinations[i] = destination; } else { this.routingHashcodesFunction(records.payload, this.destinations, records.length); if (this.mask == -1) for (int i = 0; i < records.length; i++) destinations[i] = (Int32.MaxValue & this.destinations[i]) % this.mailboxes.Length; else for (int i = 0; i < records.length; i++) this.destinations[i] = this.destinations[i] & this.mask; } } /// <summary> /// Flushes the mailboxes and makes sure the scheduler knows about the latest counts /// </summary> public override void Flush() { this.FlushBuffers(); // first flush all the non-local mailboxes for (int i = 0; i < this.mailboxes.Length; i++) if (this.mailboxes[i].ThreadIndex != this.threadindex) this.mailboxes[i].RequestFlush(new ReturnAddress(this.ProcessID, this.VertexID, this.ThreadIndex)); // now flush the local mailbox, which may cut-through to more execution for (int i = 0; i < this.mailboxes.Length; i++) if (this.mailboxes[i].ThreadIndex == this.threadindex) this.mailboxes[i].RequestFlush(new ReturnAddress(this.ProcessID, this.VertexID, this.ThreadIndex)); //Console.WriteLine("Flushing " + this.channelID); if (progressBuffer != null) progressBuffer.Flush(); } public BufferingPostbox(int channelID, VertexOutput<S, T> sender, StageInput<S, T> receiverBundle, Mailbox<S, T>[] mailboxes, Action<S[], int[], int> routingHashcodeFunction, NetworkChannel networkChannel, Runtime.Progress.ProgressUpdateBuffer<T> progressBuffer) : base(channelID, sender, receiverBundle, mailboxes, routingHashcodeFunction, networkChannel, progressBuffer) { if (((this.mailboxes.Length - 1) & this.mailboxes.Length) == 0) this.mask = this.mailboxes.Length - 1; else this.mask = -1; this.Buffers = new Message<S, T>[this.mailboxes.Length]; } } internal class NoHashCodePostbox<S, T> : Postbox<S, T> where T : Time<T> { private readonly int destination; private int recordsSent; public override void Send(Message<S, T> records) { var newMessage = new Message<S, T>(records.time); newMessage.Allocate(AllocationReason.PostOfficeChannel); Array.Copy(records.payload, newMessage.payload, records.length); newMessage.length = records.length; this.recordsSent += records.length; if (progressBuffer != null) progressBuffer.Update(records.time, records.length); this.mailboxes[this.destination].Send(newMessage, this.returnAddress); } public override void Flush() { this.mailboxes[this.destination].RequestFlush(this.returnAddress); if (progressBuffer != null) progressBuffer.Flush(); } public NoHashCodePostbox(int channelID, VertexOutput<S, T> sender, StageInput<S, T> receiverBundle, Mailbox<S, T>[] mailboxes, NetworkChannel networkChannel, Runtime.Progress.ProgressUpdateBuffer<T> progressBuffer) : base(channelID, sender, receiverBundle, mailboxes, null, networkChannel, progressBuffer) { this.destination = this.vertexid % this.mailboxes.Length; } } internal class PostOffice { private readonly Scheduler scheduler; private readonly List<LocalMailbox> mailboxes; public readonly Queue<LocalMailbox> MailboxesToFlush = new Queue<LocalMailbox>(); public PostOffice(Scheduling.Scheduler scheduler) { this.scheduler = scheduler; this.mailboxes = new List<LocalMailbox>(); } public void DrainAllMailboxes() { foreach (LocalMailbox mailbox in this.mailboxes) mailbox.Drain(); this.Flush(); } public void Flush() { while (this.MailboxesToFlush.Count > 0) this.MailboxesToFlush.Dequeue().Flush(); } public void ProposeDrain(LocalMailbox mailbox) { if (this.scheduler.ProposeDrain(mailbox)) mailbox.Drain(); } public void Signal() { this.scheduler.Signal(); } public void RegisterMailbox(LocalMailbox mailbox) { this.mailboxes.Add(mailbox); } } internal interface Mailbox { void DeliverSerializedMessage(SerializedMessage message, ReturnAddress from); int GraphId { get; } int ChannelId { get; } int VertexId { get; } } internal interface LocalMailbox : Mailbox { void Drain(); void Flush(); } internal interface Mailbox<S, T> : Mailbox where T : Time<T> { void Send(Message<S, T> message, ReturnAddress from); void RequestFlush(ReturnAddress from); // returns the ThreadId for mailboxes on the same computer, and -1 for remote ones int ThreadIndex { get; } } internal class LocalMailbox<S, T> : LocalMailbox, Mailbox<S, T> where T : Time<T> { /// <summary> /// The PostOffice responsible for this mailbox. /// </summary> protected readonly PostOffice postOffice; protected volatile bool dirty; protected readonly VertexInput<S, T> endpoint; /// <summary> /// Reports the identifier associated with the channel. /// </summary> public int ChannelId { get { return this.channelId; } } private readonly int channelId; /// <summary> /// Reports the identifier associated with the target vertex. /// </summary> public int VertexId { get { return this.vertexId; } } private readonly int vertexId; // receiver /// <summary> /// Reports the identifier associated with the containing computation. /// </summary> public int GraphId { get { return this.graphId; } } private readonly int graphId; /// <summary> /// Reports the identifier associated with the scheduler responsible for the target vertex. /// </summary> public int ThreadIndex { get { return this.endpoint.Vertex.scheduler.Index; } } protected Runtime.Progress.ProgressUpdateBuffer<T> progressBuffer; private readonly ConcurrentQueue<Message<S, T>> sharedQueue; private readonly ConcurrentQueue<SerializedMessage> sharedSerializedQueue; private readonly AutoSerializedMessageDecoder<S, T> decoder; private bool InFlushingQueue; /// <summary> /// Move records from the private queue into the operator state by giving them to the endpoint. /// </summary> public void Drain() { // entrancy is checked beforehand in LLM, and not needed when called from the scheduler. if (this.dirty) { this.dirty = false; // Pull messages received from other processes SerializedMessage superChannelMessage; while (this.sharedSerializedQueue.TryDequeue(out superChannelMessage)) { this.endpoint.SerializedMessageReceived(superChannelMessage, new ReturnAddress()); if (progressBuffer != null) { Pair<T, int> delta = this.decoder.Time(superChannelMessage); progressBuffer.Update(delta.First, -delta.Second); } // superChannelMessage.Dispose(); } // Pull messages received from the local process var message = new Message<S, T>(); while (this.sharedQueue.TryDequeue(out message)) { this.endpoint.OnReceive(message, new ReturnAddress()); if (progressBuffer != null) progressBuffer.Update(message.time, -message.length); message.Release(AllocationReason.PostOfficeChannel); } // buffered progress updates and downstream work may need to be flushed. if (!this.InFlushingQueue) { this.postOffice.MailboxesToFlush.Enqueue(this); this.InFlushingQueue = true; } } } /// <summary> /// Flush the target of the channel, and then any buffered progress updates. /// </summary> public void Flush() { // only called as part of a dequeue from the flushing queue. this.InFlushingQueue = false; endpoint.Flush(); if (progressBuffer != null) progressBuffer.Flush(); } /// <summary> /// Enqueues the incoming network message on the shared queue, called by the network channel. /// </summary> /// <param name="message">message</param> /// <param name="from">sender</param> public void DeliverSerializedMessage(SerializedMessage message, ReturnAddress from) { this.sharedSerializedQueue.Enqueue(message); if (!this.dirty) this.dirty = true; this.postOffice.Signal(); } /// <summary> /// Flushes the queue of local messages. /// Called by the postbox. /// </summary> /// <param name="from">Identity of the upstream postbox</param> public void RequestFlush(ReturnAddress from) { } /// <summary> /// Forwards a local message by moving it to the shared queue. This makes the message visible to the receiver. /// </summary> /// <param name="message">message of data</param> /// <param name="from">information about calling thread</param> public void Send(Message<S, T> message, ReturnAddress from) { // Deliver the message this.sharedQueue.Enqueue(message); // Notify postoffice that there is a message in the shared queue if (!this.dirty) this.dirty = true; this.postOffice.Signal(); // questionable cut-through logic. probably better to let the scheduler decide about this ... if (this.endpoint.Vertex.Scheduler.Index == from.ThreadIndex && this.endpoint.AvailableEntrancy >= 0) { this.endpoint.AvailableEntrancy = this.endpoint.AvailableEntrancy - 1; this.postOffice.ProposeDrain(this); this.endpoint.AvailableEntrancy = this.endpoint.AvailableEntrancy + 1; } } /// <summary> /// Constructs a new Mailbox for a local instance of a vertex. /// </summary> /// <param name="postOffice">PostOffice managing this Mailbox</param> /// <param name="endpoint">target for delivered messages</param> /// <param name="channelId">identifier for the channel</param> /// <param name="vertexId">identifier for tthe target vertex</param> /// <param name="progressBuffer">accumulator for progress updates</param> public LocalMailbox(PostOffice postOffice, VertexInput<S, T> endpoint, int channelId, int vertexId, Runtime.Progress.ProgressUpdateBuffer<T> progressBuffer) { this.postOffice = postOffice; this.dirty = false; this.endpoint = endpoint; this.channelId = channelId; this.vertexId = vertexId; this.graphId = endpoint.Vertex.Stage.InternalComputation.Index; this.sharedQueue = new ConcurrentQueue<Message<S, T>>(); this.sharedSerializedQueue = new ConcurrentQueue<SerializedMessage>(); this.decoder = new AutoSerializedMessageDecoder<S, T>(endpoint.Vertex.SerializationFormat); this.progressBuffer = progressBuffer; } } internal class RemoteMailbox<S, T> : Mailbox<S, T> where T : Time<T> { public int ChannelId { get { return this.channelID; } } private readonly int channelID; public int VertexId { get { return this.vertexID; } } private readonly int vertexID; public int GraphId { get { return this.graphID; } } private readonly int graphID; private readonly int processID; public int ThreadIndex { get { return -1; } } private readonly NetworkChannel networkChannel; private readonly AutoSerializedMessageEncoder<S, T>[] encodersFromLocalVertices; public void RequestFlush(ReturnAddress from) { this.encodersFromLocalVertices[from.ThreadIndex].Flush(); } public void Send(Pair<S, T> record, ReturnAddress from) { this.encodersFromLocalVertices[from.ThreadIndex].Write(record, from.VertexID); } public void Send(Message<S, T> message, ReturnAddress from) { this.encodersFromLocalVertices[from.ThreadIndex].SetCurrentTime(message.time); this.encodersFromLocalVertices[from.ThreadIndex].Write(new ArraySegment<S>(message.payload, 0, message.length), from.VertexID); message.Release(AllocationReason.PostOfficeChannel); } public void DeliverSerializedMessage(SerializedMessage message, ReturnAddress from) { throw new NotImplementedException("Attempted to deliver message from a remote sender to a remote recipient, which is not currently supported."); } public RemoteMailbox(int channelID, int processID, int vertexID, InternalComputation manager) { this.channelID = channelID; this.processID = processID; this.vertexID = vertexID; this.graphID = manager.Index; this.networkChannel = manager.Controller.NetworkChannel; var controller = manager.Controller; this.encodersFromLocalVertices = new AutoSerializedMessageEncoder<S, T>[controller.Workers.Count]; for (int i = 0; i < controller.Workers.Count; ++i) { this.encodersFromLocalVertices[i] = new AutoSerializedMessageEncoder<S, T>(this.vertexID, this.graphID << 16 | this.channelID, this.networkChannel.GetBufferPool(this.processID, i), this.networkChannel.SendPageSize, manager.SerializationFormat, SerializedMessageType.Data, () => this.networkChannel.GetSequenceNumber(this.processID)); this.encodersFromLocalVertices[i].CompletedMessage += (o, a) => { this.networkChannel.SendBufferSegment(a.Hdr, this.processID, a.Segment); }; } } } }
//------------------------------------------------------------------------------ // <copyright file="ProcessStartInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Diagnostics { using System.Threading; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Security; using System.Security.Permissions; using Microsoft.Win32; using System.IO; using System.ComponentModel.Design; using System.Collections.Specialized; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Runtime.Versioning; /// <devdoc> /// A set of values used to specify a process to start. This is /// used in conjunction with the <see cref='System.Diagnostics.Process'/> /// component. /// </devdoc> [ TypeConverter(typeof(ExpandableObjectConverter)), // Disabling partial trust scenarios PermissionSet(SecurityAction.LinkDemand, Name="FullTrust"), HostProtection(SharedState=true, SelfAffectingProcessMgmt=true) ] public sealed class ProcessStartInfo { string fileName; string arguments; string directory; string verb; ProcessWindowStyle windowStyle; bool errorDialog; IntPtr errorDialogParentHandle; #if FEATURE_PAL bool useShellExecute = false; #else //FEATURE_PAL bool useShellExecute = true; string userName; string domain; SecureString password; string passwordInClearText; bool loadUserProfile; #endif //FEATURE_PAL bool redirectStandardInput = false; bool redirectStandardOutput = false; bool redirectStandardError = false; Encoding standardOutputEncoding; Encoding standardErrorEncoding; bool createNoWindow = false; WeakReference weakParentProcess; internal StringDictionary environmentVariables; /// <devdoc> /// Default constructor. At least the <see cref='System.Diagnostics.ProcessStartInfo.FileName'/> /// property must be set before starting the process. /// </devdoc> public ProcessStartInfo() { } internal ProcessStartInfo(Process parent) { this.weakParentProcess = new WeakReference(parent); } /// <devdoc> /// Specifies the name of the application or document that is to be started. /// </devdoc> [ResourceExposure(ResourceScope.Machine)] public ProcessStartInfo(string fileName) { this.fileName = fileName; } /// <devdoc> /// Specifies the name of the application that is to be started, as well as a set /// of command line arguments to pass to the application. /// </devdoc> [ResourceExposure(ResourceScope.Machine)] public ProcessStartInfo(string fileName, string arguments) { this.fileName = fileName; this.arguments = arguments; } /// <devdoc> /// <para> /// Specifies the verb to use when opening the filename. For example, the "print" /// verb will print a document specified using <see cref='System.Diagnostics.ProcessStartInfo.FileName'/>. /// Each file extension has it's own set of verbs, which can be obtained using the /// <see cref='System.Diagnostics.ProcessStartInfo.Verbs'/> property. /// The default verb can be specified using "". /// </para> /// <note type="rnotes"> /// Discuss 'opening' vs. 'starting.' I think the part about the /// default verb was a dev comment. /// Find out what /// that means. /// </note> /// </devdoc> [ DefaultValueAttribute(""), TypeConverter("System.Diagnostics.Design.VerbConverter, " + AssemblyRef.SystemDesign), MonitoringDescription(SR.ProcessVerb), NotifyParentProperty(true) ] public string Verb { get { if (verb == null) return string.Empty; return verb; } set { verb = value; } } /// <devdoc> /// Specifies the set of command line arguments to use when starting the application. /// </devdoc> [ DefaultValueAttribute(""), MonitoringDescription(SR.ProcessArguments), SettingsBindable(true), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), NotifyParentProperty(true) ] public string Arguments { get { if (arguments == null) return string.Empty; return arguments; } set { arguments = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessCreateNoWindow), NotifyParentProperty(true) ] public bool CreateNoWindow { get { return createNoWindow; } set { createNoWindow = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ Editor("System.Diagnostics.Design.StringDictionaryEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), DefaultValue( null ), MonitoringDescription(SR.ProcessEnvironmentVariables), NotifyParentProperty(true) ] public StringDictionary EnvironmentVariables { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { // Note: // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. // When used with an existing Process.ProcessStartInfo the following behavior // * Desktop - Populates with current Environment (rather than that of the process) if (environmentVariables == null) { #if PLATFORM_UNIX environmentVariables = new CaseSensitiveStringDictionary(); #else environmentVariables = new StringDictionaryWithComparer (); #endif // PLATFORM_UNIX // if not in design mode, initialize the child environment block with all the parent variables if (!(this.weakParentProcess != null && this.weakParentProcess.IsAlive && ((Component)this.weakParentProcess.Target).Site != null && ((Component)this.weakParentProcess.Target).Site.DesignMode)) { foreach (DictionaryEntry entry in System.Environment.GetEnvironmentVariables()) environmentVariables.Add((string)entry.Key, (string)entry.Value); } } return environmentVariables; } } private IDictionary<string,string> environment; [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null), NotifyParentProperty(true) ] public IDictionary<string, string> Environment { get { if (environment == null) { environment = this.EnvironmentVariables.AsGenericDictionary(); } return environment; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessRedirectStandardInput), NotifyParentProperty(true) ] public bool RedirectStandardInput { get { return redirectStandardInput; } set { redirectStandardInput = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessRedirectStandardOutput), NotifyParentProperty(true) ] public bool RedirectStandardOutput { get { return redirectStandardOutput; } set { redirectStandardOutput = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(false), MonitoringDescription(SR.ProcessRedirectStandardError), NotifyParentProperty(true) ] public bool RedirectStandardError { get { return redirectStandardError; } set { redirectStandardError = value; } } public Encoding StandardErrorEncoding { get { return standardErrorEncoding; } set { standardErrorEncoding = value; } } public Encoding StandardOutputEncoding { get { return standardOutputEncoding; } set { standardOutputEncoding = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ DefaultValue(true), MonitoringDescription(SR.ProcessUseShellExecute), NotifyParentProperty(true) ] public bool UseShellExecute { get { return useShellExecute; } set { useShellExecute = value; } } #if !FEATURE_PAL /// <devdoc> /// Returns the set of verbs associated with the file specified by the /// <see cref='System.Diagnostics.ProcessStartInfo.FileName'/> property. /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string[] Verbs { [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] get { ArrayList verbs = new ArrayList(); RegistryKey key = null; string extension = Path.GetExtension(FileName); try { if (extension != null && extension.Length > 0) { key = Registry.ClassesRoot.OpenSubKey(extension); if (key != null) { string value = (string)key.GetValue(String.Empty); key.Close(); key = Registry.ClassesRoot.OpenSubKey(value + "\\shell"); if (key != null) { string[] names = key.GetSubKeyNames(); for (int i = 0; i < names.Length; i++) if (string.Compare(names[i], "new", StringComparison.OrdinalIgnoreCase) != 0) verbs.Add(names[i]); key.Close(); key = null; } } } } finally { if (key != null) key.Close(); } string[] temp = new string[verbs.Count]; verbs.CopyTo(temp, 0); return temp; } } [NotifyParentProperty(true)] public string UserName { get { if( userName == null) { return string.Empty; } else { return userName; } } set { userName = value; } } public SecureString Password { get { return password; } set { password = value; } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string PasswordInClearText { get { return passwordInClearText; } set { passwordInClearText = value; } } [NotifyParentProperty(true)] public string Domain { get { if( domain == null) { return string.Empty; } else { return domain; } } set { domain = value;} } [NotifyParentProperty(true)] public bool LoadUserProfile { get { return loadUserProfile;} set { loadUserProfile = value; } } #endif // !FEATURE_PAL /// <devdoc> /// <para> /// Returns or sets the application, document, or URL that is to be launched. /// </para> /// </devdoc> [ DefaultValue(""), Editor("System.Diagnostics.Design.StartFileNameEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), MonitoringDescription(SR.ProcessFileName), SettingsBindable(true), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), NotifyParentProperty(true) ] public string FileName { [ResourceExposure(ResourceScope.Machine)] get { if (fileName == null) return string.Empty; return fileName; } [ResourceExposure(ResourceScope.Machine)] set { fileName = value;} } /// <devdoc> /// Returns or sets the initial directory for the process that is started. /// Specify "" to if the default is desired. /// </devdoc> [ DefaultValue(""), MonitoringDescription(SR.ProcessWorkingDirectory), Editor("System.Diagnostics.Design.WorkingDirectoryEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), SettingsBindable(true), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), NotifyParentProperty(true) ] public string WorkingDirectory { [ResourceExposure(ResourceScope.Machine)] get { if (directory == null) return string.Empty; return directory; } [ResourceExposure(ResourceScope.Machine)] set { directory = value; } } /// <devdoc> /// Sets or returns whether or not an error dialog should be displayed to the user /// if the process can not be started. /// </devdoc> [ DefaultValueAttribute(false), MonitoringDescription(SR.ProcessErrorDialog), NotifyParentProperty(true) ] public bool ErrorDialog { get { return errorDialog;} set { errorDialog = value;} } /// <devdoc> /// Sets or returns the window handle to use for the error dialog that is shown /// when a process can not be started. If <see cref='System.Diagnostics.ProcessStartInfo.ErrorDialog'/> /// is true, this specifies the parent window for the dialog that is shown. It is /// useful to specify a parent in order to keep the dialog in front of the application. /// </devdoc> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IntPtr ErrorDialogParentHandle { get { return errorDialogParentHandle;} set { errorDialogParentHandle = value;} } /// <devdoc> /// Sets or returns the style of window that should be used for the newly created process. /// </devdoc> [ DefaultValueAttribute(System.Diagnostics.ProcessWindowStyle.Normal), MonitoringDescription(SR.ProcessWindowStyle), NotifyParentProperty(true) ] public ProcessWindowStyle WindowStyle { get { return windowStyle;} set { if (!Enum.IsDefined(typeof(ProcessWindowStyle), value)) throw new InvalidEnumArgumentException("value", (int)value, typeof(ProcessWindowStyle)); windowStyle = value; } } } }
#define USE_EXIT_WORKAROUND_FOGBUGZ_1062258 using System; using System.Linq; using UnityEditor.UIElements; using UnityEditor.Experimental.GraphView; using UnityEngine; using UnityEngine.Experimental.VFX; using UnityEditor.Experimental.VFX; using UnityEngine.UIElements; using UnityEditor.VFX; using System.Collections.Generic; using UnityEditor; using UnityObject = UnityEngine.Object; using System.IO; namespace UnityEditor.VFX.UI { [Serializable] class VFXViewWindow : EditorWindow { ShortcutHandler m_ShortcutHandler; protected void SetupFramingShortcutHandler(VFXView view) { m_ShortcutHandler = new ShortcutHandler( new Dictionary<Event, ShortcutDelegate> { {Event.KeyboardEvent("a"), view.FrameAll }, {Event.KeyboardEvent("f"), view.FrameSelection }, {Event.KeyboardEvent("o"), view.FrameOrigin }, {Event.KeyboardEvent("^#>"), view.FramePrev }, {Event.KeyboardEvent("^>"), view.FrameNext }, {Event.KeyboardEvent("#^r"), view.Resync}, {Event.KeyboardEvent("F7"), view.Compile}, {Event.KeyboardEvent("#d"), view.OutputToDot}, {Event.KeyboardEvent("^#d"), view.OutputToDotReduced}, {Event.KeyboardEvent("#c"), view.OutputToDotConstantFolding}, {Event.KeyboardEvent("^r"), view.ReinitComponents}, {Event.KeyboardEvent("F5"), view.ReinitComponents}, }); } public static VFXViewWindow currentWindow; [MenuItem("Window/Visual Effects/Visual Effect Graph",false,3011)] public static void ShowWindow() { GetWindow<VFXViewWindow>(); } public VFXView graphView { get; private set; } public void LoadAsset(VisualEffectAsset asset, VisualEffect effectToAttach) { string assetPath = AssetDatabase.GetAssetPath(asset); VisualEffectResource resource = VisualEffectResource.GetResourceAtPath(assetPath); //Transitionning code if (resource == null) { resource = new VisualEffectResource(); resource.SetAssetPath(AssetDatabase.GetAssetPath(asset)); } LoadResource(resource, effectToAttach); } public void LoadResource(VisualEffectResource resource, VisualEffect effectToAttach = null) { if (graphView.controller == null || graphView.controller.model != resource) { bool differentAsset = resource != m_DisplayedResource; m_DisplayedResource = resource; graphView.controller = VFXViewController.GetController(resource, true); graphView.UpdateGlobalSelection(); if (differentAsset) { graphView.FrameNewController(); } } if (effectToAttach != null && graphView.controller != null && graphView.controller.model != null && effectToAttach.visualEffectAsset == graphView.controller.model.asset) graphView.attachedComponent = effectToAttach; } protected VisualEffectResource GetCurrentResource() { var objs = Selection.objects; VisualEffectResource selectedResource = null; if (objs != null && objs.Length == 1) { if (objs[0] is VisualEffectAsset) { VisualEffectAsset asset = objs[0] as VisualEffectAsset; selectedResource = asset.GetResource(); } else if (objs[0] is VisualEffectResource) { selectedResource = objs[0] as VisualEffectResource; } } if (selectedResource == null) { int instanceID = Selection.activeInstanceID; if (instanceID != 0) { string path = AssetDatabase.GetAssetPath(instanceID); if (path.EndsWith(".vfx")) { selectedResource = VisualEffectResource.GetResourceAtPath(path); } } } if (selectedResource == null && m_DisplayedResource != null) { selectedResource = m_DisplayedResource; } return selectedResource; } Action m_OnUpdateAction; protected void OnEnable() { VFXManagerEditor.CheckVFXManager(); graphView = new VFXView(); graphView.StretchToParentSize(); SetupFramingShortcutHandler(graphView); rootVisualElement.Add(graphView); // make sure we don't do something that might touch the model on the view OnEnable because // the models OnEnable might be called after in the case of a domain reload. m_OnUpdateAction = () => { var currentAsset = GetCurrentResource(); if (currentAsset != null) { LoadResource(currentAsset); } }; autoCompile = true; graphView.RegisterCallback<AttachToPanelEvent>(OnEnterPanel); graphView.RegisterCallback<DetachFromPanelEvent>(OnLeavePanel); if (rootVisualElement.panel != null) { rootVisualElement.AddManipulator(m_ShortcutHandler); } currentWindow = this; #if USE_EXIT_WORKAROUND_FOGBUGZ_1062258 EditorApplication.wantsToQuit += Quitting_Workaround; #endif } #if USE_EXIT_WORKAROUND_FOGBUGZ_1062258 private bool Quitting_Workaround() { if (graphView != null) graphView.controller = null; return true; } #endif protected void OnDisable() { #if USE_EXIT_WORKAROUND_FOGBUGZ_1062258 EditorApplication.wantsToQuit -= Quitting_Workaround; #endif if (graphView != null) { graphView.UnregisterCallback<AttachToPanelEvent>(OnEnterPanel); graphView.UnregisterCallback<DetachFromPanelEvent>(OnLeavePanel); graphView.controller = null; } currentWindow = null; } void OnEnterPanel(AttachToPanelEvent e) { rootVisualElement.AddManipulator(m_ShortcutHandler); } void OnLeavePanel(DetachFromPanelEvent e) { rootVisualElement.RemoveManipulator(m_ShortcutHandler); } public bool autoCompile {get; set; } void Update() { if (graphView == null) return; if(m_OnUpdateAction != null) { m_OnUpdateAction(); m_OnUpdateAction = null; } VFXViewController controller = graphView.controller; var filename = "No Asset"; if (controller != null) { controller.NotifyUpdate(); if (controller.model != null) { var graph = controller.graph; if (graph != null) { filename = controller.name; if (!graph.saved) { filename += "*"; } graph.RecompileIfNeeded(!autoCompile); controller.RecompileExpressionGraphIfNeeded(); } } } titleContent.text = filename; } [SerializeField] private VisualEffectResource m_DisplayedResource; } }
// 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 AlignRightByte1() { var test = new ImmBinaryOpTest__AlignRightByte1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__AlignRightByte1 { private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightByte1 testClass) { var result = Ssse3.AlignRight(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static ImmBinaryOpTest__AlignRightByte1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public ImmBinaryOpTest__AlignRightByte1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Ssse3.AlignRight( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Ssse3.AlignRight( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Ssse3.AlignRight( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), 1 ); 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(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Ssse3.AlignRight( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Ssse3.AlignRight(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Ssse3.AlignRight(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Ssse3.AlignRight(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightByte1(); var result = Ssse3.AlignRight(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Ssse3.AlignRight(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Ssse3.AlignRight(test._fld1, test._fld2, 1); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[1]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i == 15 ? left[0] : right[i+1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.AlignRight)}<Byte>(Vector128<Byte>.1, Vector128<Byte>): {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) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the /// reserved IPs for your subscription. /// </summary> public partial interface IReservedIPOperations { /// <summary> /// Abort resservedIP migration api validates and aborts the given /// reservedIP for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> AbortMigrationAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The Associate Reserved IP operation associates a Reserved IP with a /// service. /// </summary> /// <param name='reservedIpName'> /// The name of the reserved IP. /// </param> /// <param name='parameters'> /// Parameters supplied to associate Reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> AssociateAsync(string reservedIpName, NetworkReservedIPMobilityParameters parameters, CancellationToken cancellationToken); /// <summary> /// Abort resservedIP migration api validates and aborts the given /// reservedIP for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginAbortMigrationAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The BeginAssociate begins to associate a Reserved IP with a service. /// </summary> /// <param name='reservedIpName'> /// The name of the reserved IP. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin associating Reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> BeginAssociatingAsync(string reservedIpName, NetworkReservedIPMobilityParameters parameters, CancellationToken cancellationToken); /// <summary> /// Commit resservedIP migration api validates and commits the given /// reservedIP for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginCommitMigrationAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The Begin Creating Reserved IP operation creates a reserved IP from /// your the subscription. /// </summary> /// <param name='parameters'> /// Parameters supplied to the Begin Creating Reserved IP operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> BeginCreatingAsync(NetworkReservedIPCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Deleting Reserved IP operation removes a reserved IP from /// your the subscription. /// </summary> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginDeletingAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The BeginDisassociate begins to disassociate a Reserved IP from a /// service. /// </summary> /// <param name='reservedIpName'> /// The name of the reserved IP. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin disassociating Reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> BeginDisassociatingAsync(string reservedIpName, NetworkReservedIPMobilityParameters parameters, CancellationToken cancellationToken); /// <summary> /// Prepare resservedIP migration api validates and prepares the given /// reservedIP for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginPrepareMigrationAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// Commit resservedIP migration api validates and commits the given /// reservedIP for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> CommitMigrationAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Reserved IP operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> CreateAsync(NetworkReservedIPCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> DeleteAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The Disassociate Reserved IP operation disassociates a Reserved IP /// from a service. /// </summary> /// <param name='reservedIpName'> /// The name of the reserved IP. /// </param> /// <param name='parameters'> /// Parameters supplied to disassociate Reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> DisassociateAsync(string reservedIpName, NetworkReservedIPMobilityParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Get Reserved IP operation retrieves the details for the virtual /// IP reserved for the subscription. /// </summary> /// <param name='ipName'> /// The name of the reserved IP to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A reserved IP associated with your subscription. /// </returns> Task<NetworkReservedIPGetResponse> GetAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// The List Reserved IP operation retrieves all of the virtual IPs /// reserved for the subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response structure for the Server List operation. /// </returns> Task<NetworkReservedIPListResponse> ListAsync(CancellationToken cancellationToken); /// <summary> /// Prepare resservedIP migration api validates and prepares the given /// reservedIP for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> PrepareMigrationAsync(string ipName, CancellationToken cancellationToken); /// <summary> /// Validate reservedip migration api validates the given reservedip /// for IaaS Classic to ARM migration. /// </summary> /// <param name='ipName'> /// Name of the reservedIP to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Validate Network Migration operation response. /// </returns> Task<NetworkMigrationValidationResponse> ValidateMigrationAsync(string ipName, CancellationToken cancellationToken); } }