context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace EmployeeRegistration.FormsWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using CoreGraphics; using Foundation; using UIKit; using CoreVideo; using AVFoundation; namespace RosyWriter { public partial class RosyWriterViewControllerUniversal : UIViewController { RosyWriterVideoProcessor videoProcessor; RosyWriterPreviewWindow oglView; UILabel frameRateLabel; UILabel dimensionsLabel; UILabel typeLabel; NSTimer timer; bool shouldShowStats; int backgroundRecordingID; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public RosyWriterViewControllerUniversal () : base (UserInterfaceIdiomIsPhone ? "RosyWriterViewControllerUniversal_iPhone" : "RosyWriterViewControllerUniversal_iPad", null) { } // HACK: Updated method to match delegate in NSTimer.CreateRepeatingScheduledTimer() void UpdateLabels (NSTimer time) { if (shouldShowStats) { frameRateLabel.Text = String.Format ("{0:F} FPS", videoProcessor.VideoFrameRate); frameRateLabel.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); var dimension = videoProcessor.VideoDimensions; dimensionsLabel.Text = String.Format ("{0} x {1}", dimension.Width, dimension.Height); dimensionsLabel.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); // Turn the integer constant into something human readable var type = videoProcessor.VideoType; char [] code = new char [4]; for (int i = 0; i < 4; i++){ code [3-i] = (char) (type & 0xff); type = type >> 8; } var typeString = new String (code); typeLabel.Text = typeString; typeLabel.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); } else { frameRateLabel.Text = string.Empty; frameRateLabel.BackgroundColor = UIColor.Clear; dimensionsLabel.Text = string.Empty; dimensionsLabel.BackgroundColor = UIColor.Clear; typeLabel.Text = string.Empty; typeLabel.BackgroundColor = UIColor.Clear; } } UILabel LabelWithText (string text, float yPosition) { const float labelWidth = 200.0F; const float labelHeight = 40.0F; // HACK: Change this float into an nfloat nfloat xPosition = previewView.Bounds.Size.Width - labelWidth - 10; var label = new UILabel (new CGRect (xPosition, yPosition, labelWidth, labelHeight)) { Font = UIFont.SystemFontOfSize (36F), LineBreakMode = UILineBreakMode.WordWrap, TextAlignment = UITextAlignment.Right, TextColor = UIColor.White, BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F), Text = text }; label.Layer.CornerRadius = 4f; return label; } void DeviceOrientationDidChange (NSNotification notification) { var orientation = UIDevice.CurrentDevice.Orientation; // Don't update the reference orientation when the device orientation is face up/down or unknown. if (UIDeviceOrientation.Portrait == orientation || (UIDeviceOrientation.LandscapeLeft == orientation || UIDeviceOrientation.LandscapeRight == orientation)) videoProcessor.ReferenceOrientation = OrientationFromDeviceOrientation (orientation); } static AVCaptureVideoOrientation OrientationFromDeviceOrientation (UIDeviceOrientation orientation) { switch (orientation) { case UIDeviceOrientation.PortraitUpsideDown: return AVCaptureVideoOrientation.PortraitUpsideDown; case UIDeviceOrientation.Portrait: return AVCaptureVideoOrientation.Portrait; case UIDeviceOrientation.LandscapeLeft: return AVCaptureVideoOrientation.LandscapeLeft; case UIDeviceOrientation.LandscapeRight: return AVCaptureVideoOrientation.LandscapeRight; default: return (AVCaptureVideoOrientation) 0; } } void Cleanup () { frameRateLabel.Dispose (); dimensionsLabel.Dispose (); typeLabel.Dispose (); var notificationCenter = NSNotificationCenter.DefaultCenter; notificationCenter.RemoveObserver (this, UIDevice.OrientationDidChangeNotification, UIApplication.SharedApplication); UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications (); notificationCenter.RemoveObserver (this, UIApplication.DidBecomeActiveNotification, UIApplication.SharedApplication); // Stop and tear down the capture session videoProcessor.StopAndTearDownCaptureSession (); videoProcessor.Dispose (); } #region Event Handler public void OnPixelBufferReadyForDisplay (CVImageBuffer imageBuffer) { // Don't make OpenGLES calls while in the backgroud. if (UIApplication.SharedApplication.ApplicationState != UIApplicationState.Background) oglView.DisplayPixelBuffer(imageBuffer); } public void OnToggleRecording (object sender, EventArgs e) { // UIBarButtonItem btn = (UIBarButtonItem)sender; // Wait for the recording to start/stop before re-enabling the record button. InvokeOnMainThread (() => btnRecord.Enabled = false); // The recordingWill/DidStop delegate methods will fire asynchronously in the response to this call. if (videoProcessor.IsRecording) videoProcessor.StopRecording (); else videoProcessor.StartRecording (); } public void OnApplicationDidBecomeActive (NSNotification notification) { // For performance reasons, we manually pause/resume the session when saving a recoding. // If we try to resume the session in the background it will fail. Resume the session here as well to ensure we will succeed. videoProcessor.ResumeCaptureSession (); } #region Video Processer Event handlers public void OnRecordingWillStart () { InvokeOnMainThread (() => { btnRecord.Enabled = false; btnRecord.Title = "Stop"; // Disable the idle timer while we are recording UIApplication.SharedApplication.IdleTimerDisabled = true; // Make sure we have time to finish saving the movie if the app is backgrounded during recording if (UIDevice.CurrentDevice.IsMultitaskingSupported) // HACK: Cast nint to int backgroundRecordingID = (int)UIApplication.SharedApplication.BeginBackgroundTask (() => {}); }); } public void OnRecordingDidStart () { InvokeOnMainThread (() => btnRecord.Enabled = true); } public void OnRecordingWillStop () { InvokeOnMainThread (() => { // Disable until saving to the camera roll is complete btnRecord.Title = "Record"; btnRecord.Enabled = false; // Pause the capture session so the saving will be as fast as possible. // We resme the session in recordingDidStop videoProcessor.PauseCaptureSession (); }); } public void OnRecordingDidStop () { InvokeOnMainThread (() => { btnRecord.Enabled = true; UIApplication.SharedApplication.IdleTimerDisabled = false; videoProcessor.ResumeCaptureSession (); if (UIDevice.CurrentDevice.IsMultitaskingSupported) { UIApplication.SharedApplication.EndBackgroundTask (backgroundRecordingID); backgroundRecordingID = 0; } }); } #endregion #endregion #region UIViewController Methods public override void ViewDidLoad () { base.ViewDidLoad (); // Initialize the class responsible for managing AV capture session and asset writer videoProcessor = new RosyWriterVideoProcessor (); // Keep track of changes to the device orientation so we can update the video processor var notificationCenter = NSNotificationCenter.DefaultCenter; notificationCenter.AddObserver(UIApplication.DidChangeStatusBarOrientationNotification, DeviceOrientationDidChange); UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications (); // Setup and start the capture session videoProcessor.SetupAndStartCaptureSession (); notificationCenter.AddObserver (UIApplication.DidBecomeActiveNotification, OnApplicationDidBecomeActive); oglView = new RosyWriterPreviewWindow(CGRect.Empty); // Our interface is always in portrait oglView.Transform = videoProcessor.TransformFromCurrentVideoOrientationToOrientation(AVCaptureVideoOrientation.Portrait); CGRect bounds = previewView.ConvertRectToView(previewView.Bounds, oglView); oglView.Bounds = bounds; oglView.Center = new CGPoint(previewView.Bounds.Size.Width / 2.0F, previewView.Bounds.Size.Height / 2.0F); previewView.AddSubview(oglView); // Set up labels shouldShowStats = true; frameRateLabel = LabelWithText (string.Empty, 10.0F); previewView.AddSubview (frameRateLabel); dimensionsLabel = LabelWithText (string.Empty, 54.0F); previewView.AddSubview (dimensionsLabel); typeLabel = LabelWithText (string.Empty, 90F); previewView.Add (typeLabel); // btnRecord Event Handler btnRecord.Clicked += OnToggleRecording; // Video Processor Event Handlers videoProcessor.RecordingDidStart += OnRecordingDidStart; videoProcessor.RecordingDidStop += OnRecordingDidStop; videoProcessor.RecordingWillStart += OnRecordingWillStart; videoProcessor.RecordingWillStop += OnRecordingWillStop; videoProcessor.PixelBufferReadyForDisplay += OnPixelBufferReadyForDisplay; } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); timer = NSTimer.CreateRepeatingScheduledTimer (.25, UpdateLabels); } public override void ViewDidDisappear (bool animated) { base.ViewDidDisappear (animated); timer.Invalidate (); timer.Dispose (); } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { // Return true for supported orientations return (toInterfaceOrientation == UIInterfaceOrientation.Portrait); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; using System.Net; /// <summary> /// Class of extension rule /// </summary> [Export(typeof(ExtensionRule))] public class MetadataCore4103 : ExtensionRule { /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Metadata.Core.4103"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "The value of the type attribute MUST resolve to an entity type or a collection of an entity type declared in the same document or a document referenced with an edmx:Reference element, or the abstract type Edm.EntityType."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return "7.1.2"; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V4; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } /// <summary> /// Gets the flag whether the rule requires metadata document /// </summary> public override bool? RequireMetadata { get { return true; } } /// <summary> /// Gets the offline context to which the rule applies /// </summary> public override bool? IsOfflineContext { get { return false; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.Xml; } } /// <summary> /// Verify Metadata.Core.4103 /// </summary> /// <param name="context">Service context</param> /// <param name="info">out parameter to return violation information when rule fail</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; // Load MetadataDocument into XMLDOM XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(context.MetadataDocument); string xpath = "//*[local-name()='NavigationProperty']"; XmlNodeList navPropertyNodeList = xmlDoc.SelectNodes(xpath); foreach (XmlNode navProp in navPropertyNodeList) { if (navProp.Attributes["Type"] != null) { string navPropTypeName = navProp.Attributes["Type"].Value; if (navPropTypeName.Contains("Collection(")) { navPropTypeName = navPropTypeName.Substring(11, navPropTypeName.Length - 12); } // 1. See whether the navigation type is of Edm.EntityType. if (navPropTypeName.Equals("Edm.EntityType")) { passed = true; continue; } // 2. See whether the navigation type can resolve to an entity type defined in the metadata document. string navPropTypeSimpleName = navPropTypeName.GetLastSegment(); string navPropTypePrefix = navPropTypeName.Substring(0, navPropTypeName.IndexOf(navPropTypeSimpleName) - 1); bool isTypeDefinedInDoc = IsEntityTypeDefinedInDoc(navPropTypeName, context.MetadataDocument); if (isTypeDefinedInDoc) { passed = true; continue; } // 3. See whether the navigation type can resolve to an entity type defined in one of the referenced data model. string docString = MetadataHelper.GetReferenceDocByDefinedType(navPropTypeName, context); if (!string.IsNullOrEmpty(docString)) { isTypeDefinedInDoc = false; isTypeDefinedInDoc = IsEntityTypeDefinedInDoc(navPropTypeName, docString); if (isTypeDefinedInDoc) { passed = true; } } } // If the navigation type cannot resolve to an in-scope entity type, this navigation property failed in this rule. if (passed != true) { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); break; } } return passed; } /// <summary> /// See whether an entity type is defined in one of the schemas in the metadata document. /// </summary> /// <param name="typeFullName">The qualified name of the entity type.</param> /// <param name="document">The document string.</param> /// <returns>True if the entity type is defined in the document, false otherwise.</returns> bool IsEntityTypeDefinedInDoc(string typeFullName, string document) { bool result = false; string typeSimpleName = typeFullName.GetLastSegment(); XElement metaXml = XElement.Parse(document); string xpath = string.Format("//*[local-name()='EntityType' and @Name='{0}']", typeSimpleName); IEnumerable<XElement> types = metaXml.XPathSelectElements(xpath, ODataNamespaceManager.Instance); foreach (XElement type in types) { AliasNamespacePair aliasAndNamespace = MetadataHelper.GetAliasAndNamespace(type); if ( string.Format("{0}.{1}", aliasAndNamespace.Alias, typeSimpleName) == typeFullName || string.Format("{0}.{1}", aliasAndNamespace.Namespace, typeSimpleName) == typeFullName ) { result = true; break; } } return result; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Torshify.Core.Managers; namespace Torshify.Core.Native { internal class NativeSession : NativeObject, ISession { #region Fields private readonly byte[] _applicationKey; private readonly SessionOptions _options; private IPlaylistContainer _playlistContainer; private IPlaylist _starredPlaylist; private Thread _mainThread; private Thread _eventThread; private AutoResetEvent _mainThreadNotification; private Queue<DelegateInvoker> _eventQueue; private NativeSessionCallbacks _callbacks; private readonly object _eventQueueLock = new object(); #endregion Fields #region Constructors public NativeSession(byte[] applicationKey, SessionOptions options) : base(null, IntPtr.Zero) { _applicationKey = applicationKey; _options = options; } #endregion Constructors #region Events public event EventHandler<SessionEventArgs> ConnectionError; public event EventHandler<SessionEventArgs> EndOfTrack; public event EventHandler<SessionEventArgs> Exception; public event EventHandler<SessionEventArgs> LoginComplete; public event EventHandler<SessionEventArgs> LogMessage; public event EventHandler<SessionEventArgs> LogoutComplete; public event EventHandler<SessionEventArgs> MessageToUser; public event EventHandler<SessionEventArgs> MetadataUpdated; public event EventHandler<MusicDeliveryEventArgs> MusicDeliver; public event EventHandler<SessionEventArgs> PlayTokenLost; public event EventHandler<SessionEventArgs> StartPlayback; public event EventHandler<SessionEventArgs> StopPlayback; public event EventHandler<SessionEventArgs> StreamingError; public event EventHandler<SessionEventArgs> UserinfoUpdated; public event EventHandler<SessionEventArgs> OfflineStatusUpdated; public event EventHandler<SessionEventArgs> OfflineError; public event EventHandler<CredentialsBlobEventArgs> CredentialsBlobUpdated; public event EventHandler<SessionEventArgs> ConnectionStateUpdated; public event EventHandler<SessionEventArgs> ScrobbleError; public event EventHandler<PrivateSessionModeChangedEventArgs> PrivateSessionModeChanged; #endregion Events #region Properties public IPlaylistContainer PlaylistContainer { get { ConnectionState connectionState = ConnectionState; if (connectionState == ConnectionState.Disconnected || connectionState == ConnectionState.LoggedOut) { return null; } AssertHandle(); return _playlistContainer; } } public IPlaylist Starred { get { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); if (_starredPlaylist == null) { lock (Spotify.Mutex) { _starredPlaylist = PlaylistManager.Get(this, Spotify.sp_session_starred_create(Handle)); } } return _starredPlaylist; } } public ConnectionState ConnectionState { get { if (!IsInvalid) { try { lock (Spotify.Mutex) { return Spotify.sp_session_connectionstate(Handle); } } catch { return ConnectionState.Undefined; } } return ConnectionState.Undefined; } } public IUser LoggedInUser { get { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); lock (Spotify.Mutex) { return UserManager.Get(this, Spotify.sp_session_user(Handle)); } } } public int LoggedInUserCountry { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_user_country(Handle); } } } public bool IsVolumeNormalizationEnabled { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_get_volume_normalization(Handle); } } set { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_volume_normalization(Handle, value); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } } public bool IsPrivateSessionEnabled { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_is_private_session(Handle); } } set { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_private_session(Handle, value); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } } public override ISession Session { get { return this; } } #endregion Properties #region Public Methods public void Login(string userName, string password, bool rememberMe = false) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_login(Handle, userName, password, rememberMe, null); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public void LoginWithBlob(string userName, string blob) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_login(Handle, userName, null, false, blob); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public void Relogin() { AssertHandle(); lock (Spotify.Mutex) { var error = Spotify.sp_session_relogin(Handle); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public void ForgetStoredLogin() { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_forget_me(Handle); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public string GetRememberedUser() { AssertHandle(); int bufferSize = Spotify.STRINGBUFFER_SIZE; try { int userNameLength; StringBuilder builder = new StringBuilder(bufferSize); lock (Spotify.Mutex) { userNameLength = Spotify.sp_session_remembered_user(Handle, builder, bufferSize); } if (userNameLength == -1) { return string.Empty; } return builder.ToString(); } catch { return string.Empty; } } public void Logout() { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_logout(Handle); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public Error PlayerLoad(ITrack track) { AssertHandle(); INativeObject nativeObject = track as INativeObject; if (nativeObject == null) { throw new ArgumentException("Invalid argument"); } lock (Spotify.Mutex) { return Spotify.sp_session_player_load(Handle, nativeObject.Handle); } } public Error PlayerPrefetch(ITrack track) { AssertHandle(); INativeObject nativeObject = track as INativeObject; if (nativeObject == null) { throw new ArgumentException("Invalid argument"); } lock (Spotify.Mutex) { return Spotify.sp_session_player_prefetch(Handle, nativeObject.GetHandle()); } } public Error PlayerPause() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_play(Handle, false); } } public Error PlayerPlay() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_play(Handle, true); } } public Error PlayerSeek(TimeSpan offset) { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_seek(Handle, (int)offset.TotalMilliseconds); } } public Error PlayerUnload() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_unload(Handle); } } public ISearch Search( string query, int trackOffset, int trackCount, int albumOffset, int albumCount, int artistOffset, int artistCount, int playlistOffset, int playlistCount, SearchType searchType, object userData = null) { AssertHandle(); var search = new NativeSearch( this, query, trackOffset, trackCount, albumOffset, albumCount, artistOffset, artistCount, playlistOffset, playlistCount, searchType, userData); search.Initialize(); return search; } public IAlbumBrowse Browse(IAlbum album, object userData = null) { if (!(album is INativeObject)) { throw new ArgumentException("Invalid type"); } AssertHandle(); var browse = new NativeAlbumBrowse(this, album, userData); browse.Initialize(); return browse; } public IArtistBrowse Browse(IArtist artist, object userData = null) { return Browse(artist, ArtistBrowseType.Full, userData); } public IArtistBrowse Browse(IArtist artist, ArtistBrowseType browseType, object userData = null) { if (!(artist is INativeObject)) { throw new ArgumentException("Invalid type"); } AssertHandle(); var browse = new NativeArtistBrowse(this, artist.GetHandle(), browseType); browse.Initialize(); return browse; } public IToplistBrowse Browse(ToplistType type, int encodedCountryCode, object userData = null) { AssertHandle(); var browse = new NativeToplistBrowse(this, type, encodedCountryCode, userData); browse.Initialize(); return browse; } public IToplistBrowse Browse(ToplistType type, object userData = null) { return Browse(type, (int)ToplistSpecialRegion.Everywhere, userData); } public IToplistBrowse Browse(ToplistType type, string userName, object userData = null) { AssertHandle(); var browse = new NativeToplistBrowse(this, type, userName, userData); browse.Initialize(); return browse; } public IToplistBrowse BrowseCurrentUser(ToplistType type, object userData = null) { return Browse(type, null, userData); } public IImage GetImage(string id) { AssertHandle(); if (id == null) { throw new ArgumentNullException("id"); } if (id.Length != 40) { throw new ArgumentException("invalid id", "id"); } var image = new NativeImage(this, id); image.Initialize(); return image; } public ISession SetPreferredBitrate(Bitrate bitrate) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_preferred_bitrate(Handle, bitrate); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetPreferredOfflineBitrate(Bitrate bitrate, bool resync) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_preferred_offline_bitrate(Handle, bitrate, resync); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetConnectionType(ConnectionType connectionType) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_connection_type(Handle, connectionType); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetConnectionRules(ConnectionRule connectionRule) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_connection_rules(Handle, connectionRule); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetCacheSize(uint megabytes) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_cache_size(Handle, megabytes); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public int GetNumberOfOfflineTracksRemainingToSync() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_offline_tracks_to_sync(Handle); } } public int GetNumberOfOfflinePlaylists() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_offline_num_playlists(Handle); } } public OfflineSyncStatus GetOfflineSyncStatus() { AssertHandle(); var syncStatus = new OfflineSyncStatus(); lock (Spotify.Mutex) { Spotify.SpotifyOfflineSyncStatus offlineSyncStatus = new Spotify.SpotifyOfflineSyncStatus(); Spotify.sp_offline_sync_get_status(Handle, ref offlineSyncStatus); syncStatus.CopiedBytes = offlineSyncStatus.CopiedBytes; syncStatus.CopiedTracks = offlineSyncStatus.CopiedTracks; syncStatus.DoneBytes = offlineSyncStatus.DoneBytes; syncStatus.DoneTracks = offlineSyncStatus.DoneTracks; syncStatus.ErrorTracks = offlineSyncStatus.ErrorTracks; syncStatus.IsSyncing = offlineSyncStatus.Syncing; syncStatus.QueuedBytes = offlineSyncStatus.QueuedBytes; syncStatus.QueuedTracks = offlineSyncStatus.QueuedTracks; } return syncStatus; } public IPlaylist GetStarredForUser(string canonicalUserName) { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); lock (Spotify.Mutex) { IntPtr starredPtr = Spotify.sp_session_starred_for_user_create(Handle, canonicalUserName); return PlaylistManager.Get(this, starredPtr); } } public IPlaylistContainer GetPlaylistContainerForUser(string canonicalUsername) { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); lock (Spotify.Mutex) { IntPtr containerPtr = Spotify.sp_session_publishedcontainer_for_user_create(Handle, canonicalUsername); return PlaylistContainerManager.Get(this, containerPtr); } } public Error FlushCaches() { lock (Spotify.Mutex) { return Spotify.sp_session_flush_caches(Handle); } } public override void Initialize() { _callbacks = new NativeSessionCallbacks(this); if (!string.IsNullOrEmpty(_options.SettingsLocation)) { Directory.CreateDirectory(_options.SettingsLocation); } var sessionConfig = new Spotify.SpotifySessionConfig { ApiVersion = Spotify.SPOTIFY_API_VERSION, CacheLocation = _options.CacheLocation, SettingsLocation = _options.SettingsLocation, UserAgent = _options.UserAgent, CompressPlaylists = _options.CompressPlaylists, DontSaveMetadataForPlaylists = _options.DontSavePlaylistMetadata, InitiallyUnloadPlaylists = _options.InitiallyUnloadPlaylists, ApplicationKey = Marshal.AllocHGlobal(_applicationKey.Length), ApplicationKeySize = _applicationKey.Length, Callbacks = _callbacks.CallbackHandle, DeviceID = _options.DeviceID, TraceFile = _options.TraceFileLocation, Proxy = _options.Proxy, ProxyUsername = _options.ProxyUsername, ProxyPassword = _options.ProxyPassword }; try { Marshal.Copy(_applicationKey, 0, sessionConfig.ApplicationKey, _applicationKey.Length); lock (Spotify.Mutex) { IntPtr sessionPtr; Error res = Spotify.sp_session_create(ref sessionConfig, out sessionPtr); if (res != Error.OK) { throw new TorshifyException(res.GetMessage(), res); } Handle = sessionPtr; } } finally { if (sessionConfig.ApplicationKey != IntPtr.Zero) { Marshal.FreeHGlobal(sessionConfig.ApplicationKey); sessionConfig.ApplicationKey = IntPtr.Zero; } } _mainThreadNotification = new AutoResetEvent(false); _mainThread = new Thread(MainThreadLoop); _mainThread.Name = "MainLoop"; _mainThread.IsBackground = true; _mainThread.Start(); _eventQueue = new Queue<DelegateInvoker>(); _eventThread = new Thread(EventThreadLoop); _eventThread.Name = "EventLoop"; _eventThread.IsBackground = true; _eventThread.Start(); //AppDomain.CurrentDomain.ProcessExit += OnHostProcessExit; } #endregion Public Methods #region Internal Methods internal void Queue(DelegateInvoker delegateInvoker) { lock (_eventQueueLock) { _eventQueue.Enqueue(delegateInvoker); Monitor.Pulse(_eventQueueLock); } } internal void OnNotifyMainThread() { _mainThreadNotification.Set(); } internal void OnException(SessionEventArgs e) { Exception.RaiseEvent(this, e); } internal void OnLoginComplete(SessionEventArgs e) { if (e.Status == Error.OK) { _playlistContainer = PlaylistContainerManager.Get(this, Spotify.sp_session_playlistcontainer(Handle)); } LoginComplete.RaiseEvent(this, e); } internal void OnLogoutComplete(SessionEventArgs e) { LogoutComplete.RaiseEvent(this, e); } internal void OnLogMessage(SessionEventArgs e) { LogMessage.RaiseEvent(this, e); } internal void OnConnectionError(SessionEventArgs e) { ConnectionError.RaiseEvent(this, e); } internal void OnEndOfTrack(SessionEventArgs e) { EndOfTrack.RaiseEvent(this, e); } internal void OnMessageToUser(SessionEventArgs e) { MessageToUser.RaiseEvent(this, e); } internal void OnMetadataUpdated(SessionEventArgs e) { MetadataUpdated.RaiseEvent(this, e); } internal void OnMusicDeliver(MusicDeliveryEventArgs e) { MusicDeliver.RaiseEvent(this, e); } internal void OnPlayTokenLost(SessionEventArgs e) { PlayTokenLost.RaiseEvent(this, e); } internal void OnStartPlayback(SessionEventArgs e) { StartPlayback.RaiseEvent(this, e); } internal void OnStopPlayback(SessionEventArgs e) { StopPlayback.RaiseEvent(this, e); } internal void OnStreamingError(SessionEventArgs e) { StreamingError.RaiseEvent(this, e); } internal void OnUserinfoUpdated(SessionEventArgs e) { UserinfoUpdated.RaiseEvent(this, e); } internal void OnOfflineStatusUpdated(SessionEventArgs e) { OfflineStatusUpdated.RaiseEvent(this, e); } internal void OnOfflineError(SessionEventArgs e) { OfflineError.RaiseEvent(this, e); } internal void OnCredentialsBlobUpdated(CredentialsBlobEventArgs e) { CredentialsBlobUpdated.RaiseEvent(this, e); } internal void OnConnectionStateUpdated(SessionEventArgs e) { ConnectionStateUpdated.RaiseEvent(this, e); } internal void OnScrobbleError(SessionEventArgs e) { ScrobbleError.RaiseEvent(this, e); } internal void OnPrivateSessionModeChanged(PrivateSessionModeChangedEventArgs e) { PrivateSessionModeChanged.RaiseEvent(this, e); } #endregion Internal Methods #region Protected Methods protected override void Dispose(bool disposing) { if (disposing) { // Dispose managed } // Dispose unmanaged if (!IsInvalid) { try { _mainThreadNotification.Set(); lock (_eventQueueLock) { Monitor.Pulse(_eventQueueLock); } if (_callbacks != null) { _callbacks.Dispose(); _callbacks = null; } PlaylistTrackManager.RemoveAll(this); TrackManager.DisposeAll(this); LinkManager.RemoveAll(this); UserManager.RemoveAll(this); PlaylistContainerManager.RemoveAll(this); PlaylistManager.RemoveAll(this); ContainerPlaylistManager.RemoveAll(this); ArtistManager.RemoveAll(); AlbumManager.RemoveAll(); SessionManager.Remove(Handle); lock (Spotify.Mutex) { Error error = Error.OK; if (ConnectionState == ConnectionState.LoggedIn) { error = Spotify.sp_session_logout(Handle); Debug.WriteLineIf(error != Error.OK, error.GetMessage()); } Ensure(() => error = Spotify.sp_session_release(Handle)); Debug.WriteLineIf(error != Error.OK, error.GetMessage()); } } catch { // Ignore } finally { Debug.WriteLine("Session disposed"); } } base.Dispose(disposing); } #endregion Protected Methods #region Private Methods /* private void OnHostProcessExit(object sender, EventArgs e) { Dispose(); } */ private void MainThreadLoop() { int waitTime = 0; while (!IsInvalid && waitTime >= 0) { _mainThreadNotification.WaitOne(waitTime, false); do { lock (Spotify.Mutex) { try { if (IsInvalid) { break; } Error error = Spotify.sp_session_process_events(Handle, out waitTime); if (error != Error.OK) { Debug.WriteLine(Spotify.sp_error_message(error)); } } catch { waitTime = 1000; } } } while (waitTime == 0); } Debug.WriteLine("Main loop exiting."); } private void EventThreadLoop() { while (!IsInvalid) { DelegateInvoker invoker = null; lock (_eventQueueLock) { if (_eventQueue.Count == 0) { Monitor.Wait(_eventQueueLock); } if (_eventQueue.Count > 0) { invoker = _eventQueue.Dequeue(); } } if (invoker != null) { try { invoker.Execute(); } catch (Exception ex) { OnException(new SessionEventArgs(ex.ToString())); } } } Debug.WriteLine("Event loop exiting"); } #endregion Private Methods } }
/* * 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; using System.IO; using System.Reflection; using System.Net; using System.Text; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nwc.XmlRpc; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Login { public class LLLoginHandlers { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ILoginService m_LocalService; private bool m_Proxy; public LLLoginHandlers(ILoginService service, bool hasProxy) { m_LocalService = service; m_Proxy = hasProxy; } public XmlRpcResponse HandleXMLRPCLogin(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; if (m_Proxy && request.Params[3] != null) { IPEndPoint ep = Util.GetClientIPFromXFF((string)request.Params[3]); if (ep != null) // Bang! remoteClient = ep; } if (requestData != null) { if (requestData.ContainsKey("first") && requestData["first"] != null && requestData.ContainsKey("last") && requestData["last"] != null && requestData.ContainsKey("passwd") && requestData["passwd"] != null) { string first = requestData["first"].ToString(); string last = requestData["last"].ToString(); string passwd = requestData["passwd"].ToString(); string startLocation = string.Empty; UUID scopeID = UUID.Zero; if (requestData["scope_id"] != null) scopeID = new UUID(requestData["scope_id"].ToString()); if (requestData.ContainsKey("start")) startLocation = requestData["start"].ToString(); string clientVersion = "Unknown"; if (requestData.Contains("version") && requestData["version"] != null) clientVersion = requestData["version"].ToString(); // We should do something interesting with the client version... string channel = "Unknown"; if (requestData.Contains("channel") && requestData["channel"] != null) channel = requestData["channel"].ToString(); string mac = "Unknown"; if (requestData.Contains("mac") && requestData["mac"] != null) mac = requestData["mac"].ToString(); string id0 = "Unknown"; if (requestData.Contains("id0") && requestData["id0"] != null) id0 = requestData["id0"].ToString(); //m_log.InfoFormat("[LOGIN]: XMLRPC Login Requested for {0} {1}, starting in {2}, using {3}", first, last, startLocation, clientVersion); LoginResponse reply = null; reply = m_LocalService.Login(first, last, passwd, startLocation, scopeID, clientVersion, channel, mac, id0, remoteClient); XmlRpcResponse response = new XmlRpcResponse(); response.Value = reply.ToHashtable(); return response; } } return FailedXMLRPCResponse(); } public XmlRpcResponse HandleXMLRPCSetLoginLevel(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; if (requestData != null) { if (requestData.ContainsKey("first") && requestData["first"] != null && requestData.ContainsKey("last") && requestData["last"] != null && requestData.ContainsKey("level") && requestData["level"] != null && requestData.ContainsKey("passwd") && requestData["passwd"] != null) { string first = requestData["first"].ToString(); string last = requestData["last"].ToString(); string passwd = requestData["passwd"].ToString(); int level = Int32.Parse(requestData["level"].ToString()); m_log.InfoFormat("[LOGIN]: XMLRPC Set Level to {2} Requested by {0} {1}", first, last, level); Hashtable reply = m_LocalService.SetLevel(first, last, passwd, level, remoteClient); XmlRpcResponse response = new XmlRpcResponse(); response.Value = reply; return response; } } XmlRpcResponse failResponse = new XmlRpcResponse(); Hashtable failHash = new Hashtable(); failHash["success"] = "false"; failResponse.Value = failHash; return failResponse; } public OSD HandleLLSDLogin(OSD request, IPEndPoint remoteClient) { if (request.Type == OSDType.Map) { OSDMap map = (OSDMap)request; if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) { string startLocation = string.Empty; if (map.ContainsKey("start")) startLocation = map["start"].AsString(); UUID scopeID = UUID.Zero; if (map.ContainsKey("scope_id")) scopeID = new UUID(map["scope_id"].AsString()); m_log.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" + map["last"].AsString() + "' / " + startLocation); LoginResponse reply = null; reply = m_LocalService.Login(map["first"].AsString(), map["last"].AsString(), map["passwd"].AsString(), startLocation, scopeID, map["version"].AsString(), map["channel"].AsString(), map["mac"].AsString(), map["id0"].AsString(), remoteClient); return reply.ToOSDMap(); } } return FailedOSDResponse(); } private XmlRpcResponse FailedXMLRPCResponse() { Hashtable hash = new Hashtable(); hash["reason"] = "key"; hash["message"] = "Incomplete login credentials. Check your username and password."; hash["login"] = "false"; XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } private OSD FailedOSDResponse() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("key"); map["message"] = OSD.FromString("Invalid login credentials. Check your username and passwd."); map["login"] = OSD.FromString("false"); return map; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Statistics; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("OrleansTaskScheduler RunQueueLength={" + nameof(RunQueueLength) + "}")] internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant { private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private readonly SchedulerStatisticsGroup schedulerStatistics; private readonly IOptions<StatisticsOptions> statisticsOptions; private readonly ILogger taskWorkItemLogger; private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; private bool applicationTurnsStopped; private readonly CancellationTokenSource cancellationTokenSource; private readonly OrleansSchedulerAsynchAgent systemAgent; private readonly OrleansSchedulerAsynchAgent mainAgent; private readonly int maximumConcurrencyLevel; internal static TimeSpan TurnWarningLengthThreshold { get; set; } // This is the maximum number of pending work items for a single activation before we write a warning log. internal int MaxPendingItemsSoftLimit { get; private set; } public int RunQueueLength => systemAgent.Count + mainAgent.Count; public OrleansTaskScheduler( IOptions<SchedulingOptions> options, ExecutorService executorService, ILoggerFactory loggerFactory, SchedulerStatisticsGroup schedulerStatistics, IOptions<StatisticsOptions> statisticsOptions) { this.loggerFactory = loggerFactory; this.schedulerStatistics = schedulerStatistics; this.statisticsOptions = statisticsOptions; this.logger = loggerFactory.CreateLogger<OrleansTaskScheduler>(); cancellationTokenSource = new CancellationTokenSource(); WorkItemGroup.ActivationSchedulingQuantum = options.Value.ActivationSchedulingQuantum; applicationTurnsStopped = false; TurnWarningLengthThreshold = options.Value.TurnWarningLengthThreshold; this.MaxPendingItemsSoftLimit = options.Value.MaxPendingWorkItemsSoftLimit; workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>(); const int maxSystemThreads = 2; var maxActiveThreads = options.Value.MaxActiveThreads; maximumConcurrencyLevel = maxActiveThreads + maxSystemThreads; OrleansSchedulerAsynchAgent CreateSchedulerAsynchAgent(string agentName, bool drainAfterCancel, int degreeOfParallelism) { return new OrleansSchedulerAsynchAgent( agentName, executorService, degreeOfParallelism, options.Value.DelayWarningThreshold, options.Value.TurnWarningLengthThreshold, this, drainAfterCancel, loggerFactory); } mainAgent = CreateSchedulerAsynchAgent("Scheduler.LevelOne.MainQueue", false, maxActiveThreads); systemAgent = CreateSchedulerAsynchAgent("Scheduler.LevelOne.SystemQueue", true, maxSystemThreads); this.taskWorkItemLogger = loggerFactory.CreateLogger<TaskWorkItem>(); logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 2 system thread.", maxActiveThreads); IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength); if (!schedulerStatistics.CollectShedulerQueuesStats) return; FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo); } public int WorkItemGroupCount => workgroupDirectory.Count; private float AverageRunQueueLengthLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count; } } private float AverageEnqueuedLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count; } } private float AverageArrivalRateLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count; } } private float SumRunQueueLengthLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght); } } private float SumEnqueuedLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests); } } private float SumArrivalRateLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate); } } public void StopApplicationTurns() { #if DEBUG logger.Debug("StopApplicationTurns"); #endif // Do not RunDown the application run queue, since it is still used by low priority system targets. applicationTurnsStopped = true; foreach (var group in workgroupDirectory.Values) { if (!group.IsSystemGroup) group.Stop(); } } public void Start() { systemAgent.Start(); mainAgent.Start(); } public void Stop() { cancellationTokenSource.Cancel(); mainAgent.Stop(); systemAgent.Stop(); } protected override IEnumerable<Task> GetScheduledTasks() { return Array.Empty<Task>(); } protected override void QueueTask(Task task) { var contextObj = task.AsyncState; #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = contextObj as ISchedulingContext; var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped logger.Warn(ErrorCode.SchedulerAppTurnsStopped_2, string.Format("Dropping Task {0} because application turns are stopped", task)); return; } if (workItemGroup == null) { var todo = new TaskWorkItem(this, task, context, this.taskWorkItemLogger); ScheduleExecution(todo); } else { var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.", task.Id, context); logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error); throw new InvalidOperationException(error); } } public void ScheduleExecution(IWorkItem workItem) { if (workItem.IsSystemPriority) { systemAgent.QueueRequest(workItem); } else { mainAgent.QueueRequest(workItem); } } // Enqueue a work item to a given context public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context) { #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("QueueWorkItem " + context); #endif if (workItem is TaskWorkItem) { var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.", workItem.ToString(), context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error); throw new InvalidOperationException(error); } var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped var msg = string.Format("Dropping work item {0} because application turns are stopped", workItem); logger.Warn(ErrorCode.SchedulerAppTurnsStopped_1, msg); return; } workItem.SchedulingContext = context; // We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start. Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem); // This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem. if (workItemGroup == null) { t.Start(this); } else { t.Start(workItemGroup.TaskRunner); } } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public WorkItemGroup RegisterWorkContext(ISchedulingContext context) { if (context == null) return null; var wg = new WorkItemGroup( this, context, this.loggerFactory, this.cancellationTokenSource.Token, this.schedulerStatistics, this.statisticsOptions); workgroupDirectory.TryAdd(context, wg); return wg; } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public void UnregisterWorkContext(ISchedulingContext context) { if (context == null) return; WorkItemGroup workGroup; if (workgroupDirectory.TryRemove(context, out workGroup)) workGroup.Stop(); } // public for testing only -- should be private, otherwise public WorkItemGroup GetWorkItemGroup(ISchedulingContext context) { if (context == null) return null; WorkItemGroup workGroup; if(workgroupDirectory.TryGetValue(context, out workGroup)) return workGroup; var error = String.Format("QueueWorkItem was called on a non-null context {0} but there is no valid WorkItemGroup for it.", context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongContext, error); throw new InvalidSchedulingContextException(error); } internal void CheckSchedulingContextValidity(ISchedulingContext context) { if (context == null) { throw new InvalidSchedulingContextException( "CheckSchedulingContextValidity was called on a null SchedulingContext." + "Please make sure you are not trying to create a Timer from outside Orleans Task Scheduler, " + "which will be the case if you create it inside Task.Run."); } GetWorkItemGroup(context); // GetWorkItemGroup throws for Invalid context } public TaskScheduler GetTaskScheduler(ISchedulingContext context) { if (context == null) return this; WorkItemGroup workGroup; return workgroupDirectory.TryGetValue(context, out workGroup) ? (TaskScheduler) workGroup.TaskRunner : this; } public override int MaximumConcurrencyLevel => maximumConcurrencyLevel; protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { //bool canExecuteInline = WorkerPoolThread.CurrentContext != null; var ctx = RuntimeContext.Current; bool canExecuteInline = ctx == null || ctx.ActivationContext==null; #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}", task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline); } #endif if (!canExecuteInline) return false; if (taskWasPreviouslyQueued) canExecuteInline = TryDequeue(task); if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads // We are on a worker pool thread, so can execute this task bool done = TryExecuteTask(task); if (!done) { logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } return done; } /// <summary> /// Run the specified task synchronously on the current thread /// </summary> /// <param name="task"><c>Task</c> to be executed</param> public void RunTask(Task task) { #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = RuntimeContext.CurrentActivationContext; var workItemGroup = GetWorkItemGroup(context); if (workItemGroup == null) { RuntimeContext.SetExecutionContext(null); bool done = TryExecuteTask(task); if (!done) logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } else { var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.", task.Id, context); logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error); throw new InvalidOperationException(error); } #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif } // Returns true if healthy, false if not public bool CheckHealth(DateTime lastCheckTime) { return mainAgent.CheckHealth(lastCheckTime) && systemAgent.CheckHealth(lastCheckTime); } internal void PrintStatistics() { if (!logger.IsEnabled(LogLevel.Information)) return; var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), Environment.NewLine); if (stats.Length > 0) logger.Info(ErrorCode.SchedulerStatistics, "OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:" + Environment.NewLine + "{2}", RunQueueLength, WorkItemGroupCount, stats); } internal void DumpSchedulerStatus(bool alwaysOutput = true) { if (!logger.IsEnabled(LogLevel.Debug) && !alwaysOutput) return; PrintStatistics(); var sb = new StringBuilder(); sb.AppendLine("Dump of current OrleansTaskScheduler status:"); sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}", Environment.ProcessorCount, RunQueueLength, workgroupDirectory.Count, applicationTurnsStopped ? "STOPPING" : "").AppendLine(); // todo: either remove or support. At the time of writting is being used only in tests // sb.AppendLine("RunQueue:"); // RunQueue.DumpStatus(sb); - woun't work without additional costs // Pool.DumpStatus(sb); foreach (var workgroup in workgroupDirectory.Values) sb.AppendLine(workgroup.DumpStatus()); logger.Info(ErrorCode.SchedulerStatus, sb.ToString()); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCard phone number implementation. /// </summary> public class PhoneNumber { #region Members private readonly Item m_pItem; private string m_Number = ""; private PhoneNumberType_enum m_Type = PhoneNumberType_enum.Voice; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="item">Owner vCard item.</param> /// <param name="type">Phone number type. Note: This value can be flagged value !</param> /// <param name="number">Phone number.</param> internal PhoneNumber(Item item, PhoneNumberType_enum type, string number) { m_pItem = item; m_Type = type; m_Number = number; } #endregion #region Properties /// <summary> /// Gets underlaying vCrad item. /// </summary> public Item Item { get { return m_pItem; } } /// <summary> /// Gets or sets phone number. /// </summary> public string Number { get { return m_Number; } set { m_Number = value; Changed(); } } /// <summary> /// Gets or sets phone number type. Note: This property can be flagged value ! /// </summary> public PhoneNumberType_enum NumberType { get { return m_Type; } set { m_Type = value; Changed(); } } #endregion #region Internal methods /// <summary> /// Parses phone from vCard TEL structure string. /// </summary> /// <param name="item">vCard TEL item.</param> internal static PhoneNumber Parse(Item item) { PhoneNumberType_enum type = PhoneNumberType_enum.NotSpecified; if (item.ParametersString.ToUpper().IndexOf("PREF") != -1) { type |= PhoneNumberType_enum.Preferred; } if (item.ParametersString.ToUpper().IndexOf("HOME") != -1) { type |= PhoneNumberType_enum.Home; } if (item.ParametersString.ToUpper().IndexOf("MSG") != -1) { type |= PhoneNumberType_enum.Msg; } if (item.ParametersString.ToUpper().IndexOf("WORK") != -1) { type |= PhoneNumberType_enum.Work; } if (item.ParametersString.ToUpper().IndexOf("VOICE") != -1) { type |= PhoneNumberType_enum.Voice; } if (item.ParametersString.ToUpper().IndexOf("FAX") != -1) { type |= PhoneNumberType_enum.Fax; } if (item.ParametersString.ToUpper().IndexOf("CELL") != -1) { type |= PhoneNumberType_enum.Cellular; } if (item.ParametersString.ToUpper().IndexOf("VIDEO") != -1) { type |= PhoneNumberType_enum.Video; } if (item.ParametersString.ToUpper().IndexOf("PAGER") != -1) { type |= PhoneNumberType_enum.Pager; } if (item.ParametersString.ToUpper().IndexOf("BBS") != -1) { type |= PhoneNumberType_enum.BBS; } if (item.ParametersString.ToUpper().IndexOf("MODEM") != -1) { type |= PhoneNumberType_enum.Modem; } if (item.ParametersString.ToUpper().IndexOf("CAR") != -1) { type |= PhoneNumberType_enum.Car; } if (item.ParametersString.ToUpper().IndexOf("ISDN") != -1) { type |= PhoneNumberType_enum.ISDN; } if (item.ParametersString.ToUpper().IndexOf("PCS") != -1) { type |= PhoneNumberType_enum.PCS; } return new PhoneNumber(item, type, item.Value); } /// <summary> /// Converts PhoneNumberType_enum to vCard item parameters string. /// </summary> /// <param name="type">Value to convert.</param> /// <returns></returns> internal static string PhoneTypeToString(PhoneNumberType_enum type) { string retVal = ""; if ((type & PhoneNumberType_enum.BBS) != 0) { retVal += "BBS,"; } if ((type & PhoneNumberType_enum.Car) != 0) { retVal += "CAR,"; } if ((type & PhoneNumberType_enum.Cellular) != 0) { retVal += "CELL,"; } if ((type & PhoneNumberType_enum.Fax) != 0) { retVal += "FAX,"; } if ((type & PhoneNumberType_enum.Home) != 0) { retVal += "HOME,"; } if ((type & PhoneNumberType_enum.ISDN) != 0) { retVal += "ISDN,"; } if ((type & PhoneNumberType_enum.Modem) != 0) { retVal += "MODEM,"; } if ((type & PhoneNumberType_enum.Msg) != 0) { retVal += "MSG,"; } if ((type & PhoneNumberType_enum.Pager) != 0) { retVal += "PAGER,"; } if ((type & PhoneNumberType_enum.PCS) != 0) { retVal += "PCS,"; } if ((type & PhoneNumberType_enum.Preferred) != 0) { retVal += "PREF,"; } if ((type & PhoneNumberType_enum.Video) != 0) { retVal += "VIDEO,"; } if ((type & PhoneNumberType_enum.Voice) != 0) { retVal += "VOICE,"; } if ((type & PhoneNumberType_enum.Work) != 0) { retVal += "WORK,"; } if (retVal.EndsWith(",")) { retVal = retVal.Substring(0, retVal.Length - 1); } return retVal; } #endregion #region Utility methods /// <summary> /// This method is called when some property has changed, wee need to update underlaying vCard item. /// </summary> private void Changed() { m_pItem.ParametersString = PhoneTypeToString(m_Type); m_pItem.Value = m_Number; } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace HtmlHelp.UIComponents { /// <summary> /// The class <c>helpIndex</c> implements a user control which displays the HtmlHelp index pane /// known by the default HtmlHelp viewer /// </summary> public class helpIndex : System.Windows.Forms.UserControl { /// <summary> /// Event if the user changes the selection in the toc tree /// </summary> public event IndexSelectedEventHandler IndexSelected; /// <summary> /// Event if the user selects a keyword which is bound to more than one topic. /// </summary> /// <remarks>If you don't add an event handler for this event, the user control will show its own dialog /// with the found topics.</remarks> public event TopicsFoundEventHandler TopicsFound; /// <summary> /// Internal member storing the arraylist of indezes /// </summary> public ArrayList _arrIndex = null; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbLookfor; private System.Windows.Forms.ListBox lbIndex; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Button btnDisplay; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// Constructor of the class /// </summary> public helpIndex() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } /// <summary> /// Fireing the on selected event /// </summary> /// <param name="e">event parameters</param> protected virtual void OnIndexSelected(IndexEventArgs e) { if(IndexSelected != null) { IndexSelected(this,e); } } /// <summary> /// Fireing the topics found event /// </summary> /// <param name="e">event parameters</param> protected virtual void OnTopicsFound(TopicsFoundEventArgs e) { if(TopicsFound != null) { TopicsFound(this,e); } else { // if the user doesn't handle this event, // show an internal dialog listing the found topics TopicsFound frmTopics = new TopicsFound(); frmTopics.Items= e.Topics; if( frmTopics.ShowDialog() == DialogResult.OK ) { OnIndexSelected( new IndexEventArgs( frmTopics.SelectedTitle, frmTopics.SelectedUrl, false, new string[0]) ); } } } /// <summary> /// Clears the items displayed in the index pane /// </summary> public void ClearContents() { lbIndex.Items.Clear(); } /// <summary> /// Call this method to build the help-index and fill the internal list box /// </summary> /// <param name="index">Index instance extracted from the chm file(s)</param> /// <param name="typeOfIndex">type of index to display</param> public void BuildIndex(Index index, IndexType typeOfIndex) { BuildIndex(index, typeOfIndex, null); } /// <summary> /// Call this method to build the help-index and fill the internal list box /// </summary> /// <param name="index">Index instance extracted from the chm file(s)</param> /// <param name="typeOfIndex">type of index to display</param> /// <param name="filter">information type/category filter</param> public void BuildIndex(Index index, IndexType typeOfIndex, InfoTypeCategoryFilter filter) { switch(typeOfIndex) { case IndexType.AssiciativeLinks: _arrIndex = index.ALinks; break; case IndexType.KeywordLinks: _arrIndex = index.KLinks; break; } lbIndex.Items.Clear(); foreach(IndexItem curItem in _arrIndex) { bool bAdd = true; if(filter != null) { bAdd = false; if(curItem.InfoTypeStrings.Count <= 0) { bAdd=true; } else { for(int i=0;i<curItem.InfoTypeStrings.Count;i++) { bAdd |= filter.Match( curItem.InfoTypeStrings[i].ToString() ); } } } if(bAdd) { lbIndex.Items.Add( curItem.IndentKeyWord ); } } } /// <summary> /// Sets the selected index text /// </summary> /// <param name="indexText">text to select</param> public void SelectText(string indexText) { tbLookfor.Text = indexText.Trim(); int idx = lbIndex.FindString(indexText, 0); lbIndex.SelectedIndex = idx; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region 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.label1 = new System.Windows.Forms.Label(); this.tbLookfor = new System.Windows.Forms.TextBox(); this.lbIndex = new System.Windows.Forms.ListBox(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.btnDisplay = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 16); this.label1.TabIndex = 0; this.label1.Text = "Look for:"; // // tbLookfor // this.tbLookfor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbLookfor.Location = new System.Drawing.Point(0, 16); this.tbLookfor.Name = "tbLookfor"; this.tbLookfor.Size = new System.Drawing.Size(272, 20); this.tbLookfor.TabIndex = 1; this.tbLookfor.Text = ""; this.tbLookfor.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tbLookfor_KeyPress); this.tbLookfor.TextChanged += new System.EventHandler(this.tbLookfor_TextChanged); // // lbIndex // this.lbIndex.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.lbIndex.Location = new System.Drawing.Point(0, 0); this.lbIndex.Name = "lbIndex"; this.lbIndex.Size = new System.Drawing.Size(272, 277); this.lbIndex.TabIndex = 2; this.lbIndex.DoubleClick += new System.EventHandler(this.lbIndex_DoubleClick); // // panel1 // this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.tbLookfor); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(272, 40); this.panel1.TabIndex = 3; // // panel2 // this.panel2.Controls.Add(this.btnDisplay); this.panel2.Controls.Add(this.lbIndex); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(0, 40); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(272, 307); this.panel2.TabIndex = 4; // // btnDisplay // this.btnDisplay.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnDisplay.Location = new System.Drawing.Point(192, 281); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.TabIndex = 3; this.btnDisplay.Text = "&Display"; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // helpIndex // this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Name = "helpIndex"; this.Size = new System.Drawing.Size(272, 347); this.panel1.ResumeLayout(false); this.panel2.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// Called if the user double-clicks on the listbox /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void lbIndex_DoubleClick(object sender, System.EventArgs e) { DisplayTopic(false); } /// <summary> /// Called if the user clicks on the <c>Display</c> button /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void btnDisplay_Click(object sender, System.EventArgs e) { DisplayTopic(true); } /// <summary> /// Checks the selection of the listbox. If the keyword contains more than one topic, /// a "Topics found" dialog will be displayed to the user and let him select de desired topic. /// Fires the <c>IndexSelected</c> event let the parent window know, that the user wants to view /// a new help topic. /// </summary> /// <param name="errorOnNothingSelected">set this true, if you want to display an error message if no item is selected</param> private void DisplayTopic(bool errorOnNothingSelected) { if(lbIndex.SelectedIndex >= 0) { IndexItem item = (IndexItem) _arrIndex[lbIndex.SelectedIndex]; if( item.Topics.Count > 1) { OnTopicsFound( new TopicsFoundEventArgs(item.Topics)); } else { if(item.IsSeeAlso) { if( item.SeeAlso.Length>0) { SelectText( item.SeeAlso[0] ); string url = ""; string title = item.KeyWord; if (item.Topics.Count == 1) { url = ((IndexTopic)item.Topics[0]).URL; title = ((IndexTopic)item.Topics[0]).Title; } OnIndexSelected( new IndexEventArgs( title, url, item.IsSeeAlso, item.SeeAlso) ); return; } } if (item.Topics.Count == 1) { OnIndexSelected( new IndexEventArgs( ((IndexTopic)item.Topics[0]).Title, ((IndexTopic)item.Topics[0]).URL, item.IsSeeAlso, item.SeeAlso) ); } } } else { if(errorOnNothingSelected) { MessageBox.Show("Select a keyword first !","Index",MessageBoxButtons.OK, MessageBoxIcon.Error); } } } /// <summary> /// Called if the user changes the text of the "Loof for" textbox /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void tbLookfor_TextChanged(object sender, System.EventArgs e) { int idx = lbIndex.FindString(tbLookfor.Text, 0); lbIndex.SelectedIndex = idx; } /// <summary> /// Called if the user presses a key in the "Look for" textbox /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event parameter</param> private void tbLookfor_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if( e.KeyChar == (char)Keys.Enter ) { if( lbIndex.SelectedIndex >= 0) { DisplayTopic(true); e.Handled = true; } } } } }
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. // See full license at the bottom of this file. using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; namespace ClauseLibrary.Common { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { /// <summary> /// The sp host URL key /// </summary> public const string SPHostUrlKey = "SPHostUrl"; /// <summary> /// The sp application web URL key /// </summary> public const string SPAppWebUrlKey = "SPAppWebUrl"; /// <summary> /// The sp language key /// </summary> public const string SPLanguageKey = "SPLanguage"; /// <summary> /// The sp client tag key /// </summary> public const string SPClientTagKey = "SPClientTag"; /// <summary> /// The sp product number key /// </summary> public const string SPProductNumberKey = "SPProductNumber"; /// <summary> /// The access token lifetime tolerance /// </summary> protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri _spHostUrl; private readonly Uri _spAppWebUrl; private readonly string _spLanguage; private readonly string _spClientTag; private readonly string _spProductNumber; // <AccessTokenString, UtcExpiresOn> /// <summary> /// The user access token for sp host /// </summary> protected Tuple<string, DateTime> userAccessTokenForSPHost; /// <summary> /// The user access token for sp application web /// </summary> protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; /// <summary> /// The application only access token for sp host /// </summary> protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; /// <summary> /// The application only access token for sp application web /// </summary> protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return _spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return _spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return _spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return _spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return _spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this._spHostUrl = spHostUrl; this._spAppWebUrl = spAppWebUrl; this._spLanguage = spLanguage; this._spClientTag = spClientTag; this._spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(SPHostUrl, UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(SPAppWebUrl, UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(SPHostUrl, AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(SPAppWebUrl, AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { /// <summary> /// The ok /// </summary> Ok, /// <summary> /// The should redirect /// </summary> ShouldRedirect, /// <summary> /// The can not redirect /// </summary> CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { current = new SharePointAcsContextProvider(); } else { current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl) {Query = queryNameValueCollection.ToString()}; // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return contextTokenObj.ValidTo > DateTime.UtcNow ? contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return contextTokenObj.ValidTo > DateTime.UtcNow ? contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return contextTokenObj.ValidTo > DateTime.UtcNow ? contextTokenObj.RefreshToken : null; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(contextTokenObj, SPHostUrl.Authority)); } } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public override string UserAccessTokenForSPAppWeb { get { if (SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(contextTokenObj, SPAppWebUrl.Authority)); } } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(SPHostUrl))); } } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public override string AppOnlyAccessTokenForSPAppWeb { get { if (SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(SPAppWebUrl))); } } /// <summary> /// Initializes a new instance of the <see cref="SharePointAcsContext"/> class. /// </summary> /// <param name="spHostUrl">The sp host URL.</param> /// <param name="spAppWebUrl">The sp application web URL.</param> /// <param name="spLanguage">The sp language.</param> /// <param name="spClientTag">The sp client tag.</param> /// <param name="spProductNumber">The sp product number.</param> /// <param name="contextToken">The context token.</param> /// <param name="contextTokenObj">The context token object.</param> public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns> /// The SharePointContext instance. Returns <c>null</c> if errors occur. /// </returns> protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns> /// True if the given SharePointContext can be used with the specified HTTP context. /// </returns> protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns> /// The SharePointContext instance. Returns <c>null</c> if not found. /// </returns> protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return logonUserIdentity; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(SPHostUrl, LogonUserIdentity)); } } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public override string UserAccessTokenForSPAppWeb { get { if (SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(SPAppWebUrl, LogonUserIdentity)); } } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(SPHostUrl, null)); } } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public override string AppOnlyAccessTokenForSPAppWeb { get { if (SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(SPAppWebUrl, null)); } } /// <summary> /// Initializes a new instance of the <see cref="SharePointHighTrustContext"/> class. /// </summary> /// <param name="spHostUrl">The sp host URL.</param> /// <param name="spAppWebUrl">The sp application web URL.</param> /// <param name="spLanguage">The sp language.</param> /// <param name="spClientTag">The sp client tag.</param> /// <param name="spProductNumber">The sp product number.</param> /// <param name="logonUserIdentity">The logon user identity.</param> /// <exception cref="System.ArgumentNullException">logonUserIdentity</exception> public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns> /// The SharePointContext instance. Returns <c>null</c> if errors occur. /// </returns> protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns> /// True if the given SharePointContext can be used with the specified HTTP context. /// </returns> protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns> /// The SharePointContext instance. Returns <c>null</c> if not found. /// </returns> protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust } #region License // ClauseLibrary, https://github.com/OfficeDev/clauselibrary // // Copyright 2015(c) Microsoft Corporation // // All rights reserved. // // MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Exceptions; using Subtext.Framework.Infrastructure.Installation; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Framework.Components; namespace UnitTests.Subtext.InstallationTests { /// <summary> /// Tests of the InstallationManager class. /// </summary> [TestFixture] public class InstallationManagerTests { [Test] public void IsInstallationActionRequired_WithInstallerReturningNull_ReturnsTrue() { //arrange var installer = new Mock<IInstaller>(); installer.Setup(i => i.GetCurrentInstallationVersion()).Returns((Version)null); var cache = new TestCache(); cache["NeedsInstallation"] = null; var manager = new InstallationManager(installer.Object, cache); //act bool result = manager.InstallationActionRequired(new Version(), null); //assert Assert.IsTrue(result); } [Test] public void IsInstallationActionRequired_WithCachedInstallationStatusOfNeedsInstallation_ReturnsTrue() { //arrange var installer = new Mock<IInstaller>(); installer.Setup(i => i.GetCurrentInstallationVersion()).Throws(new InvalidOperationException()); var cache = new TestCache(); cache["NeedsInstallation"] = InstallationState.NeedsInstallation; var manager = new InstallationManager(installer.Object, cache); //act bool result = manager.InstallationActionRequired(new Version(), null); //assert Assert.IsTrue(result); } [Test] public void IsInstallationActionRequired_WithInstallerReturningSameVersionAsAssembly_ReturnsFalse() { //arrange var installer = new Mock<IInstaller>(); installer.Setup(i => i.GetCurrentInstallationVersion()).Returns(new Version(1, 0, 0, 0)); var installManager = new InstallationManager(installer.Object, new TestCache()); //act bool result = installManager.InstallationActionRequired(new Version(1, 0, 0, 0), null); //assert Assert.IsFalse(result); } [Test] public void IsInstallationActionRequired_WithHostDataDoesNotExistException_ReturnsTrue() { //arrange var installer = new Mock<IInstaller>(); var installManager = new InstallationManager(installer.Object, new TestCache()); //act bool result = installManager.InstallationActionRequired(new Version(), new HostDataDoesNotExistException()); //assert Assert.IsTrue(result); } [Test] public void Install_ResetsInstallationStatusCache() { // arrange var cache = new TestCache(); cache["NeedsInstallation"] = InstallationState.NeedsInstallation; var installer = new Mock<IInstaller>(); installer.Setup(i => i.Install(It.IsAny<Version>())); var installManager = new InstallationManager(installer.Object, cache); // act installManager.Install(new Version()); // assert Assert.IsNull(cache["NeedsInstallation"]); } [Test] public void Upgrade_ResetsInstallationStatusCache() { // arrange var cache = new TestCache(); cache["NeedsInstallation"] = InstallationState.NeedsInstallation; var installer = new Mock<IInstaller>(); installer.Setup(i => i.Upgrade(It.IsAny<Version>())); var installManager = new InstallationManager(installer.Object, cache); // act installManager.Upgrade(new Version()); // assert Assert.IsNull(cache["NeedsInstallation"]); } [Test] public void ResetInstallationStatusCache_WithApplicationNeedingInstallation_SetsStatusToNull() { // arrange var cache = new TestCache(); cache["NeedsInstallation"] = InstallationState.NeedsInstallation; var installManager = new InstallationManager(null, cache); // act installManager.ResetInstallationStatusCache(); // assert Assert.IsNull(cache["NeedsInstallation"]); } [Test] public void CreateWelcomeContent_CreatesIntroBlogPostAndCategories() { // arrange var installationManager = new InstallationManager(new Mock<IInstaller>().Object, null); var repository = new Mock<ObjectProvider>(); var entryPublisher = new Mock<IEntryPublisher>(); Entry entry = null; entryPublisher.Setup(p => p.Publish(It.Is<Entry>(e => e.PostType == PostType.BlogPost))).Callback<Entry>(e => entry = e); var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.AdminUrl("")).Returns("/admin/default.aspx"); urlHelper.Setup(u => u.EntryUrl(It.Is<Entry>(e => e.PostType == PostType.Story))).Returns<Entry>(e => "/articles/" + e.EntryName + ".aspx"); urlHelper.Setup(u => u.HostAdminUrl("default.aspx")).Returns("/hostadmin/default.aspx"); var context = new Mock<ISubtextContext>(); context.SetupUrlHelper(urlHelper); context.Setup(c => c.Repository).Returns(repository.Object); var blog = new Blog {Id = 123, Author = "TestAuthor"}; // act installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog); // assert Assert.AreEqual(entry.Title, "Welcome to Subtext!"); Assert.AreEqual(entry.EntryName, "welcome-to-subtext"); Assert.Contains(entry.Body, @"<a href=""/admin/default.aspx"); Assert.Contains(entry.Body, @"<a href=""/articles/welcome-to-subtext-article.aspx"); Assert.Contains(entry.Body, @"<a href=""/hostadmin/default.aspx"); Assert.IsTrue(entry.AllowComments); Assert.IsTrue(!entry.Body.Contains(@"<a href=""{0}")); Assert.IsTrue(!entry.Body.Contains(@"<a href=""{1}")); Assert.IsTrue(!entry.Body.Contains(@"<a href=""{2}")); } [Test] public void CreateWelcomeContent_CreatesIntroArticle() { // arrange var installationManager = new InstallationManager(new Mock<IInstaller>().Object, null); var repository = new Mock<ObjectProvider>(); var entryPublisher = new Mock<IEntryPublisher>(); Entry article = null; entryPublisher.Setup(p => p.Publish(It.Is<Entry>(e => e.PostType == PostType.Story))).Callback<Entry>(e => article = e); var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.AdminUrl("articles")).Returns("/admin/articles/default.aspx"); var context = new Mock<ISubtextContext>(); context.SetupUrlHelper(urlHelper); context.Setup(c => c.Repository).Returns(repository.Object); var blog = new Blog { Id = 123, Author = "TestAuthor" }; // act installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog); // assert Assert.AreEqual(article.Title, "Welcome to Subtext!"); Assert.Contains(article.Body, @"<a href=""/admin/articles/"); Assert.IsTrue(!article.Body.Contains(@"<a href=""{0}")); } [Test] public void CreateWelcomeContent_CreatesIntroComment() { // arrange var installationManager = new InstallationManager(new Mock<IInstaller>().Object, null); var repository = new Mock<ObjectProvider>(); var entryPublisher = new Mock<IEntryPublisher>(); var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.AdminUrl("feedback")).Returns("/admin/feedback/default.aspx"); var context = new Mock<ISubtextContext>(); context.SetupUrlHelper(urlHelper); context.Setup(c => c.Repository).Returns(repository.Object); var blog = new Blog { Id = 123, Author = "TestAuthor" }; FeedbackItem comment = null; repository.Setup(r => r.Create(It.IsAny<FeedbackItem>())).Callback<FeedbackItem>(c => comment = c); // act installationManager.CreateWelcomeContent(context.Object, entryPublisher.Object, blog); // assert Assert.IsTrue(comment.Approved); Assert.AreEqual(comment.Title, "re: Welcome to Subtext!"); Assert.Contains(comment.Body, @"<a href=""/admin/feedback/"); Assert.IsTrue(!comment.Body.Contains(@"<a href=""{1}")); } /// <summary> /// Called before each unit test. /// </summary> [TestFixtureSetUp] public void TestFixtureSetUp() { //Confirm app settings UnitTestHelper.AssertAppSettings(); } } }
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 NSubstitute; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Collections.Generic; using IBM.Cloud.SDK.Core.Http; using IBM.Cloud.SDK.Core.Http.Exceptions; using IBM.Cloud.SDK.Core.Authentication.NoAuth; using IBM.Watson.VisualRecognition.v4.Model; using IBM.Cloud.SDK.Core.Model; namespace IBM.Watson.VisualRecognition.v4.UnitTests { [TestClass] public class VisualRecognitionServiceUnitTests { #region Constructor [TestMethod, ExpectedException(typeof(ArgumentNullException))] public void Constructor_HttpClient_Null() { VisualRecognitionService service = new VisualRecognitionService(httpClient: null); } [TestMethod] public void ConstructorHttpClient() { VisualRecognitionService service = new VisualRecognitionService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorExternalConfig() { var apikey = System.Environment.GetEnvironmentVariable("VISUAL_RECOGNITION_APIKEY"); System.Environment.SetEnvironmentVariable("VISUAL_RECOGNITION_APIKEY", "apikey"); VisualRecognitionService service = Substitute.For<VisualRecognitionService>("versionDate"); Assert.IsNotNull(service); System.Environment.SetEnvironmentVariable("VISUAL_RECOGNITION_APIKEY", apikey); } [TestMethod] public void Constructor() { VisualRecognitionService service = new VisualRecognitionService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorAuthenticator() { VisualRecognitionService service = new VisualRecognitionService("versionDate", new NoAuthAuthenticator()); Assert.IsNotNull(service); } [TestMethod, ExpectedException(typeof(ArgumentNullException))] public void ConstructorNoVersion() { VisualRecognitionService service = new VisualRecognitionService(null, new NoAuthAuthenticator()); } [TestMethod] public void ConstructorNoUrl() { var apikey = System.Environment.GetEnvironmentVariable("VISUAL_RECOGNITION_APIKEY"); System.Environment.SetEnvironmentVariable("VISUAL_RECOGNITION_APIKEY", "apikey"); var url = System.Environment.GetEnvironmentVariable("VISUAL_RECOGNITION_URL"); System.Environment.SetEnvironmentVariable("VISUAL_RECOGNITION_URL", null); VisualRecognitionService service = Substitute.For<VisualRecognitionService>("versionDate"); Assert.IsTrue(service.ServiceUrl == "https://api.us-south.visual-recognition.watson.cloud.ibm.com"); System.Environment.SetEnvironmentVariable("VISUAL_RECOGNITION_URL", url); System.Environment.SetEnvironmentVariable("VISUAL_RECOGNITION_APIKEY", apikey); } #endregion [TestMethod] public void Analyze_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionIds = new List<string>() { "collectionIds0", "collectionIds1" }; var features = new List<string>() { "features0", "features1" }; var imagesFile = new List<FileWithMetadata>() { new FileWithMetadata() { Filename = "filename", ContentType = "contentType", Data = new System.IO.MemoryStream() } }; var imageUrl = new List<string>() { "imageUrl0", "imageUrl1" }; float? threshold = 0.5f; var result = service.Analyze(collectionIds: collectionIds, features: features, imagesFile: imagesFile, imageUrl: imageUrl, threshold: threshold); request.Received().WithArgument("version", versionDate); } [TestMethod] public void CreateCollection_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var name = "name"; var description = "description"; var result = service.CreateCollection(name: name, description: description); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(name)) { bodyObject["name"] = JToken.FromObject(name); } if (!string.IsNullOrEmpty(description)) { bodyObject["description"] = JToken.FromObject(description); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithArgument("version", versionDate); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); } [TestMethod] public void ListCollections_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var result = service.ListCollections(); request.Received().WithArgument("version", versionDate); } [TestMethod] public void GetCollection_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var result = service.GetCollection(collectionId: collectionId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v4/collections/{collectionId}"); } [TestMethod] public void UpdateCollection_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var name = "name"; var description = "description"; var result = service.UpdateCollection(collectionId: collectionId, name: name, description: description); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(name)) { bodyObject["name"] = JToken.FromObject(name); } if (!string.IsNullOrEmpty(description)) { bodyObject["description"] = JToken.FromObject(description); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithArgument("version", versionDate); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v4/collections/{collectionId}"); } [TestMethod] public void DeleteCollection_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var result = service.DeleteCollection(collectionId: collectionId); request.Received().WithArgument("version", versionDate); client.Received().DeleteAsync($"{service.ServiceUrl}/v4/collections/{collectionId}"); } [TestMethod] public void AddImages_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var imagesFile = new List<FileWithMetadata>() { new FileWithMetadata() { Filename = "filename", ContentType = "contentType", Data = new System.IO.MemoryStream() } }; var imageUrl = new List<string>() { "imageUrl0", "imageUrl1" }; var trainingData = "trainingData"; var result = service.AddImages(collectionId: collectionId, imagesFile: imagesFile, imageUrl: imageUrl, trainingData: trainingData); request.Received().WithArgument("version", versionDate); client.Received().PostAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/images"); } [TestMethod] public void ListImages_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var result = service.ListImages(collectionId: collectionId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/images"); } [TestMethod] public void GetImageDetails_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var imageId = "imageId"; var result = service.GetImageDetails(collectionId: collectionId, imageId: imageId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/images/{imageId}"); } [TestMethod] public void DeleteImage_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var imageId = "imageId"; var result = service.DeleteImage(collectionId: collectionId, imageId: imageId); request.Received().WithArgument("version", versionDate); client.Received().DeleteAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/images/{imageId}"); } [TestMethod] public void GetJpegImage_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var imageId = "imageId"; var size = "size"; var result = service.GetJpegImage(collectionId: collectionId, imageId: imageId, size: size); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/images/{imageId}/jpeg"); } [TestMethod] public void Train_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var result = service.Train(collectionId: collectionId); request.Received().WithArgument("version", versionDate); client.Received().PostAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/train"); } [TestMethod] public void AddImageTrainingData_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var collectionId = "collectionId"; var imageId = "imageId"; var objects = new List<TrainingDataObject>(); var result = service.AddImageTrainingData(collectionId: collectionId, imageId: imageId, objects: objects); JObject bodyObject = new JObject(); if (objects != null && objects.Count > 0) { bodyObject["objects"] = JToken.FromObject(objects); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithArgument("version", versionDate); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v4/collections/{collectionId}/images/{imageId}/training_data"); } [TestMethod] public void GetTrainingUsage_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var startTime = "2019-11-18"; var endTime = "2020-11-20"; var dateStartTime = DateTime.Parse(startTime); var dateEndTime = DateTime.Parse(endTime); var result = service.GetTrainingUsage(startTime: dateStartTime, endTime: dateEndTime); request.Received().WithArgument("version", versionDate); } [TestMethod] public void DeleteUserData_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); VisualRecognitionService service = new VisualRecognitionService(client); var versionDate = "versionDate"; service.Version = versionDate; var customerId = "customerId"; var result = service.DeleteUserData(customerId: customerId); request.Received().WithArgument("version", versionDate); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; #if FEATURE_SECURITY_PRINCIPAL_WINDOWS using System.Security.AccessControl; using System.Security.Principal; #endif using System.Text; using System.Threading; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Shared; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using ProjectCollection = Microsoft.Build.Evaluation.ProjectCollection; using Xunit; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Test the ProjectRootElement class /// </summary> public class ProjectRootElement_Tests { private const string SimpleProject = @"<Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <PropertyGroup> <ProjectFile>$(MSBuildProjectFullPath)</ProjectFile> <ThisFile>$(MSBuildThisFileFullPath)</ThisFile> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> </Project>"; private const string ComplexProject = @"<?xml version=""1.0"" encoding=""utf-16""?> <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <PropertyGroup Condition=""false""> <p>p1</p> <q>q1</q> </PropertyGroup> <PropertyGroup/> <PropertyGroup> <r>r1</r> </PropertyGroup> <PropertyGroup> <ProjectFile>$(MSBuildProjectFullPath)</ProjectFile> <ThisFile>$(MSBuildThisFileFullPath)</ThisFile> </PropertyGroup> <Choose> <When Condition=""true""> <Choose> <When Condition=""true""> <PropertyGroup> <s>s1</s> </PropertyGroup> </When> </Choose> </When> <When Condition=""false""> <PropertyGroup> <s>s2</s> <!-- both esses --> </PropertyGroup> </When> <Otherwise> <Choose> <When Condition=""false""/> <Otherwise> <PropertyGroup> <t>t1</t> </PropertyGroup> </Otherwise> </Choose> </Otherwise> </Choose> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets'/> </Project>"; /// <summary> /// Empty project content /// </summary> [Fact] public void EmptyProject() { ProjectRootElement project = ProjectRootElement.Create(); Assert.Equal(0, Helpers.Count(project.Children)); Assert.Equal(string.Empty, project.DefaultTargets); Assert.Equal(string.Empty, project.InitialTargets); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.ToolsVersion); Assert.True(project.HasUnsavedChanges); // it is indeed unsaved } /// <summary> /// Set default targets /// </summary> [Fact] public void SetDefaultTargets() { ProjectRootElement project = ProjectRootElement.Create(); project.DefaultTargets = "dt"; Assert.Equal("dt", project.DefaultTargets); Assert.True(project.HasUnsavedChanges); } /// <summary> /// Set initialtargets /// </summary> [Fact] public void SetInitialTargets() { ProjectRootElement project = ProjectRootElement.Create(); project.InitialTargets = "it"; Assert.Equal("it", project.InitialTargets); Assert.True(project.HasUnsavedChanges); } /// <summary> /// Set toolsversion /// </summary> [Fact] public void SetToolsVersion() { ProjectRootElement project = ProjectRootElement.Create(); project.ToolsVersion = "tv"; Assert.Equal("tv", project.ToolsVersion); Assert.True(project.HasUnsavedChanges); } /// <summary> /// Setting full path should accept and update relative path /// </summary> [Fact] public void SetFullPath() { ProjectRootElement project = ProjectRootElement.Create(); project.FullPath = "X"; Assert.Equal(project.FullPath, Path.Combine(Directory.GetCurrentDirectory(), "X")); } /// <summary> /// Attempting to load a second ProjectRootElement over the same file path simply /// returns the first one. /// A ProjectRootElement is notionally a "memory mapped" view of a file, and we assume there is only /// one per file path, so we must reject attempts to make another. /// </summary> [Fact] public void ConstructOverSameFileReturnsSame() { ProjectRootElement projectXml1 = ProjectRootElement.Create(); projectXml1.Save(FileUtilities.GetTemporaryFile()); ProjectRootElement projectXml2 = ProjectRootElement.Open(projectXml1.FullPath); Assert.True(object.ReferenceEquals(projectXml1, projectXml2)); } /// <summary> /// Attempting to load a second ProjectRootElement over the same file path simply /// returns the first one. This should work even if one of the paths is not a full path. /// </summary> [Fact] public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath() { ProjectRootElement projectXml1 = ProjectRootElement.Create(); projectXml1.FullPath = Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc"); ProjectRootElement projectXml2 = ProjectRootElement.Open(@"xyz\abc"); Assert.True(object.ReferenceEquals(projectXml1, projectXml2)); } /// <summary> /// Attempting to load a second ProjectRootElement over the same file path simply /// returns the first one. This should work even if one of the paths is not a full path. /// </summary> [Fact] public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath2() { ProjectRootElement projectXml1 = ProjectRootElement.Create(); projectXml1.FullPath = @"xyz\abc"; ProjectRootElement projectXml2 = ProjectRootElement.Open(Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc")); Assert.True(object.ReferenceEquals(projectXml1, projectXml2)); } /// <summary> /// Using TextReader /// </summary> [Fact] public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath3() { string content = "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n</Project>"; ProjectRootElement projectXml1 = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); projectXml1.FullPath = @"xyz\abc"; ProjectRootElement projectXml2 = ProjectRootElement.Open(Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc")); Assert.True(object.ReferenceEquals(projectXml1, projectXml2)); } /// <summary> /// Using TextReader /// </summary> [Fact] public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath4() { string content = "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n</Project>"; ProjectRootElement projectXml1 = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); projectXml1.FullPath = Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc"); ProjectRootElement projectXml2 = ProjectRootElement.Open(@"xyz\abc"); Assert.True(object.ReferenceEquals(projectXml1, projectXml2)); } /// <summary> /// Two ProjectRootElement's over the same file path does not throw (although you shouldn't do it) /// </summary> [Fact] public void SetFullPathProjectXmlAlreadyLoaded() { ProjectRootElement projectXml1 = ProjectRootElement.Create(); projectXml1.FullPath = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); ProjectRootElement projectXml2 = ProjectRootElement.Create(); projectXml2.FullPath = projectXml1.FullPath; } /// <summary> /// Invalid XML /// </summary> [Fact] public void InvalidXml() { Assert.Throws<InvalidProjectFileException>(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader("XXX"))); } ); } /// <summary> /// Valid Xml, invalid namespace on the root /// </summary> [Fact] public void InvalidNamespace() { Assert.Throws<InvalidProjectFileException>(() => { var content = @"<Project xmlns='XXX'/>"; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); }); } /// <summary> /// Invalid root tag /// </summary> [Fact] public void InvalidRootTag() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <XXX xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Valid Xml, invalid syntax below the root /// </summary> [Fact] public void InvalidChildBelowRoot() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <XXX/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Root indicates upgrade needed /// </summary> [Fact] public void NeedsUpgrade() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <VisualStudioProject/> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Valid Xml, invalid namespace below the root /// </summary> [Fact] public void InvalidNamespaceBelowRoot() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup xmlns='XXX'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Tests that the namespace error reports are correct /// </summary> [Fact] public void InvalidNamespaceErrorReport() { string content = @" <msb:Project xmlns:msb=`http://schemas.microsoft.com/developer/msbuild/2003`> <msb:Target Name=`t`> <msb:Message Text=`[t]`/> </msb:Target> </msb:Project> "; content = content.Replace("`", "\""); bool exceptionThrown = false; try { Project project = new Project(XmlReader.Create(new StringReader(content))); } catch (InvalidProjectFileException ex) { exceptionThrown = true; // MSB4068: The element <msb:Project> is unrecognized, or not supported in this context. Assert.NotEqual("MSB4068", ex.ErrorCode); // MSB4041: The default XML namespace of the project must be the MSBuild XML namespace. Assert.Equal("MSB4041", ex.ErrorCode); } Assert.True(exceptionThrown); // "ERROR: An invalid project file exception should have been thrown." } /// <summary> /// Valid Xml, invalid syntax thrown by child element parsing /// </summary> [Fact] public void ValidXmlInvalidSyntaxInChildElement() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <XXX YYY='ZZZ'/> </ItemGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Valid Xml, invalid syntax, should not get added to the Xml cache and /// thus returned on the second request! /// </summary> [Fact] public void ValidXmlInvalidSyntaxOpenFromDiskTwice() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <XXX YYY='ZZZ'/> </ItemGroup> </Project> "; string path = null; try { try { path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); File.WriteAllText(path, content); ProjectRootElement.Open(path); } catch (InvalidProjectFileException) { } // Should throw again, not get from cache ProjectRootElement.Open(path); } finally { File.Delete(path); } } ); } /// <summary> /// Verify that opening project using XmlTextReader does not add it to the Xml cache /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void ValidXmlXmlTextReaderNotCache() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> </Project> "; string path = null; try { path = FileUtilities.GetTemporaryFile(); File.WriteAllText(path, content); var reader1 = XmlReader.Create(path); ProjectRootElement root1 = ProjectRootElement.Create(reader1); root1.AddItem("type", "include"); // If it's in the cache, then the 2nd document won't see the add. var reader2 = XmlReader.Create(path); ProjectRootElement root2 = ProjectRootElement.Create(reader2); Assert.Single(root1.Items); Assert.Empty(root2.Items); reader1.Dispose(); reader2.Dispose(); } finally { File.Delete(path); } } /// <summary> /// Verify that opening project using the same path adds it to the Xml cache /// </summary> [Fact] public void ValidXmlXmlReaderCache() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> </Project> "; string content2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' DefaultTargets='t'> </Project> "; string path = null; try { path = FileUtilities.GetTemporaryFile(); File.WriteAllText(path, content); ProjectRootElement root1 = ProjectRootElement.Create(path); File.WriteAllText(path, content2); // If it went in the cache, and this path also reads from the cache, // then we'll see the first version of the file. ProjectRootElement root2 = ProjectRootElement.Create(path); Assert.Equal(string.Empty, root1.DefaultTargets); Assert.Equal(string.Empty, root2.DefaultTargets); } finally { File.Delete(path); } } /// <summary> /// A simple "system" test: load microsoft.*.targets and verify we don't throw /// </summary> [Fact] public void LoadCommonTargets() { ProjectCollection projectCollection = new ProjectCollection(); string toolsPath = projectCollection.Toolsets.Where(toolset => (string.Equals(toolset.ToolsVersion, ObjectModelHelpers.MSBuildDefaultToolsVersion, StringComparison.OrdinalIgnoreCase))).First().ToolsPath; string[] targets = { "Microsoft.Common.targets", "Microsoft.CSharp.targets", "Microsoft.VisualBasic.targets" }; foreach (string target in targets) { string path = Path.Combine(toolsPath, target); ProjectRootElement project = ProjectRootElement.Open(path); Console.WriteLine(@"Loaded target: {0}", target); Console.WriteLine(@"Children: {0}", Helpers.Count(project.Children)); Console.WriteLine(@"Targets: {0}", Helpers.MakeList(project.Targets).Count); Console.WriteLine(@"Root ItemGroups: {0}", Helpers.MakeList(project.ItemGroups).Count); Console.WriteLine(@"Root PropertyGroups: {0}", Helpers.MakeList(project.PropertyGroups).Count); Console.WriteLine(@"UsingTasks: {0}", Helpers.MakeList(project.UsingTasks).Count); Console.WriteLine(@"ItemDefinitionGroups: {0}", Helpers.MakeList(project.ItemDefinitionGroups).Count); } } /// <summary> /// Save project loaded from TextReader, without setting FullPath. /// </summary> [Fact] public void InvalidSaveWithoutFullPath() { Assert.Throws<InvalidOperationException>(() => { XmlReader reader = XmlReader.Create(new StringReader("<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"/>")); ProjectRootElement project = ProjectRootElement.Create(reader); project.Save(); } ); } /// <summary> /// Save content with transforms. /// The ">" should not turn into "&lt;" /// </summary> [Fact] public void SaveWithTransforms() { ProjectRootElement project = ProjectRootElement.Create(); project.AddItem("i", "@(h->'%(x)')"); StringBuilder builder = new StringBuilder(); StringWriter writer = new StringWriter(builder); project.Save(writer); // UTF-16 because writer.Encoding is UTF-16 string expected = ObjectModelHelpers.CleanupFileContents( @"<?xml version=""1.0"" encoding=""utf-16""?> <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <i Include=""@(h->'%(x)')"" /> </ItemGroup> </Project>"); Helpers.VerifyAssertLineByLine(expected, builder.ToString()); } /// <summary> /// Save content with transforms to a file. /// The ">" should not turn into "&lt;" /// </summary> [Fact] public void SaveWithTransformsToFile() { ProjectRootElement project = ProjectRootElement.Create(); project.AddItem("i", "@(h->'%(x)')"); string file = null; try { file = FileUtilities.GetTemporaryFile(); project.Save(file); string expected = ObjectModelHelpers.CleanupFileContents( @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <i Include=""@(h->'%(x)')"" /> </ItemGroup> </Project>"); string actual = File.ReadAllText(file); Helpers.VerifyAssertLineByLine(expected, actual); } finally { File.Delete(file); } } /// <summary> /// Save should create a directory if it is missing /// </summary> [Fact] public void SaveToNonexistentDirectory() { ProjectRootElement project = ProjectRootElement.Create(); string directory = null; try { directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); string file = "foo.proj"; string path = Path.Combine(directory, file); project.Save(path); Assert.True(File.Exists(path)); Assert.Equal(path, project.FullPath); Assert.Equal(directory, project.DirectoryPath); } finally { FileUtilities.DeleteWithoutTrailingBackslash(directory, true); } } /// <summary> /// Save should create a directory if it is missing /// </summary> [Fact] public void SaveToNonexistentDirectoryRelativePath() { ProjectRootElement project = ProjectRootElement.Create(); string directory = null; string savedCurrentDirectory = Directory.GetCurrentDirectory(); try { Directory.SetCurrentDirectory(Path.GetTempPath()); // should be used for project.DirectoryPath; it must exist // Use the *real* current directory for constructing the path var curDir = Directory.GetCurrentDirectory(); string file = "bar" + Path.DirectorySeparatorChar + "foo.proj"; string path = Path.Combine(curDir, file); directory = Path.Combine(curDir, "bar"); project.Save(file); // relative path: file and a single directory only; should create the "bar" part Assert.True(File.Exists(file)); Assert.Equal(path, project.FullPath); Assert.Equal(directory, project.DirectoryPath); } finally { FileUtilities.DeleteWithoutTrailingBackslash(directory, true); Directory.SetCurrentDirectory(savedCurrentDirectory); } } /// <summary> /// Saving an unnamed project without a path specified should give a nice exception /// </summary> [Fact] public void SaveUnnamedProject() { Assert.Throws<InvalidOperationException>(() => { ProjectRootElement project = ProjectRootElement.Create(); project.Save(); } ); } /// <summary> /// Verifies that the ProjectRootElement.Encoding property getter returns values /// that are based on the XML declaration in the file. /// </summary> [Fact] public void EncodingGetterBasedOnXmlDeclaration() { ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-16""?> <Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> </Project>")))); Assert.Equal(Encoding.Unicode, project.Encoding); project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-8""?> <Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> </Project>")))); Assert.Equal(Encoding.UTF8, project.Encoding); project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""us-ascii""?> <Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> </Project>")))); Assert.Equal(Encoding.ASCII, project.Encoding); } /// <summary> /// Verifies that ProjectRootElement.Encoding returns the correct value /// after reading a file off disk, even if no xml declaration is present. /// </summary> [Fact] public void EncodingGetterBasedOnActualEncodingWhenXmlDeclarationIsAbsent() { string projectFullPath = FileUtilities.GetTemporaryFile(); try { VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.UTF8); VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.Unicode); // We don't test ASCII, since there is no byte order mark for it, // and the XmlReader will legitimately decide to interpret it as UTF8, // which would fail the test although it's a reasonable assumption // when no xml declaration is present. ////VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.ASCII); } finally { File.Delete(projectFullPath); } } /// <summary> /// Verifies that the Save method saves an otherwise unmodified project /// with a specified file encoding. /// </summary> [Fact] public void SaveUnmodifiedWithNewEncoding() { ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> </Project>")))); project.FullPath = FileUtilities.GetTemporaryFile(); string projectFullPath = project.FullPath; try { project.Save(); project = null; // We haven't made any changes to the project, but we want to save it using various encodings. SaveProjectWithEncoding(projectFullPath, Encoding.Unicode); SaveProjectWithEncoding(projectFullPath, Encoding.ASCII); SaveProjectWithEncoding(projectFullPath, Encoding.UTF8); } finally { File.Delete(projectFullPath); } } /// <summary> /// Enumerate over all properties from the project directly. /// It should traverse into Choose's. /// </summary> [Fact] public void PropertiesEnumerator() { string content = ObjectModelHelpers.CleanupFileContents( @"<?xml version=""1.0"" encoding=""utf-16""?> <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <PropertyGroup Condition=""false""> <p>p1</p> <q>q1</q> </PropertyGroup> <PropertyGroup/> <PropertyGroup> <r>r1</r> </PropertyGroup> <Choose> <When Condition=""true""> <Choose> <When Condition=""true""> <PropertyGroup> <s>s1</s> </PropertyGroup> </When> </Choose> </When> <When Condition=""false""> <PropertyGroup> <s>s2</s> <!-- both esses --> </PropertyGroup> </When> <Otherwise> <Choose> <When Condition=""false""/> <Otherwise> <PropertyGroup> <t>t1</t> </PropertyGroup> </Otherwise> </Choose> </Otherwise> </Choose> </Project>"); ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); List<ProjectPropertyElement> properties = Helpers.MakeList(project.Properties); Assert.Equal(6, properties.Count); Assert.Equal("q", properties[1].Name); Assert.Equal("r1", properties[2].Value); Assert.Equal("t1", properties[5].Value); } /// <summary> /// Enumerate over all items from the project directly. /// It should traverse into Choose's. /// </summary> [Fact] public void ItemsEnumerator() { string content = ObjectModelHelpers.CleanupFileContents( @"<?xml version=""1.0"" encoding=""utf-16""?> <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup Condition=""false""> <i Include=""i1""/> <j Include=""j1""/> </ItemGroup> <ItemGroup/> <ItemGroup> <k Include=""k1""/> </ItemGroup> <Choose> <When Condition=""true""> <Choose> <When Condition=""true""> <ItemGroup> <k Include=""k2""/> </ItemGroup> </When> </Choose> </When> <When Condition=""false""> <ItemGroup> <k Include=""k3""/> </ItemGroup> </When> <Otherwise> <Choose> <When Condition=""false""/> <Otherwise> <ItemGroup> <k Include=""k4""/> </ItemGroup> </Otherwise> </Choose> </Otherwise> </Choose> </Project>"); ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); List<ProjectItemElement> items = Helpers.MakeList(project.Items); Assert.Equal(6, items.Count); Assert.Equal("j", items[1].ItemType); Assert.Equal("k1", items[2].Include); Assert.Equal("k4", items[5].Include); } #if FEATURE_SECURITY_PRINCIPAL_WINDOWS /// <summary> /// Build a solution file that can't be accessed /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Security classes are not supported on Unix public void SolutionCanNotBeOpened() { Assert.Throws<InvalidProjectFileException>(() => { string solutionFile = null; string tempFileSentinel = null; IdentityReference identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null); FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Deny); FileSecurity security = null; try { tempFileSentinel = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); solutionFile = Path.ChangeExtension(tempFileSentinel, ".sln"); File.Copy(tempFileSentinel, solutionFile); security = new FileSecurity(solutionFile, System.Security.AccessControl.AccessControlSections.All); security.AddAccessRule(rule); File.SetAccessControl(solutionFile, security); ProjectRootElement.Open(solutionFile); } catch (PrivilegeNotHeldException) { throw new InvalidProjectFileException("Running unelevated so skipping this scenario."); } finally { security?.RemoveAccessRule(rule); File.Delete(solutionFile); File.Delete(tempFileSentinel); Assert.False(File.Exists(solutionFile)); } } ); } /// <summary> /// Build a project file that can't be accessed /// </summary> [Fact] [PlatformSpecific (TestPlatforms.Windows)] // FileSecurity class is not supported on Unix public void ProjectCanNotBeOpened() { Assert.Throws<InvalidProjectFileException>(() => { string projectFile = null; IdentityReference identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null); FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Deny); FileSecurity security = null; try { // Does not have .sln or .vcproj extension so loads as project projectFile = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); security = new FileSecurity(projectFile, System.Security.AccessControl.AccessControlSections.All); security.AddAccessRule(rule); File.SetAccessControl(projectFile, security); ProjectRootElement.Open(projectFile); } catch (PrivilegeNotHeldException) { throw new InvalidProjectFileException("Running unelevated so skipping the scenario."); } finally { security?.RemoveAccessRule(rule); File.Delete(projectFile); Assert.False(File.Exists(projectFile)); } } ); } #endif /// <summary> /// Build a corrupt solution /// </summary> [Fact] public void SolutionCorrupt() { Assert.Throws<InvalidProjectFileException>(() => { string solutionFile = null; try { solutionFile = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); // Arbitrary corrupt content string content = @"Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio Codename Orcas Project(""{"; File.WriteAllText(solutionFile, content); ProjectRootElement.Open(solutionFile); } finally { File.Delete(solutionFile); } } ); } /// <summary> /// Open lots of projects concurrently to try to trigger problems /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] //This test is platform specific for Windows public void ConcurrentProjectOpenAndCloseThroughProject() { int iterations = 500; string[] paths = ObjectModelHelpers.GetTempFiles(iterations); try { Project[] projects = new Project[iterations]; for (int i = 0; i < iterations; i++) { CreatePREWithSubstantialContent().Save(paths[i]); } var collection = new ProjectCollection(); int counter = 0; int remaining = iterations; var done = new ManualResetEvent(false); for (int i = 0; i < iterations; i++) { ThreadPool.QueueUserWorkItem(delegate { var current = Interlocked.Increment(ref counter) - 1; projects[current] = collection.LoadProject(paths[current]); if (Interlocked.Decrement(ref remaining) == 0) { done.Set(); } }); } done.WaitOne(); Assert.Equal(iterations, collection.LoadedProjects.Count); counter = 0; remaining = iterations; done.Reset(); for (int i = 0; i < iterations; i++) { ThreadPool.QueueUserWorkItem(delegate { var current = Interlocked.Increment(ref counter) - 1; var pre = projects[current].Xml; collection.UnloadProject(projects[current]); collection.UnloadProject(pre); if (Interlocked.Decrement(ref remaining) == 0) { done.Set(); } }); } done.WaitOne(); Assert.Empty(collection.LoadedProjects); } finally { for (int i = 0; i < iterations; i++) { File.Delete(paths[i]); } } } /// <summary> /// Open lots of projects concurrently to try to trigger problems /// </summary> [Fact] public void ConcurrentProjectOpenAndCloseThroughProjectRootElement() { int iterations = 500; string[] paths = ObjectModelHelpers.GetTempFiles(iterations); try { var projects = new ProjectRootElement[iterations]; var collection = new ProjectCollection(); int counter = 0; int remaining = iterations; var done = new ManualResetEvent(false); for (int i = 0; i < iterations; i++) { ThreadPool.QueueUserWorkItem(delegate { var current = Interlocked.Increment(ref counter) - 1; CreatePREWithSubstantialContent().Save(paths[current]); projects[current] = ProjectRootElement.Open(paths[current], collection); if (Interlocked.Decrement(ref remaining) == 0) { done.Set(); } }); } done.WaitOne(); counter = 0; remaining = iterations; done.Reset(); for (int i = 0; i < iterations; i++) { ThreadPool.QueueUserWorkItem(delegate { var current = Interlocked.Increment(ref counter) - 1; collection.UnloadProject(projects[current]); if (Interlocked.Decrement(ref remaining) == 0) { done.Set(); } }); } done.WaitOne(); } finally { for (int i = 0; i < iterations; i++) { File.Delete(paths[i]); } } } /// <summary> /// Tests DeepClone and CopyFrom for ProjectRootElements. /// </summary> [Fact] public void DeepClone() { var pre = ProjectRootElement.Create(); var pg = pre.AddPropertyGroup(); pg.AddProperty("a", "$(b)"); pg.AddProperty("c", string.Empty); var ig = pre.AddItemGroup(); var item = ig.AddItem("Foo", "boo$(hoo)"); item.AddMetadata("Some", "Value"); var target = pre.AddTarget("SomeTarget"); target.Condition = "Some Condition"; var task = target.AddTask("SomeTask"); task.AddOutputItem("p1", "it"); task.AddOutputProperty("prop", "it2"); target.AppendChild(pre.CreateOnErrorElement("someTarget")); var idg = pre.AddItemDefinitionGroup(); var id = idg.AddItemDefinition("SomeType"); id.AddMetadata("sm", "sv"); pre.AddUsingTask("name", "assembly", null); var inlineUt = pre.AddUsingTask("anotherName", "somefile", null); inlineUt.TaskFactory = "SomeFactory"; inlineUt.AddUsingTaskBody("someEvaluate", "someTaskBody"); var choose = pre.CreateChooseElement(); pre.AppendChild(choose); var when1 = pre.CreateWhenElement("some condition"); choose.AppendChild(when1); when1.AppendChild(pre.CreatePropertyGroupElement()); var otherwise = pre.CreateOtherwiseElement(); choose.AppendChild(otherwise); otherwise.AppendChild(pre.CreateItemGroupElement()); var importGroup = pre.AddImportGroup(); importGroup.AddImport("Some imported project"); pre.AddImport("direct import"); ValidateDeepCloneAndCopyFrom(pre); } /// <summary> /// Tests DeepClone and CopyFrom for ProjectRootElement that contain ProjectExtensions with text inside. /// </summary> [Fact] public void DeepCloneWithProjectExtensionsElementOfText() { var pre = ProjectRootElement.Create(); var extensions = pre.CreateProjectExtensionsElement(); extensions.Content = "Some foo content"; pre.AppendChild(extensions); ValidateDeepCloneAndCopyFrom(pre); } /// <summary> /// Tests DeepClone and CopyFrom for ProjectRootElement that contain ProjectExtensions with xml inside. /// </summary> [Fact] public void DeepCloneWithProjectExtensionsElementOfXml() { var pre = ProjectRootElement.Create(); var extensions = pre.CreateProjectExtensionsElement(); extensions.Content = "<a><b/></a>"; pre.AppendChild(extensions); ValidateDeepCloneAndCopyFrom(pre); } /// <summary> /// Tests DeepClone and CopyFrom when there is metadata expressed as attributes /// </summary> [Fact] public void DeepCloneWithMetadataAsAttributes() { var project = @"<?xml version=`1.0` encoding=`utf-8`?> <Project xmlns = 'msbuildnamespace'> <ItemDefinitionGroup> <Compile A=`a`/> <B M1=`dv1`> <M2>dv2</M2> </B> <C/> </ItemDefinitionGroup> <ItemGroup> <Compile Include=`Class1.cs` A=`a` /> <Compile Include=`Class2.cs` /> </ItemGroup> <PropertyGroup> <P>val</P> </PropertyGroup> <Target Name=`Build`> <ItemGroup> <A Include=`a` /> <B Include=`b` M1=`v1`> <M2>v2</M2> </B> <C Include=`c`/> </ItemGroup> </Target> </Project>"; var pre = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(project)))); ValidateDeepCloneAndCopyFrom(pre); } /// <summary> /// Tests TryOpen when preserveFormatting is the same and different than the cached project. /// </summary> [Fact] public void TryOpenWithPreserveFormatting() { string project = @"<?xml version=`1.0` encoding=`utf-8`?> <Project xmlns = 'msbuildnamespace'> </Project>"; using (var env = TestEnvironment.Create()) using (var projectCollection = new ProjectCollection()) { var projectFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" }); var projectFile = projectFiles.CreatedFiles.First(); var projectXml = ProjectRootElement.Create( XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(project))), projectCollection, preserveFormatting: true); projectXml.Save(projectFile); var xml0 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: true); Assert.True(xml0.PreserveFormatting); var xml1 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: false); Assert.False(xml1.PreserveFormatting); var xml2 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: null); // reuses existing setting Assert.False(xml2.PreserveFormatting); Assert.NotNull(xml0); Assert.Same(xml0, xml1); Assert.Same(xml0, xml2); } } [Theory] [InlineData(true, false, false)] [InlineData(true, true, true)] [InlineData(false, false, false)] [InlineData(false, true, true)] [InlineData(true, null, true)] [InlineData(false, null, false)] public void ReloadCanSpecifyPreserveFormatting(bool initialPreserveFormatting, bool? reloadShouldPreserveFormatting, bool expectedFormattingAfterReload) { using (var env = TestEnvironment.Create()) { var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" }); var projectFile = testFiles.CreatedFiles.First(); var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject, null, initialPreserveFormatting); projectElement.Save(projectFile); Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting); projectElement.Reload(false, reloadShouldPreserveFormatting); Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting); // reset project to original preserve formatting projectElement.Reload(false, initialPreserveFormatting); Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting); projectElement.ReloadFrom(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(SimpleProject))), false, reloadShouldPreserveFormatting); Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting); // reset project to original preserve formatting projectElement.Reload(false, initialPreserveFormatting); Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting); projectElement.ReloadFrom(projectFile, false, reloadShouldPreserveFormatting); Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting); } } [Theory] // same content should still dirty the project [InlineData( SimpleProject, SimpleProject, true, false, false)] // new comment [InlineData( @"<Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> </Project>", @" <!-- new comment --> <Project xmlns=`msbuildnamespace`> <PropertyGroup> <P><!-- new comment -->property value<!-- new comment --></P> </PropertyGroup> <!-- new comment --> <ItemGroup> <i Include=`a`> <!-- new comment --> <m>metadata value</m> </i> </ItemGroup> </Project>", true, false, true)] // changed comment [InlineData( @" <!-- new comment --> <Project xmlns=`msbuildnamespace`> <PropertyGroup> <P><!-- new comment -->property value<!-- new comment --></P> </PropertyGroup> <!-- new comment --> <ItemGroup> <i Include=`a`> <!-- new comment --> <m>metadata value</m> </i> </ItemGroup> </Project>", @" <!-- changed comment --> <Project xmlns=`msbuildnamespace`> <PropertyGroup> <P><!-- changed comment -->property value<!-- changed comment --></P> </PropertyGroup> <!-- changed comment --> <ItemGroup> <i Include=`a`> <!-- changed comment --> <m>metadata value</m> </i> </ItemGroup> </Project>", true, false, true)] // deleted comment [InlineData( @" <!-- new comment --> <Project xmlns=`msbuildnamespace`> <PropertyGroup> <P><!-- new comment -->property value<!-- new comment --></P> </PropertyGroup> <!-- new comment --> <ItemGroup> <i Include=`a`> <!-- new comment --> <m>metadata value</m> </i> </ItemGroup> </Project>", @" <Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> </Project>", true, false, true)] // new comments and changed code [InlineData( @"<Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> </Project>", @" <!-- new comment --> <Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> <P2><!-- new comment -->property value<!-- new comment --></P2> </PropertyGroup> </Project>", true, true, true)] // commented out code [InlineData( @"<Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> </Project>", @"<Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <!-- <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> --> </Project>", true, true, true)] public void ReloadRespectsNewContents(string initialProjectContents, string changedProjectContents, bool versionChanged, bool msbuildChildrenChanged, bool xmlChanged) { Action<ProjectRootElement, string> act = (p, c) => { p.ReloadFrom( XmlReader.Create(new StringReader(c)), throwIfUnsavedChanges: false); }; AssertReload(initialProjectContents, changedProjectContents, versionChanged, msbuildChildrenChanged, xmlChanged, act); } [Fact] public void ReloadedStateIsResilientToChangesAndDiskRoundtrip() { var initialProjectContents = ObjectModelHelpers.CleanupFileContents( @" <!-- new comment --> <Project xmlns=`msbuildnamespace`> <!-- new comment --> <ItemGroup> <i Include=`a`> <!-- new comment --> <m>metadata value</m> </i> </ItemGroup> </Project>"); var changedProjectContents1 = ObjectModelHelpers.CleanupFileContents( @" <!-- changed comment --> <Project xmlns=`msbuildnamespace`> <!-- changed comment --> <ItemGroup> <i Include=`a`> <!-- changed comment --> <m>metadata value</m> </i> </ItemGroup> </Project>"); var changedProjectContents2 = ObjectModelHelpers.CleanupFileContents( // spurious comment placement issue: https://github.com/Microsoft/msbuild/issues/1503 @" <!-- changed comment --> <Project xmlns=`msbuildnamespace`> <!-- changed comment --> <PropertyGroup> <P>v</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <!-- changed comment --> <m>metadata value</m> </i> </ItemGroup> </Project>"); using (var env = TestEnvironment.Create()) { var projectCollection1 = env.CreateProjectCollection().Collection; var projectCollection2 = env.CreateProjectCollection().Collection; var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" }); var projectPath = testFiles.CreatedFiles.First(); var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(initialProjectContents, projectCollection1, preserveFormatting: true); projectElement.Save(projectPath); projectElement.ReloadFrom(XmlReader.Create(new StringReader(changedProjectContents1))); VerifyAssertLineByLine(changedProjectContents1, projectElement.RawXml); projectElement.AddProperty("P", "v"); VerifyAssertLineByLine(changedProjectContents2, projectElement.RawXml); projectElement.Save(); var projectElement2 = ProjectRootElement.Open(projectPath, projectCollection2, preserveFormatting: true); VerifyAssertLineByLine(changedProjectContents2, projectElement2.RawXml); } } [Fact] public void ReloadThrowsOnInvalidXmlSyntax() { var missingClosingTag = @"<Project xmlns=`msbuildnamespace`> <PropertyGroup> <P>property value</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value<m> </i> </ItemGroup> </Project>"; Action<ProjectRootElement, string> act = (p, c) => { var exception = Assert.Throws<InvalidProjectFileException>( () => p.ReloadFrom( XmlReader.Create( new StringReader(c)), throwIfUnsavedChanges: false)); Assert.Contains(@"The project file could not be loaded. The 'm' start tag on line", exception.Message); }; // reload does not mutate the project element AssertReload(SimpleProject, missingClosingTag, false, false, false, act); } [Fact] public void ReloadThrowsForInMemoryProjectsWithoutAPath() { Action<ProjectRootElement, string> act = (p, c) => { var exception = Assert.Throws<InvalidOperationException>( () => p.Reload(throwIfUnsavedChanges: false)); Assert.Contains(@"Value not set:", exception.Message); }; // reload does not mutate the project element AssertReload(SimpleProject, ComplexProject, false, false, false, act); } [Fact] public void ReloadFromAPathThrowsOnMissingPath() { Action<ProjectRootElement, string> act = (p, c) => { var fullPath = Path.GetFullPath("foo"); var exception = Assert.Throws<InvalidOperationException>( () => p.ReloadFrom(fullPath, throwIfUnsavedChanges: false)); Assert.Contains(@"File to reload from does not exist:", exception.Message); }; // reload does not mutate the project element AssertReload(SimpleProject, ComplexProject, false, false, false, act); } [Fact] public void ReloadFromMemoryWhenProjectIsInMemoryKeepsProjectFileEmpty() { AssertProjectFileAfterReload( true, true, (initial, reload, actualFile) => { Assert.Equal(String.Empty, actualFile); }); } [Fact] public void ReloadFromMemoryWhenProjectIsInFileKeepsProjectFile() { AssertProjectFileAfterReload( false, true, (initial, reload, actualFile) => { Assert.Equal(initial, actualFile); }); } [Fact] public void ReloadFromFileWhenProjectIsInMemorySetsProjectFile() { AssertProjectFileAfterReload( true, false, (initial, reload, actualFile) => { Assert.Equal(reload, actualFile);}); } [Fact] public void ReloadFromFileWhenProjectIsInFileUpdatesProjectFile() { AssertProjectFileAfterReload( false, false, (initial, reload, actualFile) => { Assert.Equal(reload, actualFile); }); } private void AssertProjectFileAfterReload( bool initialProjectFromMemory, bool reloadProjectFromMemory, Action<string, string, string> projectFileAssert) { using (var env = TestEnvironment.Create()) { var projectCollection = env.CreateProjectCollection().Collection; string initialLocation = null; ProjectRootElement rootElement = null; if (initialProjectFromMemory) { rootElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject, projectCollection); } else { initialLocation = env.CreateFile().Path; File.WriteAllText(initialLocation, ObjectModelHelpers.CleanupFileContents(SimpleProject)); rootElement = ProjectRootElement.Open(initialLocation, projectCollection); } var project = new Project(rootElement, null, null, projectCollection); string reloadLocation = null; if (reloadProjectFromMemory) { rootElement.ReloadFrom(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(ComplexProject))), false); } else { reloadLocation = env.CreateFile().Path; File.WriteAllText(reloadLocation, ObjectModelHelpers.CleanupFileContents(ComplexProject)); rootElement.ReloadFrom(reloadLocation, false); } project.ReevaluateIfNecessary(); projectFileAssert.Invoke(initialLocation, reloadLocation, EmptyIfNull(rootElement.FullPath)); projectFileAssert.Invoke(initialLocation, reloadLocation, rootElement.ProjectFileLocation.File); projectFileAssert.Invoke(initialLocation, reloadLocation, rootElement.AllChildren.Last().Location.File); projectFileAssert.Invoke(initialLocation, reloadLocation, project.GetPropertyValue("ProjectFile")); projectFileAssert.Invoke(initialLocation, reloadLocation, project.GetPropertyValue("ThisFile")); if (initialProjectFromMemory && reloadProjectFromMemory) { Assert.Equal(NativeMethodsShared.GetCurrentDirectory(), rootElement.DirectoryPath); } else { projectFileAssert.Invoke(Path.GetDirectoryName(initialLocation), Path.GetDirectoryName(reloadLocation), rootElement.DirectoryPath); } } } private static string EmptyIfNull(string aString) => aString ?? string.Empty; [Fact] public void ReloadThrowsOnInvalidMsBuildSyntax() { var unknownAttribute = @"<Project xmlns=`msbuildnamespace`> <PropertyGroup Foo=`bar`> <P>property value</P> </PropertyGroup> <ItemGroup> <i Include=`a`> <m>metadata value</m> </i> </ItemGroup> </Project>"; Action<ProjectRootElement, string> act = (p, c) => { var exception = Assert.Throws<InvalidProjectFileException>( () => p.ReloadFrom( XmlReader.Create( new StringReader(c)), throwIfUnsavedChanges: false)); Assert.Contains(@"The attribute ""Foo"" in element <PropertyGroup> is unrecognized", exception.Message); }; // reload does not mutate the project element AssertReload(SimpleProject, unknownAttribute, false, false, false, act); } [Fact] public void ReloadThrowsByDefaultIfThereAreUnsavedChanges() { Action<ProjectRootElement, string> act = (p, c) => { var exception = Assert.Throws<InvalidOperationException>( () => p.ReloadFrom( XmlReader.Create( new StringReader(c)))); Assert.Contains(@"ProjectRootElement can't reload if it contains unsaved changes.", exception.Message); }; // reload does not mutate the project element AssertReload(SimpleProject, ComplexProject, false, false, false, act); } [Fact] public void ReloadCanOverwriteUnsavedChanges() { Action<ProjectRootElement, string> act = (p, c) => { p.ReloadFrom( XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(c))), throwIfUnsavedChanges: false); }; AssertReload(SimpleProject, ComplexProject, true, true, true, act); } private void AssertReload( string initialContents, string changedContents, bool versionChanged, bool msbuildChildrenChanged, bool xmlChanged, Action<ProjectRootElement, string> act) { var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(initialContents); var version = projectElement.Version; var childrenCount = projectElement.AllChildren.Count(); var xml = projectElement.RawXml; Assert.True(projectElement.HasUnsavedChanges); act(projectElement, ObjectModelHelpers.CleanupFileContents(changedContents)); if (versionChanged) { Assert.NotEqual(version, projectElement.Version); } else { Assert.Equal(version, projectElement.Version); } if (msbuildChildrenChanged) { Assert.NotEqual(childrenCount, projectElement.AllChildren.Count()); } else { Assert.Equal(childrenCount, projectElement.AllChildren.Count()); } if (xmlChanged) { Assert.NotEqual(xml, projectElement.RawXml); } else { Assert.Equal(xml, projectElement.RawXml); } } /// <summary> /// Test helper for validating that DeepClone and CopyFrom work as advertised. /// </summary> private static void ValidateDeepCloneAndCopyFrom(ProjectRootElement pre) { var pre2 = pre.DeepClone(); Assert.NotSame(pre2, pre); Assert.Equal(pre.RawXml, pre2.RawXml); var pre3 = ProjectRootElement.Create(); pre3.AddPropertyGroup(); // this should get wiped out in the DeepCopyFrom pre3.DeepCopyFrom(pre); Assert.Equal(pre.RawXml, pre3.RawXml); } /// <summary> /// Re-saves a project with a new encoding and thoroughly verifies that the right things happen. /// </summary> private void SaveProjectWithEncoding(string projectFullPath, Encoding encoding) { // Always use a new project collection to guarantee we're reading off disk. ProjectRootElement project = ProjectRootElement.Open(projectFullPath, new ProjectCollection()); project.Save(encoding); Assert.Equal(encoding, project.Encoding); // "Changing an unmodified project's encoding failed to update ProjectRootElement.Encoding." // Try to verify that the xml declaration was emitted, and that the correct byte order marks // are also present. using (var reader = FileUtilities.OpenRead(projectFullPath, encoding, true)) { Assert.Equal(encoding, reader.CurrentEncoding); string actual = reader.ReadLine(); string expected = string.Format(@"<?xml version=""1.0"" encoding=""{0}""?>", encoding.WebName); Assert.Equal(expected, actual); // "The encoding was not emitted as an XML declaration." } project = ProjectRootElement.Open(projectFullPath, new ProjectCollection()); // It's ok for the read Encoding to differ in fields like DecoderFallback, // so a pure equality check here is too much. Assert.Equal(encoding.CodePage, project.Encoding.CodePage); Assert.Equal(encoding.EncodingName, project.Encoding.EncodingName); } /// <summary> /// Creates a project at a given path with a given encoding but without the Xml declaration, /// and then verifies that when loaded by MSBuild, the encoding is correctly reported. /// </summary> private void VerifyLoadedProjectHasEncoding(string projectFullPath, Encoding encoding) { CreateProjectWithEncodingWithoutDeclaration(projectFullPath, encoding); // Let's just be certain the project has been read off disk... ProjectRootElement project = ProjectRootElement.Open(projectFullPath, new ProjectCollection()); Assert.Equal(encoding.WebName, project.Encoding.WebName); } /// <summary> /// Creates a project file with a specific encoding, but without an XML declaration. /// </summary> private void CreateProjectWithEncodingWithoutDeclaration(string projectFullPath, Encoding encoding) { const string EmptyProject = @"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> </Project>"; using (StreamWriter writer = FileUtilities.OpenWrite(projectFullPath, false, encoding)) { writer.Write(ObjectModelHelpers.CleanupFileContents(EmptyProject)); } } /// <summary> /// Create a nice big PRE /// </summary> private ProjectRootElement CreatePREWithSubstantialContent() { string content = ObjectModelHelpers.CleanupFileContents(ComplexProject); ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); return project; } private void VerifyAssertLineByLine(string expected, string actual) { Helpers.VerifyAssertLineByLine(expected, actual, false); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; using CoreXml.Test.XLinq; namespace System.Xml.Linq.Tests { public static class AxisOrderValidation { [Fact] public static void NodesAfterSelfBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText, bText); IEnumerable<XNode> nodes = aText.NodesAfterSelf(); Assert.Equal(1, nodes.Count()); bText.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void NodesBeforeSelfBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText, bText); IEnumerable<XNode> nodes = bText.NodesBeforeSelf(); Assert.Equal(1, nodes.Count()); aText.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void AncestorsBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); a.Add(b); IEnumerable<XElement> nodes = bText.Ancestors(); Assert.Equal(2, nodes.Count()); bText.Remove(); a.Add(bText); Assert.Equal(1, nodes.Count()); } [Fact] public static void AncestorsWithXNameBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); a.Add(b); IEnumerable<XElement> nodes = bText.Ancestors("B"); Assert.Equal(1, nodes.Count()); bText.Remove(); a.Add(bText); Assert.Equal(0, nodes.Count()); } [Fact] public static void ElementsAfterSelfBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); a.Add(b); IEnumerable<XElement> nodes = aText.ElementsAfterSelf(); Assert.Equal(1, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void ElementsAfterSelfWithXNameBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); a.Add(b); IEnumerable<XElement> nodes = aText.ElementsAfterSelf("B"); Assert.Equal(1, nodes.Count()); b.ReplaceWith(a); Assert.Equal(0, nodes.Count()); } [Fact] public static void ElementsBeforeSelfBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); aText.AddBeforeSelf(b); IEnumerable<XElement> nodes = aText.ElementsBeforeSelf(); Assert.Equal(1, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void ElementsBeforeSelfWithXNameBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); aText.AddBeforeSelf(b); IEnumerable<XElement> nodes = aText.ElementsBeforeSelf("B"); Assert.Equal(1, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void NodesOnXDocBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText, bText); XDocument xDoc = new XDocument(a); IEnumerable<XNode> nodes = xDoc.Nodes(); Assert.Equal(1, nodes.Count()); a.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void DescendantNodesOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XNode> nodes = xDoc.DescendantNodes(); Assert.Equal(4, nodes.Count()); a.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void ElementsOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XElement> nodes = xDoc.Elements(); Assert.Equal(1, nodes.Count()); a.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void ElementsWithXNameOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XElement> nodes = xDoc.Elements("A"); Assert.Equal(1, nodes.Count()); a.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void DescendantsOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XElement> nodes = xDoc.Descendants("B"); Assert.Equal(1, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void DescendantsWithXNameOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); b.Add(b, b); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XElement> nodes = xDoc.Descendants("B"); Assert.Equal(4, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void NodesOnXElementBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XNode> nodes = a.Nodes(); Assert.Equal(2, nodes.Count()); b.Remove(); Assert.Equal(1, nodes.Count()); } [Fact] public static void DescendantNodesOnXElementBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XNode> nodes = a.DescendantNodes(); Assert.Equal(3, nodes.Count()); a.Add("New Text Node"); Assert.Equal(4, nodes.Count()); } [Fact] public static void ElementsOnXElementBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); IEnumerable<XElement> nodes = a.Elements(); Assert.Equal(0, nodes.Count()); a.Add(b, b, b, b); Assert.Equal(4, nodes.Count()); } [Fact] public static void ElementsWithXNameOnXElementBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); IEnumerable<XElement> nodes = a.Elements("B"); Assert.Equal(0, nodes.Count()); a.Add(b, b, b, b); Assert.Equal(4, nodes.Count()); } [Fact] public static void DescendantsOnXElementBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XElement> nodes = a.Descendants(); Assert.Equal(1, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void DescendantsWithXNameOnXElementBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XElement> nodes = a.Descendants("B"); Assert.Equal(1, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); } [Fact] public static void DescendantNodesAndSelfBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XNode> nodes = a.DescendantNodesAndSelf(); Assert.Equal(4, nodes.Count()); a.Add("New Text Node"); Assert.Equal(5, nodes.Count()); } [Fact] public static void DescendantsAndSelfBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XElement> nodes = a.DescendantsAndSelf(); Assert.Equal(2, nodes.Count()); b.Add(a); Assert.Equal(4, nodes.Count()); } [Fact] public static void DescendantsAndSelfWithXNameBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XElement> nodes = a.DescendantsAndSelf("A"); Assert.Equal(1, nodes.Count()); b.ReplaceWith(a); Assert.Equal(2, nodes.Count()); } [Fact] public static void AncestorsAndSelfBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XElement> nodes = b.AncestorsAndSelf(); Assert.Equal(2, nodes.Count()); XElement c = new XElement("C", "c", a); Assert.Equal(3, nodes.Count()); } [Fact] public static void AncestorsAndSelfWithXNameBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); IEnumerable<XElement> nodes = b.AncestorsAndSelf("A"); Assert.Equal(1, nodes.Count()); XElement c = new XElement("A", "a", a); Assert.Equal(2, nodes.Count()); } [Fact] public static void AttributesBeforeAndAfter() { XElement a = new XElement("A", "a"); IEnumerable<XAttribute> nodes = a.Attributes(); Assert.Equal(0, nodes.Count()); a.Add(new XAttribute("name", "a"), new XAttribute("type", "alphabet")); Assert.Equal(2, nodes.Count()); } [Fact] public static void AttributeWithXNameBeforeAndAfter() { XElement a = new XElement("A", "a"); IEnumerable<XAttribute> nodes = a.Attributes("name"); Assert.Equal(0, nodes.Count()); a.Add(new XAttribute("name", "a"), new XAttribute("type", "alphabet")); Assert.Equal(1, nodes.Count()); } [Fact] public static void IEnumerableInDocumentOrderVariationOne() { XDocument xDoc = TestData.GetDocumentWithContacts(); IEnumerable<XNode> xNodes = xDoc.Root.DescendantNodesAndSelf().Reverse(); Assert.True(xNodes.InDocumentOrder().EqualsAll(xDoc.Root.DescendantNodesAndSelf(), XNode.DeepEquals)); } [Fact] public static void IEnumerableInDocumentOrderVariationTwo() { XDocument xDoc = TestData.GetDocumentWithContacts(); IEnumerable<XElement> xElement = xDoc.Root.DescendantsAndSelf().Reverse(); Assert.True(xElement.InDocumentOrder().EqualsAll(xDoc.Root.DescendantsAndSelf(), XNode.DeepEquals)); } [Fact] public static void ReorderToDocumentOrder() { XDocument xDoc = TestData.GetDocumentWithContacts(); Random rnd = new Random(); var randomOrderedElements = xDoc.Root.DescendantNodesAndSelf().OrderBy(n => rnd.Next(0, int.MaxValue)); using (var en = randomOrderedElements.InDocumentOrder().GetEnumerator()) { en.MoveNext(); var nodeFirst = en.Current; while (en.MoveNext()) { var nodeSecond = en.Current; Assert.True(XNode.DocumentOrderComparer.Compare(nodeFirst, nodeSecond) < 0); nodeFirst = nodeSecond; } } } } }
// 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: The CLR wrapper for all Win32 as well as ** ROTOR-style Unix PAL, etc. native operations ** ** ===========================================================*/ /** * Notes to PInvoke users: Getting the syntax exactly correct is crucial, and * more than a little confusing. Here's some guidelines. * * For handles, you should use a SafeHandle subclass specific to your handle * type. For files, we have the following set of interesting definitions: * * [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)] * private static extern SafeFileHandle CreateFile(...); * * [DllImport(KERNEL32, SetLastError=true)] * unsafe internal static extern int ReadFile(SafeFileHandle handle, ...); * * [DllImport(KERNEL32, SetLastError=true)] * internal static extern bool CloseHandle(IntPtr handle); * * P/Invoke will create the SafeFileHandle instance for you and assign the * return value from CreateFile into the handle atomically. When we call * ReadFile, P/Invoke will increment a ref count, make the call, then decrement * it (preventing handle recycling vulnerabilities). Then SafeFileHandle's * ReleaseHandle method will call CloseHandle, passing in the handle field * as an IntPtr. * * If for some reason you cannot use a SafeHandle subclass for your handles, * then use IntPtr as the handle type (or possibly HandleRef - understand when * to use GC.KeepAlive). If your code will run in SQL Server (or any other * long-running process that can't be recycled easily), use a constrained * execution region to prevent thread aborts while allocating your * handle, and consider making your handle wrapper subclass * CriticalFinalizerObject to ensure you can free the handle. As you can * probably guess, SafeHandle will save you a lot of headaches if your code * needs to be robust to thread aborts and OOM. * * * If you have a method that takes a native struct, you have two options for * declaring that struct. You can make it a value type ('struct' in CSharp), * or a reference type ('class'). This choice doesn't seem very interesting, * but your function prototype must use different syntax depending on your * choice. For example, if your native method is prototyped as such: * * bool GetVersionEx(OSVERSIONINFO & lposvi); * * * you must use EITHER THIS OR THE NEXT syntax: * * [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] * internal struct OSVERSIONINFO { ... } * * [DllImport(KERNEL32, CharSet=CharSet.Auto)] * internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi); * * OR: * * [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] * internal class OSVERSIONINFO { ... } * * [DllImport(KERNEL32, CharSet=CharSet.Auto)] * internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi); * * Note that classes require being marked as [In, Out] while value types must * be passed as ref parameters. * * Also note the CharSet.Auto on GetVersionEx - while it does not take a String * as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so * the size of the struct varies on different platforms, and there's a * GetVersionExA & a GetVersionExW. Also, the OSVERSIONINFO struct has a sizeof * field so the OS can ensure you've passed in the correctly-sized copy of an * OSVERSIONINFO. You must explicitly set this using Marshal.SizeOf(Object); * * For security reasons, if you're making a P/Invoke method to a Win32 method * that takes an ANSI String and that String is the name of some resource you've * done a security check on (such as a file name), you want to disable best fit * mapping in WideCharToMultiByte. Do this by setting BestFitMapping=false * in your DllImportAttribute. */ namespace Microsoft.Win32 { using System; using System.Security; using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using BOOL = System.Int32; using DWORD = System.UInt32; using ULONG = System.UInt32; /** * Win32 encapsulation for MSCORLIB. */ // Remove the default demands for all P/Invoke methods with this // global declaration on the class. [SuppressUnmanagedCodeSecurityAttribute()] internal static class Win32Native { internal const int KEY_QUERY_VALUE = 0x0001; internal const int KEY_SET_VALUE = 0x0002; internal const int KEY_CREATE_SUB_KEY = 0x0004; internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008; internal const int KEY_NOTIFY = 0x0010; internal const int KEY_CREATE_LINK = 0x0020; internal const int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~SYNCHRONIZE)); internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~SYNCHRONIZE)); internal const int KEY_WOW64_64KEY = 0x0100; // internal const int KEY_WOW64_32KEY = 0x0200; // internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges internal const int REG_NONE = 0; // No value type internal const int REG_SZ = 1; // Unicode nul terminated string internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string // (with environment variable references) internal const int REG_BINARY = 3; // Free form binary internal const int REG_DWORD = 4; // 32-bit number internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD) internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number internal const int REG_LINK = 6; // Symbolic Link (unicode) internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10; internal const int REG_QWORD = 11; // 64-bit number internal const int HWND_BROADCAST = 0xffff; internal const int WM_SETTINGCHANGE = 0x001A; // TimeZone internal const int TIME_ZONE_ID_INVALID = -1; internal const int TIME_ZONE_ID_UNKNOWN = 0; internal const int TIME_ZONE_ID_STANDARD = 1; internal const int TIME_ZONE_ID_DAYLIGHT = 2; internal const int MAX_PATH = 260; internal const int MUI_LANGUAGE_ID = 0x4; internal const int MUI_LANGUAGE_NAME = 0x8; internal const int MUI_PREFERRED_UI_LANGUAGES = 0x10; internal const int MUI_INSTALLED_LANGUAGES = 0x20; internal const int MUI_ALL_LANGUAGES = 0x40; internal const int MUI_LANG_NEUTRAL_PE_FILE = 0x100; internal const int MUI_NON_LANG_NEUTRAL_FILE = 0x200; internal const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002; internal const int LOAD_STRING_MAX_LENGTH = 500; [StructLayout(LayoutKind.Sequential)] internal struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; [MarshalAs(UnmanagedType.U2)] public short Month; [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; [MarshalAs(UnmanagedType.U2)] public short Day; [MarshalAs(UnmanagedType.U2)] public short Hour; [MarshalAs(UnmanagedType.U2)] public short Minute; [MarshalAs(UnmanagedType.U2)] public short Second; [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public Int32 Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SystemTime StandardDate; [MarshalAs(UnmanagedType.I4)] public Int32 StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SystemTime DaylightDate; [MarshalAs(UnmanagedType.I4)] public Int32 DaylightBias; public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi) { Bias = dtzi.Bias; StandardName = dtzi.StandardName; StandardDate = dtzi.StandardDate; StandardBias = dtzi.StandardBias; DaylightName = dtzi.DaylightName; DaylightDate = dtzi.DaylightDate; DaylightBias = dtzi.DaylightBias; } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DynamicTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public Int32 Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SystemTime StandardDate; [MarshalAs(UnmanagedType.I4)] public Int32 StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SystemTime DaylightDate; [MarshalAs(UnmanagedType.I4)] public Int32 DaylightBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string TimeZoneKeyName; [MarshalAs(UnmanagedType.Bool)] public bool DynamicDaylightTimeDisabled; } [StructLayout(LayoutKind.Sequential)] internal struct RegistryTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public Int32 Bias; [MarshalAs(UnmanagedType.I4)] public Int32 StandardBias; [MarshalAs(UnmanagedType.I4)] public Int32 DaylightBias; public SystemTime StandardDate; public SystemTime DaylightDate; public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi) { Bias = tzi.Bias; StandardDate = tzi.StandardDate; StandardBias = tzi.StandardBias; DaylightDate = tzi.DaylightDate; DaylightBias = tzi.DaylightBias; } public RegistryTimeZoneInformation(Byte[] bytes) { // // typedef struct _REG_TZI_FORMAT { // [00-03] LONG Bias; // [04-07] LONG StandardBias; // [08-11] LONG DaylightBias; // [12-27] SYSTEMTIME StandardDate; // [12-13] WORD wYear; // [14-15] WORD wMonth; // [16-17] WORD wDayOfWeek; // [18-19] WORD wDay; // [20-21] WORD wHour; // [22-23] WORD wMinute; // [24-25] WORD wSecond; // [26-27] WORD wMilliseconds; // [28-43] SYSTEMTIME DaylightDate; // [28-29] WORD wYear; // [30-31] WORD wMonth; // [32-33] WORD wDayOfWeek; // [34-35] WORD wDay; // [36-37] WORD wHour; // [38-39] WORD wMinute; // [40-41] WORD wSecond; // [42-43] WORD wMilliseconds; // } REG_TZI_FORMAT; // if (bytes == null || bytes.Length != 44) { throw new ArgumentException(SR.Argument_InvalidREG_TZI_FORMAT, nameof(bytes)); } Bias = BitConverter.ToInt32(bytes, 0); StandardBias = BitConverter.ToInt32(bytes, 4); DaylightBias = BitConverter.ToInt32(bytes, 8); StandardDate.Year = BitConverter.ToInt16(bytes, 12); StandardDate.Month = BitConverter.ToInt16(bytes, 14); StandardDate.DayOfWeek = BitConverter.ToInt16(bytes, 16); StandardDate.Day = BitConverter.ToInt16(bytes, 18); StandardDate.Hour = BitConverter.ToInt16(bytes, 20); StandardDate.Minute = BitConverter.ToInt16(bytes, 22); StandardDate.Second = BitConverter.ToInt16(bytes, 24); StandardDate.Milliseconds = BitConverter.ToInt16(bytes, 26); DaylightDate.Year = BitConverter.ToInt16(bytes, 28); DaylightDate.Month = BitConverter.ToInt16(bytes, 30); DaylightDate.DayOfWeek = BitConverter.ToInt16(bytes, 32); DaylightDate.Day = BitConverter.ToInt16(bytes, 34); DaylightDate.Hour = BitConverter.ToInt16(bytes, 36); DaylightDate.Minute = BitConverter.ToInt16(bytes, 38); DaylightDate.Second = BitConverter.ToInt16(bytes, 40); DaylightDate.Milliseconds = BitConverter.ToInt16(bytes, 42); } } // end of TimeZone // Win32 ACL-related constants: internal const int READ_CONTROL = 0x00020000; internal const int SYNCHRONIZE = 0x00100000; internal const int MAXIMUM_ALLOWED = 0x02000000; internal const int STANDARD_RIGHTS_READ = READ_CONTROL; internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; // STANDARD_RIGHTS_REQUIRED (0x000F0000L) // SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3) // SEMAPHORE and Event both use 0x0002 // MUTEX uses 0x001 (MUTANT_QUERY_STATE) // Note that you may need to specify the SYNCHRONIZE bit as well // to be able to open a synchronization primitive. internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; internal const int EVENT_MODIFY_STATE = 0x00000002; internal const int MUTEX_MODIFY_STATE = 0x00000001; // CreateEventEx: flags internal const uint CREATE_EVENT_MANUAL_RESET = 0x1; internal const uint CREATE_EVENT_INITIAL_SET = 0x2; // CreateMutexEx: flags internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1; internal const int LMEM_FIXED = 0x0000; internal const int LMEM_ZEROINIT = 0x0040; internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class OSVERSIONINFO { internal OSVERSIONINFO() { OSVersionInfoSize = (int)Marshal.SizeOf(this); } // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) internal int OSVersionInfoSize = 0; internal int MajorVersion = 0; internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal String CSDVersion = null; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class OSVERSIONINFOEX { public OSVERSIONINFOEX() { OSVersionInfoSize = (int)Marshal.SizeOf(this); } // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) internal int OSVersionInfoSize = 0; internal int MajorVersion = 0; internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string CSDVersion = null; internal ushort ServicePackMajor = 0; internal ushort ServicePackMinor = 0; internal short SuiteMask = 0; internal byte ProductType = 0; internal byte Reserved = 0; } [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = 0; // don't remove null, or this field will disappear in bcl.small internal unsafe byte* pSecurityDescriptor = null; internal int bInheritHandle = 0; } [StructLayout(LayoutKind.Sequential)] internal struct WIN32_FILE_ATTRIBUTE_DATA { internal int fileAttributes; internal uint ftCreationTimeLow; internal uint ftCreationTimeHigh; internal uint ftLastAccessTimeLow; internal uint ftLastAccessTimeHigh; internal uint ftLastWriteTimeLow; internal uint ftLastWriteTimeHigh; internal int fileSizeHigh; internal int fileSizeLow; internal void PopulateFrom(WIN32_FIND_DATA findData) { // Copy the information to data fileAttributes = findData.dwFileAttributes; ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime; ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime; ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime; ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime; ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime; ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime; fileSizeHigh = findData.nFileSizeHigh; fileSizeLow = findData.nFileSizeLow; } } [StructLayout(LayoutKind.Sequential)] internal struct MEMORYSTATUSEX { // The length field must be set to the size of this data structure. internal int length; internal int memoryLoad; internal ulong totalPhys; internal ulong availPhys; internal ulong totalPageFile; internal ulong availPageFile; internal ulong totalVirtual; internal ulong availVirtual; internal ulong availExtendedVirtual; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct MEMORY_BASIC_INFORMATION { internal void* BaseAddress; internal void* AllocationBase; internal uint AllocationProtect; internal UIntPtr RegionSize; internal uint State; internal uint Protect; internal uint Type; } #if !FEATURE_PAL internal const String KERNEL32 = "kernel32.dll"; internal const String USER32 = "user32.dll"; internal const String OLE32 = "ole32.dll"; internal const String OLEAUT32 = "oleaut32.dll"; #else //FEATURE_PAL internal const String KERNEL32 = "libcoreclr"; internal const String USER32 = "libcoreclr"; internal const String OLE32 = "libcoreclr"; internal const String OLEAUT32 = "libcoreclr"; #endif //FEATURE_PAL internal const String ADVAPI32 = "advapi32.dll"; internal const String SHELL32 = "shell32.dll"; internal const String SHIM = "mscoree.dll"; internal const String CRYPT32 = "crypt32.dll"; internal const String SECUR32 = "secur32.dll"; internal const String MSCORWKS = "coreclr.dll"; [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)] internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments); // Gets an error message for a Win32 error code. internal static String GetMessage(int errorCode) { StringBuilder sb = StringBuilderCache.Acquire(512); int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero); if (result != 0) { // result is the # of characters copied to the StringBuilder. return StringBuilderCache.GetStringAndRelease(sb); } else { StringBuilderCache.Release(sb); return SR.Format(SR.UnknownError_Num, errorCode); } } [DllImport(KERNEL32, EntryPoint = "LocalAlloc")] internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes); [DllImport(KERNEL32, SetLastError = true)] internal static extern IntPtr LocalFree(IntPtr handle); internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX)); return GlobalMemoryStatusExNative(ref buffer); } [DllImport(KERNEL32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")] private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer); [DllImport(KERNEL32, SetLastError = true)] unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer); // VirtualAlloc should generally be avoided, but is needed in // the MemoryFailPoint implementation (within a CER) to increase the // size of the page file, ignoring any host memory allocators. [DllImport(KERNEL32, SetLastError = true)] unsafe internal static extern void* VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode); [DllImport(KERNEL32, SetLastError = true)] unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode); [DllImport(KERNEL32, CharSet = CharSet.Ansi, ExactSpelling = true, EntryPoint = "lstrlenA")] internal static extern int lstrlenA(IntPtr ptr); [DllImport(KERNEL32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")] internal static extern int lstrlenW(IntPtr ptr); [DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)] internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR [DllImport(Win32Native.OLEAUT32)] internal static extern uint SysStringLen(IntPtr bstr); [DllImport(Win32Native.OLEAUT32)] internal static extern void SysFreeString(IntPtr bstr); #if FEATURE_COMINTEROP [DllImport(Win32Native.OLEAUT32)] internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); // BSTR [DllImport(Win32Native.OLEAUT32)] internal static extern uint SysStringByteLen(IntPtr bstr); #endif [DllImport(KERNEL32, SetLastError = true)] internal static extern bool SetEvent(SafeWaitHandle handle); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool ResetEvent(SafeWaitHandle handle); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateEventEx(SECURITY_ATTRIBUTES lpSecurityAttributes, string name, uint flags, uint desiredAccess); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenEvent(uint desiredAccess, bool inheritHandle, string name); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateMutexEx(SECURITY_ATTRIBUTES lpSecurityAttributes, string name, uint flags, uint desiredAccess); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool ReleaseMutex(SafeWaitHandle handle); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool CloseHandle(IntPtr handle); [DllImport(KERNEL32, SetLastError = true)] internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateSemaphoreEx(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess); [DllImport(KERNEL32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); // Will be in winnls.h internal const int FIND_STARTSWITH = 0x00100000; // see if value is at the beginning of source internal const int FIND_ENDSWITH = 0x00200000; // see if value is at the end of source internal const int FIND_FROMSTART = 0x00400000; // look for value in source, starting at the beginning internal const int FIND_FROMEND = 0x00800000; // look for value in source, starting at the end [StructLayout(LayoutKind.Sequential)] internal struct NlsVersionInfoEx { internal int dwNLSVersionInfoSize; internal int dwNLSVersion; internal int dwDefinedVersion; internal int dwEffectiveId; internal Guid guidCustomVersion; } [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length); internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h // Note, these are #defines used to extract handles, and are NOT handles. internal const int STD_INPUT_HANDLE = -10; internal const int STD_OUTPUT_HANDLE = -11; internal const int STD_ERROR_HANDLE = -12; [DllImport(KERNEL32, SetLastError = true)] internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one! // From wincon.h internal const int CTRL_C_EVENT = 0; internal const int CTRL_BREAK_EVENT = 1; internal const int CTRL_CLOSE_EVENT = 2; internal const int CTRL_LOGOFF_EVENT = 5; internal const int CTRL_SHUTDOWN_EVENT = 6; internal const short KEY_EVENT = 1; // From WinBase.h internal const int FILE_TYPE_DISK = 0x0001; internal const int FILE_TYPE_CHAR = 0x0002; internal const int FILE_TYPE_PIPE = 0x0003; internal const int REPLACEFILE_WRITE_THROUGH = 0x1; internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2; private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; internal const uint FILE_MAP_WRITE = 0x0002; internal const uint FILE_MAP_READ = 0x0004; // Constants from WinNT.h internal const int FILE_ATTRIBUTE_READONLY = 0x00000001; internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010; internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400; internal const int IO_REPARSE_TAG_MOUNT_POINT = unchecked((int)0xA0000003); internal const int PAGE_READWRITE = 0x04; internal const int MEM_COMMIT = 0x1000; internal const int MEM_RESERVE = 0x2000; internal const int MEM_RELEASE = 0x8000; internal const int MEM_FREE = 0x10000; // Error codes from WinError.h internal const int ERROR_SUCCESS = 0x0; internal const int ERROR_INVALID_FUNCTION = 0x1; internal const int ERROR_FILE_NOT_FOUND = 0x2; internal const int ERROR_PATH_NOT_FOUND = 0x3; internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_INVALID_HANDLE = 0x6; internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; internal const int ERROR_INVALID_DATA = 0xd; internal const int ERROR_INVALID_DRIVE = 0xf; internal const int ERROR_NO_MORE_FILES = 0x12; internal const int ERROR_NOT_READY = 0x15; internal const int ERROR_BAD_LENGTH = 0x18; internal const int ERROR_SHARING_VIOLATION = 0x20; internal const int ERROR_NOT_SUPPORTED = 0x32; internal const int ERROR_FILE_EXISTS = 0x50; internal const int ERROR_INVALID_PARAMETER = 0x57; internal const int ERROR_BROKEN_PIPE = 0x6D; internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78; internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; internal const int ERROR_INVALID_NAME = 0x7B; internal const int ERROR_BAD_PATHNAME = 0xA1; internal const int ERROR_ALREADY_EXISTS = 0xB7; internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long. internal const int ERROR_NO_DATA = 0xE8; internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_DIRECTORY = 0x10B; internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation internal const int ERROR_NOT_FOUND = 0x490; // 1168; For IO Cancellation internal const int ERROR_NO_TOKEN = 0x3f0; internal const int ERROR_DLL_INIT_FAILED = 0x45A; internal const int ERROR_NON_ACCOUNT_SID = 0x4E9; internal const int ERROR_NOT_ALL_ASSIGNED = 0x514; internal const int ERROR_UNKNOWN_REVISION = 0x519; internal const int ERROR_INVALID_OWNER = 0x51B; internal const int ERROR_INVALID_PRIMARY_GROUP = 0x51C; internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521; internal const int ERROR_PRIVILEGE_NOT_HELD = 0x522; internal const int ERROR_NONE_MAPPED = 0x534; internal const int ERROR_INVALID_ACL = 0x538; internal const int ERROR_INVALID_SID = 0x539; internal const int ERROR_INVALID_SECURITY_DESCR = 0x53A; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542; internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543; internal const int ERROR_NO_SECURITY_ON_OBJECT = 0x546; internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD; // Error codes from ntstatus.h internal const uint STATUS_SUCCESS = 0x00000000; internal const uint STATUS_SOME_NOT_MAPPED = 0x00000107; internal const uint STATUS_NO_MEMORY = 0xC0000017; internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034; internal const uint STATUS_NONE_MAPPED = 0xC0000073; internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A; internal const uint STATUS_ACCESS_DENIED = 0xC0000022; internal const int INVALID_FILE_SIZE = -1; // From WinStatus.h internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int)0xC000006E); // Use this to translate error codes like the above into HRESULTs like // 0x80070006 for ERROR_INVALID_HANDLE internal static int MakeHRFromErrorCode(int errorCode) { BCLDebug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!"); return unchecked(((int)0x80070000) | errorCode); } // Win32 Structs in N/Direct style [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] [BestFitMapping(false)] internal class WIN32_FIND_DATA { internal int dwFileAttributes = 0; // ftCreationTime was a by-value FILETIME structure internal uint ftCreationTime_dwLowDateTime = 0; internal uint ftCreationTime_dwHighDateTime = 0; // ftLastAccessTime was a by-value FILETIME structure internal uint ftLastAccessTime_dwLowDateTime = 0; internal uint ftLastAccessTime_dwHighDateTime = 0; // ftLastWriteTime was a by-value FILETIME structure internal uint ftLastWriteTime_dwLowDateTime = 0; internal uint ftLastWriteTime_dwHighDateTime = 0; internal int nFileSizeHigh = 0; internal int nFileSizeLow = 0; // If the file attributes' reparse point flag is set, then // dwReserved0 is the file tag (aka reparse tag) for the // reparse point. Use this to figure out whether something is // a volume mount point or a symbolic link. internal int dwReserved0 = 0; internal int dwReserved1 = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] internal String cFileName = null; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] internal String cAlternateFileName = null; } [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern bool FindNextFile( SafeFindHandle hndFindFile, [In, Out, MarshalAs(UnmanagedType.LPStruct)] WIN32_FIND_DATA lpFindFileData); [DllImport(KERNEL32)] internal static extern bool FindClose(IntPtr handle); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids [DllImport(KERNEL32)] internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern bool SetEnvironmentVariable(string lpName, string lpValue); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int GetEnvironmentVariable(string lpName, [Out]StringBuilder lpValue, int size); [DllImport(KERNEL32, CharSet = CharSet.Unicode)] internal static unsafe extern char* GetEnvironmentStrings(); [DllImport(KERNEL32, CharSet = CharSet.Unicode)] internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] internal static extern uint GetCurrentProcessId(); [DllImport(OLE32)] internal extern static int CoCreateGuid(out Guid guid); [DllImport(OLE32)] internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb); [DllImport(OLE32)] internal static extern void CoTaskMemFree(IntPtr ptr); [DllImport(OLE32)] internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb); #if FEATURE_WIN32_REGISTRY [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out]StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass, int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys, int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen, ref int lpcValues, int[] lpcbMaxValueNameLen, int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor, int[] lpftLastWriteTime); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref int lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref long lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, String lpData, int cbData); #endif // FEATURE_WIN32_REGISTRY [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize); [DllImport(KERNEL32)] internal static extern IntPtr LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags); internal const int SHGFP_TYPE_CURRENT = 0; // the current (user) folder path setting internal const int UOI_FLAGS = 1; internal const int WSF_VISIBLE = 1; // .NET Framework 4.0 and newer - all versions of windows ||| \public\sdk\inc\shlobj.h internal const int CSIDL_FLAG_CREATE = 0x8000; // force folder creation in SHGetFolderPath internal const int CSIDL_FLAG_DONT_VERIFY = 0x4000; // return an unverified folder path internal const int CSIDL_ADMINTOOLS = 0x0030; // <user name>\Start Menu\Programs\Administrative Tools internal const int CSIDL_CDBURN_AREA = 0x003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning internal const int CSIDL_COMMON_ADMINTOOLS = 0x002f; // All Users\Start Menu\Programs\Administrative Tools internal const int CSIDL_COMMON_DOCUMENTS = 0x002e; // All Users\Documents internal const int CSIDL_COMMON_MUSIC = 0x0035; // All Users\My Music internal const int CSIDL_COMMON_OEM_LINKS = 0x003a; // Links to All Users OEM specific apps internal const int CSIDL_COMMON_PICTURES = 0x0036; // All Users\My Pictures internal const int CSIDL_COMMON_STARTMENU = 0x0016; // All Users\Start Menu internal const int CSIDL_COMMON_PROGRAMS = 0X0017; // All Users\Start Menu\Programs internal const int CSIDL_COMMON_STARTUP = 0x0018; // All Users\Startup internal const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019; // All Users\Desktop internal const int CSIDL_COMMON_TEMPLATES = 0x002d; // All Users\Templates internal const int CSIDL_COMMON_VIDEO = 0x0037; // All Users\My Video internal const int CSIDL_FONTS = 0x0014; // windows\fonts internal const int CSIDL_MYVIDEO = 0x000e; // "My Videos" folder internal const int CSIDL_NETHOOD = 0x0013; // %APPDATA%\Microsoft\Windows\Network Shortcuts internal const int CSIDL_PRINTHOOD = 0x001b; // %APPDATA%\Microsoft\Windows\Printer Shortcuts internal const int CSIDL_PROFILE = 0x0028; // %USERPROFILE% (%SystemDrive%\Users\%USERNAME%) internal const int CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c; // x86 Program Files\Common on RISC internal const int CSIDL_PROGRAM_FILESX86 = 0x002a; // x86 C:\Program Files on RISC internal const int CSIDL_RESOURCES = 0x0038; // %windir%\Resources internal const int CSIDL_RESOURCES_LOCALIZED = 0x0039; // %windir%\resources\0409 (code page) internal const int CSIDL_SYSTEMX86 = 0x0029; // %windir%\system32 internal const int CSIDL_WINDOWS = 0x0024; // GetWindowsDirectory() // .NET Framework 3.5 and earlier - all versions of windows internal const int CSIDL_APPDATA = 0x001a; internal const int CSIDL_COMMON_APPDATA = 0x0023; internal const int CSIDL_LOCAL_APPDATA = 0x001c; internal const int CSIDL_COOKIES = 0x0021; internal const int CSIDL_FAVORITES = 0x0006; internal const int CSIDL_HISTORY = 0x0022; internal const int CSIDL_INTERNET_CACHE = 0x0020; internal const int CSIDL_PROGRAMS = 0x0002; internal const int CSIDL_RECENT = 0x0008; internal const int CSIDL_SENDTO = 0x0009; internal const int CSIDL_STARTMENU = 0x000b; internal const int CSIDL_STARTUP = 0x0007; internal const int CSIDL_SYSTEM = 0x0025; internal const int CSIDL_TEMPLATES = 0x0015; internal const int CSIDL_DESKTOPDIRECTORY = 0x0010; internal const int CSIDL_PERSONAL = 0x0005; internal const int CSIDL_PROGRAM_FILES = 0x0026; internal const int CSIDL_PROGRAM_FILES_COMMON = 0x002b; internal const int CSIDL_DESKTOP = 0x0000; internal const int CSIDL_DRIVES = 0x0011; internal const int CSIDL_MYMUSIC = 0x000d; internal const int CSIDL_MYPICTURES = 0x0027; internal const int NameSamCompatible = 2; [DllImport(USER32, SetLastError = true, BestFitMapping = false)] internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult); [DllImport(KERNEL32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime); internal const byte VER_GREATER_EQUAL = 0x3; internal const uint VER_MAJORVERSION = 0x0000002; internal const uint VER_MINORVERSION = 0x0000001; internal const uint VER_SERVICEPACKMAJOR = 0x0000020; internal const uint VER_SERVICEPACKMINOR = 0x0000010; [DllImport("kernel32.dll")] internal static extern bool VerifyVersionInfoW([In, Out] OSVERSIONINFOEX lpVersionInfo, uint dwTypeMask, ulong dwlConditionMask); [DllImport("kernel32.dll")] internal static extern ulong VerSetConditionMask(ulong dwlConditionMask, uint dwTypeBitMask, byte dwConditionMask); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using PagedBytes = Lucene.Net.Util.PagedBytes; using PostingsFormat = Lucene.Net.Codecs.PostingsFormat; // javadocs using SeekStatus = Lucene.Net.Index.TermsEnum.SeekStatus; using StringHelper = Lucene.Net.Util.StringHelper; /// <summary> /// This class enables fast access to multiple term ords for /// a specified field across all docIDs. /// <para/> /// Like <see cref="Search.IFieldCache"/>, it uninverts the index and holds a /// packed data structure in RAM to enable fast access. /// Unlike <see cref="Search.IFieldCache"/>, it can handle multi-valued fields, /// and, it does not hold the term bytes in RAM. Rather, you /// must obtain a <see cref="TermsEnum"/> from the <see cref="GetOrdTermsEnum"/> /// method, and then seek-by-ord to get the term's bytes. /// <para/> /// While normally term ords are type <see cref="long"/>, in this API they are /// <see cref="int"/> as the internal representation here cannot address /// more than <see cref="BufferedUpdates.MAX_INT32"/> unique terms. Also, typically this /// class is used on fields with relatively few unique terms /// vs the number of documents. In addition, there is an /// internal limit (16 MB) on how many bytes each chunk of /// documents may consume. If you trip this limit you'll hit /// an <see cref="InvalidOperationException"/>. /// <para/> /// Deleted documents are skipped during uninversion, and if /// you look them up you'll get 0 ords. /// <para/> /// The returned per-document ords do not retain their /// original order in the document. Instead they are returned /// in sorted (by ord, ie term's <see cref="BytesRef"/> comparer) order. They /// are also de-dup'd (ie if doc has same term more than once /// in this field, you'll only get that ord back once). /// <para/> /// This class tests whether the provided reader is able to /// retrieve terms by ord (ie, it's single segment, and it /// uses an ord-capable terms index). If not, this class /// will create its own term index internally, allowing to /// create a wrapped <see cref="TermsEnum"/> that can handle ord. The /// <see cref="GetOrdTermsEnum"/> method then provides this /// wrapped enum, if necessary. /// <para/> /// The RAM consumption of this class can be high! /// <para/> /// @lucene.experimental /// </summary> /// <remarks> /// Final form of the un-inverted field: /// <list type="bullet"> /// <item><description>Each document points to a list of term numbers that are contained in that document.</description></item> /// <item><description> /// Term numbers are in sorted order, and are encoded as variable-length deltas from the /// previous term number. Real term numbers start at 2 since 0 and 1 are reserved. A /// term number of 0 signals the end of the termNumber list. /// </description></item> /// <item><description> /// There is a single int[maxDoc()] which either contains a pointer into a byte[] for /// the termNumber lists, or directly contains the termNumber list if it fits in the 4 /// bytes of an integer. If the first byte in the integer is 1, the next 3 bytes /// are a pointer into a byte[] where the termNumber list starts. /// </description></item> /// <item><description> /// There are actually 256 byte arrays, to compensate for the fact that the pointers /// into the byte arrays are only 3 bytes long. The correct byte array for a document /// is a function of it's id. /// </description></item> /// <item><description> /// To save space and speed up faceting, any term that matches enough documents will /// not be un-inverted... it will be skipped while building the un-inverted field structure, /// and will use a set intersection method during faceting. /// </description></item> /// <item><description> /// To further save memory, the terms (the actual string values) are not all stored in /// memory, but a TermIndex is used to convert term numbers to term values only /// for the terms needed after faceting has completed. Only every 128th term value /// is stored, along with it's corresponding term number, and this is used as an /// index to find the closest term and iterate until the desired number is hit (very /// much like Lucene's own internal term index). /// </description></item> /// </list> /// </remarks> public class DocTermOrds { /// <summary> /// Term ords are shifted by this, internally, to reserve /// values 0 (end term) and 1 (index is a pointer into byte array) /// </summary> private static readonly int TNUM_OFFSET = 2; /// <summary> /// Every 128th term is indexed, by default. </summary> public static readonly int DEFAULT_INDEX_INTERVAL_BITS = 7; // decrease to a low number like 2 for testing private int indexIntervalBits; private int indexIntervalMask; private int indexInterval; /// <summary> /// Don't uninvert terms that exceed this count. </summary> protected readonly int m_maxTermDocFreq; /// <summary> /// Field we are uninverting. </summary> protected readonly string m_field; /// <summary> /// Number of terms in the field. </summary> protected int m_numTermsInField; /// <summary> /// Total number of references to term numbers. </summary> protected long m_termInstances; private long memsz; /// <summary> /// Total time to uninvert the field. </summary> protected int m_total_time; /// <summary> /// Time for phase1 of the uninvert process. </summary> protected int m_phase1_time; /// <summary> /// Holds the per-document ords or a pointer to the ords. </summary> protected int[] m_index; /// <summary> /// Holds term ords for documents. </summary> [CLSCompliant(false)] // LUCENENET NOTE: Since jagged arrays are not CLS compliant anyway, this would need to be byte[,] to be CLS compliant - not sure it is worth the effort protected sbyte[][] m_tnums = new sbyte[256][]; /// <summary> /// Total bytes (sum of term lengths) for all indexed terms. </summary> protected long m_sizeOfIndexedStrings; /// <summary> /// Holds the indexed (by default every 128th) terms. </summary> protected BytesRef[] m_indexedTermsArray; /// <summary> /// If non-null, only terms matching this prefix were /// indexed. /// </summary> protected BytesRef m_prefix; /// <summary> /// Ordinal of the first term in the field, or 0 if the /// <see cref="PostingsFormat"/> does not implement /// <see cref="TermsEnum.Ord"/>. /// </summary> protected int m_ordBase; /// <summary> /// Used while uninverting. </summary> protected DocsEnum m_docsEnum; /// <summary> /// Returns total bytes used. </summary> public virtual long RamUsedInBytes() { // can cache the mem size since it shouldn't change if (memsz != 0) { return memsz; } long sz = 8 * 8 + 32; // local fields if (m_index != null) { sz += m_index.Length * 4; } if (m_tnums != null) { for (int i = 0; i < m_tnums.Length; i++) { var arr = m_tnums[i]; if (arr != null) sz += arr.Length; } } memsz = sz; return sz; } /// <summary> /// Inverts all terms </summary> public DocTermOrds(AtomicReader reader, IBits liveDocs, string field) : this(reader, liveDocs, field, null, int.MaxValue) { } /// <summary> /// Inverts only terms starting w/ prefix </summary> public DocTermOrds(AtomicReader reader, IBits liveDocs, string field, BytesRef termPrefix) : this(reader, liveDocs, field, termPrefix, int.MaxValue) { } /// <summary> /// Inverts only terms starting w/ prefix, and only terms /// whose docFreq (not taking deletions into account) is /// &lt;= <paramref name="maxTermDocFreq"/> /// </summary> public DocTermOrds(AtomicReader reader, IBits liveDocs, string field, BytesRef termPrefix, int maxTermDocFreq) : this(reader, liveDocs, field, termPrefix, maxTermDocFreq, DEFAULT_INDEX_INTERVAL_BITS) { } /// <summary> /// Inverts only terms starting w/ prefix, and only terms /// whose docFreq (not taking deletions into account) is /// &lt;= <paramref name="maxTermDocFreq"/>, with a custom indexing interval /// (default is every 128nd term). /// </summary> public DocTermOrds(AtomicReader reader, IBits liveDocs, string field, BytesRef termPrefix, int maxTermDocFreq, int indexIntervalBits) : this(field, maxTermDocFreq, indexIntervalBits) { Uninvert(reader, liveDocs, termPrefix); } /// <summary> /// Subclass inits w/ this, but be sure you then call /// uninvert, only once /// </summary> protected DocTermOrds(string field, int maxTermDocFreq, int indexIntervalBits) { //System.out.println("DTO init field=" + field + " maxTDFreq=" + maxTermDocFreq); this.m_field = field; this.m_maxTermDocFreq = maxTermDocFreq; this.indexIntervalBits = indexIntervalBits; indexIntervalMask = (int)((uint)0xffffffff >> (32 - indexIntervalBits)); indexInterval = 1 << indexIntervalBits; } /// <summary> /// Returns a <see cref="TermsEnum"/> that implements <see cref="TermsEnum.Ord"/>. If the /// provided <paramref name="reader"/> supports <see cref="TermsEnum.Ord"/>, we just return its /// <see cref="TermsEnum"/>; if it does not, we build a "private" terms /// index internally (WARNING: consumes RAM) and use that /// index to implement <see cref="TermsEnum.Ord"/>. This also enables <see cref="TermsEnum.Ord"/> on top /// of a composite reader. The returned <see cref="TermsEnum"/> is /// unpositioned. This returns <c>null</c> if there are no terms. /// /// <para/><b>NOTE</b>: you must pass the same reader that was /// used when creating this class /// </summary> public virtual TermsEnum GetOrdTermsEnum(AtomicReader reader) { if (m_indexedTermsArray == null) { //System.out.println("GET normal enum"); Fields fields = reader.Fields; if (fields == null) { return null; } Terms terms = fields.GetTerms(m_field); if (terms == null) { return null; } else { return terms.GetIterator(null); } } else { //System.out.println("GET wrapped enum ordBase=" + ordBase); return new OrdWrappedTermsEnum(this, reader); } } /// <summary> /// Returns the number of terms in this field /// </summary> public virtual int NumTerms => m_numTermsInField; /// <summary> /// Returns <c>true</c> if no terms were indexed. /// </summary> public virtual bool IsEmpty => m_index == null; /// <summary> /// Subclass can override this </summary> protected virtual void VisitTerm(TermsEnum te, int termNum) { } /// <summary> /// Invoked during <see cref="Uninvert(AtomicReader, IBits, BytesRef)"/> /// to record the document frequency for each uninverted /// term. /// </summary> protected virtual void SetActualDocFreq(int termNum, int df) { } /// <summary> /// Call this only once (if you subclass!) </summary> protected virtual void Uninvert(AtomicReader reader, IBits liveDocs, BytesRef termPrefix) { FieldInfo info = reader.FieldInfos.FieldInfo(m_field); if (info != null && info.HasDocValues) { throw new InvalidOperationException("Type mismatch: " + m_field + " was indexed as " + info.DocValuesType); } //System.out.println("DTO uninvert field=" + field + " prefix=" + termPrefix); long startTime = Environment.TickCount; m_prefix = termPrefix == null ? null : BytesRef.DeepCopyOf(termPrefix); int maxDoc = reader.MaxDoc; int[] index = new int[maxDoc]; // immediate term numbers, or the index into the byte[] representing the last number int[] lastTerm = new int[maxDoc]; // last term we saw for this document var bytes = new sbyte[maxDoc][]; // list of term numbers for the doc (delta encoded vInts) Fields fields = reader.Fields; if (fields == null) { // No terms return; } Terms terms = fields.GetTerms(m_field); if (terms == null) { // No terms return; } TermsEnum te = terms.GetIterator(null); BytesRef seekStart = termPrefix != null ? termPrefix : new BytesRef(); //System.out.println("seekStart=" + seekStart.utf8ToString()); if (te.SeekCeil(seekStart) == TermsEnum.SeekStatus.END) { // No terms match return; } // If we need our "term index wrapper", these will be // init'd below: IList<BytesRef> indexedTerms = null; PagedBytes indexedTermsBytes = null; bool testedOrd = false; // we need a minimum of 9 bytes, but round up to 12 since the space would // be wasted with most allocators anyway. var tempArr = new sbyte[12]; // // enumerate all terms, and build an intermediate form of the un-inverted field. // // During this intermediate form, every document has a (potential) byte[] // and the int[maxDoc()] array either contains the termNumber list directly // or the *end* offset of the termNumber list in it's byte array (for faster // appending and faster creation of the final form). // // idea... if things are too large while building, we could do a range of docs // at a time (but it would be a fair amount slower to build) // could also do ranges in parallel to take advantage of multiple CPUs // OPTIONAL: remap the largest df terms to the lowest 128 (single byte) // values. this requires going over the field first to find the most // frequent terms ahead of time. int termNum = 0; m_docsEnum = null; // Loop begins with te positioned to first term (we call // seek above): for (; ; ) { BytesRef t = te.Term; if (t == null || (termPrefix != null && !StringHelper.StartsWith(t, termPrefix))) { break; } //System.out.println("visit term=" + t.utf8ToString() + " " + t + " termNum=" + termNum); if (!testedOrd) { try { m_ordBase = (int)te.Ord; //System.out.println("got ordBase=" + ordBase); } #pragma warning disable 168 catch (NotSupportedException uoe) #pragma warning restore 168 { // Reader cannot provide ord support, so we wrap // our own support by creating our own terms index: indexedTerms = new List<BytesRef>(); indexedTermsBytes = new PagedBytes(15); //System.out.println("NO ORDS"); } testedOrd = true; } VisitTerm(te, termNum); if (indexedTerms != null && (termNum & indexIntervalMask) == 0) { // Index this term m_sizeOfIndexedStrings += t.Length; BytesRef indexedTerm = new BytesRef(); indexedTermsBytes.Copy(t, indexedTerm); // TODO: really should 1) strip off useless suffix, // and 2) use FST not array/PagedBytes indexedTerms.Add(indexedTerm); } int df = te.DocFreq; if (df <= m_maxTermDocFreq) { m_docsEnum = te.Docs(liveDocs, m_docsEnum, DocsFlags.NONE); // dF, but takes deletions into account int actualDF = 0; for (; ; ) { int doc = m_docsEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { break; } //System.out.println(" chunk=" + chunk + " docs"); actualDF++; m_termInstances++; //System.out.println(" docID=" + doc); // add TNUM_OFFSET to the term number to make room for special reserved values: // 0 (end term) and 1 (index into byte array follows) int delta = termNum - lastTerm[doc] + TNUM_OFFSET; lastTerm[doc] = termNum; int val = index[doc]; if ((val & 0xff) == 1) { // index into byte array (actually the end of // the doc-specific byte[] when building) int pos = (int)((uint)val >> 8); int ilen = VInt32Size(delta); var arr = bytes[doc]; int newend = pos + ilen; if (newend > arr.Length) { // We avoid a doubling strategy to lower memory usage. // this faceting method isn't for docs with many terms. // In hotspot, objects have 2 words of overhead, then fields, rounded up to a 64-bit boundary. // TODO: figure out what array lengths we can round up to w/o actually using more memory // (how much space does a byte[] take up? Is data preceded by a 32 bit length only? // It should be safe to round up to the nearest 32 bits in any case. int newLen = (newend + 3) & unchecked((int)0xfffffffc); // 4 byte alignment var newarr = new sbyte[newLen]; Array.Copy(arr, 0, newarr, 0, pos); arr = newarr; bytes[doc] = newarr; } pos = WriteInt32(delta, arr, pos); index[doc] = (pos << 8) | 1; // update pointer to end index in byte[] } else { // OK, this int has data in it... find the end (a zero starting byte - not // part of another number, hence not following a byte with the high bit set). int ipos; if (val == 0) { ipos = 0; } else if ((val & 0x0000ff80) == 0) { ipos = 1; } else if ((val & 0x00ff8000) == 0) { ipos = 2; } else if ((val & 0xff800000) == 0) { ipos = 3; } else { ipos = 4; } //System.out.println(" ipos=" + ipos); int endPos = WriteInt32(delta, tempArr, ipos); //System.out.println(" endpos=" + endPos); if (endPos <= 4) { //System.out.println(" fits!"); // value will fit in the integer... move bytes back for (int j = ipos; j < endPos; j++) { val |= (tempArr[j] & 0xff) << (j << 3); } index[doc] = val; } else { // value won't fit... move integer into byte[] for (int j = 0; j < ipos; j++) { tempArr[j] = (sbyte)val; val = (int)((uint)val >> 8); } // point at the end index in the byte[] index[doc] = (endPos << 8) | 1; bytes[doc] = tempArr; tempArr = new sbyte[12]; } } } SetActualDocFreq(termNum, actualDF); } termNum++; if (te.Next() == null) { break; } } m_numTermsInField = termNum; long midPoint = Environment.TickCount; if (m_termInstances == 0) { // we didn't invert anything // lower memory consumption. m_tnums = null; } else { this.m_index = index; // // transform intermediate form into the final form, building a single byte[] // at a time, and releasing the intermediate byte[]s as we go to avoid // increasing the memory footprint. // for (int pass = 0; pass < 256; pass++) { var target = m_tnums[pass]; var pos = 0; // end in target; if (target != null) { pos = target.Length; } else { target = new sbyte[4096]; } // loop over documents, 0x00ppxxxx, 0x01ppxxxx, 0x02ppxxxx // where pp is the pass (which array we are building), and xx is all values. // each pass shares the same byte[] for termNumber lists. for (int docbase = pass << 16; docbase < maxDoc; docbase += (1 << 24)) { int lim = Math.Min(docbase + (1 << 16), maxDoc); for (int doc = docbase; doc < lim; doc++) { //System.out.println(" pass=" + pass + " process docID=" + doc); int val = index[doc]; if ((val & 0xff) == 1) { int len = (int)((uint)val >> 8); //System.out.println(" ptr pos=" + pos); index[doc] = (pos << 8) | 1; // change index to point to start of array if ((pos & 0xff000000) != 0) { // we only have 24 bits for the array index throw new InvalidOperationException("Too many values for UnInvertedField faceting on field " + m_field); } var arr = bytes[doc]; /* for(byte b : arr) { //System.out.println(" b=" + Integer.toHexString((int) b)); } */ bytes[doc] = null; // IMPORTANT: allow GC to avoid OOM if (target.Length <= pos + len) { int newlen = target.Length; //* we don't have to worry about the array getting too large // since the "pos" param will overflow first (only 24 bits available) // if ((newlen<<1) <= 0) { // // overflow... // newlen = Integer.MAX_VALUE; // if (newlen <= pos + len) { // throw new SolrException(400,"Too many terms to uninvert field!"); // } // } else { // while (newlen <= pos + len) newlen<<=1; // doubling strategy // } // while (newlen <= pos + len) // doubling strategy { newlen <<= 1; } var newtarget = new sbyte[newlen]; Array.Copy(target, 0, newtarget, 0, pos); target = newtarget; } Array.Copy(arr, 0, target, pos, len); pos += len + 1; // skip single byte at end and leave it 0 for terminator } } } // shrink array if (pos < target.Length) { var newtarget = new sbyte[pos]; Array.Copy(target, 0, newtarget, 0, pos); target = newtarget; } m_tnums[pass] = target; if ((pass << 16) > maxDoc) { break; } } } if (indexedTerms != null) { m_indexedTermsArray = new BytesRef[indexedTerms.Count]; indexedTerms.CopyTo(m_indexedTermsArray, 0); } long endTime = Environment.TickCount; m_total_time = (int)(endTime - startTime); m_phase1_time = (int)(midPoint - startTime); } /// <summary> /// Number of bytes to represent an unsigned int as a vint. /// <para/> /// NOTE: This was vIntSize() in Lucene /// </summary> private static int VInt32Size(int x) { if ((x & (0xffffffff << (7 * 1))) == 0) { return 1; } if ((x & (0xffffffff << (7 * 2))) == 0) { return 2; } if ((x & (0xffffffff << (7 * 3))) == 0) { return 3; } if ((x & (0xffffffff << (7 * 4))) == 0) { return 4; } return 5; } // todo: if we know the size of the vInt already, we could do // a single switch on the size /// <summary> /// NOTE: This was writeInt() in Lucene /// </summary> private static int WriteInt32(int x, sbyte[] arr, int pos) { var a = ((int)((uint)x >> (7 * 4))); if (a != 0) { arr[pos++] = (sbyte)(a | 0x80); } a = ((int)((uint)x >> (7 * 3))); if (a != 0) { arr[pos++] = (sbyte)(a | 0x80); } a = ((int)((uint)x >> (7 * 2))); if (a != 0) { arr[pos++] = (sbyte)(a | 0x80); } a = ((int)((uint)x >> (7 * 1))); if (a != 0) { arr[pos++] = (sbyte)(a | 0x80); } arr[pos++] = (sbyte)(x & 0x7f); return pos; } /// <summary> /// Only used if original <see cref="IndexReader"/> doesn't implement /// <see cref="TermsEnum.Ord"/>; in this case we "wrap" our own terms index /// around it. /// </summary> private sealed class OrdWrappedTermsEnum : TermsEnum { internal void InitializeInstanceFields() { ord = -outerInstance.indexInterval - 1; } private readonly DocTermOrds outerInstance; internal readonly TermsEnum termsEnum; internal BytesRef term; internal long ord; // force "real" seek public OrdWrappedTermsEnum(DocTermOrds outerInstance, AtomicReader reader) { this.outerInstance = outerInstance; InitializeInstanceFields(); Debug.Assert(outerInstance.m_indexedTermsArray != null); termsEnum = reader.Fields.GetTerms(outerInstance.m_field).GetIterator(null); } public override IComparer<BytesRef> Comparer => termsEnum.Comparer; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { return termsEnum.Docs(liveDocs, reuse, flags); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { return termsEnum.DocsAndPositions(liveDocs, reuse, flags); } public override BytesRef Term => term; public override BytesRef Next() { if (++ord < 0) { ord = 0; } if (termsEnum.Next() == null) { term = null; return null; } return SetTerm(); // this is extra work if we know we are in bounds... } public override int DocFreq => termsEnum.DocFreq; public override long TotalTermFreq => termsEnum.TotalTermFreq; public override long Ord => outerInstance.m_ordBase + ord; public override SeekStatus SeekCeil(BytesRef target) { // already here if (term != null && term.Equals(target)) { return SeekStatus.FOUND; } int startIdx = Array.BinarySearch(outerInstance.m_indexedTermsArray, target); if (startIdx >= 0) { // we hit the term exactly... lucky us! TermsEnum.SeekStatus seekStatus = termsEnum.SeekCeil(target); Debug.Assert(seekStatus == TermsEnum.SeekStatus.FOUND); ord = startIdx << outerInstance.indexIntervalBits; SetTerm(); Debug.Assert(term != null); return SeekStatus.FOUND; } // we didn't hit the term exactly startIdx = -startIdx - 1; if (startIdx == 0) { // our target occurs *before* the first term TermsEnum.SeekStatus seekStatus = termsEnum.SeekCeil(target); Debug.Assert(seekStatus == TermsEnum.SeekStatus.NOT_FOUND); ord = 0; SetTerm(); Debug.Assert(term != null); return SeekStatus.NOT_FOUND; } // back up to the start of the block startIdx--; if ((ord >> outerInstance.indexIntervalBits) == startIdx && term != null && term.CompareTo(target) <= 0) { // we are already in the right block and the current term is before the term we want, // so we don't need to seek. } else { // seek to the right block TermsEnum.SeekStatus seekStatus = termsEnum.SeekCeil(outerInstance.m_indexedTermsArray[startIdx]); Debug.Assert(seekStatus == TermsEnum.SeekStatus.FOUND); ord = startIdx << outerInstance.indexIntervalBits; SetTerm(); Debug.Assert(term != null); // should be non-null since it's in the index } while (term != null && term.CompareTo(target) < 0) { Next(); } if (term == null) { return SeekStatus.END; } else if (term.CompareTo(target) == 0) { return SeekStatus.FOUND; } else { return SeekStatus.NOT_FOUND; } } public override void SeekExact(long targetOrd) { int delta = (int)(targetOrd - outerInstance.m_ordBase - ord); //System.out.println(" seek(ord) targetOrd=" + targetOrd + " delta=" + delta + " ord=" + ord + " ii=" + indexInterval); if (delta < 0 || delta > outerInstance.indexInterval) { int idx = (int)((long)((ulong)targetOrd >> outerInstance.indexIntervalBits)); BytesRef @base = outerInstance.m_indexedTermsArray[idx]; //System.out.println(" do seek term=" + base.utf8ToString()); ord = idx << outerInstance.indexIntervalBits; delta = (int)(targetOrd - ord); TermsEnum.SeekStatus seekStatus = termsEnum.SeekCeil(@base); Debug.Assert(seekStatus == TermsEnum.SeekStatus.FOUND); } else { //System.out.println("seek w/in block"); } while (--delta >= 0) { BytesRef br = termsEnum.Next(); if (br == null) { Debug.Assert(false); return; } ord++; } SetTerm(); Debug.Assert(term != null); } private BytesRef SetTerm() { term = termsEnum.Term; //System.out.println(" setTerm() term=" + term.utf8ToString() + " vs prefix=" + (prefix == null ? "null" : prefix.utf8ToString())); if (outerInstance.m_prefix != null && !StringHelper.StartsWith(term, outerInstance.m_prefix)) { term = null; } return term; } } /// <summary> /// Returns the term (<see cref="BytesRef"/>) corresponding to /// the provided ordinal. /// </summary> public virtual BytesRef LookupTerm(TermsEnum termsEnum, int ord) { termsEnum.SeekExact(ord); return termsEnum.Term; } /// <summary> /// Returns a <see cref="SortedSetDocValues"/> view of this instance </summary> public virtual SortedSetDocValues GetIterator(AtomicReader reader) { if (IsEmpty) { return DocValues.EMPTY_SORTED_SET; } else { return new Iterator(this, reader); } } private class Iterator : SortedSetDocValues { private readonly DocTermOrds outerInstance; private readonly AtomicReader reader; private readonly TermsEnum te; // used internally for lookupOrd() and lookupTerm() // currently we read 5 at a time (using the logic of the old iterator) private readonly int[] buffer = new int[5]; private int bufferUpto; private int bufferLength; private int tnum; private int upto; private sbyte[] arr; internal Iterator(DocTermOrds outerInstance, AtomicReader reader) { this.outerInstance = outerInstance; this.reader = reader; this.te = GetTermsEnum(); } public override long NextOrd() { while (bufferUpto == bufferLength) { if (bufferLength < buffer.Length) { return NO_MORE_ORDS; } else { bufferLength = Read(buffer); bufferUpto = 0; } } return buffer[bufferUpto++]; } /// <summary> /// Buffer must be at least 5 <see cref="int"/>s long. Returns number /// of term ords placed into buffer; if this count is /// less than buffer.Length then that is the end. /// </summary> internal virtual int Read(int[] buffer) { int bufferUpto = 0; if (arr == null) { // code is inlined into upto //System.out.println("inlined"); int code = upto; int delta = 0; for (; ; ) { delta = (delta << 7) | (code & 0x7f); if ((code & 0x80) == 0) { if (delta == 0) { break; } tnum += delta - TNUM_OFFSET; buffer[bufferUpto++] = outerInstance.m_ordBase + tnum; //System.out.println(" tnum=" + tnum); delta = 0; } code = (int)((uint)code >> 8); } } else { // code is a pointer for (; ; ) { int delta = 0; for (; ; ) { sbyte b = arr[upto++]; delta = (delta << 7) | (b & 0x7f); //System.out.println(" cycle: upto=" + upto + " delta=" + delta + " b=" + b); if ((b & 0x80) == 0) { break; } } //System.out.println(" delta=" + delta); if (delta == 0) { break; } tnum += delta - TNUM_OFFSET; //System.out.println(" tnum=" + tnum); buffer[bufferUpto++] = outerInstance.m_ordBase + tnum; if (bufferUpto == buffer.Length) { break; } } } return bufferUpto; } public override void SetDocument(int docID) { tnum = 0; int code = outerInstance.m_index[docID]; if ((code & 0xff) == 1) { // a pointer upto = (int)((uint)code >> 8); //System.out.println(" pointer! upto=" + upto); int whichArray = ((int)((uint)docID >> 16)) & 0xff; arr = outerInstance.m_tnums[whichArray]; } else { //System.out.println(" inline!"); arr = null; upto = code; } bufferUpto = 0; bufferLength = Read(buffer); } public override void LookupOrd(long ord, BytesRef result) { BytesRef @ref = null; try { @ref = outerInstance.LookupTerm(te, (int)ord); } catch (IOException e) { throw new Exception(e.ToString(), e); } result.Bytes = @ref.Bytes; result.Offset = @ref.Offset; result.Length = @ref.Length; } public override long ValueCount => outerInstance.NumTerms; public override long LookupTerm(BytesRef key) { try { if (te.SeekCeil(key) == SeekStatus.FOUND) { return te.Ord; } else { return -te.Ord - 1; } } catch (IOException e) { throw new Exception(e.ToString(), e); } } public override TermsEnum GetTermsEnum() { try { return outerInstance.GetOrdTermsEnum(reader); } #pragma warning disable 168 catch (IOException e) #pragma warning restore 168 { throw new Exception(e.ToString(), e); } } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /// <summary> /// base class shared by the Tween and TweenChain classes to allow a seemless API when controlling /// either of them /// </summary> public abstract class AbstractGoTween { public int id { get; set; } // optional id used for identifying this tween public string tag { get; set; } // optional tag used for identifying this tween public GoTweenState state { get; protected set; } // current state of the tween public float duration { get; protected set; } // duration for a single loop public float totalDuration { get; protected set; } // duration for all loops of this tween public float timeScale { get; set; } // time scale to be used by this tween public GoUpdateType updateType { get; protected set; } public GoLoopType loopType { get; protected set; } public int iterations { get; protected set; } // set to -1 for infinite public bool autoRemoveOnComplete { get; set; } // should we automatically remove ourself from the Go's list of tweens when done? public bool isReversed { get; protected set; } // have we been reversed? this is different than a PingPong loop's backwards section public bool allowEvents { get; set; } // allow the user to surpress events. protected bool _didInit; // flag to ensure event only gets fired once protected bool _didBegin; // flag to ensure event only gets fired once protected bool _fireIterationStart; protected bool _fireIterationEnd; // internal state for update logic protected float _elapsedTime; // elapsed time for the current loop iteration protected float _totalElapsedTime; // total elapsed time of the entire tween public float totalElapsedTime { get { return _totalElapsedTime; } } protected bool _isLoopingBackOnPingPong; public bool isLoopingBackOnPingPong { get { return _isLoopingBackOnPingPong; } } protected bool _didIterateLastFrame; protected bool _didIterateThisFrame; protected int _deltaIterations; // change in completed iterations this frame. protected int _completedIterations; public int completedIterations { get { return _completedIterations; } } // action event handlers protected Action<AbstractGoTween> _onInit; // executes before initial setup. protected Action<AbstractGoTween> _onBegin; // executes when a tween starts. protected Action<AbstractGoTween> _onIterationStart; // executes whenever a tween starts an iteration. protected Action<AbstractGoTween> _onUpdate; // execute whenever a tween updates. protected Action<AbstractGoTween> _onIterationEnd; // executes whenever a tween ends an iteration. protected Action<AbstractGoTween> _onComplete; // exectures whenever a tween completes public void setOnInitHandler( Action<AbstractGoTween> onInit ) { _onInit = onInit; } public void setOnBeginHandler( Action<AbstractGoTween> onBegin ) { _onBegin = onBegin; } public void setonIterationStartHandler( Action<AbstractGoTween> onIterationStart ) { _onIterationStart = onIterationStart; } public void setOnUpdateHandler( Action<AbstractGoTween> onUpdate ) { _onUpdate = onUpdate; } public void setonIterationEndHandler( Action<AbstractGoTween> onIterationEnd ) { _onIterationEnd = onIterationEnd; } public void setOnCompleteHandler( Action<AbstractGoTween> onComplete ) { _onComplete = onComplete; } /// <summary> /// called once per tween when it is first updated /// </summary> protected virtual void onInit() { if( !allowEvents ) return; if( _onInit != null ) _onInit( this ); _didInit = true; } /// <summary> /// called whenever the tween is updated and the playhead is at the start (or end, depending on isReversed) of the tween. /// </summary> protected virtual void onBegin() { if( !allowEvents ) return; if( isReversed && _totalElapsedTime != totalDuration ) return; else if( !isReversed && _totalElapsedTime != 0f ) return; if( _onBegin != null ) _onBegin( this ); _didBegin = true; } /// <summary> /// called once per iteration at the start of the iteration. /// </summary> protected virtual void onIterationStart() { if( !allowEvents ) return; if( _onIterationStart != null ) _onIterationStart( this ); } /// <summary> /// called once per update, after the update has occured. /// </summary> protected virtual void onUpdate() { if( !allowEvents ) return; if( _onUpdate != null ) _onUpdate( this ); } /// <summary> /// called once per iteration at the end of the iteration. /// </summary> protected virtual void onIterationEnd() { if( !allowEvents ) return; if( _onIterationEnd != null ) _onIterationEnd( this ); } /// <summary> /// called when the tween completes playing. /// </summary> protected virtual void onComplete() { if( !allowEvents ) return; if( _onComplete != null ) _onComplete( this ); } /// <summary> /// tick method. if it returns true it indicates the tween is complete. /// note: at it's base, AbstractGoTween does not fire events, it is up to the implementer to /// do so. see GoTween and AbstractGoTweenCollection for examples. /// </summary> public virtual bool update( float deltaTime ) { // increment or decrement the total elapsed time then clamp from 0 to totalDuration if( isReversed ) _totalElapsedTime -= deltaTime; else _totalElapsedTime += deltaTime; _totalElapsedTime = Mathf.Clamp( _totalElapsedTime, 0, totalDuration ); _didIterateLastFrame = _didIterateThisFrame || ( !isReversed && _totalElapsedTime == 0 ) || ( isReversed && _totalElapsedTime == totalDuration ); // we flip between ceil and floor based on the direction, because we want the iteration change // to happen when "duration" seconds has elapsed, not immediately, as was the case if you // were doing a floor and were going in reverse. if( isReversed ) _deltaIterations = Mathf.CeilToInt( _totalElapsedTime / duration ) - _completedIterations; else _deltaIterations = Mathf.FloorToInt( _totalElapsedTime / duration ) - _completedIterations; // we iterated this frame if we have done a goTo() to an iteration point, or we've passed over // an iteration threshold. _didIterateThisFrame = !_didIterateLastFrame && ( _deltaIterations != 0f || _totalElapsedTime % duration == 0f ); _completedIterations += _deltaIterations; // set the elapsedTime, given what we know. if( _didIterateLastFrame ) { _elapsedTime = isReversed ? duration : 0f; } else if( _didIterateThisFrame ) { // if we iterated this frame, we force the _elapsedTime to the end of the timeline. _elapsedTime = isReversed ? 0f : duration; } else { _elapsedTime = _totalElapsedTime % duration; // if you do a goTo(x) where x is a multiple of duration, we assume that you want // to be at the end of your duration, as this sets you up to have an automatic OnIterationStart fire // the next updated frame. the only caveat is when you do a goTo(0) when playing forwards, // or a goTo(totalDuration) when playing in reverse. we assume that at that point, you want to be // at the start of your tween. if( _elapsedTime == 0f && ( ( isReversed && _totalElapsedTime == totalDuration ) || ( !isReversed && _totalElapsedTime > 0f ) ) ) { _elapsedTime = duration; } } // we can only be looping back on a PingPong if our loopType is PingPong and we are on an odd numbered iteration _isLoopingBackOnPingPong = false; if( loopType == GoLoopType.PingPong ) { // due to the way that we count iterations, and force a tween to remain at the end // of it's timeline for one frame after passing the duration threshold, // we need to make sure that _isLoopingBackOnPingPong references the current // iteration, and not the next one. if( isReversed ) { _isLoopingBackOnPingPong = _completedIterations % 2 == 0; if( _elapsedTime == 0f ) _isLoopingBackOnPingPong = !_isLoopingBackOnPingPong; } else { _isLoopingBackOnPingPong = _completedIterations % 2 != 0; if( _elapsedTime == duration ) _isLoopingBackOnPingPong = !_isLoopingBackOnPingPong; } } // set a flag whether to fire the onIterationEnd event or not. _fireIterationStart = _didIterateThisFrame || ( !isReversed && _elapsedTime == duration ) || ( isReversed && _elapsedTime == 0f ); _fireIterationEnd = _didIterateThisFrame; // check for completion if( ( !isReversed && iterations >= 0 && _completedIterations >= iterations ) || ( isReversed && _totalElapsedTime <= 0 ) ) state = GoTweenState.Complete; if( state == GoTweenState.Complete ) { // these variables need to be reset here. if a tween were to complete, // and then get played again: // * The onIterationStart event would get fired // * tweens would flip their elapsedTime between 0 and totalDuration _fireIterationStart = false; _didIterateThisFrame = false; return true; // true if complete } return false; // false if not complete } /// <summary> /// subclasses should return true if they are a valid and ready to be added to the list of running tweens /// or false if not ready. /// technically, this should be marked as internal /// </summary> public abstract bool isValid(); /// <summary> /// attempts to remove the tween property returning true if successful /// technically, this should be marked as internal /// </summary> public abstract bool removeTweenProperty( AbstractTweenProperty property ); /// <summary> /// returns true if the tween contains the same type (or propertyName) property in its property list /// technically, this should be marked as internal /// </summary> public abstract bool containsTweenProperty( AbstractTweenProperty property ); /// <summary> /// returns a list of all the TweenProperties contained in the tween and all its children (if it is /// a TweenChain or a TweenFlow) /// technically, this should be marked as internal /// </summary> public abstract List<AbstractTweenProperty> allTweenProperties(); /// <summary> /// removes the Tween from action and cleans up its state /// </summary> public virtual void destroy() { state = GoTweenState.Destroyed; } /// <summary> /// pauses playback /// </summary> public virtual void pause() { state = GoTweenState.Paused; } /// <summary> /// resumes playback /// </summary> public virtual void play() { state = GoTweenState.Running; } /// <summary> /// plays the tween forward. if it is already playing forward has no effect /// </summary> public void playForward() { if( isReversed ) reverse(); play(); } /// <summary> /// plays the tween backwards. if it is already playing backwards has no effect /// </summary> public void playBackwards() { if( !isReversed ) reverse(); play(); } /// <summary> /// resets the tween to the beginning, taking isReversed into account. /// </summary> protected virtual void reset( bool skipDelay = true ) { goTo( isReversed ? totalDuration : 0, skipDelay ); _fireIterationStart = true; } /// <summary> /// rewinds the tween to the beginning (or end, depending on isReversed) and pauses playback. /// </summary> public virtual void rewind( bool skipDelay = true ) { reset( skipDelay ); pause(); } /// <summary> /// rewinds the tween to the beginning (or end, depending on isReversed) and starts playback, /// optionally skipping delay (only relevant for Tweens). /// </summary> public void restart( bool skipDelay = true ) { reset( skipDelay ); play(); } /// <summary> /// reverses playback. if going forward it will be going backward after this and vice versa. /// </summary> public virtual void reverse() { isReversed = !isReversed; _completedIterations = isReversed ? Mathf.CeilToInt( _totalElapsedTime / duration ) : Mathf.FloorToInt( _totalElapsedTime / duration ); // if we are at the "start" of the timeline, based on isReversed, // allow the onBegin/onIterationStart callbacks to fire again. if( ( isReversed && _totalElapsedTime == totalDuration ) || ( !isReversed && _totalElapsedTime == 0f ) ) { _didBegin = false; _fireIterationStart = true; } } /// <summary> /// completes the tween. sets the playhead to it's final position as if the tween completed normally. /// takes into account if the tween was playing forward or reversed. /// </summary> public virtual void complete() { if( iterations < 0 ) return; // set full elapsed time and let the next iteration finish it off goTo( isReversed ? 0 : totalDuration, true ); } /// <summary> /// goes to the specified time clamping it from 0 to the total duration of the tween. if the tween is /// not playing it can optionally be force updated to the time specified. delays are not taken into effect. /// </summary> public void goTo( float time ) { goTo( time, true ); } /// <summary> /// goes to the specified time clamping it from 0 to the total duration of the tween. if the tween is /// not playing it can optionally be force updated to the time specified. /// (must be implemented by inherited classes.) /// </summary> public abstract void goTo( float time, bool skipDelay); /// <summary> /// goes to the time and starts playback skipping any delays /// </summary> public void goToAndPlay( float time, bool skipDelay = true ) { goTo( time, skipDelay ); play(); } /// <summary> /// waits for either completion or destruction. call in a Coroutine and yield on the return /// </summary> public IEnumerator waitForCompletion() { while( state != GoTweenState.Complete && state != GoTweenState.Destroyed ) yield return null; yield break; } }
// // 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. // namespace Microsoft.PowerShell.PackageManagement.Cmdlets { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation; using Microsoft.PackageManagement.Internal.Packaging; using Microsoft.PackageManagement.Internal.Utility.Async; using Microsoft.PackageManagement.Internal.Utility.Collections; using Microsoft.PackageManagement.Internal.Utility.Extensions; using Utility; using System.Security; [Cmdlet(VerbsLifecycle.Register, Constants.Nouns.PackageSourceNoun, SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=517139")] public sealed class RegisterPackageSource : CmdletWithProvider { public RegisterPackageSource() : base(new[] {OptionCategory.Provider, OptionCategory.Source}) { } [Parameter] [ValidateNotNull()] public Uri Proxy { get; set; } [Parameter] [ValidateNotNull()] public PSCredential ProxyCredential { get; set; } public override string CredentialUsername { get { return Credential != null ? Credential.UserName : null; } } public override SecureString CredentialPassword { get { return Credential != null ? Credential.Password : null; } } /// <summary> /// Returns web proxy that provider can use /// Construct the webproxy using InternalWebProxy /// </summary> public override System.Net.IWebProxy WebProxy { get { if (Proxy != null) { return new PackageManagement.Utility.InternalWebProxy(Proxy, ProxyCredential == null ? null : ProxyCredential.GetNetworkCredential()); } return null; } } protected override IEnumerable<string> ParameterSets { get { return new[] {""}; } } protected override void GenerateCmdletSpecificParameters(Dictionary<string, object> unboundArguments) { if (!IsInvocation) { var providerNames = PackageManagementService.AllProviderNames; var whatsOnCmdline = GetDynamicParameterValue<string[]>("ProviderName"); if (whatsOnCmdline != null) { providerNames = providerNames.Concat(whatsOnCmdline).Distinct(); } DynamicParameterDictionary.AddOrSet("ProviderName", new RuntimeDefinedParameter("ProviderName", typeof(string), new Collection<Attribute> { new ParameterAttribute { ValueFromPipelineByPropertyName = true, ParameterSetName = Constants.ParameterSets.SourceBySearchSet }, new AliasAttribute("Provider"), new ValidateSetAttribute(providerNames.ToArray()) })); } else { DynamicParameterDictionary.AddOrSet("ProviderName", new RuntimeDefinedParameter("ProviderName", typeof(string), new Collection<Attribute> { new ParameterAttribute { ValueFromPipelineByPropertyName = true, ParameterSetName = Constants.ParameterSets.SourceBySearchSet }, new AliasAttribute("Provider") })); } } [Parameter(Position = 0)] public string Name {get; set;} [Parameter(Position = 1)] public string Location {get; set;} [Parameter] public PSCredential Credential {get; set;} [Parameter] public SwitchParameter Trusted {get; set;} public override bool ProcessRecordAsync() { if (Stopping) { return false; } var packageProvider = SelectProviders(ProviderName).ReEnumerable(); if (ProviderName.IsNullOrEmpty()) { Error(Constants.Errors.ProviderNameNotSpecified, packageProvider.Select(p => p.ProviderName).JoinWithComma()); return false; } switch (packageProvider.Count()) { case 0: Error(Constants.Errors.UnknownProvider, ProviderName); return false; case 1: break; default: Error(Constants.Errors.MatchesMultipleProviders, packageProvider.Select(p => p.ProviderName).JoinWithComma()); return false; } var provider = packageProvider.First(); using (var sources = provider.ResolvePackageSources(this).CancelWhen(CancellationEvent.Token)) { // first, check if there is a source by this name already. var existingSources = sources.Where(each => each.IsRegistered && each.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)).ToArray(); if (existingSources.Any()) { // if there is, and the user has said -Force, then let's remove it. foreach (var existingSource in existingSources) { if (Force) { if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, existingSource.Name, existingSource.Location, existingSource.ProviderName), Constants.Messages.ActionReplacePackageSource).Result) { var removedSources = provider.RemovePackageSource(existingSource.Name, this).CancelWhen(CancellationEvent.Token); foreach (var removedSource in removedSources) { Verbose(Constants.Messages.OverwritingPackageSource, removedSource.Name); } } } else { Error(Constants.Errors.PackageSourceExists, existingSource.Name); return false; } } } } string providerNameForProcessMessage = ProviderName.JoinWithComma(); if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, Name, Location, providerNameForProcessMessage), FormatMessageString(Constants.Messages.ActionRegisterPackageSource)).Result) { //Need to resolve the path created via psdrive. //e.g., New-PSDrive -Name x -PSProvider FileSystem -Root \\foobar\myfolder. Here we are resolving x:\ try { if (FilesystemExtensions.LooksLikeAFilename(Location)) { ProviderInfo providerInfo = null; var resolvedPaths = GetResolvedProviderPathFromPSPath(Location, out providerInfo); // Ensure the path is a single path from the file system provider if ((providerInfo != null) && (resolvedPaths.Count == 1) && String.Equals(providerInfo.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)) { Location = resolvedPaths[0]; } } } catch (Exception) { //allow to continue handling the cases other than file system } using (var added = provider.AddPackageSource(Name, Location, Trusted, this).CancelWhen(CancellationEvent.Token)) { foreach (var addedSource in added) { WriteObject(addedSource); } } return true; } return false; } } }
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; #if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Xml.Serialization; #endif using Telerik.JustMock.Core.Castle.Core.Logging; using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.Core.Internal; #if NETCORE using Debug = Telerik.JustMock.Diagnostics.JMDebug; #else using Debug = System.Diagnostics.Debug; #endif /// <summary> /// Base class that exposes the common functionalities /// to proxy generation. /// </summary> internal abstract class BaseProxyGenerator { protected readonly Type targetType; private readonly ModuleScope scope; private ILogger logger = NullLogger.Instance; private ProxyGenerationOptions proxyGenerationOptions; protected BaseProxyGenerator(ModuleScope scope, Type targetType) { this.scope = scope; this.targetType = targetType; } public ILogger Logger { get { return logger; } set { logger = value; } } protected ProxyGenerationOptions ProxyGenerationOptions { get { if (proxyGenerationOptions == null) { throw new InvalidOperationException("ProxyGenerationOptions must be set before being retrieved."); } return proxyGenerationOptions; } set { if (proxyGenerationOptions != null) { throw new InvalidOperationException("ProxyGenerationOptions can only be set once."); } proxyGenerationOptions = value; } } protected ModuleScope Scope { get { return scope; } } protected void AddMapping(Type @interface, ITypeContributor implementer, IDictionary<Type, ITypeContributor> mapping) { Debug.Assert(implementer != null, "implementer != null"); Debug.Assert(@interface != null, "@interface != null"); Debug.Assert(@interface.GetTypeInfo().IsInterface, "@interface.IsInterface"); if (!mapping.ContainsKey(@interface)) { AddMappingNoCheck(@interface, implementer, mapping); } } #if FEATURE_SERIALIZATION protected void AddMappingForISerializable(IDictionary<Type, ITypeContributor> typeImplementerMapping, ITypeContributor instance) { AddMapping(typeof(ISerializable), instance, typeImplementerMapping); } #endif /// <summary> /// It is safe to add mapping (no mapping for the interface exists) /// </summary> /// <param name = "implementer"></param> /// <param name = "interface"></param> /// <param name = "mapping"></param> protected void AddMappingNoCheck(Type @interface, ITypeContributor implementer, IDictionary<Type, ITypeContributor> mapping) { mapping.Add(@interface, implementer); } protected void AddToCache(CacheKey key, Type type) { scope.RegisterInCache(key, type); } protected virtual ClassEmitter BuildClassEmitter(string typeName, Type parentType, IEnumerable<Type> interfaces) { CheckNotGenericTypeDefinition(parentType, "parentType"); CheckNotGenericTypeDefinitions(interfaces, "interfaces"); return new ClassEmitter(Scope, typeName, parentType, interfaces); } protected void CheckNotGenericTypeDefinition(Type type, string argumentName) { if (type != null && type.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException("Type cannot be a generic type definition. Type: " + type.FullName, argumentName); } } protected void CheckNotGenericTypeDefinitions(IEnumerable<Type> types, string argumentName) { if (types == null) { return; } foreach (var t in types) { CheckNotGenericTypeDefinition(t, argumentName); } } protected void CompleteInitCacheMethod(ConstructorCodeBuilder constCodeBuilder) { constCodeBuilder.AddStatement(new ReturnStatement()); } protected virtual void CreateFields(ClassEmitter emitter) { CreateOptionsField(emitter); CreateSelectorField(emitter); CreateInterceptorsField(emitter); } protected void CreateInterceptorsField(ClassEmitter emitter) { var interceptorsField = emitter.CreateField("__interceptors", typeof(IInterceptor[])); #if FEATURE_SERIALIZATION emitter.DefineCustomAttributeFor<XmlIgnoreAttribute>(interceptorsField); #endif } protected FieldReference CreateOptionsField(ClassEmitter emitter) { return emitter.CreateStaticField("proxyGenerationOptions", typeof(ProxyGenerationOptions)); } protected void CreateSelectorField(ClassEmitter emitter) { if (ProxyGenerationOptions.Selector == null) { return; } emitter.CreateField("__selector", typeof(IInterceptorSelector)); } protected virtual void CreateTypeAttributes(ClassEmitter emitter) { emitter.AddCustomAttributes(ProxyGenerationOptions); #if FEATURE_SERIALIZATION emitter.DefineCustomAttribute<XmlIncludeAttribute>(new object[] { targetType }); #endif } protected void EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions options) { if (Logger.IsWarnEnabled) { // Check the proxy generation hook if (!OverridesEqualsAndGetHashCode(options.Hook.GetType())) { Logger.WarnFormat("The IProxyGenerationHook type {0} does not override both Equals and GetHashCode. " + "If these are not correctly overridden caching will fail to work causing performance problems.", options.Hook.GetType().FullName); } // Interceptor selectors no longer need to override Equals and GetHashCode } } protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseConstructor, params FieldReference[] fields) { GenerateConstructor(emitter, baseConstructor, ProxyConstructorImplementation.CallBase, fields); } protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseConstructor, ProxyConstructorImplementation impl, params FieldReference[] fields) { if (impl == ProxyConstructorImplementation.SkipConstructor) return; ArgumentReference[] args; ParameterInfo[] baseConstructorParams = null; if (baseConstructor != null) { baseConstructorParams = baseConstructor.GetParameters(); } if (baseConstructorParams != null && baseConstructorParams.Length != 0) { args = new ArgumentReference[fields.Length + baseConstructorParams.Length]; var offset = fields.Length; for (var i = offset; i < offset + baseConstructorParams.Length; i++) { var paramInfo = baseConstructorParams[i - offset]; args[i] = new ArgumentReference(paramInfo.ParameterType, paramInfo.DefaultValue); } } else { args = new ArgumentReference[fields.Length]; } for (var i = 0; i < fields.Length; i++) { args[i] = new ArgumentReference(fields[i].Reference.FieldType); } var constructor = emitter.CreateConstructor(args); if (baseConstructorParams != null && baseConstructorParams.Length != 0) { var last = baseConstructorParams.Last(); if (last.ParameterType.IsArray && last.IsDefined(typeof(ParamArrayAttribute))) { var parameter = constructor.ConstructorBuilder.DefineParameter(args.Length, ParameterAttributes.None, last.Name); var builder = AttributeUtil.CreateBuilder<ParamArrayAttribute>(); parameter.SetCustomAttribute(builder); } } for (var i = 0; i < fields.Length; i++) { constructor.CodeBuilder.AddStatement(new AssignStatement(fields[i], args[i].ToExpression())); } // Invoke base constructor if (impl == ProxyConstructorImplementation.CallBase) { if (baseConstructor != null) { Debug.Assert(baseConstructorParams != null); var slice = new ArgumentReference[baseConstructorParams.Length]; Array.Copy(args, fields.Length, slice, 0, baseConstructorParams.Length); constructor.CodeBuilder.InvokeBaseConstructor(baseConstructor, slice); } else { constructor.CodeBuilder.InvokeBaseConstructor(); } } constructor.CodeBuilder.AddStatement(new ReturnStatement()); } protected void GenerateConstructors(ClassEmitter emitter, Type baseType, params FieldReference[] fields) { var constructors = baseType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var ctorGenerationHook = (ProxyGenerationOptions.Hook as IConstructorGenerationHook) ?? AllMethodsHook.Instance; bool defaultCtorConsidered = false; foreach (var constructor in constructors) { if (constructor.GetParameters().Length == 0) defaultCtorConsidered = true; bool ctorVisible = IsConstructorVisible(constructor); var analysis = new ConstructorImplementationAnalysis(ctorVisible); var impl = ctorGenerationHook.GetConstructorImplementation(constructor, analysis); GenerateConstructor(emitter, constructor, impl, fields); } if (!defaultCtorConsidered) { GenerateConstructor(emitter, null, ctorGenerationHook.DefaultConstructorImplementation, fields); } } /// <summary> /// Generates a parameters constructor that initializes the proxy /// state with <see cref = "StandardInterceptor" /> just to make it non-null. /// <para> /// This constructor is important to allow proxies to be XML serializable /// </para> /// </summary> protected void GenerateParameterlessConstructor(ClassEmitter emitter, Type baseClass, FieldReference interceptorField) { // Check if the type actually has a default constructor var defaultConstructor = baseClass.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null); if (defaultConstructor == null) { defaultConstructor = baseClass.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); if (defaultConstructor == null || defaultConstructor.IsPrivate) { return; } } var constructor = emitter.CreateConstructor(); // initialize fields with an empty interceptor constructor.CodeBuilder.AddStatement(new AssignStatement(interceptorField, new NewArrayExpression(1, typeof(IInterceptor)))); constructor.CodeBuilder.AddStatement( new AssignArrayStatement(interceptorField, 0, new NewInstanceExpression(typeof(StandardInterceptor), new Type[0]))); // Invoke base constructor constructor.CodeBuilder.InvokeBaseConstructor(defaultConstructor); constructor.CodeBuilder.AddStatement(new ReturnStatement()); } protected ConstructorEmitter GenerateStaticConstructor(ClassEmitter emitter) { return emitter.CreateTypeConstructor(); } protected Type GetFromCache(CacheKey key) { return scope.GetFromCache(key); } protected void HandleExplicitlyPassedProxyTargetAccessor(ICollection<Type> targetInterfaces, ICollection<Type> additionalInterfaces) { var interfaceName = typeof(IProxyTargetAccessor).ToString(); //ok, let's determine who tried to sneak the IProxyTargetAccessor in... string message; if (targetInterfaces.Contains(typeof(IProxyTargetAccessor))) { message = string.Format( "Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?", interfaceName); } else if (ProxyGenerationOptions.MixinData.ContainsMixin(typeof(IProxyTargetAccessor))) { var mixinType = ProxyGenerationOptions.MixinData.GetMixinInstance(typeof(IProxyTargetAccessor)).GetType(); message = string.Format( "Mixin type {0} implements {1} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to mix in an existing proxy?", mixinType.Name, interfaceName); } else if (additionalInterfaces.Contains(typeof(IProxyTargetAccessor))) { message = string.Format( "You passed {0} as one of additional interfaces to proxy which is a DynamicProxy infrastructure interface and is implemented by every proxy anyway. Please remove it from the list of additional interfaces to proxy.", interfaceName); } else { // this can technically never happen message = string.Format("It looks like we have a bug with regards to how we handle {0}. Please report it.", interfaceName); } throw new ProxyGenerationException("This is a DynamicProxy2 error: " + message); } protected void InitializeStaticFields(Type builtType) { builtType.SetStaticField("proxyGenerationOptions", BindingFlags.NonPublic, ProxyGenerationOptions); } protected Type ObtainProxyType(CacheKey cacheKey, Func<string, INamingScope, Type> factory) { Type cacheType; using (var locker = Scope.Lock.ForReading()) { cacheType = GetFromCache(cacheKey); if (cacheType != null) { Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", cacheType.FullName, targetType.FullName); return cacheType; } } // This is to avoid generating duplicate types under heavy multithreaded load. using (var locker = Scope.Lock.ForWriting()) { // Only one thread at a time may enter a write lock. // See if an earlier lock holder populated the cache. cacheType = GetFromCache(cacheKey); if (cacheType != null) { Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", cacheType.FullName, targetType.FullName); return cacheType; } // Log details about the cache miss Logger.DebugFormat("No cached proxy type was found for target type {0}.", targetType.FullName); EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions); var name = Scope.NamingScope.GetUniqueName("Castle.Proxies." + targetType.Name + "Proxy"); var proxyType = factory.Invoke(name, Scope.NamingScope.SafeSubScope()); AddToCache(cacheKey, proxyType); return proxyType; } } private bool IsConstructorVisible(ConstructorInfo constructor) { return constructor.IsPublic || constructor.IsFamily || constructor.IsFamilyOrAssembly || (constructor.IsAssembly && ProxyUtil.AreInternalsVisibleToDynamicProxy(constructor.DeclaringType.GetTypeInfo().Assembly)); } private bool OverridesEqualsAndGetHashCode(Type type) { var equalsMethod = type.GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance); if (equalsMethod == null || equalsMethod.DeclaringType == typeof(object) || equalsMethod.IsAbstract) { return false; } var getHashCodeMethod = type.GetMethod("GetHashCode", BindingFlags.Public | BindingFlags.Instance); if (getHashCodeMethod == null || getHashCodeMethod.DeclaringType == typeof(object) || getHashCodeMethod.IsAbstract) { return false; } return true; } } }
namespace OpenKh.Tools.OloEditor { partial class TriggerDataControl { /// <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.GBox = new System.Windows.Forms.GroupBox(); this.NumericUnkParam2 = new System.Windows.Forms.NumericUpDown(); this.NumericUnkParam1 = new System.Windows.Forms.NumericUpDown(); this.label9 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.StopCheckbox = new System.Windows.Forms.CheckBox(); this.FireCheckbox = new System.Windows.Forms.CheckBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.TriggerShapeComboBox = new System.Windows.Forms.ComboBox(); this.TriggerTypeComboBox = new System.Windows.Forms.ComboBox(); this.TriggerScaleZ = new System.Windows.Forms.TextBox(); this.TriggerLocZ = new System.Windows.Forms.TextBox(); this.TriggerScaleY = new System.Windows.Forms.TextBox(); this.TriggerLocY = new System.Windows.Forms.TextBox(); this.TriggerYaw = new System.Windows.Forms.TextBox(); this.TriggerScaleX = new System.Windows.Forms.TextBox(); this.TriggerLocX = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.NumericTriggerTID = new System.Windows.Forms.NumericUpDown(); this.NumericCTDID = new System.Windows.Forms.NumericUpDown(); this.NumericTriggerID = new System.Windows.Forms.NumericUpDown(); this.GBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericUnkParam2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericUnkParam1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericTriggerTID)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCTDID)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericTriggerID)).BeginInit(); this.SuspendLayout(); // // GBox // this.GBox.Controls.Add(this.NumericUnkParam2); this.GBox.Controls.Add(this.NumericUnkParam1); this.GBox.Controls.Add(this.label9); this.GBox.Controls.Add(this.label6); this.GBox.Controls.Add(this.StopCheckbox); this.GBox.Controls.Add(this.FireCheckbox); this.GBox.Controls.Add(this.label5); this.GBox.Controls.Add(this.label4); this.GBox.Controls.Add(this.TriggerShapeComboBox); this.GBox.Controls.Add(this.TriggerTypeComboBox); this.GBox.Controls.Add(this.TriggerScaleZ); this.GBox.Controls.Add(this.TriggerLocZ); this.GBox.Controls.Add(this.TriggerScaleY); this.GBox.Controls.Add(this.TriggerLocY); this.GBox.Controls.Add(this.TriggerYaw); this.GBox.Controls.Add(this.TriggerScaleX); this.GBox.Controls.Add(this.TriggerLocX); this.GBox.Controls.Add(this.label10); this.GBox.Controls.Add(this.label3); this.GBox.Controls.Add(this.label2); this.GBox.Controls.Add(this.label8); this.GBox.Controls.Add(this.label7); this.GBox.Controls.Add(this.label1); this.GBox.Controls.Add(this.NumericTriggerTID); this.GBox.Controls.Add(this.NumericCTDID); this.GBox.Controls.Add(this.NumericTriggerID); this.GBox.Location = new System.Drawing.Point(4, 0); this.GBox.Name = "GBox"; this.GBox.Size = new System.Drawing.Size(483, 213); this.GBox.TabIndex = 0; this.GBox.TabStop = false; this.GBox.Text = "Trigger Data 1"; // // NumericUnkParam2 // this.NumericUnkParam2.Location = new System.Drawing.Point(355, 179); this.NumericUnkParam2.Name = "NumericUnkParam2"; this.NumericUnkParam2.Size = new System.Drawing.Size(93, 23); this.NumericUnkParam2.TabIndex = 10; // // NumericUnkParam1 // this.NumericUnkParam1.Location = new System.Drawing.Point(355, 131); this.NumericUnkParam1.Name = "NumericUnkParam1"; this.NumericUnkParam1.Size = new System.Drawing.Size(93, 23); this.NumericUnkParam1.TabIndex = 9; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(355, 161); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(112, 15); this.label9.TabIndex = 8; this.label9.Text = "P2 (Room Entrance)"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(355, 113); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(63, 15); this.label6.TabIndex = 8; this.label6.Text = "P1 (Room)"; // // StopCheckbox // this.StopCheckbox.AutoSize = true; this.StopCheckbox.Location = new System.Drawing.Point(290, 183); this.StopCheckbox.Name = "StopCheckbox"; this.StopCheckbox.Size = new System.Drawing.Size(50, 19); this.StopCheckbox.TabIndex = 7; this.StopCheckbox.Text = "Stop"; this.StopCheckbox.UseVisualStyleBackColor = true; // // FireCheckbox // this.FireCheckbox.AutoSize = true; this.FireCheckbox.Location = new System.Drawing.Point(239, 183); this.FireCheckbox.Name = "FireCheckbox"; this.FireCheckbox.Size = new System.Drawing.Size(45, 19); this.FireCheckbox.TabIndex = 6; this.FireCheckbox.Text = "Fire"; this.FireCheckbox.UseVisualStyleBackColor = true; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(134, 161); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(70, 15); this.label5.TabIndex = 5; this.label5.Text = "Trigger Type"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(7, 161); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(70, 15); this.label4.TabIndex = 5; this.label4.Text = "Trigger Type"; // // TriggerShapeComboBox // this.TriggerShapeComboBox.AutoCompleteCustomSource.AddRange(new string[] { "Box", "Sphere", "Cylinder"}); this.TriggerShapeComboBox.FormattingEnabled = true; this.TriggerShapeComboBox.Items.AddRange(new object[] { "Box", "Sphere", "Cylinder"}); this.TriggerShapeComboBox.Location = new System.Drawing.Point(133, 179); this.TriggerShapeComboBox.Name = "TriggerShapeComboBox"; this.TriggerShapeComboBox.Size = new System.Drawing.Size(100, 23); this.TriggerShapeComboBox.TabIndex = 4; this.TriggerShapeComboBox.Text = "Box"; // // TriggerTypeComboBox // this.TriggerTypeComboBox.FormattingEnabled = true; this.TriggerTypeComboBox.Items.AddRange(new object[] { "Scene Jump", "Appear Enemy", "Begin Gimmick", "Begin Event", "Destination", "Message", "Mission"}); this.TriggerTypeComboBox.Location = new System.Drawing.Point(6, 179); this.TriggerTypeComboBox.Name = "TriggerTypeComboBox"; this.TriggerTypeComboBox.Size = new System.Drawing.Size(121, 23); this.TriggerTypeComboBox.TabIndex = 4; this.TriggerTypeComboBox.Text = "Scene Jump"; // // TriggerScaleZ // this.TriggerScaleZ.Location = new System.Drawing.Point(239, 85); this.TriggerScaleZ.Name = "TriggerScaleZ"; this.TriggerScaleZ.Size = new System.Drawing.Size(110, 23); this.TriggerScaleZ.TabIndex = 3; // // TriggerLocZ // this.TriggerLocZ.Location = new System.Drawing.Point(239, 41); this.TriggerLocZ.Name = "TriggerLocZ"; this.TriggerLocZ.Size = new System.Drawing.Size(110, 23); this.TriggerLocZ.TabIndex = 3; // // TriggerScaleY // this.TriggerScaleY.Location = new System.Drawing.Point(123, 85); this.TriggerScaleY.Name = "TriggerScaleY"; this.TriggerScaleY.Size = new System.Drawing.Size(110, 23); this.TriggerScaleY.TabIndex = 3; // // TriggerLocY // this.TriggerLocY.Location = new System.Drawing.Point(123, 41); this.TriggerLocY.Name = "TriggerLocY"; this.TriggerLocY.Size = new System.Drawing.Size(110, 23); this.TriggerLocY.TabIndex = 3; // // TriggerYaw // this.TriggerYaw.Location = new System.Drawing.Point(239, 131); this.TriggerYaw.Name = "TriggerYaw"; this.TriggerYaw.Size = new System.Drawing.Size(110, 23); this.TriggerYaw.TabIndex = 3; // // TriggerScaleX // this.TriggerScaleX.Location = new System.Drawing.Point(7, 85); this.TriggerScaleX.Name = "TriggerScaleX"; this.TriggerScaleX.Size = new System.Drawing.Size(110, 23); this.TriggerScaleX.TabIndex = 3; // // TriggerLocX // this.TriggerLocX.Location = new System.Drawing.Point(7, 41); this.TriggerLocX.Name = "TriggerLocX"; this.TriggerLocX.Size = new System.Drawing.Size(110, 23); this.TriggerLocX.TabIndex = 3; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(239, 113); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(28, 15); this.label10.TabIndex = 2; this.label10.Text = "Yaw"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(7, 67); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(73, 15); this.label3.TabIndex = 2; this.label3.Text = "Trigger Scale"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(7, 23); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(92, 15); this.label2.TabIndex = 2; this.label2.Text = "Trigger Location"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(355, 68); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(59, 15); this.label8.TabIndex = 1; this.label8.Text = "TriggerTid"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(355, 23); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(43, 15); this.label7.TabIndex = 1; this.label7.Text = "CTD ID"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 113); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(57, 15); this.label1.TabIndex = 1; this.label1.Text = "Trigger ID"; // // NumericTriggerTID // this.NumericTriggerTID.Location = new System.Drawing.Point(355, 86); this.NumericTriggerTID.Maximum = new decimal(new int[] { 0, 1, 0, 0}); this.NumericTriggerTID.Name = "NumericTriggerTID"; this.NumericTriggerTID.Size = new System.Drawing.Size(93, 23); this.NumericTriggerTID.TabIndex = 0; // // NumericCTDID // this.NumericCTDID.Location = new System.Drawing.Point(355, 41); this.NumericCTDID.Maximum = new decimal(new int[] { 0, 1, 0, 0}); this.NumericCTDID.Name = "NumericCTDID"; this.NumericCTDID.Size = new System.Drawing.Size(93, 23); this.NumericCTDID.TabIndex = 0; // // NumericTriggerID // this.NumericTriggerID.Location = new System.Drawing.Point(6, 131); this.NumericTriggerID.Maximum = new decimal(new int[] { 0, 1, 0, 0}); this.NumericTriggerID.Name = "NumericTriggerID"; this.NumericTriggerID.Size = new System.Drawing.Size(101, 23); this.NumericTriggerID.TabIndex = 0; // // TriggerDataControl // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.GBox); this.Name = "TriggerDataControl"; this.Size = new System.Drawing.Size(505, 219); this.GBox.ResumeLayout(false); this.GBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericUnkParam2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericUnkParam1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericTriggerTID)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCTDID)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericTriggerID)).EndInit(); this.ResumeLayout(false); } #endregion public System.Windows.Forms.GroupBox GBox; private System.Windows.Forms.Label label1; public System.Windows.Forms.NumericUpDown NumericTriggerID; private System.Windows.Forms.Label label4; public System.Windows.Forms.ComboBox TriggerTypeComboBox; public System.Windows.Forms.TextBox TriggerScaleZ; public System.Windows.Forms.TextBox TriggerLocZ; public System.Windows.Forms.TextBox TriggerScaleY; public System.Windows.Forms.TextBox TriggerLocY; public System.Windows.Forms.TextBox TriggerScaleX; public System.Windows.Forms.TextBox TriggerLocX; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label5; public System.Windows.Forms.ComboBox TriggerShapeComboBox; public System.Windows.Forms.NumericUpDown NumericUnkParam2; public System.Windows.Forms.NumericUpDown NumericUnkParam1; private System.Windows.Forms.Label label6; public System.Windows.Forms.CheckBox StopCheckbox; public System.Windows.Forms.CheckBox FireCheckbox; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; public System.Windows.Forms.NumericUpDown NumericTriggerTID; public System.Windows.Forms.NumericUpDown NumericCTDID; private System.Windows.Forms.Label label9; public System.Windows.Forms.TextBox TriggerYaw; private System.Windows.Forms.Label label10; } }
/* * Copyright (c) 2006-2014, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org 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.Net; using System.Threading; using OpenMetaverse.StructuredData; namespace OpenMetaverse.Http { public class EventQueueClient { /// <summary>=</summary> public const int REQUEST_TIMEOUT = 1000 * 120; public delegate void ConnectedCallback(); public delegate void EventCallback(string eventName, OSDMap body); public ConnectedCallback OnConnected; public EventCallback OnEvent; public bool Running { get { return _Running; } } protected Uri _Address; protected bool _Dead; protected bool _Running; protected HttpWebRequest _Request; /// <summary>Number of times we've received an unknown CAPS exception in series.</summary> private int _errorCount; /// <summary>For exponential backoff on error.</summary> private static Random _random = new Random(); public EventQueueClient(Uri eventQueueLocation) { _Address = eventQueueLocation; } public void Start() { _Dead = false; // Create an EventQueueGet request OSDMap request = new OSDMap(); request["ack"] = new OSD(); request["done"] = OSD.FromBoolean(false); byte[] postData = OSDParser.SerializeLLSDXmlBytes(request); _Request = CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler); } public void Stop(bool immediate) { _Dead = true; if (immediate) _Running = false; if (_Request != null) _Request.Abort(); } void OpenWriteHandler(HttpWebRequest request) { _Running = true; _Request = request; Logger.DebugLog("Capabilities event queue connected"); // The event queue is starting up for the first time if (OnConnected != null) { try { OnConnected(); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); } } } void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error) { // We don't care about this request now that it has completed _Request = null; OSDArray events = null; int ack = 0; if (responseData != null) { _errorCount = 0; // Got a response OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap; if (result != null) { events = result["events"] as OSDArray; ack = result["id"].AsInteger(); } else { Logger.Log("Got an unparseable response from the event queue: \"" + System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning); } } else if (error != null) { #region Error handling HttpStatusCode code = HttpStatusCode.OK; if (error is WebException) { WebException webException = (WebException)error; if (webException.Response != null) code = ((HttpWebResponse)webException.Response).StatusCode; else if (webException.Status == WebExceptionStatus.RequestCanceled) goto HandlingDone; } if (error is WebException && ((WebException)error).Response != null) code = ((HttpWebResponse)((WebException)error).Response).StatusCode; if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone) { Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info); _Running = false; _Dead = true; } else if (code == HttpStatusCode.BadGateway) { // This is not good (server) protocol design, but it's normal. // The EventQueue server is a proxy that connects to a Squid // cache which will time out periodically. The EventQueue server // interprets this as a generic error and returns a 502 to us // that we ignore } else { ++_errorCount; // Try to log a meaningful error message if (code != HttpStatusCode.OK) { Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}", _Address, code), Helpers.LogLevel.Warning); } else if (error.InnerException != null) { Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}", _Address, error.InnerException.Message), Helpers.LogLevel.Warning); } else { Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}", _Address, error.Message), Helpers.LogLevel.Warning); } } #endregion Error handling } else { ++_errorCount; Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning); } HandlingDone: #region Resume the connection if (_Running) { OSDMap osdRequest = new OSDMap(); if (ack != 0) osdRequest["ack"] = OSD.FromInteger(ack); else osdRequest["ack"] = new OSD(); osdRequest["done"] = OSD.FromBoolean(_Dead); byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest); if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount))); // Resume the connection. The event handler for the connection opening // just sets class _Request variable to the current HttpWebRequest CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler); // If the event queue is dead at this point, turn it off since // that was the last thing we want to do if (_Dead) { _Running = false; Logger.DebugLog("Sent event queue shutdown message"); } } #endregion Resume the connection #region Handle incoming events if (OnEvent != null && events != null && events.Count > 0) { // Fire callbacks for each event received foreach (OSDMap evt in events) { string msg = evt["message"].AsString(); OSDMap body = (OSDMap)evt["body"]; try { OnEvent(msg, body); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); } } } #endregion Handle incoming events } } }
/* <copyright file="WatchedDirectoryTest.cs"> Copyright 2015 MadDonkey Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </copyright> */ using System; using System.Collections.Generic; using System.IO; using DonkeySuite.DesktopMonitor.Domain.Model; using DonkeySuite.DesktopMonitor.Domain.Model.Providers; using DonkeySuite.DesktopMonitor.Domain.Model.Repositories; using DonkeySuite.DesktopMonitor.Domain.Model.Settings; using log4net; using Moq; using NUnit.Framework; namespace DonkeySuite.Tests.DesktopMonitor.Domain.Model { [TestFixture] public class WatchedDirectoryTests { private class WatchedDirectoryTestBundle { private WatchedDirectory _watchedDirectory; public Mock<ILogProvider> MockLogProvider { get; private set; } public Mock<IEntityProvider> MockServiceLocator { get; private set; } public Mock<IDirectoryScanner> MockDirectoryScanner { get; private set; } public WatchedDirectory WatchedDirectory { get { return _watchedDirectory ?? (_watchedDirectory = new WatchedDirectory(MockServiceLocator.Object, MockLogProvider.Object, MockDirectoryScanner.Object)); } } public WatchedDirectoryTestBundle() { MockLogProvider = new Mock<ILogProvider>(); MockServiceLocator = new Mock<IEntityProvider>(); MockDirectoryScanner = new Mock<IDirectoryScanner>(); } } [Test] public void WatchedDirectoryConfigureWhenStrategyNotDefinedPullsValuesFromWatchDirectoryProperly() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var mockWatchDirectory = new Mock<IWatchDirectory>(); mockWatchDirectory.SetupGet(x => x.FileExtensions).Returns("abc"); // Act testBundle.WatchedDirectory.Configure(mockWatchDirectory.Object); // Assert mockWatchDirectory.VerifyGet(x => x.Path, Times.Once()); mockWatchDirectory.VerifyGet(x => x.IncludeSubDirectories, Times.Once()); mockWatchDirectory.VerifyGet(x => x.Mode, Times.Once()); mockWatchDirectory.VerifyGet(x => x.SortStrategy, Times.Once()); mockWatchDirectory.VerifyGet(x => x.FileExtensions, Times.Once()); } [Test] public void WatchedDirectoryConfigureWhenStrategyDefinedPullsValuesFromWatchDirectoryProperly() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var mockWatchDirectory = new Mock<IWatchDirectory>(); mockWatchDirectory.SetupGet(x => x.FileExtensions).Returns("abc"); mockWatchDirectory.SetupGet(x => x.SortStrategy).Returns("simple"); // Act testBundle.WatchedDirectory.Configure(mockWatchDirectory.Object); // Assert mockWatchDirectory.VerifyGet(x => x.Path, Times.Once()); mockWatchDirectory.VerifyGet(x => x.IncludeSubDirectories, Times.Once()); mockWatchDirectory.VerifyGet(x => x.Mode, Times.Once()); mockWatchDirectory.VerifyGet(x => x.SortStrategy, Times.Once()); mockWatchDirectory.VerifyGet(x => x.FileExtensions, Times.Once()); } [Test] public void WatchedDirectoryProcessAvailableImagesWhenNothingToProcess() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var mockWatchFileRepository = new Mock<IWatchedFileRepository>(); var mockServer = new Mock<ImageServer>(); testBundle.MockDirectoryScanner.Setup(x => x.GetAvailableImages(mockWatchFileRepository.Object, null, It.IsAny<IList<string>>(), false, null)) .Returns(new List<IWatchedFile>()); // Act testBundle.WatchedDirectory.ProcessAvailableImages(mockWatchFileRepository.Object, mockServer.Object); // Assert mockWatchFileRepository.Verify(x => x.LoadFileForPath(It.IsAny<string>()), Times.Never); mockWatchFileRepository.Verify(x => x.CreateNew(), Times.Never); mockWatchFileRepository.Verify(x => x.Save(It.IsAny<WatchedFile>()), Times.Never); } [Test] public void WatchedDirectoryProcessAvailableImagesWhenImageHasNotBeenUploadedAndModeIsUploadOnlyShouldUploadFile() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var watchDirectory = new WatchDirectory {FileExtensions = "abc", Mode = OperationMode.UploadOnly}; var mockWatchedFileRepository = new Mock<IWatchedFileRepository>(); var mockWatchedFile = new Mock<IWatchedFile>(); var mockServer = new Mock<ImageServer>(); testBundle.MockDirectoryScanner.Setup(x => x.GetAvailableImages(mockWatchedFileRepository.Object, null, It.IsAny<IList<string>>(), false, null)) .Returns(new List<IWatchedFile> {mockWatchedFile.Object}); testBundle.WatchedDirectory.Configure(watchDirectory); // Act testBundle.WatchedDirectory.ProcessAvailableImages(mockWatchedFileRepository.Object, mockServer.Object); // Assert mockWatchedFileRepository.Verify(x => x.LoadFileForPath(It.IsAny<string>()), Times.Never); mockWatchedFileRepository.Verify(x => x.CreateNew(), Times.Never); mockWatchedFileRepository.Verify(x => x.Save(mockWatchedFile.Object), Times.Once); mockWatchedFile.VerifySet(x => x.UploadSuccessful = false, Times.Never); mockWatchedFile.Verify(x => x.SendToServer(mockServer.Object), Times.Once); mockWatchedFile.Verify(x => x.SortFile(), Times.Never); mockWatchedFile.Verify(x => x.RemoveFromDisk(), Times.Never); } [Test] public void WatchedDirectoryProcessAvailableImagesWhenImageIsInBaseDirectoryAndModeIsSortOnlyShouldSortFile() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var watchDirectory = new WatchDirectory {FileExtensions = "abc", Mode = OperationMode.SortOnly}; var mockWatchedFileRepository = new Mock<IWatchedFileRepository>(); var mockWatchedFile = new Mock<IWatchedFile>(); var mockLog = new Mock<ILog>(); var mockServer = new Mock<ImageServer>(); testBundle.MockDirectoryScanner.Setup(x => x.GetAvailableImages(mockWatchedFileRepository.Object, null, It.IsAny<IList<string>>(), false, null)) .Returns(new List<IWatchedFile> {mockWatchedFile.Object}); testBundle.MockLogProvider.Setup(x => x.GetLogger(It.IsAny<Type>())).Returns(mockLog.Object); mockWatchedFile.Setup(x => x.IsInBaseDirectory(null)).Returns(true); // Act testBundle.WatchedDirectory.Configure(watchDirectory); testBundle.WatchedDirectory.ProcessAvailableImages(mockWatchedFileRepository.Object, mockServer.Object); // Assert mockWatchedFileRepository.Verify(x => x.LoadFileForPath(It.IsAny<string>()), Times.Never); mockWatchedFileRepository.Verify(x => x.CreateNew(), Times.Never); mockWatchedFileRepository.Verify(x => x.Save(mockWatchedFile.Object), Times.Never); mockWatchedFile.VerifySet(x => x.UploadSuccessful = false, Times.Never); mockWatchedFile.Verify(x => x.SendToServer(mockServer.Object), Times.Never); mockWatchedFile.Verify(x => x.SortFile(), Times.Once); mockWatchedFile.Verify(x => x.RemoveFromDisk(), Times.Never); } [Test] public void WatchedDirectoryProcessAvailableImagesWhenImageIsInBaseDirectoryAndModeIsUploadAndClearShouldThrowNotImplementedException() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var watchDirectory = new WatchDirectory {FileExtensions = "abc", Mode = OperationMode.UploadAndClear}; var mockWatchedFileRepository = new Mock<IWatchedFileRepository>(); var mockWatchedFile = new Mock<IWatchedFile>(); var mockLog = new Mock<ILog>(); NotImplementedException thrownException = null; var mockServer = new Mock<ImageServer>(); testBundle.MockDirectoryScanner.Setup(x => x.GetAvailableImages(mockWatchedFileRepository.Object, null, It.IsAny<IList<string>>(), false, null)) .Returns(new List<IWatchedFile> {mockWatchedFile.Object}); testBundle.MockLogProvider.Setup(x => x.GetLogger(It.IsAny<Type>())).Returns(mockLog.Object); mockWatchedFile.Setup(x => x.IsInBaseDirectory(null)).Returns(true); testBundle.WatchedDirectory.Configure(watchDirectory); // Act try { testBundle.WatchedDirectory.ProcessAvailableImages(mockWatchedFileRepository.Object, mockServer.Object); } catch (NotImplementedException ex) { thrownException = ex; } // Assert mockWatchedFileRepository.Verify(x => x.LoadFileForPath(It.IsAny<string>()), Times.Never); mockWatchedFileRepository.Verify(x => x.CreateNew(), Times.Never); mockWatchedFileRepository.Verify(x => x.Save(mockWatchedFile.Object), Times.Never); mockWatchedFile.VerifySet(x => x.UploadSuccessful = false, Times.Never); mockWatchedFile.Verify(x => x.SendToServer(mockServer.Object), Times.Never); mockWatchedFile.Verify(x => x.SortFile(), Times.Never); mockWatchedFile.Verify(x => x.RemoveFromDisk(), Times.Never); Assert.IsNotNull(thrownException); } [Test] public void WatchedDirectoryProcessAvailableImagesWhenIOExceptionThrownShouldSortFile() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var watchDirectory = new WatchDirectory {FileExtensions = "abc", Mode = OperationMode.UploadOnly}; var mockWatchedFileRepository = new Mock<IWatchedFileRepository>(); var mockWatchedFile = new Mock<IWatchedFile>(); var mockLog = new Mock<ILog>(); var mockServer = new Mock<ImageServer>(); testBundle.MockDirectoryScanner.Setup(x => x.GetAvailableImages(mockWatchedFileRepository.Object, null, It.IsAny<IList<string>>(), false, null)) .Returns(new List<IWatchedFile> {mockWatchedFile.Object}); testBundle.MockLogProvider.Setup(x => x.GetLogger(It.IsAny<Type>())).Returns(mockLog.Object); mockWatchedFile.SetupGet(x => x.UploadSuccessful).Returns(false); mockWatchedFile.Setup(x => x.SendToServer(mockServer.Object)).Throws(new IOException()); // Act testBundle.WatchedDirectory.Configure(watchDirectory); testBundle.WatchedDirectory.ProcessAvailableImages(mockWatchedFileRepository.Object, mockServer.Object); // Assert mockWatchedFileRepository.Verify(x => x.LoadFileForPath(It.IsAny<string>()), Times.Never); mockWatchedFileRepository.Verify(x => x.CreateNew(), Times.Never); mockWatchedFileRepository.Verify(x => x.Save(mockWatchedFile.Object), Times.Once); mockWatchedFile.VerifySet(x => x.UploadSuccessful = false, Times.Once); mockWatchedFile.Verify(x => x.SendToServer(mockServer.Object), Times.Once); mockWatchedFile.Verify(x => x.SortFile(), Times.Never); mockWatchedFile.Verify(x => x.RemoveFromDisk(), Times.Never); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Scriban.Helpers; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Parsing { /// <summary> /// The parser. /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif partial class Parser { private readonly Lexer _lexer; private readonly bool _isLiquid; private Lexer.Enumerator _tokenIt; private readonly List<Token> _tokensPreview; private int _tokensPreviewStart; private Token _previousToken; private Token _token; private bool _inCodeSection; private bool _isLiquidTagSection; private int _blockLevel; private bool _inFrontMatter; private bool _isExpressionDepthLimitReached; private int _expressionDepth; private bool _hasFatalError; private readonly bool _isScientific; private readonly bool _isKeepTrivia; private readonly List<ScriptTrivia> _trivias; private readonly Queue<ScriptStatement> _pendingStatements; private IScriptTerminal _lastTerminalWithTrivias; /// <summary> /// Initializes a new instance of the <see cref="Parser"/> class. /// </summary> /// <param name="lexer">The lexer.</param> /// <param name="options">The options.</param> /// <exception cref="System.ArgumentNullException"></exception> public Parser(Lexer lexer, ParserOptions? options = null) { _lexer = lexer ?? throw new ArgumentNullException(nameof(lexer)); _isLiquid = _lexer.Options.Lang == ScriptLang.Liquid; _isScientific = _lexer.Options.Lang == ScriptLang.Scientific; _tokensPreview = new List<Token>(4); Messages = new LogMessageBag(); _trivias = new List<ScriptTrivia>(); Options = options ?? new ParserOptions(); CurrentParsingMode = lexer.Options.Mode; _isKeepTrivia = lexer.Options.KeepTrivia; _pendingStatements = new Queue<ScriptStatement>(2); Blocks = new Stack<ScriptNode>(); // Initialize the iterator _tokenIt = lexer.GetEnumerator(); NextToken(); } public readonly ParserOptions Options; private ScriptFrontMatter _frontmatter; public LogMessageBag Messages { get; private set; } public bool HasErrors { get; private set; } private Stack<ScriptNode> Blocks { get; } private Token Current => _token; private Token Previous => _previousToken; public SourceSpan CurrentSpan => GetSpanForToken(Current); private ScriptMode CurrentParsingMode { get; set; } public ScriptPage Run() { Messages = new LogMessageBag(); HasErrors = false; _blockLevel = 0; _isExpressionDepthLimitReached = false; Blocks.Clear(); var page = Open<ScriptPage>(); var parsingMode = CurrentParsingMode; switch (parsingMode) { case ScriptMode.FrontMatterAndContent: case ScriptMode.FrontMatterOnly: if (Current.Type != TokenType.FrontMatterMarker) { LogError($"When `{CurrentParsingMode}` is enabled, expecting a `{_lexer.Options.FrontMatterMarker}` at the beginning of the text instead of `{Current.GetText(_lexer.Text)}`"); return null; } _inFrontMatter = true; _inCodeSection = true; _frontmatter = Open<ScriptFrontMatter>(); // Parse the frontmatter start=-marker ExpectAndParseTokenTo(_frontmatter.StartMarker, TokenType.FrontMatterMarker); // Parse front-marker statements _frontmatter.Statements = ParseBlockStatement(_frontmatter); // We should not be in a frontmatter after parsing the statements if (_inFrontMatter) { LogError($"End of frontmatter `{_lexer.Options.FrontMatterMarker}` not found"); } page.FrontMatter = _frontmatter; page.Span = _frontmatter.Span; if (parsingMode == ScriptMode.FrontMatterOnly) { return page; } break; case ScriptMode.ScriptOnly: _inCodeSection = true; break; } page.Body = ParseBlockStatement(null); if (page.Body != null) { page.Span = page.Body.Span; } // Flush any pending trivias if (_isKeepTrivia && _lastTerminalWithTrivias != null) { FlushTriviasToLastTerminal(); } if (page.FrontMatter != null) { FixRawStatementAfterFrontMatter(page); } if (_lexer.HasErrors) { foreach (var lexerError in _lexer.Errors) { Log(lexerError); } } return page; } private void PushTokenToTrivia() { if (_isKeepTrivia) { if (Current.Type == TokenType.NewLine) { _trivias.Add(new ScriptTrivia(CurrentSpan, ScriptTriviaType.NewLine, CurrentStringSlice)); } else if (Current.Type == TokenType.SemiColon) { _trivias.Add(new ScriptTrivia(CurrentSpan, ScriptTriviaType.SemiColon, CurrentStringSlice)); } else if (Current.Type == TokenType.Comma) { _trivias.Add(new ScriptTrivia(CurrentSpan, ScriptTriviaType.Comma, CurrentStringSlice)); } } } private ScriptStringSlice CurrentStringSlice => GetAsStringSlice(Current); private ScriptStringSlice GetAsStringSlice(Token token) { return new ScriptStringSlice(_lexer.Text, token.Start.Offset, token.End.Offset - token.Start.Offset + 1); } private T Open<T>(T element) where T : ScriptNode { element.Span = new SourceSpan() { FileName = _lexer.SourcePath, Start = Current.Start }; if (_isKeepTrivia && element is IScriptTerminal terminal) { FlushTrivias(terminal, true); } return element; } private T Open<T>() where T : ScriptNode, new() { var element = new T() { Span = {FileName = _lexer.SourcePath, Start = Current.Start}}; if (_isKeepTrivia && element is IScriptTerminal terminal) { FlushTrivias(terminal, true); } return element; } private void FlushTrivias(IScriptTerminal element, bool isBefore) { if (_isKeepTrivia && _trivias.Count > 0) { element.AddTrivias(_trivias, isBefore); _trivias.Clear(); } } private T Close<T>(T node) where T : ScriptNode { node.Span.End = Previous.End; if (_isKeepTrivia && node is IScriptTerminal terminal) { _lastTerminalWithTrivias = terminal; FlushTrivias(terminal, false); } return node; } private void FlushTriviasToLastTerminal() { if (_isKeepTrivia && _lastTerminalWithTrivias != null) { FlushTrivias(_lastTerminalWithTrivias, false); } } private string GetAsText(Token localToken) { return localToken.GetText(_lexer.Text); } private bool MatchText(Token localToken, string text) { return localToken.Match(text, _lexer.Text); } private void NextToken() { _previousToken = _token; bool result; while (_tokensPreviewStart < _tokensPreview.Count) { _token = _tokensPreview[_tokensPreviewStart]; _tokensPreviewStart++; // We can reset the tokens if we hit the upper limit of the preview if (_tokensPreviewStart == _tokensPreview.Count) { _tokensPreviewStart = 0; _tokensPreview.Clear(); } if (IsHidden(_token.Type)) { if (_isKeepTrivia) { PushTrivia(_token); } } else { return; } } // Skip Comments while ((result = _tokenIt.MoveNext())) { if (IsHidden(_tokenIt.Current.Type)) { if (_isKeepTrivia) { PushTrivia(_tokenIt.Current); } } else { break; } } _token = result ? _tokenIt.Current : Token.Eof; } private void PushTrivia(Token token) { ScriptTriviaType type; switch (token.Type) { case TokenType.Comment: type = ScriptTriviaType.Comment; break; case TokenType.CommentMulti: type = ScriptTriviaType.CommentMulti; break; case TokenType.Whitespace: type = ScriptTriviaType.Whitespace; break; case TokenType.WhitespaceFull: type = ScriptTriviaType.WhitespaceFull; break; case TokenType.NewLine: type = ScriptTriviaType.NewLine; break; default: throw new InvalidOperationException($"Token type `{token.Type}` not supported by trivia"); } var trivia = new ScriptTrivia(GetSpanForToken(token), type, GetAsStringSlice(token)); _trivias.Add(trivia); } private Token PeekToken() { // Do we have preview token available? for (int i = _tokensPreviewStart; i < _tokensPreview.Count; i++) { var nextToken = _tokensPreview[i]; if (!IsHidden(nextToken.Type)) { return nextToken; } } // Else try to find the first token not hidden while (_tokenIt.MoveNext()) { var nextToken = _tokenIt.Current; _tokensPreview.Add(nextToken); if (!IsHidden(nextToken.Type)) { return nextToken; } } return Token.Eof; } private ScriptIdentifier ParseIdentifier() { var identifier = Open<ScriptIdentifier>(); identifier.Value = GetAsText(Current); NextToken(); return Close(identifier); } private bool IsHidden(TokenType tokenType) { return tokenType == TokenType.Comment || tokenType == TokenType.CommentMulti || tokenType == TokenType.Whitespace || tokenType == TokenType.WhitespaceFull || (tokenType == TokenType.NewLine && _allowNewLineLevel > 0); } private void LogError(string text, bool isFatal = false) { LogError(Current, text, isFatal); } private void LogError(Token tokenArg, string text, bool isFatal = false) { LogError(GetSpanForToken(tokenArg), text, isFatal); } private SourceSpan GetSpanForToken(Token tokenArg) { return new SourceSpan(_lexer.SourcePath, tokenArg.Start, tokenArg.End); } private void LogError(SourceSpan span, string text, bool isFatal = false) { Log(new LogMessage(ParserMessageType.Error, span, text), isFatal); } private void LogError(ScriptNode node, string message, bool isFatal = false) { LogError(node, node.Span, message, isFatal); } private void LogError(ScriptNode node, SourceSpan span, string message, bool isFatal = false) { var syntax = ScriptSyntaxAttribute.Get(node); string inMessage = " in"; if (message.EndsWith("after")) { inMessage = string.Empty; } LogError(span, $"Error while parsing {syntax.TypeName}: {message}{inMessage}: {syntax.Example}", isFatal); } private void Log(LogMessage logMessage, bool isFatal = false) { if (logMessage == null) throw new ArgumentNullException(nameof(logMessage)); Messages.Add(logMessage); if (logMessage.Type == ParserMessageType.Error) { HasErrors = true; if (isFatal) { _hasFatalError = true; } } } } }
// Copyright (c) Jon Thysell <http://jonthysell.com> // Licensed under the MIT License. using System; using System.ComponentModel; namespace Mzinga.Core { public enum PlayerColor { White = 0, Black, NumPlayerColors, }; public enum BoardState { NotStarted = 0, InProgress, Draw, WhiteWins, BlackWins, }; [DefaultValue(INVALID)] public enum PieceName { INVALID = -1, wQ = 0, wS1, wS2, wB1, wB2, wG1, wG2, wG3, wA1, wA2, wA3, wM, wL, wP, bQ, bS1, bS2, bB1, bB2, bG1, bG2, bG3, bA1, bA2, bA3, bM, bL, bP, NumPieceNames }; public enum Direction { Up = 0, UpRight = 1, DownRight = 2, Down = 3, DownLeft = 4, UpLeft = 5, NumDirections = 6, #pragma warning disable CA1069 // Enums values should not be duplicated Above = 6, #pragma warning restore CA1069 // Enums values should not be duplicated }; [DefaultValue(INVALID)] public enum BugType { INVALID = -1, QueenBee = 0, Spider, Beetle, Grasshopper, SoldierAnt, Mosquito, Ladybug, Pillbug, NumBugTypes, }; [DefaultValue(INVALID)] public enum GameType { INVALID = -1, Base = 0, BaseM, BaseL, BaseP, BaseML, BaseMP, BaseLP, BaseMLP, NumGameTypes, }; public static class Enums { public static bool GameInProgress(BoardState boardState) { return boardState == BoardState.NotStarted || boardState == BoardState.InProgress; } public static bool GameIsOver(BoardState boardState) { return boardState == BoardState.WhiteWins || boardState == BoardState.BlackWins || boardState == BoardState.Draw; } public static PlayerColor GetColor(PieceName value) { switch (value) { case PieceName.wQ: case PieceName.wS1: case PieceName.wS2: case PieceName.wB1: case PieceName.wB2: case PieceName.wG1: case PieceName.wG2: case PieceName.wG3: case PieceName.wA1: case PieceName.wA2: case PieceName.wA3: case PieceName.wM: case PieceName.wL: case PieceName.wP: return PlayerColor.White; case PieceName.bQ: case PieceName.bS1: case PieceName.bS2: case PieceName.bB1: case PieceName.bB2: case PieceName.bG1: case PieceName.bG2: case PieceName.bG3: case PieceName.bA1: case PieceName.bA2: case PieceName.bA3: case PieceName.bM: case PieceName.bL: case PieceName.bP: return PlayerColor.Black; } return PlayerColor.NumPlayerColors; } public static Direction LeftOf(Direction value) { return (Direction)(((int)value + (int)Direction.NumDirections - 1) % (int)Direction.NumDirections); } public static Direction RightOf(Direction value) { return (Direction)(((int)value + 1) % (int)Direction.NumDirections); } public static BugType GetBugType(PieceName value) { switch (value) { case PieceName.wQ: case PieceName.bQ: return BugType.QueenBee; case PieceName.wS1: case PieceName.wS2: case PieceName.bS1: case PieceName.bS2: return BugType.Spider; case PieceName.wB1: case PieceName.wB2: case PieceName.bB1: case PieceName.bB2: return BugType.Beetle; case PieceName.wG1: case PieceName.wG2: case PieceName.wG3: case PieceName.bG1: case PieceName.bG2: case PieceName.bG3: return BugType.Grasshopper; case PieceName.wA1: case PieceName.wA2: case PieceName.wA3: case PieceName.bA1: case PieceName.bA2: case PieceName.bA3: return BugType.SoldierAnt; case PieceName.wM: case PieceName.bM: return BugType.Mosquito; case PieceName.wL: case PieceName.bL: return BugType.Ladybug; case PieceName.wP: case PieceName.bP: return BugType.Pillbug; default: return BugType.INVALID; } } public static bool TryParse(string str, out GameType result) { if (Enum.TryParse(str.Replace("+",""), out result)) { return true; } result = GameType.INVALID; return false; } public static string GetGameTypeString(GameType value) { switch (value) { case GameType.Base: return "Base"; case GameType.BaseM: return "Base+M"; case GameType.BaseL: return "Base+L"; case GameType.BaseP: return "Base+P"; case GameType.BaseML: return "Base+ML"; case GameType.BaseMP: return "Base+MP"; case GameType.BaseLP: return "Base+LP"; case GameType.BaseMLP: return "Base+MLP"; default: return ""; } } public static bool PieceNameIsEnabledForGameType(PieceName pieceName, GameType gameType) { switch (pieceName) { case PieceName.INVALID: return false; case PieceName.wM: case PieceName.bM: return gameType == GameType.BaseM || gameType == GameType.BaseML || gameType == GameType.BaseMP || gameType == GameType.BaseMLP; case PieceName.wL: case PieceName.bL: return gameType == GameType.BaseL || gameType == GameType.BaseML || gameType == GameType.BaseLP || gameType == GameType.BaseMLP; case PieceName.wP: case PieceName.bP: return gameType == GameType.BaseP || gameType == GameType.BaseMP || gameType == GameType.BaseLP || gameType == GameType.BaseMLP; default: return true; } } public static bool BugTypeIsEnabledForGameType(BugType bugType, GameType gameType) { switch (bugType) { case BugType.INVALID: return false; case BugType.Mosquito: return gameType == GameType.BaseM || gameType == GameType.BaseML || gameType == GameType.BaseMP || gameType == GameType.BaseMLP; case BugType.Ladybug: return gameType == GameType.BaseL || gameType == GameType.BaseML || gameType == GameType.BaseLP || gameType == GameType.BaseMLP; case BugType.Pillbug: return gameType == GameType.BaseP || gameType == GameType.BaseMP || gameType == GameType.BaseLP || gameType == GameType.BaseMLP; default: return true; } } public static GameType EnableBugType(BugType bugType, GameType gameType, bool enabled) { bool includeM = bugType == BugType.Mosquito ? enabled : BugTypeIsEnabledForGameType(BugType.Mosquito, gameType); bool includeL = bugType == BugType.Ladybug ? enabled : BugTypeIsEnabledForGameType(BugType.Ladybug, gameType); bool includeP = bugType == BugType.Pillbug ? enabled : BugTypeIsEnabledForGameType(BugType.Pillbug, gameType); if (includeM && includeL && includeP) { return GameType.BaseMLP; } else if (includeL && includeP) { return GameType.BaseLP; } else if (includeM && includeP) { return GameType.BaseMP; } else if (includeM && includeL) { return GameType.BaseML; } else if (includeP) { return GameType.BaseP; } else if (includeL) { return GameType.BaseL; } else if (includeM) { return GameType.BaseM; } return GameType.Base; } public static int NumPieceNames(GameType gameType) { switch (gameType) { case GameType.Base: return (int)PieceName.NumPieceNames - 6; case GameType.BaseM: case GameType.BaseL: case GameType.BaseP: return (int)PieceName.NumPieceNames - 4; case GameType.BaseML: case GameType.BaseMP: case GameType.BaseLP: return (int)PieceName.NumPieceNames - 2; case GameType.BaseMLP: default: return (int)PieceName.NumPieceNames; } } public static int NumBugTypes(GameType gameType) { switch (gameType) { case GameType.Base: return (int)BugType.NumBugTypes - 3; case GameType.BaseM: case GameType.BaseL: case GameType.BaseP: return (int)BugType.NumBugTypes - 2; case GameType.BaseML: case GameType.BaseMP: case GameType.BaseLP: return (int)BugType.NumBugTypes - 1; case GameType.BaseMLP: default: return (int)BugType.NumBugTypes; } } } }
// 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; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Framework.Input.StateChanges; using osu.Framework.Input.States; using osu.Framework.Testing; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Framework.Tests.Visual.Input { public class TestSceneTouchInput : ManualInputManagerTestScene { private static readonly TouchSource[] touch_sources = (TouchSource[])Enum.GetValues(typeof(TouchSource)); private Container<InputReceptor> receptors; [SetUp] public new void SetUp() => Schedule(() => { Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Gray.Darken(2f), }, new SpriteText { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Text = "Parent" }, } }, receptors = new Container<InputReceptor> { Padding = new MarginPadding { Bottom = 20f }, RelativeSizeAxes = Axes.Both, ChildrenEnumerable = touch_sources.Select(s => new InputReceptor(s) { RelativePositionAxes = Axes.Both, RelativeSizeAxes = Axes.Both, Colour = Color4.Gray.Lighten((float)s / TouchState.MAX_TOUCH_COUNT), X = (float)s / TouchState.MAX_TOUCH_COUNT, }) }, new TestSceneTouchVisualiser.TouchVisualiser(), }; }); private float getTouchXPos(TouchSource source) => receptors[(int)source].DrawPosition.X + 10f; private Vector2 getTouchDownPos(TouchSource source) => receptors.ToScreenSpace(new Vector2(getTouchXPos(source), 1f)); private Vector2 getTouchMovePos(TouchSource source) => receptors.ToScreenSpace(new Vector2(getTouchXPos(source), receptors.DrawHeight / 2f)); private Vector2 getTouchUpPos(TouchSource source) => receptors.ToScreenSpace(new Vector2(getTouchXPos(source), receptors.DrawHeight - 1f)); [Test] public void TestTouchInputHandling() { AddStep("activate touches", () => { foreach (var s in touch_sources) InputManager.BeginTouch(new Touch(s, getTouchDownPos(s))); }); AddAssert("received correct event for each receptor", () => { foreach (var r in receptors) { // attempt dequeuing from touch events queue. if (!(r.TouchEvents.TryDequeue(out TouchEvent te) && te is TouchDownEvent touchDown)) return false; // check correct provided information. if (touchDown.ScreenSpaceTouch.Source != r.AssociatedSource || touchDown.ScreenSpaceTouch.Position != getTouchDownPos(r.AssociatedSource) || touchDown.ScreenSpaceTouchDownPosition != getTouchDownPos(r.AssociatedSource)) return false; // check no other events popped up. if (r.TouchEvents.Count > 0) return false; } return true; }); AddStep("move touches", () => { foreach (var s in touch_sources) InputManager.MoveTouchTo(new Touch(s, getTouchMovePos(s))); }); AddAssert("received correct event for each receptor", () => { foreach (var r in receptors) { if (!(r.TouchEvents.TryDequeue(out TouchEvent te) && te is TouchMoveEvent touchMove)) return false; if (touchMove.ScreenSpaceTouch.Source != r.AssociatedSource || touchMove.ScreenSpaceTouch.Position != getTouchMovePos(r.AssociatedSource) || touchMove.ScreenSpaceLastTouchPosition != getTouchDownPos(r.AssociatedSource) || touchMove.ScreenSpaceTouchDownPosition != getTouchDownPos(r.AssociatedSource)) return false; if (r.TouchEvents.Count > 0) return false; } return true; }); AddStep("move touches outside of area", () => { foreach (var s in touch_sources) InputManager.MoveTouchTo(new Touch(s, getTouchUpPos(s))); }); AddAssert("received correct event for each receptor", () => { foreach (var r in receptors) { if (!(r.TouchEvents.TryDequeue(out TouchEvent te) && te is TouchMoveEvent touchMove)) return false; if (touchMove.ScreenSpaceTouch.Source != r.AssociatedSource || touchMove.ScreenSpaceTouch.Position != getTouchUpPos(r.AssociatedSource) || touchMove.ScreenSpaceLastTouchPosition != getTouchMovePos(r.AssociatedSource) || touchMove.ScreenSpaceTouchDownPosition != getTouchDownPos(r.AssociatedSource)) return false; if (r.TouchEvents.Count > 0) return false; } return true; }); AddStep("deactivate touches out of receptors", () => { foreach (var s in touch_sources) InputManager.EndTouch(new Touch(s, getTouchUpPos(s))); }); AddAssert("received correct event for each receptor", () => { foreach (var r in receptors) { if (!(r.TouchEvents.TryDequeue(out TouchEvent te) && te is TouchUpEvent touchUp)) return false; if (touchUp.ScreenSpaceTouch.Source != r.AssociatedSource || touchUp.ScreenSpaceTouch.Position != getTouchUpPos(r.AssociatedSource) || touchUp.ScreenSpaceTouchDownPosition != getTouchDownPos(r.AssociatedSource)) return false; if (r.TouchEvents.Count > 0) return false; } return true; }); // All touch events have been handled, mouse input should not be performed. // For simplicity, let's check whether we received mouse events or not. AddAssert("no mouse input performed", () => receptors.All(r => r.MouseEvents.Count == 0)); } [Test] public void TestMouseInputAppliedFromLatestTouch() { InputReceptor firstReceptor = null, lastReceptor = null; AddStep("setup receptors to receive mouse-from-touch", () => { foreach (var r in receptors) r.HandleTouch = _ => false; }); AddStep("retrieve receptors", () => { firstReceptor = receptors[(int)TouchSource.Touch1]; lastReceptor = receptors[(int)TouchSource.Touch10]; }); AddStep("activate first", () => { InputManager.BeginTouch(new Touch(firstReceptor.AssociatedSource, getTouchDownPos(firstReceptor.AssociatedSource))); }); AddAssert("received mouse-down event on first", () => { // event #1: move mouse to first touch position. if (!(firstReceptor.MouseEvents.TryDequeue(out MouseEvent me1) && me1 is MouseMoveEvent mouseMove)) return false; if (mouseMove.ScreenSpaceMousePosition != getTouchDownPos(firstReceptor.AssociatedSource)) return false; // event #2: press mouse left-button (from first touch activation). if (!(firstReceptor.MouseEvents.TryDequeue(out MouseEvent me2) && me2 is MouseDownEvent mouseDown)) return false; if (mouseDown.Button != MouseButton.Left || mouseDown.ScreenSpaceMousePosition != getTouchDownPos(firstReceptor.AssociatedSource) || mouseDown.ScreenSpaceMouseDownPosition != getTouchDownPos(firstReceptor.AssociatedSource)) return false; return firstReceptor.MouseEvents.Count == 0; }); // Activate each touch after first source and assert mouse has jumped to it. foreach (var s in touch_sources.Skip(1)) { Touch touch = default; AddStep($"activate {s}", () => InputManager.BeginTouch(touch = new Touch(s, getTouchDownPos(s)))); AddAssert("mouse jumped to new touch", () => assertMouseOnTouchChange(touch, null, true)); } Vector2? lastMovePosition = null; // Move each touch inside area and assert regular mouse-move events received. foreach (var s in touch_sources) { Touch touch = default; AddStep($"move {s} inside area", () => InputManager.MoveTouchTo(touch = new Touch(s, getTouchMovePos(s)))); AddAssert("received regular mouse-move event", () => { // ReSharper disable once AccessToModifiedClosure var result = assertMouseOnTouchChange(touch, lastMovePosition, true); lastMovePosition = touch.Position; return result; }); } // Move each touch outside of area and assert no MouseMoveEvent expected to be received. foreach (var s in touch_sources) { Touch touch = default; AddStep($"move {s} outside of area", () => InputManager.MoveTouchTo(touch = new Touch(s, getTouchUpPos(s)))); AddAssert("no mouse-move event received", () => { // ReSharper disable once AccessToModifiedClosure var result = assertMouseOnTouchChange(touch, lastMovePosition, false); lastMovePosition = touch.Position; return result; }); } // Deactivate each touch but last touch and assert mouse did not jump to it. foreach (var s in touch_sources.SkipLast(1)) { AddStep($"deactivate {s}", () => InputManager.EndTouch(new Touch(s, getTouchUpPos(s)))); AddAssert("no mouse event received", () => receptors[(int)s].MouseEvents.Count == 0); } AddStep("deactivate last", () => { InputManager.EndTouch(new Touch(lastReceptor.AssociatedSource, getTouchUpPos(lastReceptor.AssociatedSource))); }); AddAssert("received mouse-up event", () => { // First receptor is the one handling the mouse down event, mouse up would be raised to it. if (!(firstReceptor.MouseEvents.TryDequeue(out MouseEvent me) && me is MouseUpEvent mouseUp)) return false; if (mouseUp.Button != MouseButton.Left || mouseUp.ScreenSpaceMousePosition != getTouchUpPos(lastReceptor.AssociatedSource) || mouseUp.ScreenSpaceMouseDownPosition != getTouchDownPos(firstReceptor.AssociatedSource)) return false; return firstReceptor.MouseEvents.Count == 0; }); AddAssert("all events dequeued", () => receptors.All(r => r.MouseEvents.Count == 0)); bool assertMouseOnTouchChange(Touch touch, Vector2? lastPosition, bool expectsMouseMove) { var receptor = receptors[(int)touch.Source]; if (expectsMouseMove) { if (!(receptor.MouseEvents.TryDequeue(out MouseEvent me1) && me1 is MouseMoveEvent mouseMove)) return false; if (mouseMove.ScreenSpaceMousePosition != touch.Position || (lastPosition != null && mouseMove.ScreenSpaceLastMousePosition != lastPosition.Value)) return false; } // Dequeue the "false drag" from first receptor to ensure there isn't any unexpected hidden event in this receptor. if (!(firstReceptor.MouseEvents.TryDequeue(out MouseEvent me2) && me2 is DragEvent mouseDrag)) return false; if (mouseDrag.Button != MouseButton.Left || mouseDrag.ScreenSpaceMousePosition != touch.Position || (lastPosition != null && mouseDrag.ScreenSpaceLastMousePosition != lastPosition.Value) || mouseDrag.ScreenSpaceMouseDownPosition != getTouchDownPos(firstReceptor.AssociatedSource)) return false; return receptor.MouseEvents.Count == 0; } } [Test] public void TestMouseEventFromTouchIndication() { InputReceptor primaryReceptor = null; AddStep("retrieve primary receptor", () => primaryReceptor = receptors[(int)TouchSource.Touch1]); AddStep("setup receptors to discard mouse-from-touch events", () => { primaryReceptor.HandleTouch = _ => false; primaryReceptor.HandleMouse = e => !(e.CurrentState.Mouse.LastSource is ISourcedFromTouch); }); AddStep("perform input on primary touch", () => { InputManager.BeginTouch(new Touch(TouchSource.Touch1, getTouchDownPos(TouchSource.Touch1))); InputManager.MoveTouchTo(new Touch(TouchSource.Touch1, getTouchMovePos(TouchSource.Touch1))); InputManager.EndTouch(new Touch(TouchSource.Touch1, getTouchUpPos(TouchSource.Touch1))); }); AddAssert("no mouse event received", () => primaryReceptor.MouseEvents.Count == 0); AddStep("perform input on mouse", () => { InputManager.MoveMouseTo(getTouchDownPos(TouchSource.Touch1)); InputManager.PressButton(MouseButton.Left); InputManager.MoveMouseTo(getTouchMovePos(TouchSource.Touch1)); InputManager.ReleaseButton(MouseButton.Left); }); AddAssert("all mouse events received", () => { // mouse moved. if (!(primaryReceptor.MouseEvents.TryDequeue(out var me1) && me1 is MouseMoveEvent)) return false; // left down. if (!(primaryReceptor.MouseEvents.TryDequeue(out var me2) && me2 is MouseDownEvent)) return false; // mouse dragged with left. if (!(primaryReceptor.MouseEvents.TryDequeue(out var me3) && me3 is MouseMoveEvent)) return false; if (!(primaryReceptor.MouseEvents.TryDequeue(out var me4) && me4 is DragEvent)) return false; // left up. if (!(primaryReceptor.MouseEvents.TryDequeue(out var me5) && me5 is MouseUpEvent)) return false; return primaryReceptor.MouseEvents.Count == 0; }); } [Test] public void TestMouseStillReleasedOnHierarchyInterference() { InputReceptor primaryReceptor = null; AddStep("retrieve primary receptor", () => primaryReceptor = receptors[(int)TouchSource.Touch1]); AddStep("setup handlers to receive mouse", () => { primaryReceptor.HandleTouch = _ => false; }); AddStep("begin touch", () => InputManager.BeginTouch(new Touch(TouchSource.Touch1, getTouchDownPos(TouchSource.Touch1)))); AddAssert("primary receptor received mouse", () => { bool event1 = primaryReceptor.MouseEvents.Dequeue() is MouseMoveEvent; bool event2 = primaryReceptor.MouseEvents.Dequeue() is MouseDownEvent; return event1 && event2 && primaryReceptor.MouseEvents.Count == 0; }); AddStep("add drawable", () => primaryReceptor.Add(new InputReceptor(TouchSource.Touch1) { RelativeSizeAxes = Axes.Both, HandleTouch = _ => true, })); AddStep("end touch", () => InputManager.EndTouch(new Touch(TouchSource.Touch1, getTouchDownPos(TouchSource.Touch1)))); AddAssert("primary receptor received mouse", () => { bool event1 = primaryReceptor.MouseEvents.Dequeue() is MouseUpEvent; return event1 && primaryReceptor.MouseEvents.Count == 0; }); AddAssert("child receptor received nothing", () => primaryReceptor.TouchEvents.Count == 0 && primaryReceptor.MouseEvents.Count == 0); } private class InputReceptor : Container { public readonly TouchSource AssociatedSource; public readonly Queue<TouchEvent> TouchEvents = new Queue<TouchEvent>(); public readonly Queue<MouseEvent> MouseEvents = new Queue<MouseEvent>(); public Func<TouchEvent, bool> HandleTouch; public Func<MouseEvent, bool> HandleMouse; protected override Container<Drawable> Content => content; private readonly Container content; public InputReceptor(TouchSource source) { AssociatedSource = source; InternalChildren = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, }, new SpriteText { X = 15f, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Text = source.ToString(), Colour = Color4.Black, }, content = new Container { RelativeSizeAxes = Axes.Both, } }; } protected override bool Handle(UIEvent e) { switch (e) { case TouchEvent te: if (HandleTouch?.Invoke(te) != false) { TouchEvents.Enqueue(te); return true; } break; case MouseDownEvent _: case MouseMoveEvent _: case DragEvent _: case MouseUpEvent _: if (HandleMouse?.Invoke((MouseEvent)e) != false) { MouseEvents.Enqueue((MouseEvent)e); return true; } break; // not worth enqueuing, just handle for receiving drag. case DragStartEvent dse: return HandleMouse?.Invoke(dse) ?? true; } return false; } } } }
using Saga.Managers; using Saga.Packets; using Saga.PrimaryTypes; using Saga.Quests; using Saga.Shared.PacketLib.Login; using Saga.Tasks; using System; using System.Diagnostics; using System.Net.Sockets; namespace Saga.Map.Client { [System.Reflection.Obfuscation(Exclude = false, StripAfterObfuscation = true, ApplyToMembers = true)] public partial class Client : Saga.Shared.NetworkCore.Client { #region Private Members /// <summary> /// Boolean defining if the client is first loading for /// the first or seccond time /// </summary> private bool IsFirstTimeLoad = true; /// <summary> /// Booleasn indicated if the map is loaded. /// </summary> /// <remarks> /// All packets objects that are not on demand generated e.d. monster updates /// should check if this is set to true prior to the update sending. /// </remarks> internal volatile bool isloaded = false; /// <summary> /// Character associated with the current client /// </summary> internal Character character; internal QuestBase pendingquest; #endregion Private Members #region Constructor / Deconstructor public Client() { //.this.chatLua.RegisterFunction("Create", this, typeof(Client).GetMethod("Create")); this.OnClose += new EventHandler(Client_OnClose); } public Client(Socket h) : base(h) { //.this.chatLua.RegisterFunction("Create", this, typeof(Client).GetMethod("Create")); this.OnClose += new EventHandler(Client_OnClose); } #endregion Constructor / Deconstructor #region Events protected override void OnConnect() { } private void Client_OnClose(object sender, EventArgs e) { try { CM_PARTYQUIT(null); //Release current session Singleton.NetworkService.AuthenticationClient.SM_RELEASESESSION(this.character.id); if (this.IsConnected == true) { SMSG_KICKSESSION spkt2 = new SMSG_KICKSESSION(); spkt2.SessionId = this.character.id; this.Send((byte[])spkt2); } } catch (Exception) { } try { if (this.character != null) { GC.SuppressFinalize(this.character); //Disallows garbage collector to clean up if (this.character.currentzone != null) //Leave the current zone if any this.character.currentzone.OnLeave(this.character); //zone you are registered on. LifeCycle.Unsubscribe(this.character); //Unsubscribe yourself on life thread //Singleton.Database.SaveCharacter(this.character); if (Singleton.Database.TransSave(this.character) == false) { Trace.WriteLine("Creating restore point could not save into database"); Singleton.Database.CreateRestorePoint(this.character); } GC.ReRegisterForFinalize(this.character); //Allow garbage collector to clean up } //Set character instance to null this.character = null; } catch (Exception ex) { Console.WriteLine(ex); } } private void Login(CMSG_LOGIN cpkt) { if (cpkt.Cmd != 0x0501) { Trace.TraceError("Attempt to hack login protocol"); WorldConnectionError(); return; } try { Character tempCharacter = new Character(this, cpkt.CharacterId, cpkt.SessionId); if (Singleton.Database.TransLoad(tempCharacter) && Singleton.Zones.TryGetZone((uint)tempCharacter.map, out tempCharacter._currentzone)) { Singleton.Database.PostLoad(tempCharacter); this.character = tempCharacter; this.SendStart(); LifeCycle.Subscribe(this.character); this.character.GmLevel = cpkt.GmLevel; this.character.gender = cpkt.Gender; } else { WorldConnectionError(); LifeCycle.Unsubscribe(this.character); } } catch (Exception e) { //WRITE OUT ANY ERRORS Trace.TraceWarning(e.ToString()); WorldConnectionError(); LifeCycle.Unsubscribe(this.character); } } public void SendStart() { SMSG_SENDSTART spkt = new SMSG_SENDSTART(); spkt.Channel = 1; spkt.MapId = this.character.map; spkt.SessionId = this.character.id; spkt.X = this.character.Position.x; spkt.Y = this.character.Position.y; spkt.Z = this.character.Position.z; spkt.Unknown = (byte)(this.character.map + 0x65); this.Send((byte[])spkt); } #endregion Events #region Protected Methods public TraceLog log = new TraceLog("WorldClient.Packetlog", "Log class to log all packet trafic", 0); #if DEBUG public override void Send(byte[] body) { ushort subpacketIdentifier = (ushort)(body[13] + (body[12] << 8)); switch (log.LogLevel) { case 1: log.WriteLine("Network debug world", "Packet Sent: {0:X4}", subpacketIdentifier); break; case 2: log.WriteLine("Network debug world", "Packet Sent: {0:X4}", subpacketIdentifier); Console.WriteLine("Packet Sent: {0:X4} from: {1}", subpacketIdentifier, "world client"); break; case 3: log.WriteLine("Network debug world", "Packet Sent: {0:X4} data {1}", subpacketIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); break; case 4: log.WriteLine("Network debug world", "Packet Sent: {0:X4} data {1}", subpacketIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); Console.WriteLine("Packet Sent: {0:X4} from: {1}", subpacketIdentifier, "world client"); break; } base.Send(body); } public override void Send(ref byte[] body) { ushort subpacketIdentifier = (ushort)(body[13] + (body[12] << 8)); switch (log.LogLevel) { case 1: log.WriteLine("Network debug world", "Packet Sent: {0:X4}", subpacketIdentifier); break; case 2: log.WriteLine("Network debug world", "Packet Sent: {0:X4}", subpacketIdentifier); Console.WriteLine("Packet Sent: {0:X4} from: {1}", subpacketIdentifier, "world client"); break; case 3: log.WriteLine("Network debug world", "Packet Sent: {0:X4} data {1}", subpacketIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); break; case 4: log.WriteLine("Network debug world", "Packet Sent: {0:X4} data {1}", subpacketIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); Console.WriteLine("Packet Sent: {0:X4} from: {1}", subpacketIdentifier, "world client"); break; } base.Send(body); } #endif protected override void ProcessPacket(ref byte[] body) { try { #region Identification ushort subpacketIdentifier = (ushort)(body[13] + (body[12] << 8)); #if DEBUG switch (log.LogLevel) { case 1: log.WriteLine("Network debug world", "Packet Recieved: {0:X4}", subpacketIdentifier); break; case 2: log.WriteLine("Network debug world", "Packet Recieved: {0:X4}", subpacketIdentifier); Console.WriteLine("Packet received: {0:X4} from: {1}", subpacketIdentifier, "world client"); break; case 3: log.WriteLine("Network debug world", "Packet Recieved: {0:X4} data {1}", subpacketIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); break; case 4: log.WriteLine("Network debug world", "Packet Recieved: {0:X4} data {1}", subpacketIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); Console.WriteLine("Packet received: {0:X4} from: {1}", subpacketIdentifier, "world client"); break; } #endif switch (body[12]) { case 0x00: goto Px00; case 0x03: goto Px03; case 0x04: goto Px04; case 0x05: goto Px05; case 0x06: goto Px06; case 0x07: goto Px07; case 0x08: goto Px08; case 0x09: goto Px09; case 0x0A: goto Px0A; case 0x0C: goto Px0C; case 0x0E: goto Px0E; case 0x0F: goto Px0F; case 0x10: goto Px10; case 0x11: goto Px11; case 0x12: goto Px12; default: goto Px10; } #endregion Identification #region 0x00 - Internal Packets Px00: switch (subpacketIdentifier) { case 0x0001: Login((CMSG_LOGIN)body); return; } return; #endregion 0x00 - Internal Packets #region 0x03 - Misc. Movement Packets Px03: switch (subpacketIdentifier) { case 0x0301: this.CM_CHARACTER_MAPLOADED(); break; case 0x0302: this.CM_CHARACTER_MOVEMENTSTART((CMSG_MOVEMENTSTART)body); break; case 0x0303: this.CM_CHARACTER_MOVEMENTSTOPPED((CMSG_MOVEMENTSTOPPED)body); break; case 0x0304: this.CM_CHARACTER_UPDATEYAW((CMSG_SENDYAW)body); break; case 0x0305: this.CM_CHARACTER_CHANGESTATE((CMSG_ACTORCHANGESTATE)body); break; case 0x0306: this.CM_CHARACTER_USEPORTAL((CMSG_USEPORTAL)body); break; case 0x0307: this.CM_CHARACTER_JOBCHANGE((CMSG_CHANGEJOB)body); break; case 0x0308: this.CM_CHARACTER_RETURNTOHOMEPOINT((CMSG_SENDHOMEPOINT)body); break; case 0x0309: this.CM_CHARACTER_STATPOINTUPDATE((CMSG_STATUPDATE)body); break; case 0x030A: this.CM_CHARACTER_DIVEUP(); break; //newly packet case 0x030B: this.CM_CHARACTER_JUMP(); break; case 0x030C: this.CM_CHARACTER_SHOWLOVE((CMSG_SHOWLOVE)body); break; case 0x030D: this.CM_CHARACTER_CONFIRMSHOWLOVE((CMSG_SHOWLOVECONFIRM)body); break; case 0x030E: this.CM_CHARACTER_FALL((CMSG_ACTORFALL)body); break; case 0x030F: this.CM_CHARACTER_DIVEDOWN(); break; case 0x0310: this.CM_CHARACTER_DIVEUP(); break; case 0x0311: this.CM_CHARACTER_EXPENSIVESFORJOBCHANGE((CMSG_SELECTJOB)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x03 - Misc. Movement Packets #region 0x04 - Chat packets Px04: switch (subpacketIdentifier) { case 0x0401: this.CM_SENDCHAT((CMSG_SENDCHAT)body); break; case 0x0402: this.CM_SENDWHISPER((CMSG_SENDWHISPER)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x04 - Chat packets #region 0x05 - Misc. Item packets Px05: switch (subpacketIdentifier) { case 0x0501: this.CM_MOVEITEM((CMSG_MOVEITEM)body); break; case 0x0504: this.CM_IVENTORY_SORT((CMSG_SORTINVENTORYLIST)body); break; case 0x0505: this.CM_STORAGE_SORT((CMSG_SORTSTORAGELIST)body); break; case 0x0507: this.CM_DISCARDITEM((CMSG_DELETEITEM)body); break; case 0x0508: this.CM_REPAIREQUIPMENT((CMSG_REPAIRITEM)body); break; case 0x050B: this.CM_WEAPONMOVE((CMSG_WEAPONMOVE)body); break; case 0x050D: this.CM_WEAPONSWITCH((CMSG_WEAPONSWITCH)body); break; case 0x050F: this.CM_WEAPONARY_UPGRADE((CMSG_WEAPONUPGRADE)body); break; case 0x0512: this.CM_WEAPONAUGE((CMSG_WEAPONAUGE)body); break; case 0x0515: this.CM_WEAPONARY_CHANGESUFFIX((CMSG_WEAPONCHANGESUFFIX)body); break; case 0x0516: this.CM_WEAPONARY_NEWCHANGESUFFIX((CMSG_WEAPONCHANGESUFFIX2)body); break; case 0x0517: this.CM_USEMAPITEM((CMSG_USEMAP)body); break; case 0x0518: this.CM_USEADMISSIONWEAPON((CMSG_USEWEAPONADMISSION)body); break; case 0x0519: this.CM_USEDYEITEM((CMSG_USEDYEITEM)body); break; case 0x051A: this.CM_USESTATRESETITEM((CMSG_STATRESETPOTION)body); break; case 0x051B: this.CM_USESUPLEMENTSTONE((CMSG_USESUPPLEMENTSTONE)body); break; default: Console.WriteLine("Recieved {0:X4}", subpacketIdentifier); break; } return; #endregion 0x05 - Misc. Item packets #region 0x06 - Misc. NPC Packets Px06: switch (subpacketIdentifier) { case 0x0601: this.CM_NPCCHAT((CMSG_NPCCHAT)body); break; case 0x0602: this.CM_ONSELECTBUTTON((CMSG_SELECTBUTTON)body); break; case 0x0603: this.CM_LEAVENPC(); break; case 0x0604: this.CM_ONSELECTMENUSUBITEM((CMSG_NPCMENU)body); break; case 0x0605: this.CM_PERSONALREQUESTCONFIRMATION((CMSG_PERSONALREQUEST)body); break; case 0x0606: this.CM_REQUESTSHOWNPCLOCATION((CMSG_NPCLOCATIONSELECT)body); break; case 0x0607: this.CM_GETHATEINFO((CMSG_HATEINFO)body); break; case 0x0608: this.CM_GETATTRIBUTE((CMSG_ATTRIBUTE)body); break; case 0x0609: this.CM_RELEASEATTRIBUTE(); break; case 0x060B: this.CM_SELECTSUPPPLYMENU((CMSG_SUPPLYSELECT)body); break; case 0x060D: this.CM_EXCHANGEGOODS((CMSG_SUPPLYEXCHANGE)body); break; case 0x060F: this.CM_CLEARCORPSE(); break; case 0x0610: this.CM_REQUESTITEMDROPLIST((CMSG_DROPLIST)body); break; case 0x0611: this.CM_NPCINTERACTION_SHOPSELL((CMSG_NPCSHOPSELL)body); break; case 0x0612: this.CM_NPCINTERACTION_SHOPBUY((CMSG_NPCSHOPBUY)body); break; case 0x0613: this.CM_NPCINTERACTION_SHOPREBUY((CMSG_NPCREBUY)body); break; case 0x0614: this.CM_DROPSELECT((CMSG_DROPSELECT)body); break; case 0x0615: this.CM_EVENTPARTICIPATE((CMSG_SELECTEVENTINFO)body); break; case 0x0616: this.CM_EVENTRECIEVEITEM((CMSG_RECEIVEEVENTITEM)body); break; case 0x0617: this.CM_NPCINTERACTION_WARPSELECT((CMSG_WARP)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x06 - Misc. NPC Packets #region 0x07 - Questing packets Px07: switch (subpacketIdentifier) { case 0x0701: this.OnWantQuestGroupList(); break; case 0x0704: this.CM_QUESTCONFIRMCANCEL((CMSG_QUESTCONFIRMCANCEL)body); break; case 0x0705: this.CM_QUESTCONFIRM((CMSG_QUESTCONFIRMED)body); break; case 0x0706: this.CM_QUESTCOMPLETE((CMSG_QUESTCOMPLETE)body); break; case 0x0707: this.OnQuestRewardChoice(); break; case 0x0709: this.CM_QUESTITEMSTART((CMSG_QUESTITEMSTART)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x07 - Questing packets #region 0x08 - Trading Packets Px08: switch (subpacketIdentifier) { case 0x0801: this.CM_TRADEINVITATION((CMSG_REQUESTTRADE)body); break; case 0x0802: this.CM_TRADEINVITATIONREPLY((CMSG_TRADEINVITATIONRESULT)body); break; case 0x0803: this.CM_TRADEITEM((CMSG_TRADEITEM)body); break; case 0x0804: this.CM_TRADEMONEY((CMSG_TRADEZENY)body); break; case 0x0805: this.CM_TRADECONTENTAGREE((CMSG_TRADECONTENTCONFIRM)body); break; case 0x0806: this.CM_TRADECONFIRM((CMSG_TRADECONFIRM)body); break; case 0x0807: this.CM_TRADECANCEL((CMSG_TRADECANCEL)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x08 - Trading Packets #region 0x09 - Skill packets Px09: switch (subpacketIdentifier) { case 0x0903: this.CM_SKILLCAST((CMSG_SKILLCAST)body); break; case 0x0904: this.CM_SKILLCASTCANCEL((CMSG_SKILLCASTCANCEL)body); break; case 0x0905: this.CM_USEOFFENSIVESKILL((CMSG_OFFENSIVESKILL)body); break; case 0x0906: this.CM_SKILLTOGGLE((CMSG_SKILLTOGLE)body); break; case 0x090A: this.CM_ITEMTOGGLE((CMSG_ITEMTOGLE)body); break; case 0x090C: this.CM_SKILLS_LEARNFROMSKILLBOOK((CMSG_SKILLLEARN)body); break; case 0x090D: this.CM_SKILLS_ADDSPECIAL((CMSG_SETSPECIALSKILL)body); break; case 0x090E: this.CM_SKILLS_REMOVESPECIAL((CMSG_REMOVESPECIALSKILL)body); break; case 0x0911: this.CM_SKILLS_REQUESTSPECIALSET((CMSG_WANTSETSPECIALLITY)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x09 - Skill packets #region 0x0A - Shortcut packets Px0A: switch (subpacketIdentifier) { case 0x0A01: this.OnAddShortcut(); break; case 0x0A02: this.OnDelShortcut(); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x0A - Shortcut packets #region 0x0C - Mail packets Px0C: switch (subpacketIdentifier) { case 0x0C01: this.CM_REQUESTINBOXMAILLIST((CMSG_REQUESTINOX)body); break; case 0x0C02: this.CM_NEWMAILITEM((CMSG_SENDMAIL)body); break; case 0x0C03: this.CM_INBOXMAILITEM((CMSG_GETMAIL)body); break; case 0x0C04: this.CM_RETRIEVEITEMATTACHMENT((CMSG_GETITEMATTACHMENT)body); break; case 0x0C05: this.CM_RETRIEVEZENYATTACHMENT((CMSG_GETZENYATTACHMENT)body); break; case 0x0C06: this.CM_MAILDELETE((CMSG_DELETEMAIL)body); break; case 0x0C07: this.CM_REQUESTOUTBOXMAILLIST((CMSG_REQUESTOUTBOX)body); break; case 0x0C08: this.CM_MAILCANCEL((CMSG_MAILCANCEL)body); break; case 0x0C09: this.CM_OUTBOXMAILITEM((CMSG_GETMAILOUTBOX)body); break; case 0x0C0A: this.CM_MAILCLEAR((CMSG_MAILCLEAR)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x0C - Mail packets #region 0x0E - Party packets Px0E: switch (subpacketIdentifier) { case 0x0E01: this.CM_PARTYREQUEST((CMSG_PARTYINVITE_LOCAL)body); break; case 0x0E02: this.CM_PARTYREQUEST((CMSG_PARTYINVITE)body); break; case 0x0E03: this.CM_PARTYINVITATIONACCEPT((CMSG_PARTYINVITATIONACCEPT)body); break; case 0x0E04: this.CM_PARTYQUIT((CMSG_PARTYQUIT)body); break; case 0x0E05: this.CM_PARTYKICK((CMSG_PARTYKICK)body); break; case 0x0E06: this.CM_PARTYMODE((CMSG_PARTYMODE)body); break; case 0x0E07: this.CM_PARTYSETLEADER((CMSG_PARTYSETLEADER)body); break; case 0x0E08: this.CM_PARTYINVITATIONCANCELED((CMSG_PARTYINVITECANCEL)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); break; } return; #endregion 0x0E - Party packets #region 0x0F - Market packets Px0F: switch (subpacketIdentifier) { case 0x0F01: this.CM_MARKET_SEARCH((CMSG_MARKETSEARCH)body); break; case 0x0F02: this.CM_MARKET_BUY((CMSG_MARKETBUY)body); break; case 0x0F03: this.CM_MARKET_SEARCHOWNERITEMS(); break; case 0x0F04: this.CM_MARKET_REGISTERITEM((CMSG_MARKETREGISTER)body); break; case 0x0F05: this.CM_MARKET_DELETEITEM((CMSG_MARKETDELETEITEM)body); break; case 0x0F06: this.CM_MARKET_CHANGECOMMENT((CMSG_MARKETMESSAGE)body); break; case 0x0F07: this.CM_MARKET_COMMENT((CMSG_MARKETGETCOMMENT)body); break; case 0x0F08: this.CM_MARKET_OWNERCOMMENT((CMSG_MARKETOWNERCOMMENT)body); break; default: Console.WriteLine("{0} - {0:X2}", subpacketIdentifier); break; } return; #endregion 0x0F - Market packets #region 0x10 - Scenario packets Px10: switch (subpacketIdentifier) { case 0x1001: CM_SCENARIO_EVENTEND(body); break; default: Console.WriteLine("{0} - {0:X2}", subpacketIdentifier); break; } return; #endregion 0x10 - Scenario packets #region 0x11 - Misc packets Px11: switch (subpacketIdentifier) { case 0x1101: CM_SELECTCHANNEL((CMSG_SELECTCHANNEL)body); break; case 0x1102: CM_TAKESCREENSHOT((CMSG_TAKESCREENSHOT)body); break; default: Console.WriteLine("{0} - {0:X2}", subpacketIdentifier); break; } return; #endregion 0x11 - Misc packets #region 0x12 - Friendlist / Blacklist Packets Px12: switch (subpacketIdentifier) { case 0x1201: this.CM_FRIENDLIST_REGISTER((CMSG_FRIENDLIST_REGISTER)body); return; case 0x1202: this.CM_FRIENDLIST_UNREGISTER((CMSG_FRIENDLIST_UNREGISTER)body); return; case 0x1203: this.CM_FRIENDLIST_REFRESH((CMSG_FRIENDLIST_REFRESH)body); return; case 0x1204: this.CM_BLACKLIST_REGISTER((CMSG_BLACKLIST_REGISTER)body); return; case 0x1205: this.CM_BLACKLIST_UNREGISTER((CMSG_BLACKLIST_UNREGISTER)body); return; case 0x1206: this.CM_BLACKLIST_REFRESH((CMSG_BLACKLIST_REFRESH)body); break; default: Console.WriteLine("{0:X4}", subpacketIdentifier); return; } return; #endregion 0x12 - Friendlist / Blacklist Packets } catch (Exception e) { if (ConsoleCommands.DisconnectClientOnException == true) throw e; } } #endregion Protected Methods #region Private Methods /// <summary> /// Notifies the gateway that we're not able to make a connection. /// </summary> private void WorldConnectionError() { byte[] buffer2 = new byte[] { 0x0B, 0x00, 0x74, 0x17, 0x91, 0x00, 0x02, 0x07, 0x00, 0x00, 0x01 }; Array.Copy(BitConverter.GetBytes(this.character.id), 0, buffer2, 2, 4); this.Send(buffer2); } #endregion Private Methods } }
/* Copyright (c) Peter Palotas 2007 * * 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 copyright holder 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. * * $Id: StringFormatter.cs 7 2007-08-04 12:02:15Z palotas $ */ using System; using SCG = System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; using C5; namespace Plossum { /// <summary> /// Class performing various formatting operations on strings based on fixed width characters. /// </summary> public static class StringFormatter { #region Public methods /// <summary> /// Aligns the specified string within a field of the desired width, cropping it if it doesn't fit, and expanding it otherwise. /// </summary> /// <param name="str">The string to align.</param> /// <param name="width">The width of the field in characters in which the string should be fitted.</param> /// <param name="alignment">The aligmnent that will be used for fitting the string in the field in case it is shorter than the specified field width.</param> /// <returns> /// A string exactly <paramref name="width"/> characters wide, containing the specified string <paramref name="str"/> fitted /// according to the parameters specified. /// </returns> /// <remarks> /// <para>If the string consists of several lines, each line will be aligned according to the specified parameters.</para> /// <para>The padding character used will be the normal white space character (' '), and the ellipsis used will be the /// string <b>"..."</b>. Cropping will be done on the right hand side of the string.</para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> /// <exception cref="ArgumentException"><paramref name="width"/> is less than the length of the specified <paramref name="ellipsis"/>, or, /// the cropping specified is <see cref="Cropping.Both"/> and <paramref name="width"/> was less than <i>twice</i> the /// length of the <paramref name="ellipsis"/></exception> public static string Align(string str, int width, Alignment alignment) { return Align(str, width, alignment, Cropping.Right, "..."); } /// <summary> /// Aligns the specified string within a field of the desired width, cropping it if it doesn't fit, and expanding it otherwise. /// </summary> /// <param name="str">The string to align.</param> /// <param name="width">The width of the field in characters in which the string should be fitted.</param> /// <param name="alignment">The aligmnent that will be used for fitting the string in the field in case it is shorter than the specified field width.</param> /// <param name="cropping">The method that will be used for cropping if the string is too wide to fit in the specified width.</param> /// <returns> /// A string exactly <paramref name="width"/> characters wide, containing the specified string <paramref name="str"/> fitted /// according to the parameters specified. /// </returns> /// <remarks> /// <para>If the string consists of several lines, each line will be aligned according to the specified parameters.</para> /// <para>The padding character used will be the normal white space character (' '), and the ellipsis used will be the /// string <b>"..."</b>.</para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> /// <exception cref="ArgumentException"><paramref name="width"/> is less than the length of the specified <paramref name="ellipsis"/>, or, /// the cropping specified is <see cref="Cropping.Both"/> and <paramref name="width"/> was less than <i>twice</i> the /// length of the <paramref name="ellipsis"/></exception> public static string Align(string str, int width, Alignment alignment, Cropping cropping) { return Align(str, width, alignment, cropping, "..."); } /// <summary> /// Aligns the specified string within a field of the desired width, cropping it if it doesn't fit, and expanding it otherwise. /// </summary> /// <param name="str">The string to align.</param> /// <param name="width">The width of the field in characters in which the string should be fitted.</param> /// <param name="alignment">The aligmnent that will be used for fitting the string in the field in case it is shorter than the specified field width.</param> /// <param name="cropping">The method that will be used for cropping if the string is too wide to fit in the specified width.</param> /// <param name="ellipsis">A string that will be inserted at the cropped side(s) of the string to denote that the string has been cropped.</param> /// <returns> /// A string exactly <paramref name="width"/> characters wide, containing the specified string <paramref name="str"/> fitted /// according to the parameters specified. /// </returns> /// <remarks> /// <para>If the string consists of several lines, each line will be aligned according to the specified parameters.</para> /// <para>The padding character used will be the normal white space character (' ').</para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> /// <exception cref="ArgumentException"><paramref name="width"/> is less than the length of the specified <paramref name="ellipsis"/>, or, /// the cropping specified is <see cref="Cropping.Both"/> and <paramref name="width"/> was less than <i>twice</i> the /// length of the <paramref name="ellipsis"/></exception> public static string Align(string str, int width, Alignment alignment, Cropping cropping, string ellipsis) { return Align(str, width, alignment, cropping, ellipsis, ' '); } /// <summary> /// Aligns the specified string within a field of the desired width, cropping it if it doesn't fit, and expanding it otherwise. /// </summary> /// <param name="str">The string to align.</param> /// <param name="width">The width of the field in characters in which the string should be fitted.</param> /// <param name="alignment">The aligmnent that will be used for fitting the string in the field in case it is shorter than the specified field width.</param> /// <param name="cropping">The method that will be used for cropping if the string is too wide to fit in the specified width.</param> /// <param name="ellipsis">A string that will be inserted at the cropped side(s) of the string to denote that the string has been cropped.</param> /// <param name="padCharacter">The character that will be used for padding the string in case it is shorter than the specified field width.</param> /// <returns> /// A string exactly <paramref name="width"/> characters wide, containing the specified string <paramref name="str"/> fitted /// according to the parameters specified. /// </returns> /// <remarks>If the string consists of several lines, each line will be aligned according to the specified parameters.</remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> /// <exception cref="ArgumentException"><paramref name="width"/> is less than the length of the specified <paramref name="ellipsis"/>, or, /// the cropping specified is <see cref="Cropping.Both"/> and <paramref name="width"/> was less than <i>twice</i> the /// length of the <paramref name="ellipsis"/></exception> public static string Align(string str, int width, Alignment alignment, Cropping cropping, string ellipsis, char padCharacter) { if (str == null) throw new ArgumentNullException("str"); if (width <= 0) throw new ArgumentOutOfRangeException("width"); if (ellipsis != null) { if (cropping != Cropping.Both && width < ellipsis.Length) throw new ArgumentException("width must not be less than the length of ellipsis"); else if (cropping == Cropping.Both && width < ellipsis.Length * 2) throw new ArgumentException("width must not be less than twice the length of the ellipsis when cropping is set to Both"); } IIndexed<string> lines = SplitAtLineBreaks(str); StringBuilder result = new StringBuilder(); for (int j = 0; j < lines.Count; j++) { if (j != 0) result.Append(Environment.NewLine); string s = lines[j]; int length = s.Length; if (length <= width) { switch (alignment) { case Alignment.Left: result.Append(s); result.Append(padCharacter, width - length); continue; case Alignment.Right: result.Append(padCharacter, width - length); result.Append(s); continue; case Alignment.Center: result.Append(padCharacter, (width - length) / 2); result.Append(s); result.Append(padCharacter, (width - length) - ((width - length) / 2)); continue; case Alignment.Justified: string trimmed = s.Trim(); length = trimmed.Length; int spaceCount = GetWordCount(s) - 1; Debug.Assert(spaceCount >= 0); if (spaceCount == 0) // string only contain a single word { result.Append(trimmed); result.Append(padCharacter, width - length); } StringBuilder localResult = new StringBuilder(); int remainingSpace = width - length; bool readingWord = true; for (int i = 0; i < length; i++) { if (!char.IsWhiteSpace(trimmed[i])) { readingWord = true; localResult.Append(trimmed[i]); } else if (readingWord) { localResult.Append(trimmed[i]); int spacesToAdd = remainingSpace / spaceCount--; remainingSpace -= spacesToAdd; localResult.Append(padCharacter, spacesToAdd); readingWord = false; } } result.Append(localResult); continue; default: throw new InvalidOperationException("Internal error; Unimplemented Justification specified"); } } // The string is too long and need to be cropped switch (cropping) { case Cropping.Right: return s.Substring(0, width - ellipsis.Length) + ellipsis; case Cropping.Left: return ellipsis + s.Substring(length - width + ellipsis.Length); case Cropping.Both: return ellipsis + s.Substring(length / 2 - width / 2, width - ellipsis.Length * 2) + ellipsis; default: break; } } return result.ToString(); } /// <summary> /// Performs word wrapping on the specified string, making it fit within the specified width. /// </summary> /// <param name="str">The string to word wrap.</param> /// <param name="width">The width of the field in which to fit the string.</param> /// <returns>A word wrapped version of the original string aligned and padded as specified.</returns> /// <remarks><para>No padding will be performed on strings that are shorter than the specified width, and each line will be /// left aligned.</para> /// <para>This method uses <see cref="WordWrappingMethod.Optimal"/> to perform word wrapping.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> public static string WordWrap(string str, int width) { return WordWrap(str, width, WordWrappingMethod.Optimal); } /// <summary> /// Performs word wrapping on the specified string, making it fit within the specified width. /// </summary> /// <param name="str">The string to word wrap.</param> /// <param name="width">The width of the field in which to fit the string.</param> /// <param name="method">The method to use for word wrapping.</param> /// <returns>A word wrapped version of the original string aligned and padded as specified.</returns> /// <remarks>No padding will be performed on strings that are shorter than the specified width, and each line will be /// left aligned.</remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> public static string WordWrap(string str, int width, WordWrappingMethod method) { if (str == null) throw new ArgumentNullException("str"); if (width <= 0) throw new ArgumentOutOfRangeException("width"); if (method == WordWrappingMethod.Optimal) return new OptimalWordWrappedString(str, width).ToString(); // Simple word wrapping method that simply fills lines as // much as possible and then breaks. Creates a not so nice // layout. StringBuilder dest = new StringBuilder(str.Length); StringBuilder word = new StringBuilder(); int spaceLeft = width; StringReader reader = new StringReader(str); int ch; do { while ((ch = reader.Read()) != -1 && ch != ' ') { word.Append((char)ch); if (ch == '\n') spaceLeft = width; } if (word.Length > spaceLeft) { while (word.Length > width) { dest.Append('\n'); dest.Append(word.ToString(0, width)); word.Remove(0, width); spaceLeft = width; } dest.Append('\n'); dest.Append(word); spaceLeft = width - word.Length; word.Length = 0; } else { dest.Append(word); spaceLeft -= word.Length; word.Length = 0; } if (ch != -1 && spaceLeft > 0) { dest.Append(' '); spaceLeft--; } } while (ch != -1); reader.Close(); return dest.ToString(); } /// <summary> /// Performs word wrapping on the specified string, making it fit within the specified width and additionally aligns each line /// according to the <see cref="Alignment"/> specified. /// </summary> /// <param name="str">The string to word wrap and align.</param> /// <param name="width">The width of the field in which to fit the string.</param> /// <param name="method">The method to use for word wrapping.</param> /// <param name="alignment">The alignment to use for each line of the resulting string.</param> /// <returns>A word wrapped version of the original string aligned and padded as specified.</returns> /// <remarks>If padding is required, the normal simple white space character (' ') will be used.</remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> public static string WordWrap(string str, int width, WordWrappingMethod method, Alignment alignment) { return WordWrap(str, width, method, alignment, ' '); } /// <summary> /// Performs word wrapping on the specified string, making it fit within the specified width and additionally aligns each line /// according to the <see cref="Alignment"/> specified. /// </summary> /// <param name="str">The string to word wrap and align.</param> /// <param name="width">The width of the field in which to fit the string.</param> /// <param name="method">The method to use for word wrapping.</param> /// <param name="alignment">The alignment to use for each line of the resulting string.</param> /// <param name="padCharacter">The character to use for padding lines that are shorter than the specified width.</param> /// <returns>A word wrapped version of the original string aligned and padded as specified.</returns> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="width"/> was less than, or equal to zero.</exception> public static string WordWrap(string str, int width, WordWrappingMethod method, Alignment alignment, char padCharacter) { return StringFormatter.Align(WordWrap(str, width, method), width, alignment, Cropping.Left, "", padCharacter); } /// <summary> /// Splits the specified strings at line breaks, resulting in an indexed collection where each item represents one line of the /// original string. /// </summary> /// <param name="str">The string to split.</param> /// <returns>an indexed collection where each item represents one line of the /// original string.</returns> /// <remarks>This might seem identical to the String.Split method at first, but it is not exactly, since this method /// recognizes line breaks in the three formats: "\n", "\r" and "\r\n". Note that any newline characters will not be present /// in the returned collection.</remarks> public static IIndexed<string> SplitAtLineBreaks(string str) { return SplitAtLineBreaks(str, false); } /// <summary> /// Splits the specified strings at line breaks, resulting in an indexed collection where each item represents one line of the /// original string. /// </summary> /// <param name="str">The string to split.</param> /// <param name="removeEmptyLines">if set to <c>true</c> any empty lines will be removed from the resulting collection.</param> /// <returns> /// an indexed collection where each item represents one line of the /// original string. /// </returns> /// <remarks>This might seem identical to the String.Split method at first, but it is not exactly, since this method /// recognizes line breaks in the three formats: "\n", "\r" and "\r\n". Note that any newline characters will not be present /// in the returned collection.</remarks> public static IIndexed<string> SplitAtLineBreaks(string str, bool removeEmptyLines) { IIndexed<string> result = new ArrayList<string>(); StringBuilder temp = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if (i < str.Length - 1 && str[i] == '\r' && str[i + 1] == '\n') i++; if (str[i] == '\n' || str[i] == '\r') { if (!removeEmptyLines || temp.Length > 0) result.Add(temp.ToString()); temp.Length = 0; } else { temp.Append(str[i]); } } if (temp.Length > 0) result.Add(temp.ToString()); return result; } /// <summary> /// Retrieves the number of words in the specified string. /// </summary> /// <param name="str">The string in which to count the words.</param> /// <returns>The number of words in the specified string.</returns> /// <remarks>A <i>word</i> here is defined as any number (greater than zero) of non-whitespace characters, separated from /// other words by one or more white space characters.</remarks> /// <exception cref="ArgumentNullException"><paramref name="str"/> was a null reference (<b>Nothing</b> in Visual Basic)</exception> public static int GetWordCount(string str) { if (str == null) throw new ArgumentNullException("str"); int count = 0; bool readingWord = false; for (int i = 0; i < str.Length; i++) { if (!char.IsWhiteSpace(str[i])) readingWord = true; else if (readingWord) { count++; readingWord = false; } } if (readingWord) count++; return count; } /// <summary> /// Formats several fixed width strings into columns of the specified widths, performing word wrapping and alignment as specified. /// </summary> /// <param name="indent">The indentation (number of white space characters) to use before the first column.</param> /// <param name="columnSpacing">The spacing to use in between columns.</param> /// <param name="columns">An array of the <see cref="ColumnInfo"/> objects representing the columns to use.</param> /// <returns>A single string that when printed will represent the original strings formatted as specified in each <see cref="ColumnInfo"/> /// object.</returns> /// <exception cref="ArgumentNullException">A <see cref="ColumnInfo.Content"/> for a column was a null reference (<b>Nothing</b> in Visual Basic)</exception> /// <exception cref="ArgumentOutOfRangeException">The specified <see cref="ColumnInfo.Width"/> for a column was less than, or equal to zero.</exception> /// <exception cref="ArgumentException"><paramref name="columnSpacing"/> was less than zero, or, <paramref name="indent"/> was less than /// zero, or, no columns were specified.</exception> public static string FormatInColumns(int indent, int columnSpacing, params ColumnInfo[] columns) { if (columnSpacing < 0) throw new ArgumentException("columnSpacing must not be less than zero", "columnSpacing"); if (indent < 0) throw new ArgumentException("indent must not be less than zero", "indent"); if (columns.Length == 0) return ""; IIndexed<string>[] strings = new IIndexed<string>[columns.Length]; int totalLineCount = 0; // Calculate the total number of lines that needs to be printed for (int i = 0; i < columns.Length; i++) { strings[i] = SplitAtLineBreaks(WordWrap(columns[i].Content, columns[i].Width, columns[i].WordWrappingMethod, columns[i].Alignment, ' '), false); totalLineCount = Math.Max(strings[i].Count, totalLineCount); } // Calculate the first line on which each column should start to print, based // on its vertical alignment. int[] startLine = new int[columns.Length]; for (int col = 0; col < columns.Length; col++) { switch (columns[col].VerticalAlignment) { case VerticalAlignment.Top: startLine[col] = 0; break; case VerticalAlignment.Bottom: startLine[col] = totalLineCount - strings[col].Count; break; case VerticalAlignment.Middle: startLine[col] = (totalLineCount - strings[col].Count) / 2; break; default: throw new InvalidOperationException(Resources.CommandLineStrings.InternalErrorUnimplementedVerticalAlignmentUsed); } } StringBuilder result = new StringBuilder(); for (int line = 0; line < totalLineCount; line++) { result.Append(' ', indent); for (int col = 0; col < columns.Length; col++) { if (line >= startLine[col] && line - startLine[col] < strings[col].Count) { result.Append(strings[col][line - startLine[col]]); } else { result.Append(' ', columns[col].Width); } if (col < columns.Length - 1) result.Append(' ', columnSpacing); } if (line != totalLineCount - 1) result.Append(Environment.NewLine); } return result.ToString(); } #endregion #region Private classes /// <summary> /// Class performing an "optimal solution" word wrapping creating a somewhat more estetically pleasing layout. /// </summary> /// <remarks><para>This is based on the /// "optimal solution" as described on the Wikipedia page for "Word Wrap" (http://en.wikipedia.org/wiki/Word_wrap). /// The drawback of this method compared to the simple "greedy" technique is that this is much, much slower. However for /// short strings to print as console messages this will not be a problem, but using it in a WYSIWYG word processor is probably /// not a very good idea.</para></remarks> private class OptimalWordWrappedString { #region Constructors public OptimalWordWrappedString(string s, int lineWidth) { string[] lines = s.Split('\n'); for (int c = 0; c < lines.Length; c++) { mStr = lines[c].Trim(); mLineWidth = lineWidth; BuildWordList(mStr, mLineWidth); mCostCache = new int[mWordList.Length, mWordList.Length]; for (int x = 0; x < mWordList.Length; x++) for (int y = 0; y < mWordList.Length; y++) mCostCache[x, y] = -1; mfCache = new LineBreakResult[mWordList.Length]; IStack<int> stack = new ArrayList<int>(); LineBreakResult last = new LineBreakResult(0, mWordList.Length - 1); stack.Push(last.K); while (last.K >= 0) { last = FindLastOptimalBreak(last.K); if (last.K >= 0) stack.Push(last.K); } int start = 0; while (!stack.IsEmpty) { int next = stack.Pop(); mResult.Append(GetWords(start, next)); if (!stack.IsEmpty) mResult.Append(Environment.NewLine); start = next + 1; } if (c != lines.Length - 1) mResult.Append(Environment.NewLine); } mWordList = null; mfCache = null; mStr = null; mCostCache = null; } #endregion #region Public methods public override string ToString() { return mResult.ToString(); } #endregion #region Private methods private string GetWords(int i, int j) { int start = mWordList[i].pos; int end = (j + 1 >= mWordList.Length) ? mStr.Length : mWordList[j + 1].pos - (mWordList[j + 1].spacesBefore - mWordList[j].spacesBefore); return mStr.Substring(start, end - start); } private struct WordInfo { public int spacesBefore; public int pos; public int length; public int totalLength; } private void BuildWordList(string s, int lineWidth) { Debug.Assert(!s.Contains("\n")); ArrayList<WordInfo> mWordListAL = new ArrayList<WordInfo>(); bool lookingForWs = false; WordInfo we = new WordInfo(); we.pos = 0; int spaces = 0; int totalLength = 0; for (int i = 0; i < s.Length; i++) { char ch = s[i]; if (lookingForWs && ch == ' ') { spaces++; if (we.pos != i) mWordListAL.Add(we); we = new WordInfo(); we.spacesBefore = spaces; we.pos = i + 1; lookingForWs = false; continue; } else if (ch != ' ') { lookingForWs = true; } we.length++; totalLength++; we.totalLength = totalLength; if (we.length == lineWidth) { mWordListAL.Add(we); we = new WordInfo(); we.spacesBefore = spaces; we.pos = i + 1; } } mWordListAL.Add(we); mWordList = mWordListAL.ToArray(); } private int SumWidths(int i, int j) { return i == 0 ? mWordList[j].totalLength : mWordList[j].totalLength - mWordList[i - 1].totalLength; } private int GetCost(int i, int j) { int cost = mCostCache[i, j]; if (cost == -1) { cost = mLineWidth - (mWordList[j].spacesBefore - mWordList[i].spacesBefore) - SumWidths(i, j); cost = cost < 0 ? mInfinity : cost * cost; mCostCache[i, j] = cost; } return cost; } private LineBreakResult FindLastOptimalBreak(int j) { if (mfCache[j] != null) { return mfCache[j]; } int cost = GetCost(0, j); if (cost < mInfinity) { return new LineBreakResult(cost, -1); } LineBreakResult min = new LineBreakResult(); for (int k = 0; k < j; k++) { int result = FindLastOptimalBreak(k).Cost + GetCost(k + 1, j); if (result < min.Cost) { min.Cost = result; min.K = k; } } mfCache[j] = min; return min; } #endregion #region Private types private class LineBreakResult { public LineBreakResult() { Cost = mInfinity; K = -1; } public LineBreakResult(int cost, int k) { this.Cost = cost; this.K = k; } public int Cost; public int K; } #endregion #region Private fields private WordInfo[] mWordList; private StringBuilder mResult = new StringBuilder(); private LineBreakResult[] mfCache; private string mStr; private int mLineWidth; private const int mInfinity = int.MaxValue / 2; // We need a rectangular array here, so this warning is unwarranted. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Member")] private int[,] mCostCache; #endregion } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.Dispensers; using System.Reflection.Runtime.PropertyInfos; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; //================================================================================================================= // This file collects the various chokepoints that create the various Runtime*Info objects. This allows // easy reviewing of the overall caching and unification policy. // // The dispenser functions are defined as static members of the associated Info class. This permits us // to keep the constructors private to ensure that these really are the only ways to obtain these objects. //================================================================================================================= namespace System.Reflection.Runtime.Assemblies { //----------------------------------------------------------------------------------------------------------- // Assemblies (maps 1-1 with a MetadataReader/ScopeDefinitionHandle. //----------------------------------------------------------------------------------------------------------- internal partial class RuntimeAssembly { /// <summary> /// Returns non-null or throws. /// </summary> internal static RuntimeAssembly GetRuntimeAssembly(RuntimeAssemblyName assemblyRefName) { RuntimeAssembly result; Exception assemblyLoadException = TryGetRuntimeAssembly(assemblyRefName, out result); if (assemblyLoadException != null) throw assemblyLoadException; return result; } /// <summary> /// Returns non-null or throws. /// </summary> internal static RuntimeAssembly GetRuntimeAssemblyFromByteArray(byte[] rawAssembly, byte[] pdbSymbolStore) { AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder; AssemblyBindResult bindResult; Exception exception; if (!binder.Bind(rawAssembly, pdbSymbolStore, out bindResult, out exception)) { if (exception != null) throw exception; else throw new BadImageFormatException(); } RuntimeAssembly result = null; GetNativeFormatRuntimeAssembly(bindResult, ref result); if (result != null) return result; GetEcmaRuntimeAssembly(bindResult, ref result); if (result != null) return result; else throw new PlatformNotSupportedException(); } /// <summary> /// Returns null if no assembly matches the assemblyRefName. Throws for other error cases. /// </summary> internal static RuntimeAssembly GetRuntimeAssemblyIfExists(RuntimeAssemblyName assemblyRefName) { return s_assemblyRefNameToAssemblyDispenser.GetOrAdd(assemblyRefName); } internal static Exception TryGetRuntimeAssembly(RuntimeAssemblyName assemblyRefName, out RuntimeAssembly result) { result = GetRuntimeAssemblyIfExists(assemblyRefName); if (result != null) return null; else return new FileNotFoundException(SR.Format(SR.FileNotFound_AssemblyNotFound, assemblyRefName.FullName)); } private static readonly Dispenser<RuntimeAssemblyName, RuntimeAssembly> s_assemblyRefNameToAssemblyDispenser = DispenserFactory.CreateDispenser<RuntimeAssemblyName, RuntimeAssembly>( DispenserScenario.AssemblyRefName_Assembly, delegate (RuntimeAssemblyName assemblyRefName) { AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder; AssemblyName convertedAssemblyRefName = assemblyRefName.ToAssemblyName(); AssemblyBindResult bindResult; Exception exception; if (!binder.Bind(convertedAssemblyRefName, out bindResult, out exception)) return null; RuntimeAssembly result = null; GetNativeFormatRuntimeAssembly(bindResult, ref result); if (result != null) return result; GetEcmaRuntimeAssembly(bindResult, ref result); if (result != null) return result; return null; } ); // Use C# partial method feature to avoid complex #if logic, whichever code files are included will drive behavior static partial void GetNativeFormatRuntimeAssembly(AssemblyBindResult bindResult, ref RuntimeAssembly runtimeAssembly); static partial void GetEcmaRuntimeAssembly(AssemblyBindResult bindResult, ref RuntimeAssembly runtimeAssembly); } } namespace System.Reflection.Runtime.Modules { //----------------------------------------------------------------------------------------------------------- // Modules (these exist only because Modules still exist in the Win8P surface area. There is a 1-1 // mapping between Assemblies and Modules.) //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeModule { internal static RuntimeModule GetRuntimeModule(RuntimeAssembly assembly) { return new RuntimeModule(assembly); } } } namespace System.Reflection.Runtime.MethodInfos { //----------------------------------------------------------------------------------------------------------- // ConstructorInfos //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimePlainConstructorInfo<TRuntimeMethodCommon> : RuntimeConstructorInfo { internal static RuntimePlainConstructorInfo<TRuntimeMethodCommon> GetRuntimePlainConstructorInfo(TRuntimeMethodCommon common) { return new RuntimePlainConstructorInfo<TRuntimeMethodCommon>(common); } } //----------------------------------------------------------------------------------------------------------- // Constructors for array types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeSyntheticConstructorInfo : RuntimeConstructorInfo { internal static RuntimeSyntheticConstructorInfo GetRuntimeSyntheticConstructorInfo(SyntheticMethodId syntheticMethodId, RuntimeTypeInfo declaringType, RuntimeTypeInfo[] runtimeParameterTypes, InvokerOptions options, Func<Object, Object[], Object> invoker) { return new RuntimeSyntheticConstructorInfo(syntheticMethodId, declaringType, runtimeParameterTypes, options, invoker); } } //----------------------------------------------------------------------------------------------------------- // Nullary constructor for types manufactured by Type.GetTypeFromCLSID(). //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeCLSIDNullaryConstructorInfo : RuntimeConstructorInfo { internal static RuntimeCLSIDNullaryConstructorInfo GetRuntimeCLSIDNullaryConstructorInfo(RuntimeCLSIDTypeInfo declaringType) { return new RuntimeCLSIDNullaryConstructorInfo(declaringType); } } //----------------------------------------------------------------------------------------------------------- // MethodInfos for method definitions (i.e. Foo.Moo() or Foo.Moo<>() but not Foo.Moo<int>) //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeNamedMethodInfo<TRuntimeMethodCommon> { internal static RuntimeNamedMethodInfo<TRuntimeMethodCommon> GetRuntimeNamedMethodInfo(TRuntimeMethodCommon common, RuntimeTypeInfo reflectedType) { RuntimeNamedMethodInfo<TRuntimeMethodCommon> method = new RuntimeNamedMethodInfo<TRuntimeMethodCommon>(common, reflectedType); method.WithDebugName(); return method; } } //----------------------------------------------------------------------------------------------------------- // MethodInfos for constructed generic methods (Foo.Moo<int> but not Foo.Moo<>) //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeConstructedGenericMethodInfo : RuntimeMethodInfo { internal static RuntimeMethodInfo GetRuntimeConstructedGenericMethodInfo(RuntimeNamedMethodInfo genericMethodDefinition, RuntimeTypeInfo[] genericTypeArguments) { return new RuntimeConstructedGenericMethodInfo(genericMethodDefinition, genericTypeArguments).WithDebugName(); } } //----------------------------------------------------------------------------------------------------------- // MethodInfos for the Get/Set methods on array types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeSyntheticMethodInfo : RuntimeMethodInfo { internal static RuntimeMethodInfo GetRuntimeSyntheticMethodInfo(SyntheticMethodId syntheticMethodId, String name, RuntimeTypeInfo declaringType, RuntimeTypeInfo[] runtimeParameterTypes, RuntimeTypeInfo returnType, InvokerOptions options, Func<Object, Object[], Object> invoker) { return new RuntimeSyntheticMethodInfo(syntheticMethodId, name, declaringType, runtimeParameterTypes, returnType, options, invoker).WithDebugName(); } } } namespace System.Reflection.Runtime.ParameterInfos { //----------------------------------------------------------------------------------------------------------- // ParameterInfos for MethodBase objects with no Parameter metadata. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeThinMethodParameterInfo : RuntimeMethodParameterInfo { internal static RuntimeThinMethodParameterInfo GetRuntimeThinMethodParameterInfo(MethodBase member, int position, QSignatureTypeHandle qualifiedParameterType, TypeContext typeContext) { return new RuntimeThinMethodParameterInfo(member, position, qualifiedParameterType, typeContext); } } //----------------------------------------------------------------------------------------------------------- // ParameterInfos returned by PropertyInfo.GetIndexParameters() //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimePropertyIndexParameterInfo : RuntimeParameterInfo { internal static RuntimePropertyIndexParameterInfo GetRuntimePropertyIndexParameterInfo(RuntimePropertyInfo member, RuntimeParameterInfo backingParameter) { return new RuntimePropertyIndexParameterInfo(member, backingParameter); } } //----------------------------------------------------------------------------------------------------------- // ParameterInfos returned by Get/Set methods on array types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeSyntheticParameterInfo : RuntimeParameterInfo { internal static RuntimeSyntheticParameterInfo GetRuntimeSyntheticParameterInfo(MemberInfo member, int position, RuntimeTypeInfo parameterType) { return new RuntimeSyntheticParameterInfo(member, position, parameterType); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Data; using ServiceStack.DataAnnotations; using ServiceStack.OrmLite.Firebird.DbSchema; namespace ServiceStack.OrmLite.Firebird { public class Schema : ISchema<Table, Column, Procedure, Parameter> { private string sqlTables; private StringBuilder sqlColumns = new StringBuilder(); private StringBuilder sqlFieldGenerator = new StringBuilder(); private StringBuilder sqlGenerator = new StringBuilder(); private StringBuilder sqlProcedures = new StringBuilder(); private StringBuilder sqlParameters = new StringBuilder(); public IDbConnection Connection { private get; set; } public Schema() { Init(); } public List<Table> Tables { get { using (IDbCommand dbCmd = Connection.CreateCommand()) { return dbCmd.Select<Table>(sqlTables); } } } public Table GetTable(string name) { string sql = sqlTables + string.Format(" AND a.rdb$relation_name ='{0}' ", name); using (IDbCommand dbCmd = Connection.CreateCommand()) { var query = dbCmd.Select<Table>(sql); return query.FirstOrDefault(); } } public List<Column> GetColumns(string tableName) { string sql = string.Format(sqlColumns.ToString(), string.IsNullOrEmpty(tableName) ? "idx.rdb$relation_name" : string.Format("'{0}'", tableName), string.IsNullOrEmpty(tableName) ? "r.rdb$relation_name" : string.Format("'{0}'", tableName)); using (IDbCommand dbCmd = Connection.CreateCommand()) { List<Column> columns =dbCmd.Select<Column>(sql); List<Generador> gens = dbCmd.Select<Generador>(sqlGenerator.ToString()); sql = string.Format(sqlFieldGenerator.ToString(), string.IsNullOrEmpty(tableName) ? "TRIGGERS.RDB$RELATION_NAME" : string.Format("'{0}'", tableName)); List<FieldGenerator> fg = dbCmd.Select<FieldGenerator>(sql); foreach (var record in columns) { IEnumerable<string> query= from q in fg where q.TableName == record.TableName && q.FieldName == record.Name select q.SequenceName; if (query.Count() == 1) record.Sequence = query.First(); else{ string g = (from gen in gens where gen.Name==tableName+"_"+record.Name+"_GEN" select gen.Name).FirstOrDefault() ; if( !string.IsNullOrEmpty(g) ) record.Sequence=g.Trim(); } } return columns; } } public List<Column> GetColumns(Table table) { return GetColumns(table.Name); } public Procedure GetProcedure(string name) { string sql= sqlProcedures.ToString() + string.Format("WHERE b.rdb$procedure_name ='{0}'", name); using (IDbCommand dbCmd = Connection.CreateCommand()) { var query = dbCmd.Select<Procedure>(sql); return query.FirstOrDefault(); } } public List<Procedure> Procedures { get { using (IDbCommand dbCmd = Connection.CreateCommand()) { return dbCmd.Select<Procedure>(sqlProcedures.ToString()); } } } public List<Parameter> GetParameters(Procedure procedure) { return GetParameters(procedure.Name); } public List<Parameter> GetParameters(string procedureName) { string sql = string.Format(sqlParameters.ToString(), string.IsNullOrEmpty(procedureName) ? "a.rdb$procedure_name" : string.Format("'{0}'", procedureName)); using (IDbCommand dbCmd = Connection.CreateCommand()) { return dbCmd.Select<Parameter>(sql); } } private void Init() { sqlTables = "SELECT \n" + " trim(a.rdb$relation_name) AS name, \n" + " trim(a.rdb$owner_name) AS owner \n" + "FROM \n" + " rdb$relations a \n" + "WHERE\n" + " rdb$system_flag = 0 \n" + " AND rdb$view_blr IS NULL \n"; sqlColumns.Append("SELECT TRIM(r.rdb$field_name) AS field_name, \n"); sqlColumns.Append(" r.rdb$field_position AS field_position, \n"); sqlColumns.Append(" CASE f.rdb$field_type \n"); sqlColumns.Append(" WHEN 261 THEN " + " trim(iif(f.rdb$field_sub_type = 0,'BLOB', 'TEXT')) \n"); sqlColumns.Append(" WHEN 14 THEN trim(iif( cset.rdb$character_set_name='OCTETS'and f.rdb$field_length=16,'GUID', 'CHAR' )) \n"); //CHAR sqlColumns.Append(" WHEN 40 THEN trim('VARCHAR') \n"); //CSTRING sqlColumns.Append(" WHEN 11 THEN trim('FLOAT') \n"); //D_FLOAT sqlColumns.Append(" WHEN 27 THEN trim('DOUBLE') \n"); sqlColumns.Append(" WHEN 10 THEN trim('FLOAT') \n"); sqlColumns.Append(" WHEN 16 THEN trim(Iif(f.rdb$field_sub_type = 0, 'BIGINT', \n"); sqlColumns.Append(" Iif(f.rdb$field_sub_type = 1, 'NUMERIC', 'DECIMAL'))) \n"); sqlColumns.Append(" WHEN 8 THEN trim(Iif(f.rdb$field_sub_type = 0, 'INTEGER', \n"); sqlColumns.Append(" Iif(f.rdb$field_sub_type = 1, 'NUMERIC', 'DECIMAL'))) \n"); sqlColumns.Append(" WHEN 9 THEN trim('BIGINT') \n"); //QUAD sqlColumns.Append(" WHEN 7 THEN trim('SMALLINT') \n"); sqlColumns.Append(" WHEN 12 THEN trim('DATE') \n"); sqlColumns.Append(" WHEN 13 THEN trim('TIME') \n"); sqlColumns.Append(" WHEN 35 THEN trim('TIMESTAMP') \n"); sqlColumns.Append(" WHEN 37 THEN trim('VARCHAR') \n"); sqlColumns.Append(" ELSE trim('UNKNOWN') \n"); sqlColumns.Append(" END AS field_type, \n"); //sqlColumns.Append(" f.rdb$field_sub_type as field_subtype, \n"); sqlColumns.Append(" cast(f.rdb$field_length as smallint) AS field_length, \n"); sqlColumns.Append(" cast(Coalesce(f.rdb$field_precision, -1) as smallint) AS field_precision, \n"); sqlColumns.Append(" cast( Abs(f.rdb$field_scale) as smallint ) AS field_scale, \n"); //sqlColumns.Append(" r.rdb$default_value AS default_value, \n"); sqlColumns.Append(" Iif(Coalesce(r.rdb$null_flag, 0) = 1, 0, 1) AS nullable, \n"); sqlColumns.Append(" Coalesce(r.rdb$description, '') AS DESCRIPTION, \n"); sqlColumns.Append(" TRIM(r.rdb$relation_name) AS tablename, \n"); sqlColumns.Append(" Iif(idxs.constraint_type = 'PRIMARY KEY', 1, 0) AS is_primary_key, \n"); sqlColumns.Append(" Iif(idxs.constraint_type = 'UNIQUE', 1, 0) AS is_unique, \n"); sqlColumns.Append(" cast ('' as varchar(31) ) as SEQUENCE_NAME, \n"); sqlColumns.Append(" iif(R.RDB$UPDATE_FLAG=1,0,1) as IS_COMPUTED \n"); sqlColumns.Append("FROM rdb$relation_fields r \n"); sqlColumns.Append(" LEFT JOIN rdb$fields f \n"); sqlColumns.Append(" ON r.rdb$field_source = f.rdb$field_name \n"); sqlColumns.Append(" LEFT JOIN rdb$character_sets cset \n"); sqlColumns.Append(" ON f.rdb$character_set_id = cset.rdb$character_set_id \n"); sqlColumns.Append(" LEFT JOIN (SELECT DISTINCT rc.rdb$constraint_type AS constraint_type, \n"); sqlColumns.Append(" idxflds.rdb$field_name AS field_name \n"); sqlColumns.Append(" FROM rdb$indices idx \n"); sqlColumns.Append(" LEFT JOIN rdb$relation_constraints rc \n"); sqlColumns.Append(" ON ( idx.rdb$index_name = rc.rdb$index_name ) \n"); sqlColumns.Append(" LEFT JOIN rdb$index_segments idxflds \n"); sqlColumns.Append(" ON ( idx.rdb$index_name = idxflds.rdb$index_name ) \n"); sqlColumns.Append(" WHERE idx.rdb$relation_name = {0} \n"); sqlColumns.Append(" AND rc.rdb$constraint_type IN ( 'PRIMARY KEY', 'UNIQUE' \n"); sqlColumns.Append(" )) \n"); sqlColumns.Append(" idxs \n"); sqlColumns.Append(" ON idxs.field_name = r.rdb$field_name \n"); sqlColumns.Append("WHERE r.rdb$system_flag = '0' \n"); sqlColumns.Append(" AND r.rdb$relation_name = {1} \n"); sqlColumns.Append(" ORDER BY r.rdb$relation_name,r.rdb$field_position \n"); sqlFieldGenerator.Append("SELECT trim(TRIGGERS.RDB$RELATION_NAME) as TableName,"); sqlFieldGenerator.Append("trim(deps.rdb$field_name) AS field_name, \n"); sqlFieldGenerator.Append(" trim(deps2.rdb$depended_on_name) AS sequence_name \n"); sqlFieldGenerator.Append("FROM rdb$triggers triggers \n"); sqlFieldGenerator.Append(" JOIN rdb$dependencies deps \n"); sqlFieldGenerator.Append(" ON deps.rdb$dependent_name = triggers.rdb$trigger_name \n"); sqlFieldGenerator.Append(" AND deps.rdb$depended_on_name = triggers.rdb$relation_name \n"); sqlFieldGenerator.Append(" AND deps.rdb$dependent_type = 2 \n"); sqlFieldGenerator.Append(" AND deps.rdb$depended_on_type = 0 \n"); sqlFieldGenerator.Append(" JOIN rdb$dependencies deps2 \n"); sqlFieldGenerator.Append(" ON deps2.rdb$dependent_name = triggers.rdb$trigger_name \n"); sqlFieldGenerator.Append(" AND deps2.rdb$field_name IS NULL \n"); sqlFieldGenerator.Append(" AND deps2.rdb$dependent_type = 2 \n"); sqlFieldGenerator.Append(" AND deps2.rdb$depended_on_type = 14 \n"); sqlFieldGenerator.Append("WHERE triggers.rdb$system_flag = 0 \n"); sqlFieldGenerator.Append(" AND triggers.rdb$trigger_type = 1 \n"); sqlFieldGenerator.Append(" AND triggers.rdb$trigger_inactive = 0 \n"); sqlFieldGenerator.Append(" AND triggers.rdb$relation_name = {0} "); sqlProcedures.Append("SELECT TRIM(b.rdb$procedure_name) AS name, \n"); sqlProcedures.Append(" TRIM(b.rdb$owner_name) AS owner, \n"); sqlProcedures.Append(" cast(Coalesce(b.rdb$procedure_inputs, 0) as smallint) AS inputs, \n"); sqlProcedures.Append(" cast(Coalesce(b.rdb$procedure_outputs, 0) as smallint) AS outputs \n"); sqlProcedures.Append("FROM rdb$procedures b \n"); sqlParameters.Append("SELECT TRIM(a.rdb$procedure_name) AS procedure_name, \n"); sqlParameters.Append(" TRIM(a.rdb$parameter_name) AS parameter_name, \n"); sqlParameters.Append(" CAST(a.rdb$parameter_number AS SMALLINT) AS parameter_number \n"); sqlParameters.Append(" , \n"); sqlParameters.Append(" CAST(a.rdb$parameter_type AS SMALLINT) AS \n"); sqlParameters.Append(" parameter_type, \n"); sqlParameters.Append(" TRIM(t.rdb$type_name) AS field_type, \n"); sqlParameters.Append(" CAST(b.rdb$field_length AS SMALLINT) AS field_length, \n"); sqlParameters.Append(" CAST(Coalesce(b.rdb$field_precision, -1) AS SMALLINT) AS field_precision, \n"); sqlParameters.Append(" CAST(b.rdb$field_scale AS SMALLINT) AS field_scale \n"); //sqlParameters.Append(" --b.rdb$field_type AS field_type, \n"); //sqlParameters.Append(" --b.rdb$field_sub_type AS field_sub_type, \n"); sqlParameters.Append("FROM rdb$procedure_parameters a \n"); sqlParameters.Append(" JOIN rdb$fields b \n"); sqlParameters.Append(" ON b.rdb$field_name = a.rdb$field_source \n"); sqlParameters.Append(" JOIN rdb$types t \n"); sqlParameters.Append(" ON t.rdb$type = b.rdb$field_type \n"); sqlParameters.Append("WHERE t.rdb$field_name = 'RDB$FIELD_TYPE' \n"); sqlParameters.Append(" AND a.rdb$procedure_name = {0} \n"); sqlParameters.Append("ORDER BY a.rdb$procedure_name, \n"); sqlParameters.Append(" a.rdb$parameter_type, \n"); sqlParameters.Append(" a.rdb$parameter_number "); sqlGenerator.Append("SELECT trim(RDB$GENERATOR_NAME) AS \"Name\" FROM RDB$GENERATORS"); } private class FieldGenerator { [Alias("TABLENAME")] public string TableName { get; set; } [Alias("FIELD_NAME")] public string FieldName { get; set; } [Alias("SEQUENCE_NAME")] public string SequenceName { get; set; } } private class Generador{ public string Name { get; set;} } } } /*ID--0--False--2 -- SMALLINT-- System.Int16-- NAME--1--False--60 -- VARCHAR-- System.String-- PASSWORD--2--False--30 -- VARCHAR-- System.String-- FULL_NAME--3--True--60 -- VARCHAR-- System.String-- COL1--4--False--2 -- VARCHAR-- System.String-- COL2--5--False--2 -- VARCHAR-- System.String-- COL3--6--False--2 -- VARCHAR-- System.String-- COL4--7--True--4 -- NUMERIC-- System.Nullable`1[System.Decimal]-- COL5--8--True--4 -- FLOAT-- System.Nullable`1[System.Single]-- COL6--9--True--4 -- INTEGER-- System.Nullable`1[System.Int32]-- COL7--10--True--8 -- DOUBLE-- System.Nullable`1[System.Double]-- COL8--11--True--8 -- BIGINT-- System.Nullable`1[System.Int64]-- COL9--12--True--4 -- DATE-- System.Nullable`1[System.DateTime]-- COL10--13--True--8 -- TIMESTAMP-- System.Nullable`1[System.DateTime]-- COL11--14--True--8 -- BLOB-- System.Nullable`1[System.Byte][]-- COLNUM--15--True--8 -- NUMERIC-- System.Nullable`1[System.Decimal]-- COLDECIMAL--16--True--8 -- DECIMAL-- System.Nullable`1[System.Decimal]-- -------------------------------------------- Columns for EMPLOYEE: EMP_NO--0--False--2 -- SMALLINT-- System.Int16--EMP_NO_GEN FIRST_NAME--1--False--15 -- VARCHAR-- System.String-- LAST_NAME--2--False--20 -- VARCHAR-- System.String-- PHONE_EXT--3--True--4 -- VARCHAR-- System.String-- HIRE_DATE--4--False--8 -- TIMESTAMP-- System.DateTime-- DEPT_NO--5--False--3 -- CHAR-- System.String-- JOB_CODE--6--False--5 -- VARCHAR-- System.String-- JOB_GRADE--7--False--2 -- SMALLINT-- System.Int16-- JOB_COUNTRY--8--False--15 -- VARCHAR-- System.String-- SALARY--9--False--8 -- NUMERIC-- System.Decimal-- FULL_NAME--10--True--37 -- VARCHAR-- System.String-- Caculado !!!!! Computed True ID--0--False--4 -- INTEGER-- System.Int32--COMPANY_ID_GEN NAME--1--True--100 -- VARCHAR-- System.String-- TURNOVER--2--True--4 -- FLOAT-- System.Nullable`1[System.Single]-- STARTED--3--True--4 -- DATE-- System.Nullable`1[System.DateTime]-- EMPLOYEES--4--True--4 -- INTEGER-- System.Nullable`1[System.Int32]-- CREATED_DATE--5--True--8 -- TIMESTAMP-- System.Nullable`1[System.DateTime]-- GUID--6--True--16 -- GUID-- System.Nullable`1[System.Guid]-- * * * */
// // OciLobLocator.cs // // Part of managed C#/.NET library System.Data.OracleClient.dll // // Part of the Mono class libraries at // mcs/class/System.Data.OracleClient/System.Data.OracleClient.Oci // // Assembly: System.Data.OracleClient.dll // Namespace: System.Data.OracleClient.Oci // // Author: // Tim Coleman <tim@timcoleman.com> // // Copyright (C) Tim Coleman, 2003 // using System; using System.Data.OracleClient; using System.Runtime.InteropServices; namespace System.Data.OracleClient.Oci { internal sealed class OciLobLocator : OciDescriptorHandle, IDisposable { #region Fields bool disposed = false; OciErrorHandle errorHandle; OciServiceHandle service; OciDataType type; #endregion // Fields #region Constructors public OciLobLocator (OciHandle parent, IntPtr handle) : base (OciHandleType.LobLocator, parent, handle) { } #endregion // Constructors #region Properties public OciErrorHandle ErrorHandle { get { return errorHandle; } set { errorHandle = value; } } public OciServiceHandle Service { get { return service; } set { service = value; } } public OciDataType LobType { get { return type; } set { type = value; } } #endregion // Properties #region Methods public void BeginBatch (OracleLobOpenMode mode) { int status = 0; status = OciCalls.OCILobOpen (Service, ErrorHandle, Handle, (byte) mode); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } } public uint Copy (OciLobLocator destination, uint amount, uint destinationOffset, uint sourceOffset) { OciCalls.OCILobCopy (Service, ErrorHandle, destination, Handle, amount, destinationOffset, sourceOffset); return amount; } protected override void Dispose (bool disposing) { if (!disposed) { disposed = true; base.Dispose (); } } public void EndBatch () { int status = 0; status = OciCalls.OCILobClose (Service, ErrorHandle, this); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } } public uint Erase (uint offset, uint amount) { int status = 0; uint output = amount; status = OciCalls.OCILobErase (Service, ErrorHandle, this, ref output, (uint) offset); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } return output; } public int GetChunkSize () { int status = 0; uint output; status = OciCalls.OCILobGetChunkSize (Service, ErrorHandle, this, out output); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } return (int) output; } public long GetLength (bool binary) { int status = 0; uint output; status = OciCalls.OCILobGetLength (Service, ErrorHandle, this, out output); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } if (!binary) output *= 2; return (long) output; } public int Read (byte[] buffer, uint offset, uint count, bool binary) { int status = 0; uint amount = count; // Character types are UTF-16, so amount of characters is 1/2 // the amount of bytes if (!binary) amount /= 2; status = OciCalls.OCILobRead (Service, ErrorHandle, this, ref amount, offset, buffer, count, IntPtr.Zero, IntPtr.Zero, 1000, // OCI_UCS2ID 0); // Ignored if csid is specified as above if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } return (int) amount; } public void Trim (uint newlen) { int status = 0; status = OciCalls.OCILobTrim (Service, ErrorHandle, this, newlen); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } } public int Write (byte[] buffer, uint offset, uint count, OracleType type) { int status = 0; uint amount = count; if (type == OracleType.Clob) amount /= 2; status = OciCalls.OCILobWrite (Service, ErrorHandle, this, ref amount, offset, buffer, count, 0, // OCI_ONE_PIECE IntPtr.Zero, IntPtr.Zero, 1000, // OCI_UCS2ID 0); if (status != 0) { OciErrorInfo info = ErrorHandle.HandleError (); throw new OracleException (info.ErrorCode, info.ErrorMessage); } return (int) amount; } #endregion // Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using TestSupport; using Xunit; using SL = SortedList_SortedListUtils; using SortedList_ICollection; using TestSupport.Common_TestSupport; using TestSupport.Collections.Common_GenericICollectionTest; using TestSupport.Collections.SortedList_GenericICollectionTest; using TestSupport.Collections.SortedList_GenericIEnumerableTest; namespace SortedListValues { public class Driver<KeyType, ValueType> { private Test m_test; public Driver(Test test) { m_test = test; } public void TestVanilla(KeyType[] keys, ValueType[] values) { SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>(); for (int i = 0; i < keys.Length - 1; i++) _dic.Add(keys[i], values[i]); ICollection<ValueType> _col = _dic.Values; m_test.Eval(_col.Count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", _col.Count)); IEnumerator<ValueType> _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue(_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_enum.Current))); count++; } m_test.Eval(count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", count)); ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < values.Length - 1; i++) m_test.Eval(_dic.ContainsValue(_values[i]), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_values[i]))); count = 0; foreach (ValueType currValue in _dic.Values) { m_test.Eval(_dic.ContainsValue(currValue), String.Format("Err_53497gs! Not equal {0}", _dic.ContainsValue(currValue))); count++; } m_test.Eval(count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", count)); try { //The behavior here is undefined as long as we don't AV were fine ValueType item = _enum.Current; } catch (Exception) { } if (keys.Length > 0) { _dic.Add(keys[keys.Length - 1], values[values.Length - 1]); try { _enum.MoveNext(); m_test.Eval(false, "Expected InvalidOperationException, but got no exception."); } catch (InvalidOperationException) { } catch (Exception E) { m_test.Eval(false, "Expected InvalidOperationException, but got unknown exception: " + E); } } } public void TestModify(KeyType[] keys, ValueType[] values, ValueType[] newValues) { SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>(); for (int i = 0; i < keys.Length; i++) _dic.Add(keys[i], values[i]); ICollection<ValueType> _col = _dic.Values; for (int i = 0; i < keys.Length; i++) _dic.Remove(keys[i]); m_test.Eval(_col.Count == 0, String.Format("Err_3497gs! Not equal {0}", _col.Count)); IEnumerator<ValueType> _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue(_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_enum.Current))); count++; } m_test.Eval(count == 0, String.Format("Err_3497gs! Not equal {0}", count)); for (int i = 0; i < keys.Length; i++) _dic[keys[i]] = newValues[i]; m_test.Eval(_col.Count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", _col.Count)); _enum = _col.GetEnumerator(); count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue(_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_enum.Current))); count++; } m_test.Eval(count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", count)); ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length; i++) m_test.Eval(_dic.ContainsValue(_values[i]), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_values[i]))); } public void NonGenericIDictionaryTestVanilla(KeyType[] keys, ValueType[] values) { SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>(); IDictionary _idic = _dic; for (int i = 0; i < keys.Length - 1; i++) _dic.Add(keys[i], values[i]); ICollection _col = _idic.Values; m_test.Eval(_col.Count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", _col.Count)); IEnumerator _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue((ValueType)_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue((ValueType)_enum.Current))); count++; } m_test.Eval(count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", count)); ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length - 1; i++) m_test.Eval(_dic.ContainsValue(_values[i]), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_values[i]))); _enum.Reset(); count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue((ValueType)_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue((ValueType)_enum.Current))); count++; } m_test.Eval(count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", count)); _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length - 1; i++) m_test.Eval(_dic.ContainsValue(_values[i]), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_values[i]))); try { _dic.ContainsValue((ValueType)_enum.Current); m_test.Eval(false, "Expected InvalidOperationException, but got no exception."); } catch (InvalidOperationException) { } catch (Exception E) { m_test.Eval(false, "Expected InvalidOperationException, but got unknown exception: " + E); } if (keys.Length > 0) { _dic.Add(keys[keys.Length - 1], values[values.Length - 1]); try { _enum.MoveNext(); m_test.Eval(false, "Expected InvalidOperationException, but got no exception."); } catch (InvalidOperationException) { } catch (Exception E) { m_test.Eval(false, "Expected InvalidOperationException, but got unknown exception: " + E); } try { _enum.Reset(); m_test.Eval(false, "Expected InvalidOperationException, but got no exception."); } catch (InvalidOperationException) { } catch (Exception E) { m_test.Eval(false, "Expected InvalidOperationException, but got unknown exception: " + E); } } } public void NonGenericIDictionaryTestModify(KeyType[] keys, ValueType[] values, ValueType[] newValues) { SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>(); IDictionary _idic = _dic; for (int i = 0; i < keys.Length; i++) _dic.Add(keys[i], values[i]); ICollection _col = _idic.Values; for (int i = 0; i < keys.Length; i++) _dic.Remove(keys[i]); m_test.Eval(_col.Count == 0, String.Format("Err_3497gs! Not equal {0}", _col.Count)); IEnumerator _enum = _col.GetEnumerator(); int count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue((ValueType)_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue((ValueType)_enum.Current))); count++; } m_test.Eval(count == 0, String.Format("Err_3497gs! Not equal {0}", count)); for (int i = 0; i < keys.Length; i++) _dic[keys[i]] = newValues[i]; m_test.Eval(_col.Count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", _col.Count)); _enum = _col.GetEnumerator(); count = 0; while (_enum.MoveNext()) { m_test.Eval(_dic.ContainsValue((ValueType)_enum.Current), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue((ValueType)_enum.Current))); count++; } m_test.Eval(count == _dic.Count, String.Format("Err_3497gs! Not equal {0}", count)); ValueType[] _values = new ValueType[_dic.Count]; _col.CopyTo(_values, 0); for (int i = 0; i < keys.Length; i++) m_test.Eval(_dic.ContainsValue(_values[i]), String.Format("Err_3497gs! Not equal {0}", _dic.ContainsValue(_values[i]))); } public void TestVanillaIListReturned(KeyType[] keys, ValueType[] values, ValueType valueNotInList) { SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>(); IList<ValueType> _ilist; for (int i = 0; i < keys.Length; i++) _dic.Add(keys[i], values[i]); _ilist = _dic.Values; //IsReadOnly m_test.Eval(_ilist.IsReadOnly == true, "Expected IsReadOnly of IList of Values to be true, but found " + _ilist.IsReadOnly); //This get for (int i = 0; i < values.Length; i++) { m_test.Eval(Array.IndexOf(values, _ilist[i]) != -1, "This get: Expected This at " + i + " to be found in original array , but it was not"); } try { Console.WriteLine(_ilist[-1]); m_test.Eval(false, "This get: Expected ArgumentOutOfRangeException, but found value of " + _ilist[-1]); } catch (ArgumentOutOfRangeException) { } catch (Exception E) { m_test.Eval(false, "This get: Expected ArgumentOutOfRangeException, but found " + E); } try { Console.WriteLine(_ilist[values.Length]); m_test.Eval(false, "This get: Expected ArgumentOutOfRangeException, but found value of " + _ilist[values.Length]); } catch (ArgumentOutOfRangeException) { } catch (Exception E) { m_test.Eval(false, "This get: Expected ArgumentOutOfRangeException, but found " + E); } //Add try { _ilist.Add(values[values.Length - 1]); m_test.Eval(false, "Add: Expected NotSupportedException, but was able to Add a value with no key"); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "Add: Expected NotSupportedException, but found " + E); } //Clear try { _ilist.Clear(); m_test.Eval(false, "Clear: Expected NotSupportedException, but was able to Clear a value list"); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "Clear: Expected NotSupportedException, but found " + E); } //Contains for (int i = 0; i < values.Length; i++) { m_test.Eval(_ilist.Contains(values[i]), "Contains: Expected Contains of item " + i + " with value " + values[i] + " to return true, but found false"); } //IndexOf for (int i = 0; i < values.Length; i++) { m_test.Eval(_ilist.IndexOf(values[i]) < values.Length && _ilist.IndexOf(values[i]) >= 0, "IndexOf: Expected IndexOf of item " + i + " with value " + values[i] + " to return something within the allowed length but found " + _ilist.IndexOf(values[i])); } m_test.Eval(_ilist.IndexOf(valueNotInList) == -1, "IndexOf: Expected IndexOf of item not in list, " + valueNotInList + " to return -1, but found " + _ilist.IndexOf(valueNotInList)); //Insert try { _ilist.Insert(0, values[values.Length - 1]); m_test.Eval(false, "Insert: Expected NotSupportedException, but was able to Insert a value with no key"); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "Insert: Expected NotSupportedException, but found " + E); } //Remove try { _ilist.Remove(values[values.Length - 1]); m_test.Eval(false, "Remove: Expected NotSupportedException, but was able to Insert a value with no key"); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "Remove: Expected NotSupportedException, but found " + E); } //RemoveAt try { _ilist.RemoveAt(0); m_test.Eval(false, "RemoveAt: Expected NotSupportedException, but was able to Insert a value with no key"); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "RemoveAt: Expected NotSupportedException, but found " + E); } //This set try { _ilist[values.Length - 1] = values[values.Length - 1]; m_test.Eval(false, "This set: Expected NotSupportedException, but was able to assign via This a value with no key"); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "This set: Expected NotSupportedException, but found " + E); } try { _ilist[-1] = values[values.Length - 1]; m_test.Eval(false, "This set: Expected NotSupportedException, but found value of " + _ilist[-1]); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "This set: Expected NotSupportedException, but found " + E); } try { _ilist[values.Length] = values[values.Length - 1]; m_test.Eval(false, "This set: Expected NotSupportedException, but found value of " + _ilist[values.Length]); } catch (NotSupportedException) { } catch (Exception E) { m_test.Eval(false, "This set: Expected NotSupportedException, but found " + E); } } public void TestVanillaICollectionReturned(KeyType[] keys, ValueType[] values) { SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>(); ValueType[] arrayToCheck = new ValueType[keys.Length]; for (int i = 0; i < keys.Length; i++) { arrayToCheck[i] = values[i]; _dic.Add(keys[i], values[i]); } Array.Sort(arrayToCheck); var tester = new ICollectionTester<ValueType>(); tester.RunTest(m_test, ((IDictionary)_dic).Values, keys.Length, false, ((IDictionary)_dic).SyncRoot, arrayToCheck); } public bool VerifyICollection_T(GenerateItem<KeyType> keyGenerator, GenerateItem<ValueType> valueGenerator, int numItems) { Dictionary<KeyType, ValueType> d = new Dictionary<KeyType, ValueType>(); ValueType[] values = new ValueType[numItems]; TestSupport.Collections.SortedList_GenericICollectionTest.ICollection_T_Test<ValueType> iCollectionTest; bool retValue = true; for (int i = 0; i < numItems; ++i) { values[i] = valueGenerator(); d.Add(keyGenerator(), values[i]); } iCollectionTest = new TestSupport.Collections.SortedList_GenericICollectionTest.ICollection_T_Test<ValueType>(m_test, d.Values, valueGenerator, values, true); iCollectionTest.CollectionOrder = TestSupport.CollectionOrder.Unspecified; retValue &= m_test.Eval(iCollectionTest.RunAllTests(), "Err_98382apeuie System.Collections.Generic.ICollection<ValueType> tests FAILED"); return retValue; } } // public delegate T GenerateItem<T>(); public class get_Values { public class IntGenerator { private int _index; public IntGenerator() { _index = 0; } public int NextValue() { return _index++; } public Object NextValueObject() { return (Object)NextValue(); } } public class StringGenerator { private int _index; public StringGenerator() { _index = 0; } public String NextValue() { return (_index++).ToString(); } public Object NextValueObject() { return (Object)NextValue(); } } [Fact] public static void RunTests() { Test test = new Test(); IntGenerator intGenerator = new IntGenerator(); StringGenerator stringGenerator = new StringGenerator(); intGenerator.NextValue(); stringGenerator.NextValue(); //This mostly follows the format established by the original author of these tests //Scenario 1: Vanilla - fill in an SortedList with 10 keys and check this property Driver<int, int> IntDriver = new Driver<int, int>(test); Driver<SL.SimpleRef<String>, SL.SimpleRef<String>> simpleRef = new Driver<SL.SimpleRef<String>, SL.SimpleRef<String>>(test); Driver<SL.SimpleRef<int>, SL.SimpleRef<int>> simpleVal = new Driver<SL.SimpleRef<int>, SL.SimpleRef<int>>(test); SL.SimpleRef<int>[] simpleInts; SL.SimpleRef<String>[] simpleStrings; int[] ints; int count; count = 100; simpleInts = SL.SortedListUtils.GetSimpleInts(count); simpleStrings = SL.SortedListUtils.GetSimpleStrings(count); ints = new int[count]; for (int i = 0; i < count; i++) ints[i] = i; IntDriver.TestVanilla(ints, ints); simpleRef.TestVanilla(simpleStrings, simpleStrings); simpleVal.TestVanilla(simpleInts, simpleInts); IntDriver.NonGenericIDictionaryTestVanilla(ints, ints); simpleRef.NonGenericIDictionaryTestVanilla(simpleStrings, simpleStrings); simpleVal.NonGenericIDictionaryTestVanilla(simpleInts, simpleInts); IntDriver.TestVanillaIListReturned(ints, ints, -1); simpleRef.TestVanillaIListReturned(simpleStrings, simpleStrings, new SL.SimpleRef<string>("bozo")); simpleVal.TestVanillaIListReturned(simpleInts, simpleInts, new SL.SimpleRef<int>(-1)); IntDriver.TestVanillaICollectionReturned(ints, ints); simpleRef.TestVanillaICollectionReturned(simpleStrings, simpleStrings); simpleVal.TestVanillaICollectionReturned(simpleInts, simpleInts); //Scenario 2: Check for an empty SortedList IntDriver.TestVanilla(new int[0], new int[0]); simpleRef.TestVanilla(new SL.SimpleRef<String>[0], new SL.SimpleRef<String>[0]); simpleVal.TestVanilla(new SL.SimpleRef<int>[0], new SL.SimpleRef<int>[0]); IntDriver.NonGenericIDictionaryTestVanilla(new int[0], new int[0]); simpleRef.NonGenericIDictionaryTestVanilla(new SL.SimpleRef<String>[0], new SL.SimpleRef<String>[0]); simpleVal.NonGenericIDictionaryTestVanilla(new SL.SimpleRef<int>[0], new SL.SimpleRef<int>[0]); //Scenario 3: Check the underlying reference. Change the SortedList afterwards and examine ICollection keys and make sure that the //change is reflected SL.SimpleRef<int>[] simpleInts_1; SL.SimpleRef<String>[] simpleStrings_1; int[] ints_1; SL.SimpleRef<int>[] simpleInts_2; SL.SimpleRef<String>[] simpleStrings_2; int[] ints_2; int half = count / 2; simpleInts_1 = new SL.SimpleRef<int>[half]; simpleStrings_1 = new SL.SimpleRef<String>[half]; ints_2 = new int[half]; simpleInts_2 = new SL.SimpleRef<int>[half]; simpleStrings_2 = new SL.SimpleRef<String>[half]; ints_1 = new int[half]; for (int i = 0; i < half; i++) { simpleInts_1[i] = simpleInts[i]; simpleStrings_1[i] = simpleStrings[i]; ints_1[i] = ints[i]; simpleInts_2[i] = simpleInts[i + half]; simpleStrings_2[i] = simpleStrings[i + half]; ints_2[i] = ints[i + half]; } IntDriver.TestModify(ints_1, ints_1, ints_2); simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2); simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2); IntDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2); simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2); simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2); //Scenario 4: Change keys via ICollection (how?) and examine SortedList //How indeed? //Verify ICollection<V> through ICollection testing suite Driver<int, string> intStringDriver = new Driver<int, string>(test); Driver<string, int> stringIntDriver = new Driver<string, int>(test); test.Eval(intStringDriver.VerifyICollection_T(new GenerateItem<int>(intGenerator.NextValue), new GenerateItem<string>(stringGenerator.NextValue), 0), "Err_085184aehdke Test Int32, String Empty Dictionary FAILED\n"); test.Eval(intStringDriver.VerifyICollection_T(new GenerateItem<int>(intGenerator.NextValue), new GenerateItem<string>(stringGenerator.NextValue), 1), "Err_05164anhekjd Test Int32, String Dictionary with 1 item FAILED\n"); test.Eval(intStringDriver.VerifyICollection_T(new GenerateItem<int>(intGenerator.NextValue), new GenerateItem<string>(stringGenerator.NextValue), 16), "Err_1088ajeid Test Int32, String Dictionary with 16 items FAILED\n"); test.Eval(stringIntDriver.VerifyICollection_T(new GenerateItem<string>(stringGenerator.NextValue), new GenerateItem<int>(intGenerator.NextValue), 0), "Err_31288ajkekd Test String, Int32 Empty Dictionary FAILED\n"); test.Eval(stringIntDriver.VerifyICollection_T(new GenerateItem<string>(stringGenerator.NextValue), new GenerateItem<int>(intGenerator.NextValue), 1), "Err_0215548aheuid Test String, Int32 Dictionary with 1 item FAILED\n"); test.Eval(stringIntDriver.VerifyICollection_T(new GenerateItem<string>(stringGenerator.NextValue), new GenerateItem<int>(intGenerator.NextValue), 16), "Err_21057ajeipzd Test String, Int32 Dictionary with 16 items FAILED\n"); Assert.True(test.Pass); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Runtime; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Runtime.ConsistentRing; using Orleans.Runtime.Counters; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.LogConsistency; using Orleans.Runtime.Messaging; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Runtime.Providers; using Orleans.Runtime.ReminderService; using Orleans.Runtime.Scheduler; using Orleans.Services; using Orleans.Streams; using Orleans.Transactions; using Orleans.Runtime.Versions; using Orleans.Versions; using Orleans.ApplicationParts; using Orleans.Configuration; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// Orleans silo. /// </summary> public class Silo { /// <summary> Standard name for Primary silo. </summary> public const string PrimarySiloName = "Primary"; /// <summary> Silo Types. </summary> public enum SiloType { /// <summary> No silo type specified. </summary> None = 0, /// <summary> Primary silo. </summary> Primary, /// <summary> Secondary silo. </summary> Secondary, } private readonly ILocalSiloDetails siloDetails; private readonly ClusterOptions clusterOptions; private readonly ISiloMessageCenter messageCenter; private readonly OrleansTaskScheduler scheduler; private readonly LocalGrainDirectory localGrainDirectory; private readonly ActivationDirectory activationDirectory; private readonly IncomingMessageAgent incomingAgent; private readonly IncomingMessageAgent incomingSystemAgent; private readonly IncomingMessageAgent incomingPingAgent; private readonly ILogger logger; private TypeManager typeManager; private readonly TaskCompletionSource<int> siloTerminatedTask = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); private readonly SiloStatisticsManager siloStatistics; private readonly InsideRuntimeClient runtimeClient; private IReminderService reminderService; private SystemTarget fallbackScheduler; private readonly IMembershipOracle membershipOracle; private readonly IMultiClusterOracle multiClusterOracle; private readonly ExecutorService executorService; private Watchdog platformWatchdog; private readonly TimeSpan initTimeout; private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1); private readonly Catalog catalog; private readonly List<IHealthCheckParticipant> healthCheckParticipants = new List<IHealthCheckParticipant>(); private readonly object lockable = new object(); private readonly GrainFactory grainFactory; private readonly ISiloLifecycleSubject siloLifecycle; private List<GrainService> grainServices = new List<GrainService>(); private readonly ILoggerFactory loggerFactory; /// <summary> /// Gets the type of this /// </summary> internal string Name => this.siloDetails.Name; internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } } internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } } internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } } internal IConsistentRingProvider RingProvider { get; private set; } internal ICatalog Catalog => catalog; internal SystemStatus SystemStatus { get; set; } internal IServiceProvider Services { get; } /// <summary> SiloAddress for this silo. </summary> public SiloAddress SiloAddress => this.siloDetails.SiloAddress; /// <summary> /// Silo termination event used to signal shutdown of this silo. /// </summary> public WaitHandle SiloTerminatedEvent // one event for all types of termination (shutdown, stop and fast kill). => ((IAsyncResult)this.siloTerminatedTask.Task).AsyncWaitHandle; public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill). private SchedulingContext membershipOracleContext; private SchedulingContext multiClusterOracleContext; private SchedulingContext reminderServiceContext; private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget; /// <summary> /// Initializes a new instance of the <see cref="Silo"/> class. /// </summary> /// <param name="siloDetails">The silo initialization parameters</param> /// <param name="services">Dependency Injection container</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")] public Silo(ILocalSiloDetails siloDetails, IServiceProvider services) { string name = siloDetails.Name; // Temporarily still require this. Hopefuly gone when 2.0 is released. this.siloDetails = siloDetails; this.SystemStatus = SystemStatus.Creating; AsynchAgent.IsStarting = true; // todo. use ISiloLifecycle instead? var startTime = DateTime.UtcNow; IOptions<SiloStatisticsOptions> statisticsOptions = services.GetRequiredService<IOptions<SiloStatisticsOptions>>(); StatisticsCollector.Initialize(statisticsOptions.Value.CollectionLevel); IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>(); initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime; if (Debugger.IsAttached) { initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime); stopTimeout = initTimeout; } var localEndpoint = this.siloDetails.SiloAddress.Endpoint; services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>()); this.Services = services; this.Services.InitializeSiloUnobservedExceptionsHandler(); //set PropagateActivityId flag from node config IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>(); RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId; this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>(); logger = this.loggerFactory.CreateLogger<Silo>(); logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode)); if (!GCSettings.IsServerGC) { logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">"); logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines)."); } logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------", this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation); logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name); var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>(); BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value); try { grainFactory = Services.GetRequiredService<GrainFactory>(); } catch (InvalidOperationException exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc); throw; } // Performance metrics siloStatistics = Services.GetRequiredService<SiloStatisticsManager>(); // The scheduler scheduler = Services.GetRequiredService<OrleansTaskScheduler>(); healthCheckParticipants.Add(scheduler); runtimeClient = Services.GetRequiredService<InsideRuntimeClient>(); // Initialize the message center messageCenter = Services.GetRequiredService<MessageCenter>(); var dispatcher = this.Services.GetRequiredService<Dispatcher>(); messageCenter.RerouteHandler = dispatcher.RerouteMessage; messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage; // Now the router/directory service // This has to come after the message center //; note that it then gets injected back into the message center.; localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>(); // Now the activation directory. activationDirectory = Services.GetRequiredService<ActivationDirectory>(); // Now the consistent ring provider RingProvider = Services.GetRequiredService<IConsistentRingProvider>(); catalog = Services.GetRequiredService<Catalog>(); executorService = Services.GetRequiredService<ExecutorService>(); // Now the incoming message agents var messageFactory = this.Services.GetRequiredService<MessageFactory>(); incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory); incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory); incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory); membershipOracle = Services.GetRequiredService<IMembershipOracle>(); this.clusterOptions = Services.GetRequiredService<IOptions<ClusterOptions>>().Value; var multiClusterOptions = Services.GetRequiredService<IOptions<MultiClusterOptions>>().Value; if (!multiClusterOptions.HasMultiClusterNetwork) { logger.Info("Skip multicluster oracle creation (no multicluster network configured)"); } else { multiClusterOracle = Services.GetRequiredService<IMultiClusterOracle>(); } this.SystemStatus = SystemStatus.Created; AsynchAgent.IsStarting = false; StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME, () => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs. this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>(); // register all lifecycle participants IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>(); foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants) { participant?.Participate(this.siloLifecycle); } // register all named lifecycle participants IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>(); foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection ?.GetServices(this.Services) ?.Select(s => s.GetService(this.Services))) { participant?.Participate(this.siloLifecycle); } // add self to lifecycle this.Participate(this.siloLifecycle); logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode()); } public void Start() { StartAsync(CancellationToken.None).GetAwaiter().GetResult(); } public async Task StartAsync(CancellationToken cancellationToken) { StartTaskWithPerfAnalysis("Start Scheduler", scheduler.Start, new Stopwatch()); // SystemTarget for provider init calls this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>(); this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(lifecycleSchedulingSystemTarget); try { await this.scheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext); } catch (Exception exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc); throw; } } private void CreateSystemTargets() { logger.Debug("Creating System Targets for this silo."); logger.Debug("Creating {0} System Target", "SiloControl"); var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services); RegisterSystemTarget(siloControl); logger.Debug("Creating {0} System Target", "ProtocolGateway"); RegisterSystemTarget(new ProtocolGateway(this.SiloAddress, this.loggerFactory)); logger.Debug("Creating {0} System Target", "DeploymentLoadPublisher"); RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>()); logger.Debug("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator"); RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory); RegisterSystemTarget(LocalGrainDirectory.CacheValidator); logger.Debug("Creating {0} System Target", "RemoteClusterGrainDirectory"); RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory); logger.Debug("Creating {0} System Target", "ClientObserverRegistrar + TypeManager"); this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>()); var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); var versionDirectorManager = this.Services.GetRequiredService<CachedVersionSelectorManager>(); var grainTypeManager = this.Services.GetRequiredService<GrainTypeManager>(); IOptions<TypeManagementOptions> typeManagementOptions = this.Services.GetRequiredService<IOptions<TypeManagementOptions>>(); typeManager = new TypeManager(SiloAddress, grainTypeManager, membershipOracle, LocalScheduler, typeManagementOptions.Value.TypeMapRefreshInterval, implicitStreamSubscriberTable, this.grainFactory, versionDirectorManager, this.loggerFactory); this.RegisterSystemTarget(typeManager); logger.Debug("Creating {0} System Target", "MembershipOracle"); if (this.membershipOracle is SystemTarget) { RegisterSystemTarget((SystemTarget)membershipOracle); } if (multiClusterOracle != null && multiClusterOracle is SystemTarget) { logger.Debug("Creating {0} System Target", "MultiClusterOracle"); RegisterSystemTarget((SystemTarget)multiClusterOracle); } var transactionAgent = this.Services.GetRequiredService<ITransactionAgent>() as SystemTarget; if (transactionAgent != null) { logger.Debug("Creating {0} System Target", "TransactionAgent"); RegisterSystemTarget(transactionAgent); } logger.Debug("Finished creating System Targets for this silo."); } private async Task InjectDependencies() { healthCheckParticipants.Add(membershipOracle); catalog.SiloStatusOracle = this.membershipOracle; this.membershipOracle.SubscribeToSiloStatusEvents(localGrainDirectory); messageCenter.SiloDeadOracle = this.membershipOracle.IsDeadSilo; // consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here this.membershipOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider); this.membershipOracle.SubscribeToSiloStatusEvents(typeManager); this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>()); this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<ClientObserverRegistrar>()); var reminderTable = Services.GetService<IReminderTable>(); if (reminderTable != null) { logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}"); // Start the reminder service system target reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory); ; RegisterSystemTarget((SystemTarget)reminderService); } RegisterSystemTarget(catalog); await scheduler.QueueAction(catalog.Start, catalog.SchedulingContext) .WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}"); // SystemTarget for provider init calls this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(fallbackScheduler); } private Task OnRuntimeInitializeStart(CancellationToken ct) { lock (lockable) { if (!this.SystemStatus.Equals(SystemStatus.Created)) throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus)); this.SystemStatus = SystemStatus.Starting; } logger.Info(ErrorCode.SiloStarting, "Silo Start()"); var processExitHandlingOptions = this.Services.GetService<IOptions<ProcessExitHandlingOptions>>().Value; if(processExitHandlingOptions.FastKillOnProcessExit) AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; //TODO: setup thead pool directly to lifecycle StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings", this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew()); return Task.CompletedTask; } private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch) { stopWatch.Restart(); task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch) { stopWatch.Restart(); await task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task OnRuntimeServicesStart(CancellationToken ct) { //TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce var stopWatch = Stopwatch.StartNew(); // The order of these 4 is pretty much arbitrary. StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch); StartTaskWithPerfAnalysis("Start Incoming message agents", IncomingMessageAgentsStart, stopWatch); void IncomingMessageAgentsStart() { incomingPingAgent.Start(); incomingSystemAgent.Start(); incomingAgent.Start(); } StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start,stopWatch); // Set up an execution context for this thread so that the target creation steps can use asynch values. RuntimeContext.InitializeMainThread(); StartTaskWithPerfAnalysis("Init implicit stream subscribe table", InitImplicitStreamSubscribeTable, stopWatch); void InitImplicitStreamSubscribeTable() { // Initialize the implicit stream subscribers table. var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); var grainTypeManager = Services.GetRequiredService<GrainTypeManager>(); implicitStreamSubscriberTable.InitImplicitStreamSubscribers(grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray()); } this.runtimeClient.CurrentStreamProviderRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); // This has to follow the above steps that start the runtime components await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () => { CreateSystemTargets(); return InjectDependencies(); }, stopWatch); // Validate the configuration. // TODO - refactor validation - jbragg //GlobalConfig.Application.ValidateConfiguration(logger); } private async Task OnRuntimeGrainServicesStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); await StartAsyncTaskWithPerfAnalysis("Init transaction agent", InitTransactionAgent, stopWatch); async Task InitTransactionAgent() { ITransactionAgent transactionAgent = this.Services.GetRequiredService<ITransactionAgent>(); ISchedulingContext transactionAgentContext = (transactionAgent as SystemTarget)?.SchedulingContext; await scheduler.QueueTask(transactionAgent.Start, transactionAgentContext) .WithTimeout(initTimeout, $"Starting TransactionAgent failed due to timeout {initTimeout}"); } // Load and init grain services before silo becomes active. await StartAsyncTaskWithPerfAnalysis("Init grain services", () => CreateGrainServices(), stopWatch); this.membershipOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await StartAsyncTaskWithPerfAnalysis("Starting local silo status oracle", StartMembershipOracle, stopWatch); async Task StartMembershipOracle() { await scheduler.QueueTask(() => this.membershipOracle.Start(), this.membershipOracleContext) .WithTimeout(initTimeout, $"Starting MembershipOracle failed due to timeout {initTimeout}"); logger.Debug("Local silo status oracle created successfully."); } var versionStore = Services.GetService<IVersionStore>(); await StartAsyncTaskWithPerfAnalysis("Init type manager", () => scheduler .QueueTask(() => this.typeManager.Initialize(versionStore), this.typeManager.SchedulingContext) .WithTimeout(this.initTimeout, $"TypeManager Initializing failed due to timeout {initTimeout}"), stopWatch); //if running in multi cluster scenario, start the MultiClusterNetwork Oracle if (this.multiClusterOracle != null) { await StartAsyncTaskWithPerfAnalysis("Start multicluster oracle", StartMultiClusterOracle, stopWatch); async Task StartMultiClusterOracle() { logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.", this.clusterOptions.ServiceId, this.clusterOptions.ClusterId); this.multiClusterOracleContext = (multiClusterOracle as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await scheduler.QueueTask(() => multiClusterOracle.Start(), multiClusterOracleContext) .WithTimeout(initTimeout, $"Starting MultiClusterOracle failed due to timeout {initTimeout}"); logger.Debug("multicluster oracle created successfully."); } } try { SiloStatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<SiloStatisticsOptions>>().Value; StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch); logger.Debug("Silo statistics manager started successfully."); // Finally, initialize the deployment load collector, for grains with load-based placement await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch); async Task StartDeploymentLoadCollector() { var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>(); await this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext) .WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}"); logger.Debug("Silo deployment load publisher started successfully."); } // Start background timer tick to watch for platform execution stalls, such as when GC kicks in this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, this.healthCheckParticipants, this.executorService, this.loggerFactory); this.platformWatchdog.Start(); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); } } catch (Exception exc) { this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc)); throw; } if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); } } private async Task OnBecomeActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch); void StartGateway() { // Now that we're active, we can start the gateway var mc = this.messageCenter as MessageCenter; mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>()); logger.Debug("Message gateway service started successfully."); } await StartAsyncTaskWithPerfAnalysis("Starting local silo status oracle", BecomeActive, stopWatch); async Task BecomeActive() { await scheduler.QueueTask(this.membershipOracle.BecomeActive, this.membershipOracleContext) .WithTimeout(initTimeout, $"MembershipOracle activating failed due to timeout {initTimeout}"); logger.Debug("Local silo status oracle became active successfully."); } this.SystemStatus = SystemStatus.Running; } private async Task OnActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); if (this.reminderService != null) { await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch); async Task StartReminderService() { // so, we have the view of the membership in the consistentRingProvider. We can start the reminder service this.reminderServiceContext = (this.reminderService as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await this.scheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext) .WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}"); this.logger.Debug("Reminder service started successfully."); } } foreach (var grainService in grainServices) { await StartGrainService(grainService); } } private async Task CreateGrainServices() { var grainServices = this.Services.GetServices<IGrainService>(); foreach (var grainService in grainServices) { await RegisterGrainService(grainService); } } private async Task RegisterGrainService(IGrainService service) { var grainService = (GrainService)service; RegisterSystemTarget(grainService); grainServices.Add(grainService); await this.scheduler.QueueTask(() => grainService.Init(Services), grainService.SchedulingContext).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} registered successfully."); } private async Task StartGrainService(IGrainService service) { var grainService = (GrainService)service; await this.scheduler.QueueTask(grainService.Start, grainService.SchedulingContext).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} started successfully."); } private void ConfigureThreadPoolAndServicePointSettings() { PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value; if (performanceTuningOptions.MinDotNetThreadPoolSize > 0) { int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads || performanceTuningOptions.MinDotNetThreadPoolSize > completionPortThreads) { // if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value. int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads); int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, completionPortThreads); bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads); if (ok) { logger.Info(ErrorCode.SiloConfiguredThreadPool, "Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } else { logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool, "Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } } } // Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx logger.Info(ErrorCode.SiloConfiguredServicePointManager, "Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.", performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm); ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue; ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit; ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm; } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// Grains are not deactivated. /// </summary> public void Stop() { var cancellationSource = new CancellationTokenSource(); cancellationSource.Cancel(); StopAsync(cancellationSource.Token).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system and the application. /// All grains will be properly deactivated. /// All in-flight applications requests would be awaited and finished gracefully. /// </summary> public void Shutdown() { StopAsync(CancellationToken.None).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// </summary> public async Task StopAsync(CancellationToken cancellationToken) { bool gracefully = !cancellationToken.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; bool stopAlreadyInProgress = false; lock (lockable) { if (this.SystemStatus.Equals(SystemStatus.Stopping) || this.SystemStatus.Equals(SystemStatus.ShuttingDown) || this.SystemStatus.Equals(SystemStatus.Terminated)) { stopAlreadyInProgress = true; // Drop through to wait below } else if (!this.SystemStatus.Equals(SystemStatus.Running)) { throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus)); } else { if (gracefully) this.SystemStatus = SystemStatus.ShuttingDown; else this.SystemStatus = SystemStatus.Stopping; } } if (stopAlreadyInProgress) { logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish"); var pause = TimeSpan.FromSeconds(1); while (!this.SystemStatus.Equals(SystemStatus.Terminated)) { logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause); Thread.Sleep(pause); } await this.siloTerminatedTask.Task; return; } try { await this.scheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext); } finally { SafeExecute(scheduler.Stop); SafeExecute(scheduler.PrintStatistics); } } private Task OnRuntimeServicesStop(CancellationToken cancellationToken) { // Start rejecting all silo to silo application messages SafeExecute(messageCenter.BlockApplicationMessages); // Stop scheduling/executing application turns SafeExecute(scheduler.StopApplicationTurns); // Directory: Speed up directory handoff // will be started automatically when directory receives SiloStatusChangeNotification(Stopping) SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout)); return Task.CompletedTask; } private Task OnRuntimeInitializeStop(CancellationToken ct) { // 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ... logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()"); SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, this.membershipOracleContext) .WaitWithThrow(stopTimeout)); // incoming messages SafeExecute(incomingSystemAgent.Stop); SafeExecute(incomingPingAgent.Stop); SafeExecute(incomingAgent.Stop); // timers if (platformWatchdog != null) SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up SafeExecute(activationDirectory.PrintActivationDirectory); SafeExecute(messageCenter.Stop); SafeExecute(siloStatistics.Stop); SafeExecute(() => this.SystemStatus = SystemStatus.Terminated); SafeExecute(() => (this.Services as IDisposable)?.Dispose()); // Setting the event should be the last thing we do. // Do nothing after that! this.siloTerminatedTask.SetResult(0); return Task.CompletedTask; } private async Task OnBecomeActiveStop(CancellationToken ct) { bool gracefully = !ct.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; try { if (gracefully) { logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()"); // Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone await scheduler.QueueTask(this.membershipOracle.ShutDown, this.membershipOracleContext) .WithTimeout(stopTimeout, $"MembershipOracle Shutting down failed due to timeout {stopTimeout}"); // Deactivate all grains SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout)); } else { logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()"); // Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone await scheduler.QueueTask(this.membershipOracle.Stop, this.membershipOracleContext) .WithTimeout(stopTimeout, $"Stopping MembershipOracle faield due to timeout {stopTimeout}"); } } catch (Exception exc) { logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} membership oracle. About to FastKill this silo.", operation), exc); return; // will go to finally } // Stop the gateway SafeExecute(messageCenter.StopAcceptingClientMessages); } private async Task OnActiveStop(CancellationToken ct) { if (reminderService != null) { // 2: Stop reminder service await scheduler.QueueTask(reminderService.Stop, this.reminderServiceContext) .WithTimeout(stopTimeout, $"Stopping ReminderService failed due to timeout {stopTimeout}"); } foreach (var grainService in grainServices) { await this.scheduler.QueueTask(grainService.Stop, grainService.SchedulingContext).WithTimeout(this.stopTimeout, $"Stopping GrainService failed due to timeout {initTimeout}"); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug(String.Format("{0} Grain Service with Id {1} stopped successfully.", grainService.GetType().FullName, grainService.GetPrimaryKeyLong(out string ignored))); } } } private void SafeExecute(Action action) { Utils.SafeExecute(action, logger, "Silo.Stop"); } private void HandleProcessExit(object sender, EventArgs e) { // NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting"); this.Stop(); } internal void RegisterSystemTarget(SystemTarget target) { var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); providerRuntime.RegisterSystemTarget(target); } /// <summary> Return dump of diagnostic data from this silo. </summary> /// <param name="all"></param> /// <returns>Debug data for this silo.</returns> public string GetDebugDump(bool all = true) { var sb = new StringBuilder(); foreach (var systemTarget in activationDirectory.AllSystemTargets()) sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine(); var enumerator = activationDirectory.GetEnumerator(); while(enumerator.MoveNext()) { Utils.SafeExecute(() => { var activationData = enumerator.Current.Value; var workItemGroup = scheduler.GetWorkItemGroup(activationData.SchedulingContext); if (workItemGroup == null) { sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.", activationData.Grain, activationData.ActivationId); sb.AppendLine(); return; } if (all || activationData.State.Equals(ActivationState.Valid)) { sb.AppendLine(workItemGroup.DumpStatus()); sb.AppendLine(activationData.DumpStatus()); } }); } logger.Info(ErrorCode.SiloDebugDump, sb.ToString()); return sb.ToString(); } /// <summary> Object.ToString override -- summary info for this silo. </summary> public override string ToString() { return localGrainDirectory.ToString(); } private void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct))); } } // A dummy system target for fallback scheduler internal class FallbackSystemTarget : SystemTarget { public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.FallbackSystemTargetId, localSiloDetails.SiloAddress, loggerFactory) { } } // A dummy system target for fallback scheduler internal class LifecycleSchedulingSystemTarget : SystemTarget { public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.LifecycleSchedulingSystemTargetId, localSiloDetails.SiloAddress, loggerFactory) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Maps.Tests.Helpers; using Microsoft.Azure.Management.Maps; using Microsoft.Azure.Management.Maps.Models; using Microsoft.Azure.Management.Resources; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using System.Net; using Xunit; namespace MapsServices.Tests { using System.ComponentModel.DataAnnotations; // aad tenant id: 72f988bf-86f1-41af-91ab-2d7cd011db47 // aad application identity: 26ba1730-4c7c-4099-84b8-ec115a357455 // application key must be generated from: // https://ms.portal.azure.com/#blade/Microsoft_AAD_IAM/ApplicationBlade/appId/26ba1730-4c7c-4099-84b8-ec115a357455/objectId/e0e8b1f6-23dd-40dd-af56-abd89d14fb0d public class MapsServicesAccountTests { [Fact] public void MapsAccountCreateTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group var rgname = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); // prepare account properties string accountName = TestUtilities.GenerateName("maps"); var parameters = MapsManagementTestUtilities.GetDefaultMapsAccountParameters(); // Create account var newAccount = mapsManagementClient.Accounts.CreateOrUpdate(rgname, accountName, parameters); MapsManagementTestUtilities.VerifyAccountProperties(newAccount, true); // now get the account var account = mapsManagementClient.Accounts.Get(rgname, accountName); MapsManagementTestUtilities.VerifyAccountProperties(account, true); // now delete the account mapsManagementClient.Accounts.Delete(rgname, accountName); } } [Fact] public void MapsAccountUpdateTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group var rgname = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); // prepare account properties string accountName = TestUtilities.GenerateName("maps"); var parameters = MapsManagementTestUtilities.GetDefaultMapsAccountParameters(); // create the account var newAccount = mapsManagementClient.Accounts.CreateOrUpdate(rgname, accountName, parameters); MapsManagementTestUtilities.VerifyAccountProperties(newAccount, true); // create new parameters which are almost the same, but have different tags var newParameters = MapsManagementTestUtilities.GetDefaultMapsAccountParameters(); newParameters.Tags = new Dictionary<string, string> { { "key3", "value3" }, { "key4", "value4" } }; newParameters.Sku.Name = MapsManagementTestUtilities.S1SkuName; var updatedAccount = mapsManagementClient.Accounts.CreateOrUpdate(rgname, accountName, newParameters); MapsManagementTestUtilities.VerifyAccountProperties(updatedAccount, false, skuName: MapsManagementTestUtilities.S1SkuName); Assert.NotNull(updatedAccount.Tags); Assert.Equal(2, updatedAccount.Tags.Count); Assert.Equal("value3", updatedAccount.Tags["key3"]); Assert.Equal("value4", updatedAccount.Tags["key4"]); } } [Fact] public void MapsAccountDeleteTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group var rgname = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); // Delete an account which does not exist mapsManagementClient.Accounts.Delete(rgname, "missingaccount"); // prepare account properties var accountName = TestUtilities.GenerateName("maps"); var parameters = MapsManagementTestUtilities.GetDefaultMapsAccountParameters(); // Create account var newAccount = mapsManagementClient.Accounts.CreateOrUpdate(rgname, accountName, parameters); // Delete an account mapsManagementClient.Accounts.Delete(rgname, accountName); // Delete an account which was just deleted mapsManagementClient.Accounts.Delete(rgname, accountName); } } [Fact] public void MapsAccountListByResourceGroupTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group var rgname = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); var accounts = mapsManagementClient.Accounts.ListByResourceGroup(rgname); Assert.Empty(accounts); // Create accounts var accountName1 = MapsManagementTestUtilities.CreateDefaultMapsAccount(mapsManagementClient, rgname); var accountName2 = MapsManagementTestUtilities.CreateDefaultMapsAccount(mapsManagementClient, rgname); accounts = mapsManagementClient.Accounts.ListByResourceGroup(rgname); Assert.Equal(2, accounts.Count()); MapsManagementTestUtilities.VerifyAccountProperties(accounts.First(), true); MapsManagementTestUtilities.VerifyAccountProperties(accounts.Skip(1).First(), true); } } [Fact] public void MapsAccountListBySubscriptionTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group and account var rgname1 = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); var accountName1 = MapsManagementTestUtilities.CreateDefaultMapsAccount(mapsManagementClient, rgname1); // Create different resource group and account var rgname2 = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); var accountName2 = MapsManagementTestUtilities.CreateDefaultMapsAccount(mapsManagementClient, rgname2); var accounts = mapsManagementClient.Accounts.ListBySubscription(); Assert.True(accounts.Count() >= 2); var account1 = accounts.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName1)); MapsManagementTestUtilities.VerifyAccountProperties(account1, true); var account2 = accounts.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName2)); MapsManagementTestUtilities.VerifyAccountProperties(account2, true); } } [Fact] public void MapsAccountListKeysTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group var rgname = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); // Create account var accountName = MapsManagementTestUtilities.CreateDefaultMapsAccount(mapsManagementClient, rgname); // List keys var keys = mapsManagementClient.Accounts.ListKeys(rgname, accountName); Assert.NotNull(keys); // Validate Key1 Assert.NotNull(keys.PrimaryKey); // Validate Key2 Assert.NotNull(keys.SecondaryKey); } } [Fact] public void MapsAccountRegenerateKeyTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (var context = MockContext.Start(this.GetType())) { var resourcesClient = MapsManagementTestUtilities.GetResourceManagementClient(context, handler); var mapsManagementClient = MapsManagementTestUtilities.GetMapsManagementClient(context, handler); // Create resource group var rgname = MapsManagementTestUtilities.CreateResourceGroup(resourcesClient); // Create account var accountName = MapsManagementTestUtilities.CreateDefaultMapsAccount(mapsManagementClient, rgname); // List keys var keys = mapsManagementClient.Accounts.ListKeys(rgname, accountName); Assert.NotNull(keys); var key2 = keys.SecondaryKey; Assert.NotNull(key2); // Regenerate keys and verify that keys change var regenKeys = mapsManagementClient.Accounts.RegenerateKeys(rgname, accountName, new MapsKeySpecification("secondary")); var key2Regen = regenKeys.SecondaryKey; Assert.NotNull(key2Regen); // Validate key was regenerated Assert.NotEqual(key2, key2Regen); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization.Diagnostics.Application; using System.Security; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; #if USE_REFEMIT public class XmlObjectSerializerContext #else internal class XmlObjectSerializerContext #endif { protected XmlObjectSerializer serializer; protected DataContract rootTypeDataContract; internal ScopedKnownTypes scopedKnownTypes = new ScopedKnownTypes(); protected DataContractDictionary serializerKnownDataContracts; bool isSerializerKnownDataContractsSetExplicit; protected IList<Type> serializerKnownTypeList; [Fx.Tag.SecurityNote(Critical = "We base the decision whether to Demand SerializationFormatterPermission on this value.")] [SecurityCritical] bool demandedSerializationFormatterPermission; [Fx.Tag.SecurityNote(Critical = "We base the decision whether to Demand MemberAccess on this value.")] [SecurityCritical] bool demandedMemberAccessPermission; int itemCount; int maxItemsInObjectGraph; StreamingContext streamingContext; bool ignoreExtensionDataObject; DataContractResolver dataContractResolver; KnownTypeDataContractResolver knownTypeResolver; internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject, DataContractResolver dataContractResolver) { this.serializer = serializer; this.itemCount = 1; this.maxItemsInObjectGraph = maxItemsInObjectGraph; this.streamingContext = streamingContext; this.ignoreExtensionDataObject = ignoreExtensionDataObject; this.dataContractResolver = dataContractResolver; } internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : this(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject, null) { } internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : this(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(StreamingContextStates.All), serializer.IgnoreExtensionDataObject, dataContractResolver) { this.rootTypeDataContract = rootTypeDataContract; this.serializerKnownTypeList = serializer.knownTypeList; } internal XmlObjectSerializerContext(NetDataContractSerializer serializer) : this(serializer, serializer.MaxItemsInObjectGraph, serializer.Context, serializer.IgnoreExtensionDataObject) { } internal virtual SerializationMode Mode { get { return SerializationMode.SharedContract; } } internal virtual bool IsGetOnlyCollection { get { return false; } set { } } [Fx.Tag.SecurityNote(Critical = "Demands SerializationFormatter permission. demanding the right permission is critical.", Safe = "No data or control leaks in or out, must be callable from transparent generated IL.")] [SecuritySafeCritical] public void DemandSerializationFormatterPermission() { #if !DISABLE_CAS_USE if (!demandedSerializationFormatterPermission) { Globals.SerializationFormatterPermission.Demand(); demandedSerializationFormatterPermission = true; } #endif } [Fx.Tag.SecurityNote(Critical = "Demands MemberAccess permission. demanding the right permission is critical.", Safe = "No data or control leaks in or out, must be callable from transparent generated IL.")] [SecuritySafeCritical] public void DemandMemberAccessPermission() { #if !DISABLE_CAS_USE if (!demandedMemberAccessPermission) { Globals.MemberAccessPermission.Demand(); demandedMemberAccessPermission = true; } #endif } public StreamingContext GetStreamingContext() { return streamingContext; } static MethodInfo incrementItemCountMethod; internal static MethodInfo IncrementItemCountMethod { get { if (incrementItemCountMethod == null) incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", Globals.ScanAllMembers); return incrementItemCountMethod; } } public void IncrementItemCount(int count) { if (count > maxItemsInObjectGraph - itemCount) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ExceededMaxItemsQuota, maxItemsInObjectGraph))); itemCount += count; } internal int RemainingItemCount { get { return maxItemsInObjectGraph - itemCount; } } internal bool IgnoreExtensionDataObject { get { return ignoreExtensionDataObject; } } protected DataContractResolver DataContractResolver { get { return dataContractResolver; } } protected KnownTypeDataContractResolver KnownTypeResolver { get { if (knownTypeResolver == null) { knownTypeResolver = new KnownTypeDataContractResolver(this); } return knownTypeResolver; } } internal DataContract GetDataContract(Type type) { return GetDataContract(type.TypeHandle, type); } internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { if (IsGetOnlyCollection) { return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(typeHandle), typeHandle, type, Mode); } else { return DataContract.GetDataContract(typeHandle, type, Mode); } } internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { if (IsGetOnlyCollection) { return DataContract.GetGetOnlyCollectionDataContractSkipValidation(typeId, typeHandle, type); } else { return DataContract.GetDataContractSkipValidation(typeId, typeHandle, type); } } internal virtual DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { if (IsGetOnlyCollection) { return DataContract.GetGetOnlyCollectionDataContract(id, typeHandle, null /*type*/, Mode); } else { return DataContract.GetDataContract(id, typeHandle, Mode); } } internal virtual void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (!isMemberTypeSerializable) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TypeNotSerializable, memberType))); } internal virtual Type GetSurrogatedType(Type type) { return type; } DataContractDictionary SerializerKnownDataContracts { get { // This field must be initialized during construction by serializers using data contracts. if (!this.isSerializerKnownDataContractsSetExplicit) { this.serializerKnownDataContracts = serializer.KnownDataContracts; this.isSerializerKnownDataContractsSetExplicit = true; } return this.serializerKnownDataContracts; } } DataContract GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname) { DataContractDictionary serializerKnownDataContracts = this.SerializerKnownDataContracts; if (serializerKnownDataContracts == null) return null; DataContract outDataContract; return serializerKnownDataContracts.TryGetValue(qname, out outDataContract) ? outDataContract : null; } internal static DataContractDictionary GetDataContractsForKnownTypes(IList<Type> knownTypeList) { if (knownTypeList == null) return null; DataContractDictionary dataContracts = new DataContractDictionary(); Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>(); for (int i = 0; i < knownTypeList.Count; i++) { Type knownType = knownTypeList[i]; if (knownType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.NullKnownType, "knownTypes"))); DataContract.CheckAndAdd(knownType, typesChecked, ref dataContracts); } return dataContracts; } internal bool IsKnownType(DataContract dataContract, DataContractDictionary knownDataContracts, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } bool isKnownType = IsKnownType(dataContract, declaredType); if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } return isKnownType; } internal bool IsKnownType(DataContract dataContract, Type declaredType) { DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType); return knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType; } DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) { DataContract dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace); if (dataContract == null) { if (typeName.Name == Globals.SafeSerializationManagerName && typeName.Namespace == Globals.SafeSerializationManagerNamespace && Globals.TypeOfSafeSerializationManager != null) { return GetDataContract(Globals.TypeOfSafeSerializationManager); } dataContract = scopedKnownTypes.GetDataContract(typeName); if (dataContract == null) { dataContract = GetDataContractFromSerializerKnownTypes(typeName); } } return dataContract; } DataContract ResolveDataContractFromDataContractResolver(XmlQualifiedName typeName, Type declaredType) { if (TD.DCResolverResolveIsEnabled()) { TD.DCResolverResolve(typeName.Name + ":" + typeName.Namespace); } Type dataContractType = DataContractResolver.ResolveName(typeName.Name, typeName.Namespace, declaredType, KnownTypeResolver); if (dataContractType == null) { return null; } else { return GetDataContract(dataContractType); } } internal Type ResolveNameFromKnownTypes(XmlQualifiedName typeName) { DataContract dataContract = ResolveDataContractFromKnownTypes(typeName); if (dataContract == null) { return null; } else { return dataContract.OriginalUnderlyingType; } } protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract, Type declaredType) { XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs); DataContract dataContract; if (DataContractResolver == null) { dataContract = ResolveDataContractFromKnownTypes(qname); } else { dataContract = ResolveDataContractFromDataContractResolver(qname, declaredType); } if (dataContract == null) { if (memberTypeContract != null && !memberTypeContract.UnderlyingType.IsInterface && memberTypeContract.StableName == qname) { dataContract = memberTypeContract; } if (dataContract == null && rootTypeDataContract != null) { dataContract = ResolveDataContractFromRootDataContract(qname); } } return dataContract; } protected virtual DataContract ResolveDataContractFromRootDataContract(XmlQualifiedName typeQName) { if (rootTypeDataContract.StableName == typeQName) return rootTypeDataContract; CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract; while (collectionContract != null) { DataContract itemContract = GetDataContract(GetSurrogatedType(collectionContract.ItemType)); if (itemContract.StableName == typeQName) { return itemContract; } collectionContract = itemContract as CollectionDataContract; } return null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { /// <summary> /// Async thin tagger implementation. /// /// Actual tag information is stored in TagSource and shared between multiple taggers created for same views or buffers. /// /// It's responsibility is on interfaction between host and tagger. TagSource has responsibility on how to provide information for this tagger. /// </summary> internal sealed partial class AsynchronousTagger<TTag> : ITagger<TTag>, IDisposable where TTag : ITag { private const int MaxNumberOfRequestedSpans = 100; #region Fields that can be accessed from either thread private readonly ITextBuffer _subjectBuffer; private readonly TagSource<TTag> _tagSource; private readonly int _uiUpdateDelayInMS; #endregion #region Fields that can only be accessed from the foreground thread /// <summary> /// The batch change notifier that we use to throttle update to the UI. /// </summary> private readonly BatchChangeNotifier _batchChangeNotifier; #endregion public event EventHandler<SnapshotSpanEventArgs> TagsChanged; public AsynchronousTagger( IAsynchronousOperationListener listener, IForegroundNotificationService notificationService, TagSource<TTag> tagSource, ITextBuffer subjectBuffer, TimeSpan uiUpdateDelay) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; _uiUpdateDelayInMS = (int)uiUpdateDelay.TotalMilliseconds; _batchChangeNotifier = new BatchChangeNotifier(subjectBuffer, listener, notificationService, ReportChangedSpan); _tagSource = tagSource; _tagSource.OnTaggerAdded(this); _tagSource.TagsChangedForBuffer += OnTagsChangedForBuffer; _tagSource.Paused += OnPaused; _tagSource.Resumed += OnResumed; } public void Dispose() { _tagSource.Resumed -= OnResumed; _tagSource.Paused -= OnPaused; _tagSource.TagsChangedForBuffer -= OnTagsChangedForBuffer; _tagSource.OnTaggerDisposed(this); } private void ReportChangedSpan(SnapshotSpan changeSpan) { var tagsChanged = TagsChanged; if (tagsChanged != null) { tagsChanged(this, new SnapshotSpanEventArgs(changeSpan)); } } private void OnPaused(object sender, EventArgs e) { _batchChangeNotifier.Pause(); } private void OnResumed(object sender, EventArgs e) { _batchChangeNotifier.Resume(); } private void OnTagsChangedForBuffer(object sender, TagsChangedForBufferEventArgs args) { if (args.Buffer != _subjectBuffer) { return; } // Note: This operation is uncancellable. Once we've been notified here, our cached tags // in the tag source are new. If we don't update the UI of the editor then we will end // up in an inconsistent state between us and the editor where we have new tags but the // editor will never know. var spansChanged = args.Spans; _tagSource.RegisterNotification(() => { _tagSource.WorkQueue.AssertIsForeground(); // Now report them back to the UI on the main thread. _batchChangeNotifier.EnqueueChanges(spansChanged.First().Snapshot, spansChanged); }, _uiUpdateDelayInMS, CancellationToken.None); } public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) { if (requestedSpans.Count == 0) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var buffer = requestedSpans.First().Snapshot.TextBuffer; var tags = _tagSource.GetTagIntervalTreeForBuffer(buffer); if (tags == null) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } // Special case the case where there is only one requested span. In that case, we don't // need to allocate any intermediate collections return requestedSpans.Count == 1 ? tags.GetIntersectingSpans(requestedSpans[0]) : requestedSpans.Count < MaxNumberOfRequestedSpans ? GetTagsForSmallNumberOfSpans(requestedSpans, tags) : GetTagsForLargeNumberOfSpans(requestedSpans, tags); } private static IEnumerable<ITagSpan<TTag>> GetTagsForSmallNumberOfSpans( NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { var result = new List<ITagSpan<TTag>>(); foreach (var s in requestedSpans) { result.AddRange(tags.GetIntersectingSpans(s)); } return result; } private static IEnumerable<ITagSpan<TTag>> GetTagsForLargeNumberOfSpans( NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { // we are asked with bunch of spans. rather than asking same question again and again, ask once with big span // which will return superset of what we want. and then filter them out in O(m+n) cost. // m == number of requested spans, n = number of returned spans var mergedSpan = new SnapshotSpan(requestedSpans[0].Start, requestedSpans[requestedSpans.Count - 1].End); var result = tags.GetIntersectingSpans(mergedSpan); int requestIndex = 0; var enumerator = result.GetEnumerator(); try { if (!enumerator.MoveNext()) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var hashSet = new HashSet<ITagSpan<TTag>>(); while (true) { var currentTag = enumerator.Current; var currentRequestSpan = requestedSpans[requestIndex]; var currentTagSpan = currentTag.Span; if (currentRequestSpan.Start > currentTagSpan.End) { if (!enumerator.MoveNext()) { break; } } else if (currentTagSpan.Start > currentRequestSpan.End) { requestIndex++; if (requestIndex >= requestedSpans.Count) { break; } } else { if (currentTagSpan.Length > 0) { hashSet.Add(currentTag); } if (!enumerator.MoveNext()) { break; } } } return hashSet; } finally { enumerator.Dispose(); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Threading; using Teknik.Utilities.Cryptography; namespace Teknik.Configuration { public class Config { private const string _ConfigCacheKey = "ConfigCache"; private const string _ConfigFileName = "Config.json"; private static Config _Config { get; set; } private static string _FileHash { get; set; } private ReaderWriterLockSlim _ConfigRWLock; private ReaderWriterLockSlim _ConfigFileRWLock; private JsonSerializerSettings _JsonSettings; private bool _DevEnvironment; private bool _Migrate; private bool _UseCdn; private string _DbConnection; private string _Title; private string _Description; private string _Author; private string _Host; private string _SupportEmail; private string _NoReplyEmail; private string _BitcoinAddress; private string _Salt1; private string _Salt2; private string _CdnHost; private string _IPBlacklistFile; private string _ReferrerBlacklistFile; private List<string> _PublicKeys; private UserConfig _UserConfig; private ContactConfig _ContactConfig; private EmailConfig _EmailConfig; private GitConfig _GitConfig; private UploadConfig _UploadConfig; private PasteConfig _PasteConfig; private BlogConfig _BlogConfig; private ApiConfig _ApiConfig; private PodcastConfig _PodcastConfig; private StreamConfig _StreamConfig; private ShortenerConfig _ShortenerConfig; private VaultConfig _VaultConfig; private StatsConfig _StatsConfig; private LoggingConfig _LoggingConfig; private PiwikConfig _PiwikConfig; private IRCConfig _IRCConfig; private BillingConfig _BillingConfig; public bool DevEnvironment { get { return _DevEnvironment; } set { _DevEnvironment = value; } } public bool Migrate { get { return _Migrate; } set { _Migrate = value; } } public bool UseCdn { get { return _UseCdn; } set { _UseCdn = value; } } public string DbConnection { get { return _DbConnection; } set { _DbConnection = value; } } // Site Information public string Title { get { return _Title; } set { _Title = value; } } public string Description { get { return _Description; } set { _Description = value; } } public string Author { get { return _Author; } set { _Author = value; } } public string Host { get { return _Host; } set { _Host = value; } } public string SupportEmail { get { return _SupportEmail; } set { _SupportEmail = value; } } public string NoReplyEmail { get { return _NoReplyEmail; } set { _NoReplyEmail = value; } } public string BitcoinAddress { get { return _BitcoinAddress; } set { _BitcoinAddress = value; } } public string Salt1 { get { return _Salt1; } set { _Salt1 = value; } } public string Salt2 { get { return _Salt2; } set { _Salt2 = value; } } public string CdnHost { get { return _CdnHost; } set { _CdnHost = value; } } public string IPBlacklistFile { get { return _IPBlacklistFile;} set { _IPBlacklistFile = value; }} public string ReferrerBlacklistFile { get { return _ReferrerBlacklistFile;} set { _ReferrerBlacklistFile = value; }} public List<string> PublicKeys { get { return _PublicKeys; } set { _PublicKeys = value; } } // User Configuration public UserConfig UserConfig { get { return _UserConfig; } set { _UserConfig = value; } } // Contact Configuration public ContactConfig ContactConfig { get { return _ContactConfig; } set { _ContactConfig = value; } } // Mail Server Configuration public EmailConfig EmailConfig { get { return _EmailConfig; } set { _EmailConfig = value; } } // Git Service Configuration public GitConfig GitConfig { get { return _GitConfig; } set { _GitConfig = value; } } // Blog Configuration public BlogConfig BlogConfig { get { return _BlogConfig; } set { _BlogConfig = value; } } // Upload Configuration public UploadConfig UploadConfig { get { return _UploadConfig; } set { _UploadConfig = value; } } // Paste Configuration public PasteConfig PasteConfig { get { return _PasteConfig; } set { _PasteConfig = value; } } // API Configuration public ApiConfig ApiConfig { get { return _ApiConfig; } set { _ApiConfig = value; } } // Podcast Configuration public PodcastConfig PodcastConfig { get { return _PodcastConfig; } set { _PodcastConfig = value; } } // Stream Configuration public StreamConfig StreamConfig { get { return _StreamConfig; } set { _StreamConfig = value; } } // Shortener Configuration public ShortenerConfig ShortenerConfig { get { return _ShortenerConfig; } set { _ShortenerConfig = value; } } // Vault Configuration public VaultConfig VaultConfig { get { return _VaultConfig; } set { _VaultConfig = value; } } // Status Configuration public StatsConfig StatsConfig { get { return _StatsConfig; } set { _StatsConfig = value; } } // Logging Configuration public LoggingConfig LoggingConfig { get { return _LoggingConfig; } set { _LoggingConfig = value; } } // Piwik Configuration public PiwikConfig PiwikConfig { get { return _PiwikConfig; } set { _PiwikConfig = value; } } // IRC Configuration public IRCConfig IRCConfig { get { return _IRCConfig; } set { _IRCConfig = value; } } // Billing Configuration public BillingConfig BillingConfig { get { return _BillingConfig; } set { _BillingConfig = value; } } public Config() { _ConfigRWLock = new ReaderWriterLockSlim(); _ConfigFileRWLock = new ReaderWriterLockSlim(); _JsonSettings = new JsonSerializerSettings(); _JsonSettings.Formatting = Formatting.Indented; SetDefaults(); } public void SetDefaults() { DevEnvironment = false; Migrate = false; UseCdn = false; Title = string.Empty; Description = string.Empty; Author = string.Empty; Host = string.Empty; SupportEmail = string.Empty; NoReplyEmail = string.Empty; BitcoinAddress = string.Empty; Salt1 = string.Empty; Salt2 = string.Empty; CdnHost = string.Empty; IPBlacklistFile = string.Empty; ReferrerBlacklistFile = string.Empty; PublicKeys = new List<string>(); UserConfig = new UserConfig(); EmailConfig = new EmailConfig(); ContactConfig = new ContactConfig(); GitConfig = new GitConfig(); BlogConfig = new BlogConfig(); UploadConfig = new UploadConfig(); PasteConfig = new PasteConfig(); ApiConfig = new ApiConfig(); PodcastConfig = new PodcastConfig(); StreamConfig = new StreamConfig(); ShortenerConfig = new ShortenerConfig(); VaultConfig = new VaultConfig(); StatsConfig = new StatsConfig(); LoggingConfig = new LoggingConfig(); PiwikConfig = new PiwikConfig(); IRCConfig = new IRCConfig(); BillingConfig = new BillingConfig(); } public static Config Deserialize(string text) { return JsonConvert.DeserializeObject<Config>(text); } public static string Serialize(Config config) { return JsonConvert.SerializeObject(config, Formatting.Indented); } public static Config Load(string path) { string newHash = string.Empty; string fullPath = Path.Combine(path, _ConfigFileName); if (!File.Exists(fullPath)) { Config config = new Config(); Save(fullPath, config); } newHash = MD5.FileHash(fullPath); if (_Config == null || _FileHash == null || newHash != _FileHash) { string configContents = File.ReadAllText(fullPath); _Config = Deserialize(configContents); _FileHash = newHash; } return _Config; } public static void Save(string path, Config config) { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } string configContents = Config.Serialize(config); File.WriteAllText(path, configContents); } } }
// ZlibCodec.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-03 15:40:51> // // ------------------------------------------------------------------ // // This module defines a Codec for ZLIB compression and // decompression. This code extends code that was based the jzlib // implementation of zlib, but this code is completely novel. The codec // class is new, and encapsulates some behaviors that are new, and some // that were present in other classes in the jzlib code base. In // keeping with the license for jzlib, the copyright to the jzlib code // is included below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; using Interop=System.Runtime.InteropServices; namespace Ionic2.Zlib { /// <summary> /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951). /// </summary> /// /// <remarks> /// This class compresses and decompresses data according to the Deflate algorithm /// and optionally, the ZLIB format, as documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>. /// </remarks> [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000D")] [Interop.ComVisible(true)] #if !NETCF [Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)] #endif sealed public class ZlibCodec { /// <summary> /// The buffer from which data is taken. /// </summary> public byte[] InputBuffer; /// <summary> /// An index into the InputBuffer array, indicating where to start reading. /// </summary> public int NextIn; /// <summary> /// The number of bytes available in the InputBuffer, starting at NextIn. /// </summary> /// <remarks> /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesIn; /// <summary> /// Total number of bytes read so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesIn; /// <summary> /// Buffer to store output data. /// </summary> public byte[] OutputBuffer; /// <summary> /// An index into the OutputBuffer array, indicating where to start writing. /// </summary> public int NextOut; /// <summary> /// The number of bytes available in the OutputBuffer, starting at NextOut. /// </summary> /// <remarks> /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesOut; /// <summary> /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesOut; /// <summary> /// used for diagnostics, when something goes wrong! /// </summary> public System.String Message; internal DeflateManager dstate; internal InflateManager istate; internal uint _Adler32; /// <summary> /// The compression level to use in this codec. Useful only in compression mode. /// </summary> public CompressionLevel CompressLevel = CompressionLevel.Default; /// <summary> /// The number of Window Bits to use. /// </summary> /// <remarks> /// This gauges the size of the sliding window, and hence the /// compression effectiveness as well as memory consumption. It's best to just leave this /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies /// a 32k window. /// </remarks> public int WindowBits = ZlibConstants.WindowBitsDefault; /// <summary> /// The compression strategy to use. /// </summary> /// <remarks> /// This is only effective in compression. The theory offered by ZLIB is that different /// strategies could potentially produce significant differences in compression behavior /// for different data sets. Unfortunately I don't have any good recommendations for how /// to set it differently. When I tested changing the strategy I got minimally different /// compression performance. It's best to leave this property alone if you don't have a /// good feel for it. Or, you may want to produce a test harness that runs through the /// different strategy options and evaluates them on different file types. If you do that, /// let me know your results. /// </remarks> public CompressionStrategy Strategy = CompressionStrategy.Default; /// <summary> /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// </summary> public int Adler32 { get { return (int)_Adler32; } } /// <summary> /// Create a ZlibCodec. /// </summary> /// <remarks> /// If you use this default constructor, you will later have to explicitly call /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress /// or decompress. /// </remarks> public ZlibCodec() { } /// <summary> /// Create a ZlibCodec that either compresses or decompresses. /// </summary> /// <param name="mode"> /// Indicates whether the codec should compress (deflate) or decompress (inflate). /// </param> public ZlibCodec(CompressionMode mode) { if (mode == CompressionMode.Compress) { int rc = InitializeDeflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate."); } else if (mode == CompressionMode.Decompress) { int rc = InitializeInflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); } else throw new ZlibException("Invalid ZlibStreamFlavor."); } /// <summary> /// Initialize the inflation state. /// </summary> /// <remarks> /// It is not necessary to call this before using the ZlibCodec to inflate data; /// It is implicitly called when you call the constructor. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate() { return InitializeInflate(this.WindowBits); } /// <summary> /// Initialize the inflation state with an explicit flag to /// govern the handling of RFC1950 header bytes. /// </summary> /// /// <remarks> /// By default, the ZLIB header defined in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If /// you want to read a zlib stream you should specify true for /// expectRfc1950Header. If you have a deflate stream, you will want to specify /// false. It is only necessary to invoke this initializer explicitly if you /// want to specify false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte /// pair when reading the stream of data to be inflated.</param> /// /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(bool expectRfc1950Header) { return InitializeInflate(this.WindowBits, expectRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for inflation, with the specified number of window bits. /// </summary> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeInflate(int windowBits) { this.WindowBits = windowBits; return InitializeInflate(windowBits, true); } /// <summary> /// Initialize the inflation state with an explicit flag to govern the handling of /// RFC1950 header bytes. /// </summary> /// /// <remarks> /// If you want to read a zlib stream you should specify true for /// expectRfc1950Header. In this case, the library will expect to find a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or /// GZIP stream, which does not have such a header, you will want to specify /// false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading /// the stream of data to be inflated.</param> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(int windowBits, bool expectRfc1950Header) { this.WindowBits = windowBits; if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } /// <summary> /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and /// AvailableBytesOut before calling this method. /// </remarks> /// <example> /// <code> /// private void InflateBuffer() /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec decompressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length); /// MemoryStream ms = new MemoryStream(DecompressedBytes); /// /// int rc = decompressor.InitializeInflate(); /// /// decompressor.InputBuffer = CompressedBytes; /// decompressor.NextIn = 0; /// decompressor.AvailableBytesIn = CompressedBytes.Length; /// /// decompressor.OutputBuffer = buffer; /// /// // pass 1: inflate /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("inflating: " + decompressor.Message); /// /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("inflating: " + decompressor.Message); /// /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// decompressor.EndInflate(); /// } /// /// </code> /// </example> /// <param name="flush">The flush to use when inflating.</param> /// <returns>Z_OK if everything goes well.</returns> public int Inflate(FlushType flush) { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Inflate(flush); } /// <summary> /// Ends an inflation session. /// </summary> /// <remarks> /// Call this after successively calling Inflate(). This will cause all buffers to be flushed. /// After calling this you cannot call Inflate() without a intervening call to one of the /// InitializeInflate() overloads. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int EndInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); int ret = istate.End(); istate = null; return ret; } /// <summary> /// I don't know what this does! /// </summary> /// <returns>Z_OK if everything goes well.</returns> public int SyncInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Sync(); } /// <summary> /// Initialize the ZlibCodec for deflation operation. /// </summary> /// <remarks> /// The codec will use the MAX window bits and the default level of compression. /// </remarks> /// <example> /// <code> /// int bufferSize = 40000; /// byte[] CompressedBytes = new byte[bufferSize]; /// byte[] DecompressedBytes = new byte[bufferSize]; /// /// ZlibCodec compressor = new ZlibCodec(); /// /// compressor.InitializeDeflate(CompressionLevel.Default); /// /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress); /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = compressor.InputBuffer.Length; /// /// compressor.OutputBuffer = CompressedBytes; /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = CompressedBytes.Length; /// /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize) /// { /// compressor.Deflate(FlushType.None); /// } /// /// while (true) /// { /// int rc= compressor.Deflate(FlushType.Finish); /// if (rc == ZlibConstants.Z_STREAM_END) break; /// } /// /// compressor.EndDeflate(); /// /// </code> /// </example> /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns> public int InitializeDeflate() { return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified /// CompressionLevel. It will emit a ZLIB stream as it compresses. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level) { this.CompressLevel = level; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the explicit flag governing whether to emit an RFC1950 header byte pair. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified CompressionLevel. /// If you want to generate a zlib stream, you should specify true for /// wantRfc1950Header. In this case, the library will emit a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header) { this.CompressLevel = level; return _InternalInitializeDeflate(wantRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the specified number of window bits. /// </summary> /// <remarks> /// The codec will use the specified number of window bits and the specified CompressionLevel. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified /// CompressionLevel, the specified number of window bits, and the explicit flag /// governing whether to emit an RFC1950 header byte pair. /// </summary> /// /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(wantRfc1950Header); } private int _InternalInitializeDeflate(bool wantRfc1950Header) { if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy); } /// <summary> /// Deflate one batch of data. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer before calling this method. /// </remarks> /// <example> /// <code> /// private void DeflateBuffer(CompressionLevel level) /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec compressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length); /// MemoryStream ms = new MemoryStream(); /// /// int rc = compressor.InitializeDeflate(level); /// /// compressor.InputBuffer = UncompressedBytes; /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = UncompressedBytes.Length; /// /// compressor.OutputBuffer = buffer; /// /// // pass 1: deflate /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("deflating: " + compressor.Message); /// /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("deflating: " + compressor.Message); /// /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// compressor.EndDeflate(); /// /// ms.Seek(0, SeekOrigin.Begin); /// CompressedBytes = new byte[compressor.TotalBytesOut]; /// ms.Read(CompressedBytes, 0, CompressedBytes.Length); /// } /// </code> /// </example> /// <param name="flush">whether to flush all data as you deflate. Generally you will want to /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to /// flush everything. /// </param> /// <returns>Z_OK if all goes well.</returns> public int Deflate(FlushType flush) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.Deflate(flush); } /// <summary> /// End a deflation session. /// </summary> /// <remarks> /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public int EndDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this) //int ret = dstate.End(); dstate = null; return ZlibConstants.Z_OK; //ret; } /// <summary> /// Reset a codec for another deflation session. /// </summary> /// <remarks> /// Call this to reset the deflation state. For example if a thread is deflating /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first /// block and before the next Deflate(None) of the second block. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public void ResetDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); dstate.Reset(); } /// <summary> /// Set the CompressionStrategy and CompressionLevel for a deflation session. /// </summary> /// <param name="level">the level of compression to use.</param> /// <param name="strategy">the strategy to use for compression.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.SetParams(level, strategy); } /// <summary> /// Set the dictionary to be used for either Inflation or Deflation. /// </summary> /// <param name="dictionary">The dictionary bytes to use.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDictionary(byte[] dictionary) { if (istate != null) return istate.SetDictionary(dictionary); if (dstate != null) return dstate.SetDictionary(dictionary); throw new ZlibException("No Inflate or Deflate state!"); } // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). internal void flush_pending() { int len = dstate.pendingCount; if (len > AvailableBytesOut) len = AvailableBytesOut; if (len == 0) return; if (dstate.pending.Length <= dstate.nextPending || OutputBuffer.Length <= NextOut || dstate.pending.Length < (dstate.nextPending + len) || OutputBuffer.Length < (NextOut + len)) { throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})", dstate.pending.Length, dstate.pendingCount)); } Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len); NextOut += len; dstate.nextPending += len; TotalBytesOut += len; AvailableBytesOut -= len; dstate.pendingCount -= len; if (dstate.pendingCount == 0) { dstate.nextPending = 0; } } // Read a new buffer from the current input stream, update the adler32 // and total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). internal int read_buf(byte[] buf, int start, int size) { int len = AvailableBytesIn; if (len > size) len = size; if (len == 0) return 0; AvailableBytesIn -= len; if (dstate.WantRfc1950HeaderBytes) { _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len); } Array.Copy(InputBuffer, NextIn, buf, start, len); NextIn += len; TotalBytesIn += len; return len; } } }
//----------------------------------------------------------------------- // <copyright file="EntityInfo.cs" company="Genesys Source"> // Copyright (c) Genesys Source. All rights reserved. // 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. // </copyright> //----------------------------------------------------------------------- using Genesys.Extensions; using Genesys.Extras.Data; using Genesys.Extras.Serialization; using Genesys.Framework.Text; using Genesys.Framework.Validation; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Genesys.Framework.Data { /// <summary> /// Entity Data Access Object base class /// Purpose is to read/write this object to a /// database or file /// Use Genesys.Framework.Repository classes to read/write to database /// Id and Key can be set before saving /// Auto-tracks inserts/updates/deletes via Activity.ActivityContext /// Auto-validates before saving /// </summary> /// <remarks></remarks> public abstract partial class EntityInfo<TEntity> : IEntity, ISerializable<TEntity>, IValidatable<TEntity> where TEntity : class, IValidatable<TEntity>, new() { /// <summary> /// Id of record /// Can set Id before saving, and will be preserved /// only if using Genesys.Framework.Repository for CRUD /// </summary> public virtual int Id { get; set; } = TypeExtension.DefaultInteger; /// <summary> /// Key of record /// Can set Key before saving, and will be preserved /// only if using Genesys.Framework.Repository for CRUD /// </summary> public virtual Guid Key { get; set; } = TypeExtension.DefaultGuid; /// <summary> /// Activity history that created this record /// </summary> public virtual Guid ActivityContextKey { get; set; } = TypeExtension.DefaultGuid; /// <summary> /// Date record was created /// </summary> public virtual DateTime CreatedDate { get; set; } = TypeExtension.DefaultDate; /// <summary> /// Date record was modified /// </summary> public virtual DateTime ModifiedDate { get; set; } = TypeExtension.DefaultDate; /// <summary> /// Status of this record /// </summary> public virtual Guid State { get; set; } = RecordStates.Default; /// <summary> /// Is this a new object not yet committed to the database (Id == -1) /// </summary> public virtual bool IsNew { get { var returnValue = TypeExtension.DefaultBoolean; switch (new TEntity().GetAttributeValue<RecordIdentity, Fields>(Fields.IdOrKey)) { case Fields.Id: returnValue = Id == TypeExtension.DefaultInteger; break; case Fields.Key: returnValue = Key == TypeExtension.DefaultGuid; break; case Fields.IdOrKey: returnValue = Id == TypeExtension.DefaultInteger || Key == TypeExtension.DefaultGuid; break; case Fields.None: default: returnValue = true; break; } return returnValue; } } /// <summary> /// Rules that failed validation /// </summary> public IList<ITextMessage> FailedRules { get; protected set; } = new List<ITextMessage>(); /// <summary> /// Rules used by the validator for Data Validation and Business Validation /// </summary> public abstract IList<IValidationRule<TEntity>> Rules(); /// <summary> /// Constructor /// </summary> public EntityInfo() : base() { } /// <summary> /// Fills this object with another object's data (of the same type) /// </summary> /// <param name="newItem"></param> /// <remarks></remarks> public bool Equals(TEntity newItem) { var returnValue = TypeExtension.DefaultBoolean; var newObjectType = newItem.GetType(); returnValue = true; foreach (var newObjectProperty in newObjectType.GetRuntimeProperties()) { var currentProperty = typeof(TEntity).GetRuntimeProperty(newObjectProperty.Name); if ((currentProperty != null && currentProperty.CanWrite) && (object.Equals(currentProperty.GetValue(this, null), newObjectProperty.GetValue(newItem, null)) == false)) { returnValue = false; break; } } return returnValue; } /// <summary> /// Validates TEntity.Rules() collection /// Returns failed rules collection /// </summary> /// <returns></returns> public IEnumerable<ITextMessage> Validate() { var validator = new EntityValidator<TEntity>(this.CastSafe<TEntity>()); FailedRules = validator.Validate(); return FailedRules; } /// <summary> /// De-serializes a string into this object /// </summary> /// <returns></returns> public bool IsValid() { return !Validate().Any(); } /// <summary> /// Serializes this object into a Json string /// </summary> /// <returns></returns> public string Serialize() { var serializer = new JsonSerializer<TEntity>(this.CastSafe<TEntity>()); return serializer.Serialize(); } /// <summary> /// De-serializes a string into this object /// </summary> /// <returns></returns> public TEntity Deserialize(string data) { var serializer = new JsonSerializer<TEntity>(data); return serializer.Deserialize(); } /// <summary> /// Null-safe cast to the type TEntity /// </summary> /// <returns>This object casted to type TEntity</returns> public TEntity ToEntity() { return this.CastOrFill<TEntity>(); } /// <summary> /// Start with Id as string representation /// </summary> /// <returns></returns> /// <remarks></remarks> public override string ToString() { return Key.ToString(); } } }
using DevExpress.Mvvm.UI.Native; using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Windows; using System.Reflection; using System.ComponentModel; using System.Collections; using System.Security; namespace DevExpress { public class DependencyPropertiesConsistencyChecker { [SecuritySafeCritical] public static void CheckDependencyPropertiesConsistencyForAssembly(Assembly assembly, Dictionary<Type, Type[]> genericSubstitutes = null) { AppDomainSetup appDomainSetup = new AppDomainSetup(); appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain dom = AppDomain.CreateDomain("ConsistencyChecker", AppDomain.CurrentDomain.Evidence, appDomainSetup); dom.SetData("assembly", assembly); dom.SetData("genericSubstitutes", genericSubstitutes); try { dom.DoCallBack(DoCheck); } finally { AppDomain.Unload(dom); } } static void DoCheck() { new DependencyPropertiesConsistencyChecker().CheckDependencyPropertiesConsistencyForAssemblyCore((Assembly)AppDomain.CurrentDomain.GetData("assembly"), (Dictionary<Type, Type[]>)AppDomain.CurrentDomain.GetData("genericSubstitutes")); } List<string> errors = new List<string>(); DependencyPropertiesConsistencyChecker() { } public void CheckDependencyPropertiesConsistencyForAssemblyCore(Assembly assembly, Dictionary<Type, Type[]> genericSubstitutes = null) { foreach(Type type in assembly.GetTypes()) { if(!type.IsPublic) continue; Type actualType = type; if(type.IsGenericType && genericSubstitutes != null) actualType = GenerateTypeFromGeneric(type, genericSubstitutes); CheckDependencyPropertiesConsistencyForType(actualType); } if(errors.Count > 0) { StringBuilder messageBuilder = new StringBuilder(); for(int i = 0; i < errors.Count; i++) { messageBuilder.AppendLine(errors[i]); } Assert.Fail(messageBuilder.ToString()); } } Type GenerateTypeFromGeneric(Type type, Dictionary<Type, Type[]> genericSubstitutes) { if(!genericSubstitutes.ContainsKey(type)) return type; Type constructedType = type.MakeGenericType(genericSubstitutes[type]); return constructedType; } void CheckDependencyPropertiesConsistencyForType(Type type) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach(FieldInfo fielIndo in fields) { object[] attrs = fielIndo.GetCustomAttributes(typeof(IgnoreDependencyPropertiesConsistencyCheckerAttribute), false); if(attrs != null && attrs.Length > 0) continue; if(fielIndo.FieldType == typeof(DependencyProperty)) { CheckDependencyPropertyConsistencyForField(fielIndo); } } } void CheckDependencyPropertyConsistencyForField(FieldInfo fieldInfo) { if(fieldInfo.Name == "IsActiveExProperty") return; if(!fieldInfo.IsPublic) DependencyPropertyFieldInfoShouldBePublic(fieldInfo); if(!fieldInfo.IsStatic) { DependencyPropertyFieldInfoShouldBeStatic(fieldInfo); return; } if(!fieldInfo.IsInitOnly) DependencyPropertyFieldInfoShouldBeReadonly(fieldInfo); if(fieldInfo.DeclaringType.ContainsGenericParameters) { DependencyPropertyFieldNotTestedInGenericClass(fieldInfo); return; } DependencyProperty property = (DependencyProperty)fieldInfo.GetValue(null); if(property == null) { DependencyPropertyShouldBeRegistered(fieldInfo); return; } if(fieldInfo.Name != property.Name + "Property") DependencyPropertyFieldInfoNameShouldMatchPropertyName(fieldInfo); CheckDependencyPropertyOwner(fieldInfo, property); if(property.ReadOnly) { FieldInfo keyFieldInfo = fieldInfo.ReflectedType.GetField(fieldInfo.Name + "Key", BindingFlags.Static | BindingFlags.NonPublic); if(keyFieldInfo == null) { ReadonlyDependencyPropertyOwnerShouldHaveDependencyPropertyKey(fieldInfo); } else { if(!keyFieldInfo.IsInitOnly) { DependencyPropertyKeyFieldInfoShouldBeReadonly(fieldInfo); } } } PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(fieldInfo.ReflectedType)[property.Name]; if(propertyDescriptor != null) { PropertyInfo propertyInfo = fieldInfo.ReflectedType.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance); if(propertyInfo == null) { DependencyPropertyOwnerShouldHavePublicProperty(fieldInfo); } else { if(propertyInfo.PropertyType != property.PropertyType) DependencyPropertyTypeShouldMatchGetterType(fieldInfo); if(propertyInfo.GetSetMethod() == null && !property.ReadOnly) { DependencyPropertyOwnerShouldHavePublicSetter(fieldInfo); } if(propertyInfo.GetSetMethod() != null && property.ReadOnly) { DependencyPropertyOwnerShouldNotHavePublicSetter(fieldInfo); } } } else { MethodInfo getMethod = fieldInfo.ReflectedType.GetMethod("Get" + property.Name, BindingFlags.Static | BindingFlags.Public); if(getMethod == null) DependencyPropertyOwnerShouldHavePublicGetter(fieldInfo); else if(getMethod.ReturnType != property.PropertyType) DependencyPropertyTypeShouldMatchGetterType(fieldInfo); MethodInfo setMethod = fieldInfo.ReflectedType.GetMethod("Set" + property.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if(setMethod == null) { DependencyPropertyOwnerShouldHaveSetter(fieldInfo); } else { if(!setMethod.IsPublic && !property.ReadOnly) { DependencyPropertyOwnerShouldHavePublicSetter(fieldInfo); } if(setMethod.IsPublic && property.ReadOnly) { DependencyPropertyOwnerShouldNotHavePublicSetter(fieldInfo); } } } } static Hashtable PropertyFromName; static Type keyType; void CheckDependencyPropertyOwner(FieldInfo fieldInfo, DependencyProperty property) { if(fieldInfo.ReflectedType != property.OwnerType) { ExtractDPropertyInternals(property); if(!PropertyFromName.ContainsKey(CreateDPropertyKey(property.Name, fieldInfo.ReflectedType))) DependencyPropertyOwnerTypeShouldMatchContainerType(fieldInfo); } } object CreateDPropertyKey(string name, Type type) { return Activator.CreateInstance(keyType, name, type); } void ExtractDPropertyInternals(DependencyProperty property) { if(PropertyFromName != null) return; FieldInfo hashInfo = typeof(DependencyProperty).GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static); PropertyFromName = (Hashtable)hashInfo.GetValue(property); foreach(object key in PropertyFromName.Keys) { keyType = key.GetType(); break; } } void DependencyPropertyShouldBeRegistered(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyShouldBeRegistered"); } void DependencyPropertyFieldInfoShouldBePublic(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyFieldInfoShouldBePublic"); } void DependencyPropertyFieldNotTestedInGenericClass(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyFieldNotTestedInGenericClass"); } void DependencyPropertyFieldInfoShouldBeStatic(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyFieldInfoShouldBeStatic"); } void DependencyPropertyFieldInfoShouldBeReadonly(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyFieldInfoShouldBeReadonly"); } void DependencyPropertyKeyFieldInfoShouldBeReadonly(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyKeyFieldInfoShouldBeReadonly"); } void DependencyPropertyFieldInfoNameShouldMatchPropertyName(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyFieldInfoNameShouldMatchPropertyName"); } void DependencyPropertyOwnerTypeShouldMatchContainerType(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerTypeShouldMatchGetterType"); } void DependencyPropertyTypeShouldMatchGetterType(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerTypeShouldMatchContainerType"); } void ReadonlyDependencyPropertyOwnerShouldHaveDependencyPropertyKey(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "ReadonlyDependencyPropertyOwnerShouldHavePrivateOrInternalDependencyPropertyKey"); } void DependencyPropertyOwnerShouldHavePublicProperty(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerShouldHavePublicProperty"); } void DependencyPropertyOwnerShouldHavePublicGetter(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerShouldHavePublicGetter"); } void DependencyPropertyOwnerShouldHaveSetter(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerShouldHaveSetter"); } void DependencyPropertyOwnerShouldHavePublicSetter(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerShouldHavePublicSetter"); } void DependencyPropertyOwnerShouldNotHavePublicSetter(FieldInfo fieldInfo) { AddError(GetFieldInfoDescription(fieldInfo) + "DependencyPropertyOwnerShouldNotHavePublicSetter"); } void AddError(string error) { errors.Add(error); } string GetFieldInfoDescription(FieldInfo fieldInfo) { return string.Format("Owner type: {0}, Name: {1}: ", fieldInfo.ReflectedType.FullName, fieldInfo.Name); } } [TestFixture] public class DependencyPropertiesConsistencyTests { [Test] public void DependencyPropertiesConsistencyTest() { Dictionary<Type, Type[]> genericSubstitutes = new Dictionary<Type, Type[]>(); DependencyPropertiesConsistencyChecker.CheckDependencyPropertiesConsistencyForAssembly(Assembly.GetExecutingAssembly(), genericSubstitutes); } } }
using System.Collections; using System.Runtime.CompilerServices; namespace Meziantou.Framework.Collections; public sealed class SortedList<T> : ICollection<T>, ICollection, IReadOnlyList<T> { private readonly IComparer<T> _comparer; private T[] _items; private int _version; public SortedList() { _items = Array.Empty<T>(); Count = 0; _comparer = Comparer<T>.Default; } public SortedList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "Non-negative number required."); _items = capacity == 0 ? Array.Empty<T>() : new T[capacity]; _comparer = Comparer<T>.Default; } public SortedList(IComparer<T>? comparer) { _items = Array.Empty<T>(); Count = 0; _comparer = comparer ?? Comparer<T>.Default; } public SortedList(int capacity, IComparer<T>? comparer) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "Non-negative number required."); _items = capacity == 0 ? Array.Empty<T>() : new T[capacity]; Count = 0; _comparer = comparer ?? Comparer<T>.Default; } bool ICollection<T>.IsReadOnly => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; public int Count { get; private set; } public T this[int index] => _items[index]; public int Capacity { get => _items.Length; set { if (value < Count) { throw new ArgumentOutOfRangeException(nameof(value), "Capacity was less than the current size."); } if (value != _items.Length) { if (value > 0) { var newItems = new T[value]; if (Count > 0) { Array.Copy(_items, newItems, Count); } _items = newItems; } else { _items = Array.Empty<T>(); } } } } public void Add(T item) { var index = BinarySearch(item); if (index < 0) { index = ~index; } if (Count == _items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(_items, index, _items, index + 1, Count - index); } _items[index] = item; Count++; _version++; } public bool Remove(T item) { var index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } public void RemoveAt(int index) { if ((uint)index >= (uint)Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Count--; if (index < Count) { Array.Copy(_items, index + 1, _items, index, Count - index); } if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { _items[Count] = default!; } _version++; } public void Clear() { _version++; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { var size = Count; Count = 0; if (size > 0) { Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references. } } else { Count = 0; } } public void CopyTo(T[] array) => CopyTo(array, 0); public void CopyTo(Span<T> array) => _items.CopyTo(array); public void CopyTo(Memory<T> array) => _items.CopyTo(array); void ICollection.CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array)); try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array!, arrayIndex, Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException("Target array type is not compatible with the type of items in the collection.", nameof(array)); } } [SuppressMessage("Usage", "MA0015:Specify the parameter name in ArgumentException", Justification = "Multiple parameters are not supported by the exception")] public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (Count - index < count) throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(int index, Span<T> array, int count) { _items.AsSpan(index, count).CopyTo(array); } public void CopyTo(int index, Memory<T> array, int count) { _items.AsMemory(index, count).CopyTo(array); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, Count); } public bool Contains(T item) { return BinarySearch(item) >= 0; } public int IndexOf(T item) { var index = BinarySearch(item); if (index < 0) return -1; return index; } public int FirstIndexOf(T item) { var index = BinarySearch(item); if (index < 0) return -1; while (index > 0) { if (_comparer.Compare(_items[index - 1], item) == 0) { index--; } else { break; } } return index; } public int LastIndexOf(T item) { var index = BinarySearch(item); if (index < 0) return -1; while (index < Count - 1) { if (_comparer.Compare(_items[index + 1], item) == 0) { index++; } else { break; } } return index; } public int BinarySearch(T item) { return Array.BinarySearch(_items, index: 0, length: Count, item, _comparer); } private void EnsureCapacity(int min) { var newCapacity = _items.Length == 0 ? 4 : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > Array.MaxLength) { newCapacity = Array.MaxLength; } if (newCapacity < min) { newCapacity = min; } Capacity = newCapacity; } public ReadOnlySpan<T> UnsafeAsReadOnlySpan() { return _items.AsSpan(0, Count); } public Enumerator GetEnumerator() => new(this); IEnumerator<T> IEnumerable<T>.GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); public struct Enumerator : IEnumerator<T>, IEnumerator { private readonly SortedList<T> _list; private int _index; private readonly int _version; private T? _current; internal Enumerator(SortedList<T> list) { _list = list; _index = 0; _version = list._version; _current = default; } public readonly void Dispose() { } public bool MoveNext() { var localList = _list; if (_version == localList._version && ((uint)_index < (uint)localList.Count)) { _current = localList._items[_index]; _index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (_version != _list._version) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); _index = _list.Count + 1; _current = default; return false; } public readonly T Current => _current!; readonly object? IEnumerator.Current { get { if (_index == 0 || _index == _list.Count + 1) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); return Current; } } void IEnumerator.Reset() { if (_version != _list._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _current = default; } } }
#region license // Sqloogle // Copyright 2013-2017 Dale Newman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using NLog; using Sqloogle.Libs.DBDiff.Schema.Model; using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model.Interfaces; namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model { public class UserDataType : SQLServerSchemaBase { private readonly Logger _logger = LogManager.GetLogger("DbDiff"); public UserDataType(ISchemaBase parent) : base(parent, Enums.ObjectType.UserDataType) { Default = new Default(this); Rule = new Rule(this); Dependencys = new List<ObjectDependency>(); } public List<ObjectDependency> Dependencys { get; private set; } public Rule Rule { get; private set; } public Default Default { get; private set; } public string AssemblyName { get; set; } public Boolean IsAssembly { get; set; } public string AssemblyClass { get; set; } public int AssemblyId { get; set; } /// <summary> /// Cantidad de digitos que permite el campo (solo para campos Numeric). /// </summary> public int Scale { get; set; } /// <summary> /// Cantidad de decimales que permite el campo (solo para campos Numeric). /// </summary> public int Precision { get; set; } public Boolean AllowNull { get; set; } public int Size { get; set; } public string Type { get; set; } public String AssemblyFullName { get { if (IsAssembly) return AssemblyName + "." + AssemblyClass; return ""; } } /// <summary> /// Clona el objeto Column en una nueva instancia. /// </summary> public override ISchemaBase Clone(ISchemaBase parent) { var item = new UserDataType(parent) { Name = Name, Id = Id, Owner = Owner, Guid = Guid, AllowNull = AllowNull, Precision = Precision, Scale = Scale, Size = Size, Type = Type, Default = Default.Clone(this), Rule = Rule.Clone(this), Dependencys = Dependencys, IsAssembly = IsAssembly, AssemblyClass = AssemblyClass, AssemblyId = AssemblyId, AssemblyName = AssemblyName }; return item; } public static Boolean CompareRule(UserDataType origen, UserDataType destino) { if (destino == null) throw new ArgumentNullException("destino"); if (origen == null) throw new ArgumentNullException("origen"); if ((origen.Rule.Name != null) && (destino.Rule.Name == null)) return false; if ((origen.Rule.Name == null) && (destino.Rule.Name != null)) return false; if (origen.Rule.Name != null) if (!origen.Rule.Name.Equals(destino.Rule.Name)) return false; return true; } public static Boolean CompareDefault(UserDataType origen, UserDataType destino) { if (destino == null) throw new ArgumentNullException("destino"); if (origen == null) throw new ArgumentNullException("origen"); if ((origen.Default.Name != null) && (destino.Default.Name == null)) return false; if ((origen.Default.Name == null) && (destino.Default.Name != null)) return false; if (origen.Default.Name != null) if (!origen.Default.Name.Equals(destino.Default.Name)) return false; return true; } public override string ToSql() { string sql = "CREATE TYPE " + FullName; if (!IsAssembly) { sql += " FROM [" + Type + "]"; if (Type.Equals("binary") || Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar")) sql += "(" + Size.ToString(CultureInfo.InvariantCulture) + ")"; if (Type.Equals("numeric") || Type.Equals("decimal")) sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")"; if (AllowNull) sql += " NULL"; else sql += " NOT NULL"; } else { sql += " EXTERNAL NAME [" + AssemblyName + "].[" + AssemblyClass + "]"; } sql += "\r\nGO\r\n"; return sql + ToSQLAddBinds(); } public override string ToSqlDrop() { return "DROP TYPE " + FullName + "\r\nGO\r\n"; } public override string ToSqlAdd() { return ToSql(); } private string ToSQLAddBinds() { string sql = ""; if (!String.IsNullOrEmpty(Default.Name)) sql += Default.ToSQLAddBind(); if (!String.IsNullOrEmpty(Rule.Name)) sql += Rule.ToSQLAddBind(); return sql; } private SQLScriptList RebuildDependencys(Table table) { var list = new SQLScriptList(); List<ISchemaBase> items = ((Database)table.Parent).Dependencies.Find(table.Id); items.ForEach(item => { ISchemaBase realItem = ((Database)table.Parent).Find(item.FullName); if (realItem.IsCodeType) list.AddRange(((ICode)realItem).Rebuild()); }); return list; } private SQLScriptList ToSQLChangeColumns() { var fields = new Hashtable(); var list = new SQLScriptList(); var listDependencys = new SQLScriptList(); if ((Status == Enums.ObjectStatusType.AlterStatus) || (Status == Enums.ObjectStatusType.RebuildStatus)) { foreach (ObjectDependency dependency in Dependencys) { ISchemaBase itemDepens = ((Database)Parent).Find(dependency.Name); /*Si la dependencia es una funcion o una vista, reconstruye el objecto*/ if (dependency.IsCodeType) { if (itemDepens != null) list.AddRange(((ICode)itemDepens).Rebuild()); } /*Si la dependencia es una tabla, reconstruye los indices, constraint y columnas asociadas*/ if (dependency.Type == Enums.ObjectType.Table) { Column column = ((Table)itemDepens).Columns[dependency.ColumnName]; if ((column.Parent.Status != Enums.ObjectStatusType.DropStatus) && (column.Parent.Status != Enums.ObjectStatusType.CreateStatus) && ((column.Status != Enums.ObjectStatusType.CreateStatus) || (column.IsComputed))) { if (!fields.ContainsKey(column.FullName)) { listDependencys.AddRange(RebuildDependencys((Table)itemDepens)); if (column.HasToRebuildOnlyConstraint) //column.Parent.Status = Enums.ObjectStatusType.AlterRebuildDependenciesStatus; list.AddRange(column.RebuildDependencies()); if (!column.IsComputed) { list.AddRange(column.RebuildConstraint(true)); list.Add( "ALTER TABLE " + column.Parent.FullName + " ALTER COLUMN " + column.ToSQLRedefine(Type, Size, null) + "\r\nGO\r\n", 0, Enums.ScripActionType.AlterColumn); /*Si la columna va a ser eliminada o la tabla va a ser reconstruida, no restaura la columna*/ if ((column.Status != Enums.ObjectStatusType.DropStatus) && (column.Parent.Status != Enums.ObjectStatusType.RebuildStatus)) list.AddRange(column.Alter(Enums.ScripActionType.AlterColumnRestore)); } else { if (column.Status != Enums.ObjectStatusType.CreateStatus) { if (!column.GetWasInsertInDiffList(Enums.ScripActionType.AlterColumnFormula)) { column.SetWasInsertInDiffList(Enums.ScripActionType.AlterColumnFormula); list.Add(column.ToSqlDrop(), 0, Enums.ScripActionType.AlterColumnFormula); List<ISchemaBase> drops = ((Database)column.Parent.Parent).Dependencies.Find(column.Parent.Id, column.Id, 0); drops.ForEach(item => { if (item.Status != Enums.ObjectStatusType.CreateStatus) list.Add(item.Drop()); if (item.Status != Enums.ObjectStatusType.DropStatus) list.Add(item.Create()); }); /*Si la columna va a ser eliminada o la tabla va a ser reconstruida, no restaura la columna*/ if ((column.Status != Enums.ObjectStatusType.DropStatus) && (column.Parent.Status != Enums.ObjectStatusType.RebuildStatus)) list.Add(column.ToSqlAdd(), 0, Enums.ScripActionType.AlterColumnFormulaRestore); } } } fields.Add(column.FullName, column.FullName); } } } } } list.AddRange(listDependencys); return list; } private Boolean HasAnotherUDTClass() { if (IsAssembly) { /*Si existe otro UDT con el mismo assembly que se va a crear, debe ser borrado ANTES de crearse el nuevo*/ UserDataType other = ((Database)Parent).UserTypes.Find( item => (item.Status == Enums.ObjectStatusType.DropStatus) && (item.AssemblyName + "." + item.AssemblyClass).Equals((AssemblyName + "." + AssemblyClass))); if (other != null) return true; } return false; } private string SQLDropOlder() { UserDataType other = ((Database)Parent).UserTypes.Find( item => (item.Status == Enums.ObjectStatusType.DropStatus) && (item.AssemblyName + "." + item.AssemblyClass).Equals((AssemblyName + "." + AssemblyClass))); return other.ToSqlDrop(); } public override SQLScript Create() { Enums.ScripActionType action = Enums.ScripActionType.AddUserDataType; if (!GetWasInsertInDiffList(action)) { SetWasInsertInDiffList(action); return new SQLScript(ToSqlAdd(), 0, action); } else return null; } public override SQLScript Drop() { const Enums.ScripActionType action = Enums.ScripActionType.DropUserDataType; if (!GetWasInsertInDiffList(action)) { SetWasInsertInDiffList(action); return new SQLScript(ToSqlDrop(), 0, action); } return null; } public override SQLScriptList ToSqlDiff() { try { var list = new SQLScriptList(); if (Status == Enums.ObjectStatusType.DropStatus) { if (!HasAnotherUDTClass()) list.Add(Drop()); } if (HasState(Enums.ObjectStatusType.CreateStatus)) { list.Add(Create()); } if (Status == Enums.ObjectStatusType.AlterStatus) { if (Default.Status == Enums.ObjectStatusType.CreateStatus) list.Add(Default.ToSQLAddBind(), 0, Enums.ScripActionType.AddUserDataType); if (Default.Status == Enums.ObjectStatusType.DropStatus) list.Add(Default.ToSQLAddUnBind(), 0, Enums.ScripActionType.UnbindRuleType); if (Rule.Status == Enums.ObjectStatusType.CreateStatus) list.Add(Rule.ToSQLAddBind(), 0, Enums.ScripActionType.AddUserDataType); if (Rule.Status == Enums.ObjectStatusType.DropStatus) list.Add(Rule.ToSQLAddUnBind(), 0, Enums.ScripActionType.UnbindRuleType); } if (Status == Enums.ObjectStatusType.RebuildStatus) { list.AddRange(ToSQLChangeColumns()); if (!GetWasInsertInDiffList(Enums.ScripActionType.DropUserDataType)) { list.Add(ToSqlDrop() + ToSql(), 0, Enums.ScripActionType.AddUserDataType); } else list.Add(Create()); } if (HasState(Enums.ObjectStatusType.DropOlderStatus)) { list.Add(SQLDropOlder(), 0, Enums.ScripActionType.AddUserDataType); } return list; } catch (Exception ex) { _logger.Error(ex, ex.Message); return null; } } public bool Compare(UserDataType obj) { if (obj == null) throw new ArgumentNullException("obj"); if (Scale != obj.Scale) return false; if (Precision != obj.Precision) return false; if (AllowNull != obj.AllowNull) return false; if (Size != obj.Size) return false; if (!Type.Equals(obj.Type)) return false; if (IsAssembly != obj.IsAssembly) return false; if (!AssemblyClass.Equals(obj.AssemblyClass)) return false; if (!AssemblyName.Equals(obj.AssemblyName)) return false; if (!CompareDefault(this, obj)) return false; if (!CompareRule(this, obj)) return false; return true; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.Security.Tokens.ServiceModelSecurityTokenRequirement.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Security.Tokens { abstract public partial class ServiceModelSecurityTokenRequirement : System.IdentityModel.Selectors.SecurityTokenRequirement { #region Methods and constructors protected ServiceModelSecurityTokenRequirement() { } #endregion #region Properties and indexers public static string AuditLogLocationProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string ChannelParametersCollectionProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string DuplexClientLocalAddressProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string EndpointFilterTableProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #if !NETFRAMEWORK_3_5 public static string ExtendedProtectionPolicy { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #endif public static string HttpAuthenticationSchemeProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public bool IsInitiator { get { return default(bool); } } public static string IsInitiatorProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string IsOutOfBandTokenProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string IssuedSecurityTokenParametersProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public System.ServiceModel.EndpointAddress IssuerAddress { get { return default(System.ServiceModel.EndpointAddress); } set { } } public static string IssuerAddressProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public System.ServiceModel.Channels.Binding IssuerBinding { get { return default(System.ServiceModel.Channels.Binding); } set { } } public static string IssuerBindingContextProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string IssuerBindingProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string ListenUriProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string MessageAuthenticationAuditLevelProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string MessageDirectionProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public System.IdentityModel.Selectors.SecurityTokenVersion MessageSecurityVersion { get { return default(System.IdentityModel.Selectors.SecurityTokenVersion); } set { } } public static string MessageSecurityVersionProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string PrivacyNoticeUriProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string PrivacyNoticeVersionProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public System.ServiceModel.Channels.SecurityBindingElement SecureConversationSecurityBindingElement { get { return default(System.ServiceModel.Channels.SecurityBindingElement); } set { } } public static string SecureConversationSecurityBindingElementProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public System.ServiceModel.Security.SecurityAlgorithmSuite SecurityAlgorithmSuite { get { return default(System.ServiceModel.Security.SecurityAlgorithmSuite); } set { } } public static string SecurityAlgorithmSuiteProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public System.ServiceModel.Channels.SecurityBindingElement SecurityBindingElement { get { return default(System.ServiceModel.Channels.SecurityBindingElement); } set { } } public static string SecurityBindingElementProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string SupportingTokenAttachmentModeProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string SupportSecurityContextCancellationProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string SuppressAuditFailureProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string TargetAddressProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string TransportScheme { get { return default(string); } set { } } public static string TransportSchemeProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public static string ViaProperty { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #endregion #region Fields #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.IO; using Nini.Config; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using log4net; using OpenMetaverse; namespace OpenSim.Server.Handlers.Asset { public class XInventoryInConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; private string m_ConfigName = "InventoryService"; public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; m_log.DebugFormat("[XInventoryInConnector]: Starting with config name {0}", m_ConfigName); IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); string inventoryService = serverConfig.GetString("LocalServiceModule", String.Empty); if (inventoryService == String.Empty) throw new Exception("No InventoryService in config file"); Object[] args = new Object[] { config }; m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args); server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService)); } } public class XInventoryConnectorPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; public XInventoryConnectorPostHandler(IInventoryService service) : base("POST", "/xinventory") { m_InventoryService = service; } public override byte[] Handle(string path, Stream requestData, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); request.Remove("METHOD"); switch (method) { case "CREATEUSERINVENTORY": return HandleCreateUserInventory(request); case "GETINVENTORYSKELETON": return HandleGetInventorySkeleton(request); case "GETROOTFOLDER": return HandleGetRootFolder(request); case "GETFOLDERFORTYPE": return HandleGetFolderForType(request); case "GETFOLDERCONTENT": return HandleGetFolderContent(request); case "GETFOLDERITEMS": return HandleGetFolderItems(request); case "ADDFOLDER": return HandleAddFolder(request); case "UPDATEFOLDER": return HandleUpdateFolder(request); case "MOVEFOLDER": return HandleMoveFolder(request); case "DELETEFOLDERS": return HandleDeleteFolders(request); case "PURGEFOLDER": return HandlePurgeFolder(request); case "ADDITEM": return HandleAddItem(request); case "UPDATEITEM": return HandleUpdateItem(request); case "MOVEITEMS": return HandleMoveItems(request); case "DELETEITEMS": return HandleDeleteItems(request); case "GETITEM": return HandleGetItem(request); case "GETFOLDER": return HandleGetFolder(request); case "GETACTIVEGESTURES": return HandleGetActiveGestures(request); case "GETASSETPERMISSIONS": return HandleGetAssetPermissions(request); } m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[XINVENTORY HANDLER]: Exception {0}", e); } return FailureResult(); } private byte[] FailureResult() { return BoolResult(false); } private byte[] SuccessResult() { return BoolResult(true); } private byte[] BoolResult(bool value) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "RESULT", ""); result.AppendChild(doc.CreateTextNode(value.ToString())); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } byte[] HandleCreateUserInventory(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString()))) result["RESULT"] = "True"; else result["RESULT"] = "False"; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetInventorySkeleton(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString())); Dictionary<string, object> sfolders = new Dictionary<string, object>(); if (folders != null) { int i = 0; foreach (InventoryFolderBase f in folders) { sfolders["folder_" + i.ToString()] = EncodeFolder(f); i++; } } result["FOLDERS"] = sfolders; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetRootFolder(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal); if (rfolder != null) result["folder"] = EncodeFolder(rfolder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetFolderForType(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); int type = 0; Int32.TryParse(request["TYPE"].ToString(), out type); InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (AssetType)type); if (folder != null) result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetFolderContent(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID folderID = UUID.Zero; UUID.TryParse(request["FOLDER"].ToString(), out folderID); InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID); if (icoll != null) { Dictionary<string, object> folders = new Dictionary<string, object>(); int i = 0; foreach (InventoryFolderBase f in icoll.Folders) { folders["folder_" + i.ToString()] = EncodeFolder(f); i++; } result["FOLDERS"] = folders; i = 0; Dictionary<string, object> items = new Dictionary<string, object>(); foreach (InventoryItemBase it in icoll.Items) { items["item_" + i.ToString()] = EncodeItem(it); i++; } result["ITEMS"] = items; } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetFolderItems(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID folderID = UUID.Zero; UUID.TryParse(request["FOLDER"].ToString(), out folderID); List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID); Dictionary<string, object> sitems = new Dictionary<string, object>(); if (items != null) { int i = 0; foreach (InventoryItemBase item in items) { sitems["item_" + i.ToString()] = EncodeItem(item); i++; } } result["ITEMS"] = sitems; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleAddFolder(Dictionary<string,object> request) { InventoryFolderBase folder = BuildFolder(request); if (m_InventoryService.AddFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleUpdateFolder(Dictionary<string,object> request) { InventoryFolderBase folder = BuildFolder(request); if (m_InventoryService.UpdateFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleMoveFolder(Dictionary<string,object> request) { UUID parentID = UUID.Zero; UUID.TryParse(request["ParentID"].ToString(), out parentID); UUID folderID = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out folderID); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID); if (m_InventoryService.MoveFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleDeleteFolders(Dictionary<string,object> request) { UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<string> slist = (List<string>)request["FOLDERS"]; List<UUID> uuids = new List<UUID>(); foreach (string s in slist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) uuids.Add(u); } if (m_InventoryService.DeleteFolders(principal, uuids)) return SuccessResult(); else return FailureResult(); } byte[] HandlePurgeFolder(Dictionary<string,object> request) { UUID folderID = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out folderID); InventoryFolderBase folder = new InventoryFolderBase(folderID); if (m_InventoryService.PurgeFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleAddItem(Dictionary<string,object> request) { InventoryItemBase item = BuildItem(request); if (m_InventoryService.AddItem(item)) return SuccessResult(); else return FailureResult(); } byte[] HandleUpdateItem(Dictionary<string,object> request) { InventoryItemBase item = BuildItem(request); if (m_InventoryService.UpdateItem(item)) return SuccessResult(); else return FailureResult(); } byte[] HandleMoveItems(Dictionary<string,object> request) { List<string> idlist = (List<string>)request["IDLIST"]; List<string> destlist = (List<string>)request["DESTLIST"]; UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<InventoryItemBase> items = new List<InventoryItemBase>(); int n = 0; try { foreach (string s in idlist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) { UUID fid = UUID.Zero; if (UUID.TryParse(destlist[n++], out fid)) { InventoryItemBase item = new InventoryItemBase(u, principal); item.Folder = fid; items.Add(item); } } } } catch (Exception e) { m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message); return FailureResult(); } if (m_InventoryService.MoveItems(principal, items)) return SuccessResult(); else return FailureResult(); } byte[] HandleDeleteItems(Dictionary<string,object> request) { UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<string> slist = (List<string>)request["ITEMS"]; List<UUID> uuids = new List<UUID>(); foreach (string s in slist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) uuids.Add(u); } if (m_InventoryService.DeleteItems(principal, uuids)) return SuccessResult(); else return FailureResult(); } byte[] HandleGetItem(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID id = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out id); InventoryItemBase item = new InventoryItemBase(id); item = m_InventoryService.GetItem(item); if (item != null) result["item"] = EncodeItem(item); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetFolder(Dictionary<string,object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); UUID id = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out id); InventoryFolderBase folder = new InventoryFolderBase(id); folder = m_InventoryService.GetFolder(folder); if (folder != null) result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetActiveGestures(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal); Dictionary<string, object> items = new Dictionary<string, object>(); if (gestures != null) { int i = 0; foreach (InventoryItemBase item in gestures) { items["item_" + i.ToString()] = EncodeItem(item); i++; } } result["ITEMS"] = items; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] HandleGetAssetPermissions(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID assetID = UUID.Zero; UUID.TryParse(request["ASSET"].ToString(), out assetID); int perms = m_InventoryService.GetAssetPermissions(principal, assetID); result["RESULT"] = perms.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } private Dictionary<string, object> EncodeFolder(InventoryFolderBase f) { Dictionary<string, object> ret = new Dictionary<string, object>(); ret["ParentID"] = f.ParentID.ToString(); ret["Type"] = f.Type.ToString(); ret["Version"] = f.Version.ToString(); ret["Name"] = f.Name; ret["Owner"] = f.Owner.ToString(); ret["ID"] = f.ID.ToString(); return ret; } private Dictionary<string, object> EncodeItem(InventoryItemBase item) { Dictionary<string, object> ret = new Dictionary<string, object>(); ret["AssetID"] = item.AssetID.ToString(); ret["AssetType"] = item.AssetType.ToString(); ret["BasePermissions"] = item.BasePermissions.ToString(); ret["CreationDate"] = item.CreationDate.ToString(); if (item.CreatorId != null) ret["CreatorId"] = item.CreatorId.ToString(); else ret["CreatorId"] = String.Empty; if (item.CreatorData != null) ret["CreatorData"] = item.CreatorData; else ret["CreatorData"] = String.Empty; ret["CurrentPermissions"] = item.CurrentPermissions.ToString(); ret["Description"] = item.Description.ToString(); ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString(); ret["Flags"] = item.Flags.ToString(); ret["Folder"] = item.Folder.ToString(); ret["GroupID"] = item.GroupID.ToString(); ret["GroupOwned"] = item.GroupOwned.ToString(); ret["GroupPermissions"] = item.GroupPermissions.ToString(); ret["ID"] = item.ID.ToString(); ret["InvType"] = item.InvType.ToString(); ret["Name"] = item.Name.ToString(); ret["NextPermissions"] = item.NextPermissions.ToString(); ret["Owner"] = item.Owner.ToString(); ret["SalePrice"] = item.SalePrice.ToString(); ret["SaleType"] = item.SaleType.ToString(); return ret; } private InventoryFolderBase BuildFolder(Dictionary<string,object> data) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ParentID = new UUID(data["ParentID"].ToString()); folder.Type = short.Parse(data["Type"].ToString()); folder.Version = ushort.Parse(data["Version"].ToString()); folder.Name = data["Name"].ToString(); folder.Owner = new UUID(data["Owner"].ToString()); folder.ID = new UUID(data["ID"].ToString()); return folder; } private InventoryItemBase BuildItem(Dictionary<string,object> data) { InventoryItemBase item = new InventoryItemBase(); item.AssetID = new UUID(data["AssetID"].ToString()); item.AssetType = int.Parse(data["AssetType"].ToString()); item.Name = data["Name"].ToString(); item.Owner = new UUID(data["Owner"].ToString()); item.ID = new UUID(data["ID"].ToString()); item.InvType = int.Parse(data["InvType"].ToString()); item.Folder = new UUID(data["Folder"].ToString()); item.CreatorId = data["CreatorId"].ToString(); item.CreatorData = data["CreatorData"].ToString(); item.Description = data["Description"].ToString(); item.NextPermissions = uint.Parse(data["NextPermissions"].ToString()); item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString()); item.BasePermissions = uint.Parse(data["BasePermissions"].ToString()); item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString()); item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString()); item.GroupID = new UUID(data["GroupID"].ToString()); item.GroupOwned = bool.Parse(data["GroupOwned"].ToString()); item.SalePrice = int.Parse(data["SalePrice"].ToString()); item.SaleType = byte.Parse(data["SaleType"].ToString()); item.Flags = uint.Parse(data["Flags"].ToString()); item.CreationDate = int.Parse(data["CreationDate"].ToString()); return item; } } }
namespace CodeFighter.Data.Migrations { using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<CodeFighter.Data.CodeFighterContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(CodeFighter.Data.CodeFighterContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // #region ACTIONS var repairPart = new ActionData() { Id = 1, Type = "RepairPart", Name = "Sheild Regeneration", Description = "Shields regenerate 2HP each round", TargetSelfPart = true, ActionValuesJSON = "{\"RepairAmount\":2}" }; var repairShip = new ActionData() { Id = 2, Type = "RepairShip", Name = "Damage Control Teams", Description = "Damage Control teams repair the ship for 5HP per round", TargetSelfShip = true, ActionValuesJSON = "{\"RepairAmount\":5}" }; context.ActionData.AddOrUpdate(x => x.Id, repairPart, repairShip ); #endregion #region PARTS // weapons //** laser beam var laserBeam = new PartData() { Id = 1, Type = "Weapon", Name = "Laser Beam", Description = "Freaking Lasers", MaxHP = 1, DamageType = "Energy", FiringType = "Beam" }; //** plasma cannon var plasmaCannon = new PartData() { Id = 2, Type = "Weapon", Name = "Plasma Cannon", Description = "BURNNNNN!", MaxHP = 1, DamageType = "Plasma", FiringType = "Cannon" }; //** torpedo var torpedoLauncher = new PartData() { Id = 3, Type = "Weapon", Name = "Torpedo Launcher", Description = "All Tubes, Fire!", MaxHP = 1, DamageType = "Explosive", FiringType = "Launcher" }; // defenses //** shield generator var shieldGenerator = new PartData() { Id = 4, Type = "Defense", Name = "Shield Generator", Description = "Regenerative Shielding", MaxHP = 15, DefenseType= "Shield", ActionData = new List<ActionData>() { repairPart } }; //** armor plate var armorPlate = new PartData() { Id = 5, Type = "Defense", Name = "Armor Plating", Description = "Reactive Armor", MaxHP = 15, DefenseType="Armor" }; //** point defense var pointDefense = new PartData() { Id = 8, Type = "Defense", Name = "Point Defense Pod", Description = "Close In Weapons System", MaxHP = 15, DefenseType = "PointDefense" }; // actions //** damage control var damageControl = new PartData() { Id = 6, Type = "Action", Name = "Damage Control", Description = "Repair 5HP per round, 50% chance to repair a destroyed part", MaxHP = 1, ActionData = new List<ActionData>() { repairShip } }; // engines //** thruster var thruster = new PartData() { Id = 7, Type = "Engine", Name = "DU-1 Thruster", Description = "Make It Go Faster!", MaxHP = 1 }; context.PartData.AddOrUpdate(x => x.Id, laserBeam, plasmaCannon, torpedoLauncher, shieldGenerator, armorPlate, pointDefense, damageControl, thruster ); #endregion #region SHIPHULLS var hullIowa = new ShipHullData() { Id = 1, ClassName = "Iowa", HullSize = "CO", MaxHitPoints=40 }; var hullBunker = new ShipHullData() { Id = 2, ClassName = "Bunker", HullSize = "CO", MaxHitPoints=40 }; context.ShipHullData.AddOrUpdate(x => x.Id, hullIowa, hullBunker ); #endregion #region SHIPS var missouri = new ShipData() { Id = 1, Name = "UNSC Missouri", ShipHull = hullIowa }; missouri.Parts = new List<ShipPartData>() { new ShipPartData() { Id=1, PartData = laserBeam, ShipData=missouri }, new ShipPartData() { Id=2, PartData = laserBeam, ShipData=missouri }, new ShipPartData() { Id=3, PartData = plasmaCannon, ShipData=missouri }, new ShipPartData() { Id=4, PartData = torpedoLauncher, ShipData=missouri }, new ShipPartData() { Id=5, PartData = shieldGenerator, ShipData=missouri }, new ShipPartData() { Id=6, PartData = shieldGenerator, ShipData=missouri }, new ShipPartData() { Id=7, PartData = armorPlate, ShipData=missouri }, new ShipPartData() { Id=8, PartData = damageControl, ShipData=missouri }, new ShipPartData() { Id=9, PartData = thruster, ShipData=missouri }, new ShipPartData() { Id=10, PartData = thruster, ShipData=missouri }, new ShipPartData() { Id=11, PartData = thruster, ShipData=missouri }, new ShipPartData() { Id=12, PartData = thruster, ShipData=missouri }, new ShipPartData() { Id=13, PartData = thruster, ShipData=missouri }, new ShipPartData() { Id=14, PartData = thruster, ShipData=missouri } }; var alpha = new ShipData() { Id = 2, Name = "Alpha-01", ShipHull = hullBunker }; alpha.Parts = new List<ShipPartData>() { new ShipPartData() { Id=15, PartData = laserBeam, ShipData=alpha }, new ShipPartData() { Id=16, PartData = laserBeam, ShipData=alpha }, new ShipPartData() { Id=17, PartData = plasmaCannon, ShipData=alpha }, new ShipPartData() { Id=18, PartData = torpedoLauncher, ShipData=alpha }, new ShipPartData() { Id=19, PartData = shieldGenerator, ShipData=alpha }, new ShipPartData() { Id=20, PartData = shieldGenerator, ShipData=alpha }, new ShipPartData() { Id=21, PartData = armorPlate, ShipData=alpha }, new ShipPartData() { Id=22, PartData = damageControl, ShipData=alpha }, new ShipPartData() { Id=23, PartData = thruster, ShipData=alpha }, new ShipPartData() { Id=24, PartData = thruster, ShipData=alpha }, new ShipPartData() { Id=25, PartData = thruster, ShipData=alpha }, new ShipPartData() { Id=26, PartData = thruster, ShipData=alpha }, new ShipPartData() { Id=27, PartData = thruster, ShipData=alpha }, new ShipPartData() { Id=28, PartData = thruster, ShipData=alpha } }; context.ShipData.AddOrUpdate(x => x.Id, missouri, alpha ); #endregion #region FEATURES var asteroid = new FeatureData() { Id = 1, Name = "Asteroid", IsBlocking = true, Type = "asteroid" }; context.FeatureData.AddOrUpdate(x => x.Id, asteroid); #endregion #region SCENARIOS var scenario = new ScenarioData() { Id = 1, ScenarioGUID = new Guid("508E62F3-5B0E-4716-8B8D-FBCA000317A2"), Name = "One on One", Description = "1v1 fight to the death in an asteroid field", RoundLimit = 30 }; context.ScenarioData.AddOrUpdate(x => x.Id, scenario ); #endregion #region SCENARIOSHIPS context.ScenarioShipData.AddOrUpdate(x => x.Id, new ScenarioShipData() { Id = 1, StartingPositionX = 5, StartingPositionY = 5, ShipName = "UNSC Missouri", IsPlayer = true, Ship = missouri, Scenario = scenario }, new ScenarioShipData() { Id = 2, StartingPositionX = 20, StartingPositionY = 20, ShipName = "Alpha-01", IsPlayer = false, Ship = alpha, Scenario = scenario } ); #endregion #region SCENARIOFEATURES context.ScenarioFeatureData.AddOrUpdate(x => x.Id, new ScenarioFeatureData() { Id = 1, PositionX = 0, PositionY = 0, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 2, PositionX = 0, PositionY = 2, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 3, PositionX = 0, PositionY = 4, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 4, PositionX = 0, PositionY = 22, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 5, PositionX = 1, PositionY = 10, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 6, PositionX = 1, PositionY = 11, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 7, PositionX = 2, PositionY = 17, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 8, PositionX = 2, PositionY = 20, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 9, PositionX = 2, PositionY = 22, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 10, PositionX = 3, PositionY = 1, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 11, PositionX = 3, PositionY = 7, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 12, PositionX = 4, PositionY = 1, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 13, PositionX = 4, PositionY = 2, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 14, PositionX = 4, PositionY = 4, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 15, PositionX = 5, PositionY = 0, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 16, PositionX = 5, PositionY = 6, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 17, PositionX = 5, PositionY = 13, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 18, PositionX = 6, PositionY = 0, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 19, PositionX = 7, PositionY = 1, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 20, PositionX = 7, PositionY = 5, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 21, PositionX = 7, PositionY = 11, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 22, PositionX = 7, PositionY = 20, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 23, PositionX = 8, PositionY = 1, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 24, PositionX = 8, PositionY = 2, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 25, PositionX = 8, PositionY = 16, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 26, PositionX = 9, PositionY = 2, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 27, PositionX = 9, PositionY = 7, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 28, PositionX = 9, PositionY = 18, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 29, PositionX = 10, PositionY = 5, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 30, PositionX = 10, PositionY = 8, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 31, PositionX = 10, PositionY = 15, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 32, PositionX = 10, PositionY = 18, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 33, PositionX = 10, PositionY = 19, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 34, PositionX = 11, PositionY = 5, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 35, PositionX = 12, PositionY = 0, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 36, PositionX = 12, PositionY = 5, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 37, PositionX = 12, PositionY = 10, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 38, PositionX = 12, PositionY = 11, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 39, PositionX = 13, PositionY = 3, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 40, PositionX = 14, PositionY = 23, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 41, PositionX = 15, PositionY = 0, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 42, PositionX = 15, PositionY = 2, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 43, PositionX = 15, PositionY = 7, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 44, PositionX = 15, PositionY = 14, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 45, PositionX = 16, PositionY = 7, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 46, PositionX = 17, PositionY = 6, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 47, PositionX = 17, PositionY = 9, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 48, PositionX = 17, PositionY = 15, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 49, PositionX = 18, PositionY = 15, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 50, PositionX = 18, PositionY = 23, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 51, PositionX = 19, PositionY = 5, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 52, PositionX = 19, PositionY = 6, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 53, PositionX = 19, PositionY = 9, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 54, PositionX = 19, PositionY = 10, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 55, PositionX = 19, PositionY = 21, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 56, PositionX = 20, PositionY = 0, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 57, PositionX = 20, PositionY = 10, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 58, PositionX = 20, PositionY = 24, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 59, PositionX = 21, PositionY = 11, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 60, PositionX = 21, PositionY = 18, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 61, PositionX = 22, PositionY = 2, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 62, PositionX = 22, PositionY = 3, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 63, PositionX = 22, PositionY = 23, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 64, PositionX = 22, PositionY = 24, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 65, PositionX = 23, PositionY = 4, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 66, PositionX = 23, PositionY = 13, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 67, PositionX = 23, PositionY = 16, Feature = asteroid, Scenario = scenario }, new ScenarioFeatureData() { Id = 68, PositionX = 24, PositionY = 3, Feature = asteroid, Scenario = scenario } ); #endregion #region PLAYERS context.PlayerData.AddOrUpdate(x => x.Id, new PlayerData() { Id = 1, PlayerGUID = new Guid("550D672D-F40A-4A13-9212-DEB4CFE27F2D"), Name = "ArenaDave" }); #endregion } } }
/// <summary> /// Routines for detecting devices and receiving device notifications. /// </summary> using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace DelcomSupport.LowLevel { sealed internal partial class DeviceManagement { /// <summary> /// Compares two device path names. Used to find out if the device name /// of a recently attached or removed device matches the name of a /// device the application is communicating with. /// </summary> /// /// <param name="m"> a WM_DEVICECHANGE message. A call to RegisterDeviceNotification /// causes WM_DEVICECHANGE messages to be passed to an OnDeviceChange routine.. </param> /// <param name="mydevicePathName"> a device pathname returned by /// SetupDiGetDeviceInterfaceDetail in an SP_DEVICE_INTERFACE_DETAIL_DATA structure. </param> /// /// <returns> /// True if the names match, False if not. /// </returns> /// internal Boolean DeviceNameMatch(Message m, String mydevicePathName) { Int32 stringSize; try { DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1(); DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR(); // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure. Marshal.PtrToStructure(m.LParam, devBroadcastHeader); if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)) { // The dbch_devicetype parameter indicates that the event applies to a device interface. // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure, // which begins with a DEV_BROADCAST_HDR. // Obtain the number of characters in dbch_name by subtracting the 32 bytes // in the strucutre that are not part of dbch_name and dividing by 2 because there are // 2 bytes per character. stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2); // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name. // Trim dbcc_name to match the size of the String. devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1]; // Marshal data from the unmanaged block pointed to by m.LParam // to the managed object devBroadcastDeviceInterface. Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface); // Store the device name in a String. String DeviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize); // Compare the name of the newly attached device with the name of the device // the application is accessing (mydevicePathName). // Set ignorecase True. if ((String.Compare(DeviceNameString, mydevicePathName, true) == 0)) { return true; } else { return false; } } } catch (Exception ex) { throw; } return false; } /// <summary> /// Use SetupDi API functions to retrieve the device path name of an /// attached device that belongs to a device interface class. /// </summary> /// /// <param name="myGuid"> an interface class GUID. </param> /// <param name="devicePathName"> a pointer to the device path name /// of an attached device. </param> /// /// <returns> /// True if a device is found, False if not. /// </returns> internal Boolean FindDeviceFromGuid(System.Guid myGuid, ref String[] devicePathName) { Int32 bufferSize = 0; IntPtr detailDataBuffer = IntPtr.Zero; Boolean deviceFound; IntPtr deviceInfoSet = new System.IntPtr(); Boolean lastDevice = false; Int32 memberIndex = 0; SP_DEVICE_INTERFACE_DATA MyDeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); Boolean success; try { // *** // API function // summary // Retrieves a device information set for a specified group of devices. // SetupDiEnumDeviceInterfaces uses the device information set. // parameters // Interface class GUID. // Null to retrieve information for all device instances. // Optional handle to a top-level window (unused here). // Flags to limit the returned information to currently present devices // and devices that expose interfaces in the class specified by the GUID. // Returns // Handle to a device information set for the devices. // *** deviceInfoSet = SetupDiGetClassDevs(ref myGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); deviceFound = false; memberIndex = 0; // The cbSize element of the MyDeviceInterfaceData structure must be set to // the structure's size in bytes. // The size is 28 bytes for 32-bit code and 32 bits for 64-bit code. MyDeviceInterfaceData.cbSize = Marshal.SizeOf(MyDeviceInterfaceData); do { // Begin with 0 and increment through the device information set until // no more devices are available. // *** // API function // summary // Retrieves a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // On return, MyDeviceInterfaceData contains the handle to a // SP_DEVICE_INTERFACE_DATA structure for a detected device. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // Optional SP_DEVINFO_DATA structure that defines a device instance // that is a member of a device information set. // Device interface GUID. // Index to specify a device in a device information set. // Pointer to a handle to a SP_DEVICE_INTERFACE_DATA structure for a device. // Returns // True on success. // *** success = SetupDiEnumDeviceInterfaces (deviceInfoSet, IntPtr.Zero, ref myGuid, memberIndex, ref MyDeviceInterfaceData); // Find out if a device information set was retrieved. if (!success) { lastDevice = true; } else { // A device is present. // *** // API function: // summary: // Retrieves an SP_DEVICE_INTERFACE_DETAIL_DATA structure // containing information about a device. // To retrieve the information, call this function twice. // The first time returns the size of the structure. // The second time returns a pointer to the data. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs // SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces // A returned pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA // Structure to receive information about the specified interface. // The size of the SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Pointer to a variable that will receive the returned required size of the // SP_DEVICE_INTERFACE_DETAIL_DATA structure. // Returned pointer to an SP_DEVINFO_DATA structure to receive information about the device. // Returns // True on success. // *** success = SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref MyDeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); // Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size. detailDataBuffer = Marshal.AllocHGlobal(bufferSize); // Store cbSize in the first bytes of the array. The number of bytes varies with 32- and 64-bit systems. Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); // Call SetupDiGetDeviceInterfaceDetail again. // This time, pass a pointer to DetailDataBuffer // and the returned required buffer size. success = SetupDiGetDeviceInterfaceDetail (deviceInfoSet, ref MyDeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, IntPtr.Zero); // Skip over cbsize (4 bytes) to get the address of the devicePathName. IntPtr pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4); // Get the String containing the devicePathName. devicePathName[memberIndex] = Marshal.PtrToStringAuto(pDevicePathName); deviceFound = true; } memberIndex = memberIndex + 1; } while (!((lastDevice == true))); return deviceFound; } catch (Exception ex) { throw; } finally { if (detailDataBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(detailDataBuffer); } // *** // API function // summary // Frees the memory reserved for the DeviceInfoSet returned by SetupDiGetClassDevs. // parameters // DeviceInfoSet returned by SetupDiGetClassDevs. // returns // True on success. // *** if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } } /// <summary> /// Requests to receive a notification when a device is attached or removed. /// </summary> /// /// <param name="devicePathName"> handle to a device. </param> /// <param name="formHandle"> handle to the window that will receive device events. </param> /// <param name="classGuid"> device interface GUID. </param> /// <param name="deviceNotificationHandle"> returned device notification handle. </param> /// /// <returns> /// True on success. /// </returns> /// internal Boolean RegisterForDeviceNotifications(String devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; try { // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure. // Set the size. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; // Request to receive notifications about a class of devices. devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; // Specify the interface class to receive notifications about. devBroadcastDeviceInterface.dbcc_classguid = classGuid; // Allocate memory for the buffer that holds the DEV_BROADCAST_DEVICEINTERFACE structure. devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); // Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer. // Set fDeleteOld True to prevent memory leaks. Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); // *** // API function // summary // Request to receive notification messages when a device in an interface class // is attached or removed. // parameters // Handle to the window that will receive device events. // Pointer to a DEV_BROADCAST_DEVICEINTERFACE to specify the type of // device to send notifications for. // DEVICE_NOTIFY_WINDOW_HANDLE indicates the handle is a window handle. // Returns // Device notification handle or NULL on failure. // *** deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to // the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { return false; } else { return true; } } catch (Exception ex) { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } } /// <summary> /// Requests to stop receiving notification messages when a device in an /// interface class is attached or removed. /// </summary> /// /// <param name="deviceNotificationHandle"> handle returned previously by /// RegisterDeviceNotification. </param> internal void StopReceivingDeviceNotifications(IntPtr deviceNotificationHandle) { try { // *** // API function // summary // Stop receiving notification messages. // parameters // Handle returned previously by RegisterDeviceNotification. // returns // True on success. // *** // Ignore failures. DeviceManagement.UnregisterDeviceNotification(deviceNotificationHandle); } catch (Exception ex) { throw; } } } }
/* * Math.cs - Implementation of the "System.Math" class. * * Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System { #if CONFIG_EXTENDED_NUMERICS using System.Runtime.CompilerServices; public sealed class Math { // Constants. public const double E = 2.7182818284590452354; public const double PI = 3.14159265358979323846; // This class cannot be instantiated. private Math() {} // Get the absolute value of a number. [CLSCompliant(false)] public static sbyte Abs(sbyte value) { if(value >= 0) { return value; } else if(value != SByte.MinValue) { return (sbyte)(-value); } else { throw new OverflowException (_("Overflow_NegateTwosCompNum")); } } public static short Abs(short value) { if(value >= 0) { return value; } else if(value != Int16.MinValue) { return (short)(-value); } else { throw new OverflowException (_("Overflow_NegateTwosCompNum")); } } public static int Abs(int value) { if(value >= 0) { return value; } else if(value != Int32.MinValue) { return -value; } else { throw new OverflowException (_("Overflow_NegateTwosCompNum")); } } public static long Abs(long value) { if(value >= 0) { return value; } else if(value != Int64.MinValue) { return -value; } else { throw new OverflowException (_("Overflow_NegateTwosCompNum")); } } public static float Abs(float value) { if(value >= 0.0f) { return value; } else { return -value; } } public static double Abs(double value) { if(value >= 0.0d) { return value; } else { return -value; } } public static Decimal Abs(Decimal value) { return Decimal.Abs(value); } // Multiply two 32-bit numbers to get a 64-bit result. public static long BigMul(int a, int b) { return ((long)a) * ((long)b); } // Divide two numbers and get both the quotient and the remainder. public static int DivRem(int a, int b, out int result) { result = (a % b); return (a / b); } public static long DivRem(long a, long b, out long result) { result = (a % b); return (a / b); } // Get the logarithm of a number in a specific base. public static double Log(double a, double newBase) { return Log(a) / Log(newBase); } // Get the maximum of two values. [CLSCompliant(false)] public static sbyte Max(sbyte val1, sbyte val2) { return (sbyte)((val1 > val2) ? val1 : val2); } public static byte Max(byte val1, byte val2) { return (byte)((val1 > val2) ? val1 : val2); } public static short Max(short val1, short val2) { return (short)((val1 > val2) ? val1 : val2); } [CLSCompliant(false)] public static ushort Max(ushort val1, ushort val2) { return (ushort)((val1 > val2) ? val1 : val2); } public static int Max(int val1, int val2) { return ((val1 > val2) ? val1 : val2); } [CLSCompliant(false)] public static uint Max(uint val1, uint val2) { return ((val1 > val2) ? val1 : val2); } public static long Max(long val1, long val2) { return ((val1 > val2) ? val1 : val2); } [CLSCompliant(false)] public static ulong Max(ulong val1, ulong val2) { return ((val1 > val2) ? val1 : val2); } public static float Max(float val1, float val2) { return ((val1 > val2) ? val1 : val2); } public static double Max(double val1, double val2) { return ((val1 > val2) ? val1 : val2); } public static Decimal Max(Decimal val1, Decimal val2) { return Decimal.Max(val1, val2); } // Get the minimum of two values. [CLSCompliant(false)] public static sbyte Min(sbyte val1, sbyte val2) { return (sbyte)((val1 < val2) ? val1 : val2); } public static byte Min(byte val1, byte val2) { return (byte)((val1 < val2) ? val1 : val2); } public static short Min(short val1, short val2) { return (short)((val1 < val2) ? val1 : val2); } [CLSCompliant(false)] public static ushort Min(ushort val1, ushort val2) { return (ushort)((val1 < val2) ? val1 : val2); } public static int Min(int val1, int val2) { return ((val1 < val2) ? val1 : val2); } [CLSCompliant(false)] public static uint Min(uint val1, uint val2) { return ((val1 < val2) ? val1 : val2); } public static long Min(long val1, long val2) { return ((val1 < val2) ? val1 : val2); } [CLSCompliant(false)] public static ulong Min(ulong val1, ulong val2) { return ((val1 < val2) ? val1 : val2); } public static float Min(float val1, float val2) { return ((val1 < val2) ? val1 : val2); } public static double Min(double val1, double val2) { return ((val1 < val2) ? val1 : val2); } public static Decimal Min(Decimal val1, Decimal val2) { return Decimal.Min(val1, val2); } // Round a value to a certain number of digits. public static double Round(double value, int digits) { if(digits < 0 || digits > 15) { throw new ArgumentOutOfRangeException ("digits", _("ArgRange_RoundDigits")); } return RoundDouble(value, digits); } public static Decimal Round(Decimal value) { return Decimal.Round(value, 0); } #if !ECMA_COMPAT public static Decimal Round(Decimal value, int decimals) { return Decimal.Round(value, decimals); } #endif // Get the sign of a value. [CLSCompliant(false)] public static int Sign(sbyte value) { if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } public static int Sign(short value) { if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } public static int Sign(int value) { if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } public static int Sign(long value) { if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } public static int Sign(float value) { if(Single.IsNaN(value)) { throw new ArithmeticException(_("Arg_NotANumber")); } if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } public static int Sign(double value) { if(Double.IsNaN(value)) { throw new ArithmeticException(_("Arg_NotANumber")); } if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } public static int Sign(Decimal value) { return Decimal.Compare(value, 0.0m); } // Math methods that are implemented in the runtime engine. [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Acos(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Asin(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Atan(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Atan2(double y, double x); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Ceiling(double a); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Cos(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Cosh(double value); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Exp(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Floor(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double IEEERemainder(double x, double y); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Log(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Log10(double d); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Pow(double x, double y); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Round(double a); [MethodImpl(MethodImplOptions.InternalCall)] extern private static double RoundDouble(double value, int digits); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Sin(double a); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Sinh(double a); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Sqrt(double a); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Tan(double a); [MethodImpl(MethodImplOptions.InternalCall)] extern public static double Tanh(double value); }; // class Math #endif // CONFIG_EXTENDED_NUMERICS }; // namespace System
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using NUnit.Framework; namespace NodaTime.Test { partial class LocalInstantTest { #region IEquatable.Equals [Test] public void IEquatableEquals_ToSelf_IsTrue() { Assert.True(LocalInstant.LocalUnixEpoch.Equals(LocalInstant.LocalUnixEpoch), "epoch == epoch (same object)"); } [Test] public void IEquatableEquals_WithEqualTicks_IsTrue() { var first = new LocalInstant(100L); var second = new LocalInstant(100L); Assert.True(first.Equals(second), "100 == 100 (different objects)"); } [Test] public void IEquatableEquals_WithDifferentTicks_IsFalse() { Assert.False(one.Equals(negativeOne), "1 == -1"); Assert.False(one.Equals(threeMillion), "1 == 3,000,000"); Assert.False(one.Equals(negativeFiftyMillion), "1 == -50,000,000"); Assert.False(LocalInstant.MinValue.Equals(LocalInstant.MaxValue), "MinValue == MaxValue"); } #endregion #region object.Equals [Test] public void ObjectEquals_ToNull_IsFalse() { object oOne = one; Assert.False(oOne.Equals(null), "1 == null"); } [Test] public void ObjectEquals_ToSelf_IsTrue() { object oOne = one; Assert.True(oOne.Equals(oOne), "1 == 1 (same object)"); } [Test] public void ObjectEquals_WithEqualTicks_IsTrue() { object oOne = one; object oOnePrime = onePrime; Assert.True(oOne.Equals(oOnePrime), "1 == 1 (different objects)"); } [Test] public void ObjectEquals_WithDifferentTicks_IsFalse() { object oOne = one; object oNegativeOne = negativeOne; object oThreeMillion = threeMillion; object oNegativeFiftyMillion = negativeFiftyMillion; object oMinimum = LocalInstant.MinValue; object oMaximum = LocalInstant.MaxValue; Assert.False(oOne.Equals(oNegativeOne), "1 == -1"); Assert.False(oOne.Equals(oThreeMillion), "1 == 3,000,000"); Assert.False(oOne.Equals(oNegativeFiftyMillion), "1 == -50,000,000"); Assert.False(oMinimum.Equals(oMaximum), "MinValue == MaxValue"); } #endregion #region object.GetHashCode [Test] public void GetHashCode_Twice_IsEqual() { var test1 = new LocalInstant(123L); var test2 = new LocalInstant(123L); Assert.AreEqual(test1.GetHashCode(), test1.GetHashCode()); Assert.AreEqual(test2.GetHashCode(), test2.GetHashCode()); } [Test] public void GetHashCode_SameTicks_IsEqual() { var test1 = new LocalInstant(123L); var test2 = new LocalInstant(123L); Assert.AreEqual(test1.GetHashCode(), test2.GetHashCode()); } [Test] public void GetHashCode_DifferentTicks_IsDifferent() { var test1 = new LocalInstant(123L); var test2 = new LocalInstant(123L); var test3 = new LocalInstant(321L); Assert.AreNotEqual(test1.GetHashCode(), test3.GetHashCode()); Assert.AreNotEqual(test2.GetHashCode(), test3.GetHashCode()); } #endregion #region CompareTo [Test] public void CompareTo_Self_IsEqual() { Assert.AreEqual(0, one.CompareTo(one), "1 == 1 (same object)"); } [Test] public void CompareTo_WithEqualTicks_IsEqual() { Assert.AreEqual(0, one.CompareTo(onePrime), "1 == 1 (different objects)"); } [Test] public void CompareTo_WithMoreTicks_IsGreater() { Assert.Greater(one.CompareTo(negativeFiftyMillion), 0, "1 > -50,000,000"); Assert.Greater(threeMillion.CompareTo(one), 0, "3,000,000 > 1"); Assert.Greater(negativeOne.CompareTo(negativeFiftyMillion), 0, "-1 > -50,000,000"); Assert.Greater(LocalInstant.MaxValue.CompareTo(LocalInstant.MinValue), 0, "MaxValue > MinValue"); } [Test] public void CompareTo_WithLessTicks_IsLess() { Assert.Less(negativeFiftyMillion.CompareTo(one), 0, "-50,000,000 < 1"); Assert.Less(one.CompareTo(threeMillion), 0, "1 < 3,000,000"); Assert.Less(negativeFiftyMillion.CompareTo(negativeOne), 0, "-50,000,000 > -1"); Assert.Less(LocalInstant.MinValue.CompareTo(LocalInstant.MaxValue), 0, "MinValue < MaxValue"); } #endregion [Test] public void IEquatableIComparable_Tests() { var value = new LocalInstant(12345); var equalValue = new LocalInstant(12345); var greaterValue = new LocalInstant(5432199); TestHelper.TestEqualsStruct(value, equalValue, greaterValue); TestHelper.TestCompareToStruct(value, equalValue, greaterValue); TestHelper.TestNonGenericCompareTo(value, equalValue, greaterValue); TestHelper.TestOperatorComparisonEquality(value, equalValue, greaterValue); } #region operator == [Test] public void OperatorEquals_ToSelf_IsTrue() { // Warning CS1718: Comparison made to same variable; did you mean to compare something else? // This is intentional for testing #pragma warning disable 1718 Assert.True(one == one, "1 == 1 (same object)"); #pragma warning restore 1718 } [Test] public void OperatorEquals_WithEqualTicks_IsTrue() { Assert.True(one == onePrime, "1 == 1 (different objects)"); } [Test] public void OperatorEquals_WithDifferentTicks_IsFalse() { Assert.False(one == negativeOne, "1 == -1"); Assert.False(one == threeMillion, "1 == 3,000,000"); Assert.False(one == negativeFiftyMillion, "1 == -50,000,000"); Assert.False(LocalInstant.MinValue == LocalInstant.MaxValue, "MinValue == MaxValue"); } #endregion #region operator != [Test] public void OperatorNotEquals_ToSelf_IsFalse() { // Warning CS1718: Comparison made to same variable; did you mean to compare something else? // This is intentional for testing #pragma warning disable 1718 Assert.False(one != one, "1 != 1 (same object)"); #pragma warning restore 1718 } [Test] public void OperatorNotEquals_WithEqualTicks_IsFalse() { Assert.False(one != onePrime, "1 != 1 (different objects)"); } [Test] public void OperatorNotEquals_WithDifferentTicks_IsTrue() { Assert.True(one != negativeOne, "1 != -1"); Assert.True(one != threeMillion, "1 != 3,000,000"); Assert.True(one != negativeFiftyMillion, "1 != -50,000,000"); Assert.True(LocalInstant.MinValue != LocalInstant.MaxValue, "MinValue != MaxValue"); } #endregion #region operator < [Test] public void OperatorLessThan_Self_IsFalse() { // Warning CS1718: Comparison made to same variable; did you mean to compare something else? // This is intentional for testing #pragma warning disable 1718 Assert.False(one < one, "1 < 1 (same object)"); #pragma warning restore 1718 } [Test] public void OperatorLessThan_EqualTicks_IsFalse() { Assert.False(one < onePrime, "1 < 1 (different objects)"); } [Test] public void OperatorLessThan_MoreTicks_IsTrue() { Assert.True(one < threeMillion, "1 < 3,000,000"); Assert.True(negativeFiftyMillion < negativeOne, "-50,000,000 < -1"); Assert.True(LocalInstant.MinValue < LocalInstant.MaxValue, "MinValue < MaxValue"); } [Test] public void OperatorLessThan_LessTicks_IsFalse() { Assert.False(threeMillion < one, "3,000,000 < 1"); Assert.False(negativeOne < negativeFiftyMillion, "-1 < -50,000,000"); Assert.False(LocalInstant.MaxValue < LocalInstant.MinValue, "MaxValue < MinValue"); } #endregion #region operator <= [Test] public void OperatorLessThanOrEqual_Self_IsTrue() { // Warning CS1718: Comparison made to same variable; did you mean to compare something else? // This is intentional for testing #pragma warning disable 1718 Assert.True(one <= one, "1 <= 1 (same object)"); #pragma warning restore 1718 } [Test] public void OperatorLessThanOrEqual_EqualTicks_IsTrue() { Assert.True(one <= onePrime, "1 <= 1 (different objects)"); } [Test] public void OperatorLessThanOrEqual_MoreTicks_IsTrue() { Assert.True(one <= threeMillion, "1 <= 3,000,000"); Assert.True(negativeFiftyMillion <= negativeOne, "-50,000,000 <= -1"); Assert.True(LocalInstant.MinValue <= LocalInstant.MaxValue, "MinValue <= MaxValue"); } [Test] public void OperatorLessThanOrEqual_LessTicks_IsFalse() { Assert.False(threeMillion <= one, "3,000,000 <= 1"); Assert.False(negativeOne <= negativeFiftyMillion, "-1 <= -50,000,000"); Assert.False(LocalInstant.MaxValue <= LocalInstant.MinValue, "MaxValue <= MinValue"); } #endregion #region operator > [Test] public void OperatorGreaterThan_Self_IsFalse() { // Warning CS1718: Comparison made to same variable; did you mean to compare something else? // This is intentional for testing #pragma warning disable 1718 Assert.False(one > one, "1 > 1 (same object)"); #pragma warning restore 1718 } [Test] public void OperatorGreaterThan_EqualTicks_IsFalse() { Assert.False(one > onePrime, "1 > 1 (different objects)"); } [Test] public void OperatorGreaterThan_MoreTicks_IsFalse() { Assert.False(one > threeMillion, "1 > 3,000,000"); Assert.False(negativeFiftyMillion > negativeOne, "-50,000,000 > -1"); Assert.False(LocalInstant.MinValue > LocalInstant.MaxValue, "MinValue > MaxValue"); } [Test] public void OperatorGreaterThan_LessTicks_IsTrue() { Assert.True(threeMillion > one, "3,000,000 > 1"); Assert.True(negativeOne > negativeFiftyMillion, "-1 > -50,000,000"); Assert.True(LocalInstant.MaxValue > LocalInstant.MinValue, "MaxValue > MinValue"); } #endregion #region operator >= [Test] public void OperatorGreaterThanOrEqual_Self_IsTrue() { // Warning CS1718: Comparison made to same variable; did you mean to compare something else? // This is intentional for testing #pragma warning disable 1718 Assert.True(one >= one, "1 >= 1 (same object)"); #pragma warning restore 1718 } [Test] public void OperatorGreaterThanOrEqual_EqualTicks_IsTrue() { Assert.True(one >= onePrime, "1 >= 1 (different objects)"); } [Test] public void OperatorGreaterThanOrEqual_MoreTicks_IsFalse() { Assert.False(one >= threeMillion, "1 >= 3,000,000"); Assert.False(negativeFiftyMillion >= negativeOne, "-50,000,000 >= -1"); Assert.False(LocalInstant.MinValue >= LocalInstant.MaxValue, "MinValue >= MaxValue"); } [Test] public void OperatorGreaterThanOrEqual_LessTicks_IsTrue() { Assert.True(threeMillion >= one, "3,000,000 >= 1"); Assert.True(negativeOne >= negativeFiftyMillion, "-1 >= -50,000,000"); Assert.True(LocalInstant.MaxValue >= LocalInstant.MinValue, "MaxValue >= MinValue"); } #endregion #region operator + [Test] public void OperatorPlus_DurationZero_IsNeutralElement() { Assert.AreEqual(LocalInstant.LocalUnixEpoch, LocalInstant.LocalUnixEpoch + Duration.Zero, "LocalUnixEpoch + Duration.Zero"); Assert.AreEqual(one, one + Duration.Zero, "LocalInstant(1) + Duration.Zero"); Assert.AreEqual(one, LocalInstant.LocalUnixEpoch + Duration.One, "LocalUnixEpoch + Duration.One"); } [Test] public void OperatorPlus_DurationNonZero() { Assert.AreEqual(3000001L, (threeMillion + Duration.One).Ticks, "3,000,000 + 1"); Assert.AreEqual(0L, (one + Duration.NegativeOne).Ticks, "1 + (-1)"); Assert.AreEqual(-49999999L, (negativeFiftyMillion + Duration.One).Ticks, "-50,000,000 + 1"); } #endregion #region operator - [Test] public void OperatorMinusDuratino_Zero_IsNeutralElement() { Assert.AreEqual(0L, (LocalInstant.LocalUnixEpoch - LocalInstant.LocalUnixEpoch).Ticks, "0 - 0"); Assert.AreEqual(1L, (one - LocalInstant.LocalUnixEpoch).Ticks, "1 - 0"); Assert.AreEqual(-1L, (LocalInstant.LocalUnixEpoch - one).Ticks, "0 - 1"); } [Test] public void OperatorMinusDuration_NonZero() { Assert.AreEqual(2999999L, (threeMillion - one).Ticks, "3,000,000 - 1"); Assert.AreEqual(2L, (one - negativeOne).Ticks, "1 - (-1)"); Assert.AreEqual(-50000001L, (negativeFiftyMillion - one).Ticks, "-50,000,000 - 1"); } [Test] public void OperatorMinusOffset_Zero_IsNeutralElement() { Assert.AreEqual(Instant.UnixEpoch, LocalInstant.LocalUnixEpoch.Minus(Offset.Zero), "LocalUnixEpoch - Offset.Zero"); Assert.AreEqual(new Instant(1L), one.Minus(Offset.Zero), "LocalInstant(1) - Offset.Zero"); Assert.AreEqual(new Instant(-NodaConstants.TicksPerHour), LocalInstant.LocalUnixEpoch.Minus(offsetOneHour), "LocalUnixEpoch - offsetOneHour"); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Shell32 { internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx [DllImport(Libraries.Shell32, CharSet = CharSet.Unicode, SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal static extern int SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string ppszPath); // https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx internal static class KnownFolders { /// <summary> /// (CSIDL_ADMINTOOLS) Per user Administrative Tools /// "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Administrative Tools" /// </summary> internal const string AdminTools = "{724EF170-A42D-4FEF-9F26-B60E846FBA4F}"; /// <summary> /// (CSIDL_CDBURN_AREA) Temporary Burn folder /// "%LOCALAPPDATA%\Microsoft\Windows\Burn\Burn" /// </summary> internal const string CDBurning = "{9E52AB10-F80D-49DF-ACB8-4330F5687855}"; /// <summary> /// (CSIDL_COMMON_ADMINTOOLS) Common Administrative Tools /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Administrative Tools" /// </summary> internal const string CommonAdminTools = "{D0384E7D-BAC3-4797-8F14-CBA229B392B5}"; /// <summary> /// (CSIDL_COMMON_OEM_LINKS) OEM Links folder /// "%ALLUSERSPROFILE%\OEM Links" /// </summary> internal const string CommonOEMLinks = "{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}"; /// <summary> /// (CSIDL_COMMON_PROGRAMS) Common Programs folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs" /// </summary> internal const string CommonPrograms = "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}"; /// <summary> /// (CSIDL_COMMON_STARTMENU) Common Start Menu folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu" /// </summary> internal const string CommonStartMenu = "{A4115719-D62E-491D-AA7C-E74B8BE3B067}"; /// <summary> /// (CSIDL_COMMON_STARTUP, CSIDL_COMMON_ALTSTARTUP) Common Startup folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp" /// </summary> internal const string CommonStartup = "{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}"; /// <summary> /// (CSIDL_COMMON_TEMPLATES) Common Templates folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Templates" /// </summary> internal const string CommonTemplates = "{B94237E7-57AC-4347-9151-B08C6C32D1F7}"; /// <summary> /// (CSIDL_DRIVES) Computer virtual folder /// </summary> internal const string ComputerFolder = "{0AC0837C-BBF8-452A-850D-79D08E667CA7}"; /// <summary> /// (CSIDL_CONNECTIONS) Network Conections virtual folder /// </summary> internal const string ConnectionsFolder = "{6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD}"; /// <summary> /// (CSIDL_CONTROLS) Control Panel virtual folder /// </summary> internal const string ControlPanelFolder = "{82A74AEB-AEB4-465C-A014-D097EE346D63}"; /// <summary> /// (CSIDL_COOKIES) Cookies folder /// "%APPDATA%\Microsoft\Windows\Cookies" /// </summary> internal const string Cookies = "{2B0F765D-C0E9-4171-908E-08A611B84FF6}"; /// <summary> /// (CSIDL_DESKTOP, CSIDL_DESKTOPDIRECTORY) Desktop folder /// "%USERPROFILE%\Desktop" /// </summary> internal const string Desktop = "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}"; /// <summary> /// (CSIDL_MYDOCUMENTS, CSIDL_PERSONAL) Documents (My Documents) folder /// "%USERPROFILE%\Documents" /// </summary> internal const string Documents = "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}"; /// <summary> /// (CSIDL_FAVORITES, CSIDL_COMMON_FAVORITES) Favorites folder /// "%USERPROFILE%\Favorites" /// </summary> internal const string Favorites = "{1777F761-68AD-4D8A-87BD-30B759FA33DD}"; /// <summary> /// (CSIDL_FONTS) Fonts folder /// "%windir%\Fonts" /// </summary> internal const string Fonts = "{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}"; /// <summary> /// (CSIDL_HISTORY) History folder /// "%LOCALAPPDATA%\Microsoft\Windows\History" /// </summary> internal const string History = "{D9DC8A3B-B784-432E-A781-5A1130A75963}"; /// <summary> /// (CSIDL_INTERNET_CACHE) Temporary Internet Files folder /// "%LOCALAPPDATA%\Microsoft\Windows\Temporary Internet Files" /// </summary> internal const string InternetCache = "{352481E8-33BE-4251-BA85-6007CAEDCF9D}"; /// <summary> /// (CSIDL_INTERNET) The Internet virtual folder /// </summary> internal const string InternetFolder = "{4D9F7874-4E0C-4904-967B-40B0D20C3E4B}"; /// <summary> /// (CSIDL_LOCAL_APPDATA) Local folder /// "%LOCALAPPDATA%" ("%USERPROFILE%\AppData\Local") /// </summary> internal const string LocalAppData = "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"; /// <summary> /// (CSIDL_RESOURCES_LOCALIZED) Fixed localized resources folder /// "%windir%\resources\0409" (per active codepage) /// </summary> internal const string LocalizedResourcesDir = "{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}"; /// <summary> /// (CSIDL_MYMUSIC) Music folder /// "%USERPROFILE%\Music" /// </summary> internal const string Music = "{4BD8D571-6D19-48D3-BE97-422220080E43}"; /// <summary> /// (CSIDL_NETHOOD) Network shortcuts folder "%APPDATA%\Microsoft\Windows\Network Shortcuts" /// </summary> internal const string NetHood = "{C5ABBF53-E17F-4121-8900-86626FC2C973}"; /// <summary> /// (CSIDL_NETWORK, CSIDL_COMPUTERSNEARME) Network virtual folder /// </summary> internal const string NetworkFolder = "{D20BEEC4-5CA8-4905-AE3B-BF251EA09B53}"; /// <summary> /// (CSIDL_MYPICTURES) Pictures folder "%USERPROFILE%\Pictures" /// </summary> internal const string Pictures = "{33E28130-4E1E-4676-835A-98395C3BC3BB}"; /// <summary> /// (CSIDL_PRINTERS) Printers virtual folder /// </summary> internal const string PrintersFolder = "{76FC4E2D-D6AD-4519-A663-37BD56068185}"; /// <summary> /// (CSIDL_PRINTHOOD) Printer Shortcuts folder /// "%APPDATA%\Microsoft\Windows\Printer Shortcuts" /// </summary> internal const string PrintHood = "{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}"; /// <summary> /// (CSIDL_PROFILE) The root users profile folder "%USERPROFILE%" /// ("%SystemDrive%\Users\%USERNAME%") /// </summary> internal const string Profile = "{5E6C858F-0E22-4760-9AFE-EA3317B67173}"; /// <summary> /// (CSIDL_COMMON_APPDATA) ProgramData folder /// "%ALLUSERSPROFILE%" ("%ProgramData%", "%SystemDrive%\ProgramData") /// </summary> internal const string ProgramData = "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}"; /// <summary> /// (CSIDL_PROGRAM_FILES) Program Files folder for the current process architecture /// "%ProgramFiles%" ("%SystemDrive%\Program Files") /// </summary> internal const string ProgramFiles = "{905e63b6-c1bf-494e-b29c-65b732d3d21a}"; /// <summary> /// (CSIDL_PROGRAM_FILESX86) 32 bit Program Files folder (available to both 32/64 bit processes) /// </summary> internal const string ProgramFilesX86 = "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}"; /// <summary> /// (CSIDL_PROGRAM_FILES_COMMON) Common Program Files folder for the current process architecture /// "%ProgramFiles%\Common Files" /// </summary> internal const string ProgramFilesCommon = "{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}"; /// <summary> /// (CSIDL_PROGRAM_FILES_COMMONX86) Common 32 bit Program Files folder (available to both 32/64 bit processes) /// </summary> internal const string ProgramFilesCommonX86 = "{DE974D24-D9C6-4D3E-BF91-F4455120B917}"; /// <summary> /// (CSIDL_PROGRAMS) Start menu Programs folder /// "%APPDATA%\Microsoft\Windows\Start Menu\Programs" /// </summary> internal const string Programs = "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}"; /// <summary> /// (CSIDL_COMMON_DESKTOPDIRECTORY) Public Desktop folder /// "%PUBLIC%\Desktop" /// </summary> internal const string PublicDesktop = "{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}"; /// <summary> /// (CSIDL_COMMON_DOCUMENTS) Public Documents folder /// "%PUBLIC%\Documents" /// </summary> internal const string PublicDocuments = "{ED4824AF-DCE4-45A8-81E2-FC7965083634}"; /// <summary> /// (CSIDL_COMMON_MUSIC) Public Music folder /// "%PUBLIC%\Music" /// </summary> internal const string PublicMusic = "{3214FAB5-9757-4298-BB61-92A9DEAA44FF}"; /// <summary> /// (CSIDL_COMMON_PICTURES) Public Pictures folder /// "%PUBLIC%\Pictures" /// </summary> internal const string PublicPictures = "{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}"; /// <summary> /// (CSIDL_COMMON_VIDEO) Public Videos folder /// "%PUBLIC%\Videos" /// </summary> internal const string PublicVideos = "{2400183A-6185-49FB-A2D8-4A392A602BA3}"; /// <summary> /// (CSIDL_RECENT) Recent Items folder /// "%APPDATA%\Microsoft\Windows\Recent" /// </summary> internal const string Recent = "{AE50C081-EBD2-438A-8655-8A092E34987A}"; /// <summary> /// (CSIDL_BITBUCKET) Recycle Bin virtual folder /// </summary> internal const string RecycleBinFolder = "{B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}"; /// <summary> /// (CSIDL_RESOURCES) Resources fixed folder /// "%windir%\Resources" /// </summary> internal const string ResourceDir = "{8AD10C31-2ADB-4296-A8F7-E4701232C972}"; /// <summary> /// (CSIDL_APPDATA) Roaming user application data folder /// "%APPDATA%" ("%USERPROFILE%\AppData\Roaming") /// </summary> internal const string RoamingAppData = "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}"; /// <summary> /// (CSIDL_SENDTO) SendTo folder /// "%APPDATA%\Microsoft\Windows\SendTo" /// </summary> internal const string SendTo = "{8983036C-27C0-404B-8F08-102D10DCFD74}"; /// <summary> /// (CSIDL_STARTMENU) Start Menu folder /// "%APPDATA%\Microsoft\Windows\Start Menu" /// </summary> internal const string StartMenu = "{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}"; /// <summary> /// (CSIDL_STARTUP, CSIDL_ALTSTARTUP) Startup folder /// "%APPDATA%\Microsoft\Windows\Start Menu\Programs\StartUp" /// </summary> internal const string Startup = "{B97D20BB-F46A-4C97-BA10-5E3608430854}"; /// <summary> /// (CSIDL_SYSTEM) System32 folder /// "%windir%\system32" /// </summary> internal const string System = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}"; /// <summary> /// (CSIDL_SYSTEMX86) X86 System32 folder /// "%windir%\system32" or "%windir%\syswow64" /// </summary> internal const string SystemX86 = "{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}"; /// <summary> /// (CSIDL_TEMPLATES) Templates folder /// "%APPDATA%\Microsoft\Windows\Templates" /// </summary> internal const string Templates = "{A63293E8-664E-48DB-A079-DF759E0509F7}"; /// <summary> /// (CSIDL_MYVIDEO) Videos folder /// "%USERPROFILE%\Videos" /// </summary> internal const string Videos = "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}"; /// <summary> /// (CSIDL_WINDOWS) Windows folder "%windir%" /// </summary> internal const string Windows = "{F38BF404-1D43-42F2-9305-67DE0B28FC23}"; } } }
// 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 MultiplySubtractScalarSingle() { var test = new SimpleTernaryOpTest__MultiplySubtractScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public Vector128<Single> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractScalarSingle testClass) { var result = Fma.MultiplySubtractScalar(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) fixed (Vector128<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)), Sse.LoadVector128((Single*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Single[] _data3 = new Single[Op3ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private static Vector128<Single> _clsVar3; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private Vector128<Single> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplySubtractScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleTernaryOpTest__MultiplySubtractScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtractScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtractScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtractScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtractScalar( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) fixed (Vector128<Single>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtractScalar( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)), Sse.LoadVector128((Single*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtractScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var op3 = Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var op3 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplySubtractScalarSingle(); var result = Fma.MultiplySubtractScalar(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplySubtractScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) fixed (Vector128<Single>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtractScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)), Sse.LoadVector128((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtractScalar(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) fixed (Vector128<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)), Sse.LoadVector128((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractScalar(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractScalar( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)), Sse.LoadVector128((Single*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, Vector128<Single> op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(firstOp[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractScalar)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Text; namespace UMA { /// <summary> /// Utility class for merging multiple skinned meshes. /// </summary> public static class SkinnedMeshCombiner { /// <summary> /// Container for source mesh data. /// </summary> public class CombineInstance { public UMAMeshData meshData; public int[] targetSubmeshIndices; } private enum MeshComponents { none = 0, has_normals = 1, has_tangents = 2, has_colors32 = 4, has_uv = 8, has_uv2 = 16, has_uv3 = 32, has_uv4 = 64 } static Dictionary<int, BoneIndexEntry> bonesCollection; static List<Matrix4x4> bindPoses; static List<int> bonesList; /// <summary> /// Combines a set of meshes into the target mesh. /// </summary> /// <param name="target">Target.</param> /// <param name="sources">Sources.</param> public static void CombineMeshes(UMAMeshData target, CombineInstance[] sources) { int vertexCount = 0; int bindPoseCount = 0; int transformHierarchyCount = 0; MeshComponents meshComponents = MeshComponents.none; int subMeshCount = FindTargetSubMeshCount(sources); var subMeshTriangleLength = new int[subMeshCount]; AnalyzeSources(sources, subMeshTriangleLength, ref vertexCount, ref bindPoseCount, ref transformHierarchyCount, ref meshComponents); int[][] submeshTriangles = new int[subMeshCount][]; for (int i = 0; i < subMeshTriangleLength.Length; i++) { submeshTriangles[i] = new int[subMeshTriangleLength[i]]; subMeshTriangleLength[i] = 0; } bool has_normals = (meshComponents & MeshComponents.has_normals) != MeshComponents.none; bool has_tangents = (meshComponents & MeshComponents.has_tangents) != MeshComponents.none; bool has_uv = (meshComponents & MeshComponents.has_uv) != MeshComponents.none; bool has_uv2 = (meshComponents & MeshComponents.has_uv2) != MeshComponents.none; #if !UNITY_4_6 bool has_uv3 = (meshComponents & MeshComponents.has_uv3) != MeshComponents.none; bool has_uv4 = (meshComponents & MeshComponents.has_uv4) != MeshComponents.none; #endif bool has_colors32 = (meshComponents & MeshComponents.has_colors32) != MeshComponents.none; Vector3[] vertices = EnsureArrayLength(target.vertices, vertexCount); BoneWeight[] boneWeights = EnsureArrayLength(target.unityBoneWeights, vertexCount); Vector3[] normals = has_normals ? EnsureArrayLength(target.normals, vertexCount) : null; Vector4[] tangents = has_tangents ? EnsureArrayLength(target.tangents, vertexCount) : null; Vector2[] uv = has_uv ? EnsureArrayLength(target.uv, vertexCount) : null; Vector2[] uv2 = has_uv2 ? EnsureArrayLength(target.uv2, vertexCount) : null; #if !UNITY_4_6 Vector2[] uv3 = has_uv3 ? EnsureArrayLength(target.uv3, vertexCount) : null; Vector2[] uv4 = has_uv4 ? EnsureArrayLength(target.uv4, vertexCount) : null; #endif Color32[] colors32 = has_colors32 ? EnsureArrayLength(target.colors32, vertexCount) : null; UMATransform[] umaTransforms = EnsureArrayLength(target.umaBones, transformHierarchyCount); int boneCount = 0; foreach (var source in sources) { MergeSortedTransforms(umaTransforms, ref boneCount, source.meshData.umaBones); } int vertexIndex = 0; if (bonesCollection == null) bonesCollection = new Dictionary<int, BoneIndexEntry>(boneCount); else bonesCollection.Clear(); if (bindPoses == null) bindPoses = new List<Matrix4x4>(bindPoseCount); else bindPoses.Clear(); if (bonesList == null) bonesList = new List<int>(boneCount); else bonesList.Clear(); foreach (var source in sources) { vertexCount = source.meshData.vertices.Length; BuildBoneWeights(source.meshData.boneWeights, 0, boneWeights, vertexIndex, vertexCount, source.meshData.boneNameHashes, source.meshData.bindPoses, bonesCollection, bindPoses, bonesList); Array.Copy(source.meshData.vertices, 0, vertices, vertexIndex, vertexCount); if (has_normals) { if (source.meshData.normals != null && source.meshData.normals.Length > 0) { Array.Copy(source.meshData.normals, 0, normals, vertexIndex, vertexCount); } else { FillArray(tangents, vertexIndex, vertexCount, Vector3.zero); } } if (has_tangents) { if (source.meshData.tangents != null && source.meshData.tangents.Length > 0) { Array.Copy(source.meshData.tangents, 0, tangents, vertexIndex, vertexCount); } else { FillArray(tangents, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv) { if (source.meshData.uv != null) { Array.Copy(source.meshData.uv, 0, uv, vertexIndex, vertexCount); } else { FillArray(uv, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv2) { if (source.meshData.uv2 != null) { Array.Copy(source.meshData.uv2, 0, uv2, vertexIndex, vertexCount); } else { FillArray(uv2, vertexIndex, vertexCount, Vector4.zero); } } #if !UNITY_4_6 if (has_uv3) { if (source.meshData.uv3 != null) { Array.Copy(source.meshData.uv3, 0, uv3, vertexIndex, vertexCount); } else { FillArray(uv3, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv4) { if (source.meshData.uv4 != null) { Array.Copy(source.meshData.uv4, 0, uv4, vertexIndex, vertexCount); } else { FillArray(uv4, vertexIndex, vertexCount, Vector4.zero); } } #endif if (has_colors32) { if (source.meshData.colors32 != null && source.meshData.colors32.Length > 0) { Array.Copy(source.meshData.colors32, 0, colors32, vertexIndex, vertexCount); } else { Color32 white32 = Color.white; FillArray(colors32, vertexIndex, vertexCount, white32); } } for (int i = 0; i < source.meshData.subMeshCount; i++) { if (source.targetSubmeshIndices[i] >= 0) { int[] subTriangles = source.meshData.submeshes[i].triangles; int triangleLength = subTriangles.Length; int destMesh = source.targetSubmeshIndices[i]; CopyIntArrayAdd(subTriangles, 0, submeshTriangles[destMesh], subMeshTriangleLength[destMesh], triangleLength, vertexIndex); subMeshTriangleLength[destMesh] += triangleLength; } } vertexIndex += vertexCount; } vertexCount = vertexIndex; // fill in new values. target.vertexCount = vertexCount; target.vertices = vertices; target.unityBoneWeights = boneWeights; target.bindPoses = bindPoses.ToArray(); target.normals = normals; target.tangents = tangents; target.uv = uv; target.uv2 = uv2; #if !UNITY_4_6 target.uv3 = uv3; target.uv4 = uv4; #endif target.colors32 = colors32; target.subMeshCount = subMeshCount; target.submeshes = new SubMeshTriangles[subMeshCount]; target.umaBones = umaTransforms; target.umaBoneCount = boneCount; for (int i = 0; i < subMeshCount; i++) { target.submeshes[i].triangles = submeshTriangles[i]; } target.boneNameHashes = bonesList.ToArray(); } private static void MergeSortedTransforms(UMATransform[] mergedTransforms, ref int len1, UMATransform[] umaTransforms) { int newBones = 0; int pos1 = 0; int pos2 = 0; int len2 = umaTransforms.Length; while(pos1 < len1 && pos2 < len2 ) { long i = ((long)mergedTransforms[pos1].hash) - ((long)umaTransforms[pos2].hash); if (i == 0) { pos1++; pos2++; } else if (i < 0) { pos1++; } else { pos2++; newBones++; } } newBones += len2 - pos2; pos1 = len1 - 1; pos2 = len2 - 1; len1 += newBones; int dest = len1-1; while (pos1 >= 0 && pos2 >= 0) { long i = ((long)mergedTransforms[pos1].hash) - ((long)umaTransforms[pos2].hash); if (i == 0) { mergedTransforms[dest] = mergedTransforms[pos1]; pos1--; pos2--; } else if (i > 0) { mergedTransforms[dest] = mergedTransforms[pos1]; pos1--; } else { mergedTransforms[dest] = umaTransforms[pos2]; pos2--; } dest--; } while (pos2 >= 0) { mergedTransforms[dest] = umaTransforms[pos2]; pos2--; dest--; } } private static void AnalyzeSources(CombineInstance[] sources, int[] subMeshTriangleLength, ref int vertexCount, ref int bindPoseCount, ref int transformHierarchyCount, ref MeshComponents meshComponents) { for (int i = 0; i < subMeshTriangleLength.Length; i++) { subMeshTriangleLength[i] = 0; } foreach (var source in sources) { vertexCount += source.meshData.vertices.Length; bindPoseCount += source.meshData.bindPoses.Length; transformHierarchyCount += source.meshData.umaBones.Length; if (source.meshData.normals != null && source.meshData.normals.Length != 0) meshComponents |= MeshComponents.has_normals; if (source.meshData.tangents != null && source.meshData.tangents.Length != 0) meshComponents |= MeshComponents.has_tangents; if (source.meshData.uv != null && source.meshData.uv.Length != 0) meshComponents |= MeshComponents.has_uv; if (source.meshData.uv2 != null && source.meshData.uv2.Length != 0) meshComponents |= MeshComponents.has_uv2; #if !UNITY_4_6 if (source.meshData.uv3 != null && source.meshData.uv3.Length != 0) meshComponents |= MeshComponents.has_uv3; if (source.meshData.uv4 != null && source.meshData.uv4.Length != 0) meshComponents |= MeshComponents.has_uv4; #endif if (source.meshData.colors32 != null && source.meshData.colors32.Length != 0) meshComponents |= MeshComponents.has_colors32; for (int i = 0; i < source.meshData.subMeshCount; i++) { if (source.targetSubmeshIndices[i] >= 0) { int triangleLength = source.meshData.submeshes[i].triangles.Length; subMeshTriangleLength[source.targetSubmeshIndices[i]] += triangleLength; } } } } private static int FindTargetSubMeshCount(CombineInstance[] sources) { int highestTargetIndex = -1; foreach (var source in sources) { foreach (var targetIndex in source.targetSubmeshIndices) { if (highestTargetIndex < targetIndex) { highestTargetIndex = targetIndex; } } } return highestTargetIndex + 1; } private static void BuildBoneWeights(UMABoneWeight[] source, int sourceIndex, BoneWeight[] dest, int destIndex, int count, int[] bones, Matrix4x4[] bindPoses, Dictionary<int, BoneIndexEntry> bonesCollection, List<Matrix4x4> bindPosesList, List<int> bonesList) { int[] boneMapping = new int[bones.Length]; for (int i = 0; i < boneMapping.Length; i++) { boneMapping[i] = TranslateBoneIndex(i, bones, bindPoses, bonesCollection, bindPosesList, bonesList); } while (count-- > 0) { TranslateBoneWeight(ref source[sourceIndex++], ref dest[destIndex++], boneMapping); } } private static void TranslateBoneWeight(ref UMABoneWeight source, ref BoneWeight dest, int[] boneMapping) { dest.weight0 = source.weight0; dest.weight1 = source.weight1; dest.weight2 = source.weight2; dest.weight3 = source.weight3; dest.boneIndex0 = boneMapping[source.boneIndex0]; dest.boneIndex1 = boneMapping[source.boneIndex1]; dest.boneIndex2 = boneMapping[source.boneIndex2]; dest.boneIndex3 = boneMapping[source.boneIndex3]; } private struct BoneIndexEntry { public int index; public List<int> indices; public int Count { get { return index >= 0 ? 1 : indices.Count; } } public int this[int idx] { get { if (index >= 0) { if (idx == 0) return index; throw new ArgumentOutOfRangeException(); } return indices[idx]; } } internal void AddIndex(int idx) { if (index >= 0) { indices = new List<int>(10); indices.Add(index); index = -1; } indices.Add(idx); } } private static bool CompareSkinningMatrices(Matrix4x4 m1, ref Matrix4x4 m2) { if (Mathf.Abs(m1.m00 - m2.m00) > 0.0001) return false; if (Mathf.Abs(m1.m01 - m2.m01) > 0.0001) return false; if (Mathf.Abs(m1.m02 - m2.m02) > 0.0001) return false; if (Mathf.Abs(m1.m03 - m2.m03) > 0.0001) return false; if (Mathf.Abs(m1.m10 - m2.m10) > 0.0001) return false; if (Mathf.Abs(m1.m11 - m2.m11) > 0.0001) return false; if (Mathf.Abs(m1.m12 - m2.m12) > 0.0001) return false; if (Mathf.Abs(m1.m13 - m2.m13) > 0.0001) return false; if (Mathf.Abs(m1.m20 - m2.m20) > 0.0001) return false; if (Mathf.Abs(m1.m21 - m2.m21) > 0.0001) return false; if (Mathf.Abs(m1.m22 - m2.m22) > 0.0001) return false; if (Mathf.Abs(m1.m23 - m2.m23) > 0.0001) return false; // These never change in a TRS Matrix4x4 // if (Mathf.Abs(m1.m30 - m2.m30) > 0.0001) return false; // if (Mathf.Abs(m1.m31 - m2.m31) > 0.0001) return false; // if (Mathf.Abs(m1.m32 - m2.m32) > 0.0001) return false; // if (Mathf.Abs(m1.m33 - m2.m33) > 0.0001) return false; return true; } private static int TranslateBoneIndex(int index, int[] bonesHashes, Matrix4x4[] bindPoses, Dictionary<int, BoneIndexEntry> bonesCollection, List<Matrix4x4> bindPosesList, List<int> bonesList) { var boneTransform = bonesHashes[index]; BoneIndexEntry entry; if (bonesCollection.TryGetValue(boneTransform, out entry)) { for (int i = 0; i < entry.Count; i++) { var res = entry[i]; if (CompareSkinningMatrices(bindPosesList[res], ref bindPoses[index])) { return res; } } var idx = bindPosesList.Count; entry.AddIndex(idx); bindPosesList.Add(bindPoses[index]); bonesList.Add(boneTransform); return idx; } else { var idx = bindPosesList.Count; bonesCollection.Add(boneTransform, new BoneIndexEntry() { index = idx }); bindPosesList.Add(bindPoses[index]); bonesList.Add(boneTransform); return idx; } } private static void CopyColorsToColors32(Color[] source, int sourceIndex, Color32[] dest, int destIndex, int count) { while (count-- > 0) { var sColor = source[sourceIndex++]; dest[destIndex++] = new Color32((byte)Mathf.RoundToInt(sColor.r * 255f), (byte)Mathf.RoundToInt(sColor.g * 255f), (byte)Mathf.RoundToInt(sColor.b * 255f), (byte)Mathf.RoundToInt(sColor.a * 255f)); } } private static void FillArray(Vector4[] array, int index, int count, Vector4 value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Vector3[] array, int index, int count, Vector3 value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Vector2[] array, int index, int count, Vector2 value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Color[] array, int index, int count, Color value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Color32[] array, int index, int count, Color32 value) { while (count-- > 0) { array[index++] = value; } } private static void CopyIntArrayAdd(int[] source, int sourceIndex, int[] dest, int destIndex, int count, int add) { for (int i = 0; i < count; i++) { dest[destIndex++] = source[sourceIndex++] + add; } } private static T[] EnsureArrayLength<T>(T[] oldArray, int newLength) { if (newLength <= 0) return null; if (oldArray != null && oldArray.Length >= newLength) return oldArray; return new T[newLength]; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923121")] [WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationService); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923196")] [WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [WpfFact] public async Task TestPreviewDiagnosticTagger() { using (var workspace = await TestWorkspace.CreateCSharpAsync("class { }")) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { //// preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); //// enable preview diagnostics previewWorkspace.EnableDiagnostic(); var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpans(workspace); const string AnalzyerCount = "Analyzer Count: "; Assert.Equal(AnalzyerCount + 1, AnalzyerCount + diagnosticsAndErrorsSpans.Item1.Length); const string SquigglesCount = "Squiggles Count: "; Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Count); } } [WpfFact] public async Task TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = await TestWorkspace.CreateCSharpAsync("class { }")) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view WpfTestCase.RequireWpfFact($"{nameof(TestPreviewDiagnosticTaggerInPreviewPane)} creates a {nameof(IWpfDifferenceViewer)}"); var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); var diffView = (IWpfDifferenceViewer)(await previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None)); var foregroundService = workspace.GetService<IForegroundNotificationService>(); var optionsService = workspace.Services.GetService<IOptionService>(); var waiter = new ErrorSquiggleWaiter(); var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter); // set up tagger for both buffers var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners); var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer); using (var leftDisposable = leftTagger as IDisposable) { var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners); var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer); using (var rightDisposable = rightTagger as IDisposable) { // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers await waiter.CreateWaitTask(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(0, rightSpans.Count); } } } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using L4p.Common.Extensions; using L4p.Common.Helpers; using L4p.Common.NUnits; namespace L4p.Common.Loggers { public interface ILogFile { ILogFile Error(string msg, params object[] args); ILogFile Error(Exception ex); ILogFile Error(Exception ex, string msg, params object[] args); ILogFile Warn(string msg, params object[] args); ILogFile Warn(Exception ex, string msg, params object[] args); ILogFile Info(string msg, params object[] args); ILogFile Trace(string msg, params object[] args); ILogFile NewFile(); string Name { get; } string Path { get; } bool TraceOn { get; set; } } public class LogFile : ILogFile { #region members private const string LOG_FOLDER = "log_folder"; public static string DEFAULT_LOG_FOLDER = @"c:\logs"; private readonly string _name; private readonly string _path; private readonly bool _andTrace; private readonly string _processName; private readonly int _processId; private bool _traceOn; private bool _pemanentlyFailed; #endregion #region construction public static ILogFile New(string name, bool? andTrace = null) { bool andTrace_ = andTrace.GetValueOrDefault(); if (andTrace == null) andTrace_ = false; return new LogFile(name, andTrace_); } private LogFile(string name, bool andTrace) { string logPath = get_log_path(); var process = Process.GetCurrentProcess(); _name = name; _path = Path.Combine(logPath, name); _andTrace = andTrace; _processName = process.ProcessName; _processId = process.Id; _traceOn = true; Try.Catch.Handle( () => Directory.CreateDirectory(logPath), ex => TraceLogger.WriteLine("Failed to create log path '{0}'; {1}".Fmt(_path, ex.Message))); } #endregion #region null private static readonly ILogFile _null = new NullLogFile(); private static readonly ILogFile _console = StdLog.New(); public static ILogFile Null { get { return _null; } } public static ILogFile Console { get { return _console; } } #endregion #region private private string get_log_path() { string logPath = ConfigurationManager.AppSettings[LOG_FOLDER]; if (logPath == null) { logPath = DEFAULT_LOG_FOLDER; if (!NUnitHelpers.RunningUnderUnitTest) TraceLogger.WriteLine("AppSettings['{0}'] does not exist; using default='{1}'".Fmt(LOG_FOLDER, logPath)); } return logPath; } private void append_msg_to_file(string path, string msg) { using (TextWriter writer = File.AppendText(path)) { writer.WriteLine(msg); } } private void retry(int count, Action action) { TimeSpan nextRetry = 10.Milliseconds(); do { try { action(); break; } catch { nextRetry = nextRetry + nextRetry; Thread.Sleep(nextRetry); } if (count-- == 0) { _pemanentlyFailed = true; break; } } while (true); } private string build_message(string priority, string msg) { var now = DateTime.UtcNow; var dateTime = now.ToString("dd-MM-yy HH:mm:ss"); return "{0} {1} [{2}.{3}] {4}".Fmt(dateTime, priority, _processName, _processId, msg); } private void write_msg(string priority, string msg, params object[] args) { var formattedMsg = build_message(priority, msg.Fmt(args)); if (_andTrace || _pemanentlyFailed) TraceLogger.WriteLine(formattedMsg); if (_pemanentlyFailed) return; retry(5, () => append_msg_to_file(_path, formattedMsg)); } #endregion #region interface ILogFile ILogFile.Error(string msg, params object[] args) { write_msg("E", msg, args); return this; } ILogFile ILogFile.Error(Exception ex) { write_msg("E", ex.FormatHierarchy()); return this; } ILogFile ILogFile.Error(Exception ex, string msg, params object[] args) { var sb = new StringBuilder(); sb .Append(msg.Fmt(args)) .StartNewLine() .Append(ex.FormatHierarchy()); write_msg("E", sb.ToString()); return this; } ILogFile ILogFile.Warn(string msg, params object[] args) { write_msg("W", msg, args); return this; } ILogFile ILogFile.Warn(Exception ex, string msg, params object[] args) { var sb = new StringBuilder(); sb .Append(msg.Fmt(args)) .StartNewLine() .Append(ex.FormatHierarchy()); write_msg("W", sb.ToString()); return this; } ILogFile ILogFile.Info(string msg, params object[] args) { write_msg("I", msg, args); return this; } ILogFile ILogFile.Trace(string msg, params object[] args) { if (_traceOn == false) return this; write_msg("T", msg, args); return this; } ILogFile ILogFile.NewFile() { if (!File.Exists(_path)) return this; Try.Catch.Handle( () => File.Delete(_path), ex => TraceLogger.WriteLine("Failed to delete file '{0}'", _path)); return this; } string ILogFile.Name { get { return _name; } } string ILogFile.Path { get { return _path; } } bool ILogFile.TraceOn { get { return _traceOn; } set { _traceOn = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Represents a constructor call. /// </summary> [DebuggerTypeProxy(typeof(Expression.NewExpressionProxy))] public class NewExpression : Expression, IArgumentProvider { private readonly ConstructorInfo _constructor; private IList<Expression> _arguments; private readonly ReadOnlyCollection<MemberInfo> _members; internal NewExpression(ConstructorInfo constructor, IList<Expression> arguments, ReadOnlyCollection<MemberInfo> members) { _constructor = constructor; _arguments = arguments; _members = members; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public override Type Type { get { return _constructor.DeclaringType; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.New; } } /// <summary> /// Gets the called constructor. /// </summary> public ConstructorInfo Constructor { get { return _constructor; } } /// <summary> /// Gets the arguments to the constructor. /// </summary> public ReadOnlyCollection<Expression> Arguments { get { return ReturnReadOnly(ref _arguments); } } public Expression GetArgument(int index) { return _arguments[index]; } public int ArgumentCount { get { return _arguments.Count; } } /// <summary> /// Gets the members that can retrieve the values of the fields that were initialized with constructor arguments. /// </summary> public ReadOnlyCollection<MemberInfo> Members { get { return _members; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitNew(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public NewExpression Update(IEnumerable<Expression> arguments) { if (arguments == Arguments) { return this; } if (Members != null) { return Expression.New(Constructor, arguments, Members); } return Expression.New(Constructor, arguments); } } internal class NewValueTypeExpression : NewExpression { private readonly Type _valueType; internal NewValueTypeExpression(Type type, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members) : base(null, arguments, members) { _valueType = type; } public sealed override Type Type { get { return _valueType; } } } public partial class Expression { /// <summary> /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments. /// </summary> /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param> /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> property set to the specified value.</returns> public static NewExpression New(ConstructorInfo constructor) { return New(constructor, (IEnumerable<Expression>)null); } /// <summary> /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments. /// </summary> /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param> /// <param name="arguments">An array of <see cref="Expression"/> objects to use to populate the Arguments collection.</param> /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns> public static NewExpression New(ConstructorInfo constructor, params Expression[] arguments) { return New(constructor, (IEnumerable<Expression>)arguments); } /// <summary> /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments. /// </summary> /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param> /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param> /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns> public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments) { ContractUtils.RequiresNotNull(constructor, nameof(constructor)); ContractUtils.RequiresNotNull(constructor.DeclaringType, nameof(constructor) + "." + nameof(constructor.DeclaringType)); TypeUtils.ValidateType(constructor.DeclaringType); ValidateConstructor(constructor); var argList = arguments.ToReadOnly(); ValidateArgumentTypes(constructor, ExpressionType.New, ref argList); return new NewExpression(constructor, argList, null); } /// <summary> /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified. /// </summary> /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param> /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param> /// <param name="members">An <see cref="IEnumerable{T}"/> of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param> /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns> public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members) { ContractUtils.RequiresNotNull(constructor, nameof(constructor)); ValidateConstructor(constructor); var memberList = members.ToReadOnly(); var argList = arguments.ToReadOnly(); ValidateNewArgs(constructor, ref argList, ref memberList); return new NewExpression(constructor, argList, memberList); } /// <summary> /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified. /// </summary> /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param> /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param> /// <param name="members">An Array of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param> /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns> public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo[] members) { return New(constructor, arguments, (IEnumerable<MemberInfo>)members); } /// <summary> /// Creates a <see cref="NewExpression"/> that represents calling the parameterless constructor of the specified type. /// </summary> /// <param name="type">A <see cref="Type"/> that has a constructor that takes no arguments. </param> /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to New and the Constructor property set to the ConstructorInfo that represents the parameterless constructor of the specified type.</returns> public static NewExpression New(Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(); } ConstructorInfo ci = null; if (!type.GetTypeInfo().IsValueType) { ci = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.GetParameters().Length == 0).SingleOrDefault(); if (ci == null) { throw Error.TypeMissingDefaultConstructor(type); } return New(ci); } return new NewValueTypeExpression(type, EmptyReadOnlyCollection<Expression>.Instance, null); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCollection<Expression> arguments, ref ReadOnlyCollection<MemberInfo> members) { ParameterInfo[] pis; if ((pis = constructor.GetParametersCached()).Length > 0) { if (arguments.Count != pis.Length) { throw Error.IncorrectNumberOfConstructorArguments(); } if (arguments.Count != members.Count) { throw Error.IncorrectNumberOfArgumentsForMembers(); } Expression[] newArguments = null; MemberInfo[] newMembers = null; for (int i = 0, n = arguments.Count; i < n; i++) { Expression arg = arguments[i]; RequiresCanRead(arg, "argument"); MemberInfo member = members[i]; ContractUtils.RequiresNotNull(member, nameof(member)); if (!TypeUtils.AreEquivalent(member.DeclaringType, constructor.DeclaringType)) { throw Error.ArgumentMemberNotDeclOnType(member.Name, constructor.DeclaringType.Name); } Type memberType; ValidateAnonymousTypeMember(ref member, out memberType); if (!TypeUtils.AreReferenceAssignable(memberType, arg.Type)) { if (!TryQuote(memberType, ref arg)) { throw Error.ArgumentTypeDoesNotMatchMember(arg.Type, memberType); } } ParameterInfo pi = pis[i]; Type pType = pi.ParameterType; if (pType.IsByRef) { pType = pType.GetElementType(); } if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) { if (!TryQuote(pType, ref arg)) { throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType); } } if (newArguments == null && arg != arguments[i]) { newArguments = new Expression[arguments.Count]; for (int j = 0; j < i; j++) { newArguments[j] = arguments[j]; } } if (newArguments != null) { newArguments[i] = arg; } if (newMembers == null && member != members[i]) { newMembers = new MemberInfo[members.Count]; for (int j = 0; j < i; j++) { newMembers[j] = members[j]; } } if (newMembers != null) { newMembers[i] = member; } } if (newArguments != null) { arguments = new TrueReadOnlyCollection<Expression>(newArguments); } if (newMembers != null) { members = new TrueReadOnlyCollection<MemberInfo>(newMembers); } } else if (arguments != null && arguments.Count > 0) { throw Error.IncorrectNumberOfConstructorArguments(); } else if (members != null && members.Count > 0) { throw Error.IncorrectNumberOfMembersForGivenConstructor(); } } private static void ValidateAnonymousTypeMember(ref MemberInfo member, out Type memberType) { FieldInfo field = member as FieldInfo; if (field != null) { if (field.IsStatic) { throw Error.ArgumentMustBeInstanceMember(); } memberType = field.FieldType; return; } PropertyInfo pi = member as PropertyInfo; if (pi != null) { if (!pi.CanRead) { throw Error.PropertyDoesNotHaveGetter(pi); } if (pi.GetGetMethod().IsStatic) { throw Error.ArgumentMustBeInstanceMember(); } memberType = pi.PropertyType; return; } MethodInfo method = member as MethodInfo; if (method != null) { if (method.IsStatic) { throw Error.ArgumentMustBeInstanceMember(); } PropertyInfo prop = GetProperty(method); member = prop; memberType = prop.PropertyType; return; } throw Error.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod(); } private static void ValidateConstructor(ConstructorInfo constructor) { if (constructor.IsStatic) throw Error.NonStaticConstructorRequired(); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Verify.V2.Service; namespace Twilio.Tests.Rest.Verify.V2.Service { [TestFixture] public class MessagingConfigurationTest : TwilioTest { [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Verify, "/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations", "" ); request.AddPostParam("Country", Serialize("country")); request.AddPostParam("MessagingServiceSid", Serialize("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { MessagingConfigurationResource.Create("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"country\": \"CA\",\"messaging_service_sid\": \"MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA\"}" )); var response = MessagingConfigurationResource.Create("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Verify, "/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations/country", "" ); request.AddPostParam("MessagingServiceSid", Serialize("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { MessagingConfigurationResource.Update("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"country\": \"CA\",\"messaging_service_sid\": \"MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA\"}" )); var response = MessagingConfigurationResource.Update("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Verify, "/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations/country", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { MessagingConfigurationResource.Fetch("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"country\": \"CA\",\"messaging_service_sid\": \"MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA\"}" )); var response = MessagingConfigurationResource.Fetch("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Verify, "/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { MessagingConfigurationResource.Read("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"messaging_configurations\": [],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"messaging_configurations\"}}" )); var response = MessagingConfigurationResource.Read("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"messaging_configurations\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"country\": \"CA\",\"messaging_service_sid\": \"MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA\"}],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"messaging_configurations\"}}" )); var response = MessagingConfigurationResource.Read("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Verify, "/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations/country", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { MessagingConfigurationResource.Delete("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = MessagingConfigurationResource.Delete("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "country", client: twilioRestClient); Assert.NotNull(response); } } }
// 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { /// <summary> /// Thunk to call the underlying type's GetHashCode method on enum types. /// This method prevents boxing of 'this' that would be required before a call to /// the System.Enum's default implementation. /// </summary> internal partial class EnumGetHashCodeThunk : ILStubMethod { private TypeDesc _owningType; private MethodSignature _signature; public EnumGetHashCodeThunk(TypeDesc owningType) { Debug.Assert(owningType.IsEnum); _owningType = owningType; _signature = ObjectGetHashCodeMethod.Signature; } private MethodDesc ObjectGetHashCodeMethod { get { return Context.GetWellKnownType(WellKnownType.Object).GetKnownMethod("GetHashCode", null); } } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc OwningType { get { return _owningType; } } public override MethodSignature Signature { get { return _signature; } } public override string Name { get { return "GetHashCode"; } } public override bool IsVirtual { get { // This would be implicit (false is the default), but let's be very explicit. // Making this an actual override would cause size bloat with very little benefit. // The usefulness of this method lies in it's ability to prevent boxing of 'this'. // The base implementation on System.Enum is adequate for everything else. return false; } } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.constrained, emitter.NewToken(_owningType.UnderlyingType)); codeStream.Emit(ILOpcode.callvirt, emitter.NewToken(ObjectGetHashCodeMethod)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } } /// <summary> /// Thunk to compare underlying values of enums in the Equals method. /// This method prevents boxing of 'this' that would be required before a call to /// the System.Enum's default implementation. /// </summary> internal partial class EnumEqualsThunk : ILStubMethod { private TypeDesc _owningType; private MethodSignature _signature; public EnumEqualsThunk(TypeDesc owningType) { Debug.Assert(owningType.IsEnum); _owningType = owningType; _signature = ObjectEqualsMethod.Signature; } private MethodDesc ObjectEqualsMethod { get { return Context.GetWellKnownType(WellKnownType.Object).GetKnownMethod("Equals", null); } } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc OwningType { get { return _owningType; } } public override MethodSignature Signature { get { return _signature; } } public override string Name { get { return "Equals"; } } public override bool IsVirtual { get { // This would be implicit (false is the default), but let's be very explicit. // Making this an actual override would cause size bloat with very little benefit. // The usefulness of this method lies in it's ability to prevent boxing of 'this'. // The base implementation on System.Enum is adequate for everything else. return false; } } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // InstantiateAsOpen covers the weird case of generic enums TypeDesc owningTypeAsOpen = _owningType.InstantiateAsOpen(); ILCodeLabel lNotEqual = emitter.NewCodeLabel(); // if (!(obj is {enumtype})) // return false; codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.isinst, emitter.NewToken(owningTypeAsOpen)); codeStream.Emit(ILOpcode.dup); codeStream.Emit(ILOpcode.brfalse, lNotEqual); // return ({underlyingtype})this == ({underlyingtype})obj; // PREFER: ILOpcode.unbox, but the codegen for that is pretty bad codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(Context.GetWellKnownType(WellKnownType.Object).GetKnownField("m_pEEType"))); codeStream.EmitLdc(Context.Target.PointerSize); codeStream.Emit(ILOpcode.add); codeStream.EmitLdInd(owningTypeAsOpen); codeStream.EmitLdArg(0); codeStream.EmitLdInd(owningTypeAsOpen); codeStream.Emit(ILOpcode.ceq); codeStream.Emit(ILOpcode.ret); codeStream.EmitLabel(lNotEqual); codeStream.Emit(ILOpcode.pop); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net; using System.Threading.Tasks; using Orleans.Runtime; #if CLUSTERING_ADONET namespace Orleans.Clustering.AdoNet.Storage #elif PERSISTENCE_ADONET namespace Orleans.Persistence.AdoNet.Storage #elif REMINDERS_ADONET namespace Orleans.Reminders.AdoNet.Storage #elif TESTER_SQLUTILS namespace Orleans.Tests.SqlUtils #else // No default namespace intentionally to cause compile errors if something is not defined #endif { /// <summary> /// A class for all relational storages that support all systems stores : membership, reminders and statistics /// </summary> internal class RelationalOrleansQueries { /// <summary> /// the underlying storage /// </summary> private readonly IRelationalStorage storage; /// <summary> /// When inserting statistics and generating a batch insert clause, these are the columns in the statistics /// table that will be updated with multiple values. The other ones are updated with one value only. /// </summary> private static readonly string[] InsertStatisticsMultiupdateColumns = { DbStoredQueries.Columns.IsValueDelta, DbStoredQueries.Columns.StatValue, DbStoredQueries.Columns.Statistic }; /// <summary> /// the orleans functional queries /// </summary> private readonly DbStoredQueries dbStoredQueries; private readonly IGrainReferenceConverter grainReferenceConverter; /// <summary> /// Constructor /// </summary> /// <param name="storage">the underlying relational storage</param> /// <param name="dbStoredQueries">Orleans functional queries</param> /// <param name="grainReferenceConverter"></param> private RelationalOrleansQueries(IRelationalStorage storage, DbStoredQueries dbStoredQueries, IGrainReferenceConverter grainReferenceConverter) { this.storage = storage; this.dbStoredQueries = dbStoredQueries; this.grainReferenceConverter = grainReferenceConverter; } /// <summary> /// Creates an instance of a database of type <see cref="RelationalOrleansQueries"/> and Initializes Orleans queries from the database. /// Orleans uses only these queries and the variables therein, nothing more. /// </summary> /// <param name="invariantName">The invariant name of the connector for this database.</param> /// <param name="connectionString">The connection string this database should use for database operations.</param> /// <param name="grainReferenceConverter"></param> internal static async Task<RelationalOrleansQueries> CreateInstance(string invariantName, string connectionString, IGrainReferenceConverter grainReferenceConverter) { var storage = RelationalStorage.CreateInstance(invariantName, connectionString); var queries = await storage.ReadAsync(DbStoredQueries.GetQueriesKey, DbStoredQueries.Converters.GetQueryKeyAndValue, null); return new RelationalOrleansQueries(storage, new DbStoredQueries(queries.ToDictionary(q => q.Key, q => q.Value)), grainReferenceConverter); } private Task ExecuteAsync(string query, Func<IDbCommand, DbStoredQueries.Columns> parameterProvider) { return storage.ExecuteAsync(query, command => parameterProvider(command)); } private async Task<TAggregate> ReadAsync<TResult, TAggregate>(string query, Func<IDataRecord, TResult> selector, Func<IDbCommand, DbStoredQueries.Columns> parameterProvider, Func<IEnumerable<TResult>, TAggregate> aggregator) { var ret = await storage.ReadAsync(query, selector, command => parameterProvider(command)); return aggregator(ret); } #if REMINDERS_ADONET || TESTER_SQLUTILS /// <summary> /// Reads Orleans reminder data from the tables. /// </summary> /// <param name="serviceId">The service ID.</param> /// <param name="grainRef">The grain reference (ID).</param> /// <returns>Reminder table data.</returns> internal Task<ReminderTableData> ReadReminderRowsAsync(string serviceId, GrainReference grainRef) { return ReadAsync(dbStoredQueries.ReadReminderRowsKey, record => DbStoredQueries.Converters.GetReminderEntry(record, this.grainReferenceConverter), command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainId = grainRef.ToKeyString() }, ret => new ReminderTableData(ret.ToList())); } /// <summary> /// Reads Orleans reminder data from the tables. /// </summary> /// <param name="serviceId">The service ID.</param> /// <param name="beginHash">The begin hash.</param> /// <param name="endHash">The end hash.</param> /// <returns>Reminder table data.</returns> internal Task<ReminderTableData> ReadReminderRowsAsync(string serviceId, uint beginHash, uint endHash) { var query = (int)beginHash < (int)endHash ? dbStoredQueries.ReadRangeRows1Key : dbStoredQueries.ReadRangeRows2Key; return ReadAsync(query, record => DbStoredQueries.Converters.GetReminderEntry(record, this.grainReferenceConverter), command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, BeginHash = beginHash, EndHash = endHash }, ret => new ReminderTableData(ret.ToList())); } /// <summary> /// Reads one row of reminder data. /// </summary> /// <param name="serviceId">Service ID.</param> /// <param name="grainRef">The grain reference (ID).</param> /// <param name="reminderName">The reminder name to retrieve.</param> /// <returns>A remainder entry.</returns> internal Task<ReminderEntry> ReadReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName) { return ReadAsync(dbStoredQueries.ReadReminderRowKey, record => DbStoredQueries.Converters.GetReminderEntry(record, this.grainReferenceConverter), command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainId = grainRef.ToKeyString(), ReminderName = reminderName }, ret => ret.FirstOrDefault()); } /// <summary> /// Either inserts or updates a reminder row. /// </summary> /// <param name="serviceId">The service ID.</param> /// <param name="grainRef">The grain reference (ID).</param> /// <param name="reminderName">The reminder name to retrieve.</param> /// <param name="startTime">Start time of the reminder.</param> /// <param name="period">Period of the reminder.</param> /// <returns>The new etag of the either or updated or inserted reminder row.</returns> internal Task<string> UpsertReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName, DateTime startTime, TimeSpan period) { return ReadAsync(dbStoredQueries.UpsertReminderRowKey, DbStoredQueries.Converters.GetVersion, command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainHash = grainRef.GetUniformHashCode(), GrainId = grainRef.ToKeyString(), ReminderName = reminderName, StartTime = startTime, Period = period }, ret => ret.First().ToString()); } /// <summary> /// Deletes a reminder /// </summary> /// <param name="serviceId">Service ID.</param> /// <param name="grainRef"></param> /// <param name="reminderName"></param> /// <param name="etag"></param> /// <returns></returns> internal Task<bool> DeleteReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName, string etag) { return ReadAsync(dbStoredQueries.DeleteReminderRowKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { ServiceId = serviceId, GrainId = grainRef.ToKeyString(), ReminderName = reminderName, Version = etag }, ret => ret.First()); } /// <summary> /// Deletes all reminders rows of a service id. /// </summary> /// <param name="serviceId"></param> /// <returns></returns> internal Task DeleteReminderRowsAsync(string serviceId) { return ExecuteAsync(dbStoredQueries.DeleteReminderRowsKey, command => new DbStoredQueries.Columns(command) { ServiceId = serviceId }); } #endif #if CLUSTERING_ADONET || TESTER_SQLUTILS /// <summary> /// Lists active gateways. Used mainly by Orleans clients. /// </summary> /// <param name="deploymentId">The deployment for which to query the gateways.</param> /// <returns>The gateways for the silo.</returns> internal Task<List<Uri>> ActiveGatewaysAsync(string deploymentId) { return ReadAsync(dbStoredQueries.GatewaysQueryKey, DbStoredQueries.Converters.GetGatewayUri, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, Status = SiloStatus.Active }, ret => ret.ToList()); } /// <summary> /// Queries Orleans membership data. /// </summary> /// <param name="deploymentId">The deployment for which to query data.</param> /// <param name="siloAddress">Silo data used as parameters in the query.</param> /// <returns>Membership table data.</returns> internal Task<MembershipTableData> MembershipReadRowAsync(string deploymentId, SiloAddress siloAddress) { return ReadAsync(dbStoredQueries.MembershipReadRowKey, DbStoredQueries.Converters.GetMembershipEntry, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, SiloAddress = siloAddress }, ConvertToMembershipTableData); } /// <summary> /// returns all membership data for a deployment id /// </summary> /// <param name="deploymentId"></param> /// <returns></returns> internal Task<MembershipTableData> MembershipReadAllAsync(string deploymentId) { return ReadAsync(dbStoredQueries.MembershipReadAllKey, DbStoredQueries.Converters.GetMembershipEntry, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId }, ConvertToMembershipTableData); } /// <summary> /// deletes all membership entries for a deployment id /// </summary> /// <param name="deploymentId"></param> /// <returns></returns> internal Task DeleteMembershipTableEntriesAsync(string deploymentId) { return ExecuteAsync(dbStoredQueries.DeleteMembershipTableEntriesKey, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId }); } /// <summary> /// Updates IAmAlive for a silo /// </summary> /// <param name="deploymentId"></param> /// <param name="siloAddress"></param> /// <param name="iAmAliveTime"></param> /// <returns></returns> internal Task UpdateIAmAliveTimeAsync(string deploymentId, SiloAddress siloAddress, DateTime iAmAliveTime) { return ExecuteAsync(dbStoredQueries.UpdateIAmAlivetimeKey, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, SiloAddress = siloAddress, IAmAliveTime = iAmAliveTime }); } /// <summary> /// Inserts a version row if one does not already exist. /// </summary> /// <param name="deploymentId">The deployment for which to query data.</param> /// <returns><em>TRUE</em> if a row was inserted. <em>FALSE</em> otherwise.</returns> internal Task<bool> InsertMembershipVersionRowAsync(string deploymentId) { return ReadAsync(dbStoredQueries.InsertMembershipVersionKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId }, ret => ret.First()); } /// <summary> /// Inserts a membership row if one does not already exist. /// </summary> /// <param name="deploymentId">The deployment with which to insert row.</param> /// <param name="membershipEntry">The membership entry data to insert.</param> /// <param name="etag">The table expected version etag.</param> /// <returns><em>TRUE</em> if insert succeeds. <em>FALSE</em> otherwise.</returns> internal Task<bool> InsertMembershipRowAsync(string deploymentId, MembershipEntry membershipEntry, string etag) { return ReadAsync(dbStoredQueries.InsertMembershipKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, IAmAliveTime = membershipEntry.IAmAliveTime, SiloName = membershipEntry.SiloName, HostName = membershipEntry.HostName, SiloAddress = membershipEntry.SiloAddress, StartTime = membershipEntry.StartTime, Status = membershipEntry.Status, ProxyPort = membershipEntry.ProxyPort, Version = etag }, ret => ret.First()); } /// <summary> /// Updates membership row data. /// </summary> /// <param name="deploymentId">The deployment with which to insert row.</param> /// <param name="membershipEntry">The membership data to used to update database.</param> /// <param name="etag">The table expected version etag.</param> /// <returns><em>TRUE</em> if update SUCCEEDS. <em>FALSE</em> ot</returns> internal Task<bool> UpdateMembershipRowAsync(string deploymentId, MembershipEntry membershipEntry, string etag) { return ReadAsync(dbStoredQueries.UpdateMembershipKey, DbStoredQueries.Converters.GetSingleBooleanValue, command => new DbStoredQueries.Columns(command) { DeploymentId = deploymentId, SiloAddress = membershipEntry.SiloAddress, IAmAliveTime = membershipEntry.IAmAliveTime, Status = membershipEntry.Status, SuspectTimes = membershipEntry.SuspectTimes, Version = etag }, ret => ret.First()); } private static MembershipTableData ConvertToMembershipTableData(IEnumerable<Tuple<MembershipEntry, int>> ret) { var retList = ret.ToList(); var tableVersionEtag = retList[0].Item2; var membershipEntries = new List<Tuple<MembershipEntry, string>>(); if (retList[0].Item1 != null) { membershipEntries.AddRange(retList.Select(i => new Tuple<MembershipEntry, string>(i.Item1, string.Empty))); } return new MembershipTableData(membershipEntries, new TableVersion(tableVersionEtag, tableVersionEtag.ToString())); } #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; namespace CodeGen { namespace XmlBindings { public class EnumValue { // XML-bound properties. Used for deserialization. [XmlAttributeAttribute] public string Name; [XmlAttributeAttribute] public string Comment; [XmlAttributeAttribute] public string Value; [XmlAttributeAttribute] public string NumericalValue; } } public class EnumValue { public EnumValue(XmlBindings.EnumValue xmlData, string containingEnumName, Overrides.XmlBindings.EnumValue overrides) { m_rawNameComponent = xmlData.Name; m_nativeName = containingEnumName + "_" + m_rawNameComponent; m_stylizedName = Formatter.StylizeNameFromUnderscoreSeparators(xmlData.Name); m_shouldProject = true; m_valueExpression = GetValueExpression(xmlData); if (overrides != null) { if (overrides.ProjectedNameOverride != null) { m_stylizedName = overrides.ProjectedNameOverride; } if (overrides.ProjectedValueOverride != null) { m_valueExpression = overrides.ProjectedValueOverride; } m_shouldProject = overrides.ShouldProject; } } public EnumValue(string nativeName, string rawNameComponent, int valueExpression) { m_nativeName = nativeName; m_rawNameComponent = rawNameComponent; m_stylizedName = Formatter.StylizeNameFromUnderscoreSeparators(nativeName); m_shouldProject = true; m_valueExpression = valueExpression.ToString(); } static string GetValueExpression(XmlBindings.EnumValue xmlData) { // // Value and NumericalValue seem like they should be the same, but they're not. // // Value may be an int literal, or some other symbol. // NumericalValue is always an int literal (may be hex or dec) // // NumericalValue is used for Direct2D's internal codegen, in cases where the // symbol used for Value can't be referenced in the event manifest. // // And so, the int literal is decided according to the following priority // 1. NumericalValue if avail // 2. Value, must always be parseable as int literal // if (xmlData.NumericalValue != null) { return xmlData.NumericalValue; } else { Debug.Assert(xmlData.Value != null); return xmlData.Value; } } public void OutputCode(bool isLast, bool isFlags, Formatter idlFile) { if (!m_shouldProject) return; idlFile.WriteIndent(); // // The (int) cast is necessary for values such as "0x80000000" which // cannot be stored using a signed int. The default behavior of the // MIDL code generation/C++ compilation process is to treat enum // values as signed ints. // idlFile.Write(m_stylizedName); idlFile.Write(" = "); if(!isFlags) { idlFile.Write("(int)"); } idlFile.Write(m_valueExpression); string suffix = isLast ? "" : ","; idlFile.Write(suffix); idlFile.WriteLine(); } public string RawNameComponent { get { return m_rawNameComponent; } } public string NativeName { get { return m_nativeName; } } public string ValueExpression { get { return m_valueExpression; } } string m_rawNameComponent; string m_nativeName; string m_stylizedName; string m_valueExpression; bool m_shouldProject; } namespace XmlBindings { public class Enum { // XML-bound properties. Used for deserialization. [XmlAttributeAttribute] public string Name; [XmlAttributeAttribute] public string Comment; [XmlAttributeAttribute] public bool IsFlags; [XmlElement("Field")] public XmlBindings.EnumValue[] EnumValues { get; set; } } } public class Enum : OutputtableType { class EnumValueComparer : IComparer<EnumValue> { private int ParseValueExpression(string valueExpression) { NumberStyles numberStyle = NumberStyles.Any; if (valueExpression.StartsWith("0x")) { valueExpression = valueExpression.Remove(0, 2); numberStyle = NumberStyles.HexNumber; } return int.Parse(valueExpression, numberStyle); } public int Compare(EnumValue x, EnumValue y) { int valueX = ParseValueExpression(x.ValueExpression); int valueY = ParseValueExpression(y.ValueExpression); if (valueX < valueY) return -1; else if (valueX > valueY) return 1; else return 0; } } public Enum(Namespace parentNamespace, string rootProjectedNamespace, XmlBindings.Enum xmlData, Overrides.XmlBindings.Enum overrides, Dictionary<string, QualifiableType> typeDictionary, OutputDataTypes outputDataTypes) { m_stylizedName = Formatter.Prefix + Formatter.StylizeNameFromUnderscoreSeparators(xmlData.Name); if (parentNamespace != null) { m_rawName = parentNamespace.ApiName + "_" + xmlData.Name; typeDictionary[parentNamespace.RawName + "::" + xmlData.Name] = this; } else { // // Namespace of NULL indicates the global namespace. // These types aren't D2D types, and their full native name is // exactly what's in the name field (no need to prepend anything). // m_rawName = xmlData.Name; typeDictionary[xmlData.Name] = this; } m_isFlags = xmlData.IsFlags; m_enumValues = new List<EnumValue>(); foreach (XmlBindings.EnumValue valueXml in xmlData.EnumValues) { Overrides.XmlBindings.EnumValue overridesEnumValue = null; if (overrides != null) overridesEnumValue = overrides.Values.Find(x => x.Name == valueXml.Name); m_enumValues.Add(new EnumValue(valueXml, m_rawName, overridesEnumValue)); } Namespace = rootProjectedNamespace; bool shouldProject = false; if(overrides != null) { shouldProject = overrides.ShouldProject; if(overrides.ProjectedNameOverride != null) { m_stylizedName = Formatter.Prefix + overrides.ProjectedNameOverride; } if (overrides.Namespace != null) { Namespace = Namespace + "." + overrides.Namespace; } } // One of the XML files has a mistake where it doesn't properly order its enums. if (m_isFlags) { m_enumValues.Sort(new EnumValueComparer()); } // Enums in the global namespace are defined as aliases only. By convention, only enums in a namespace are output. if (parentNamespace != null && shouldProject) { outputDataTypes.AddEnum(this); } } public Enum(string rawName, List<EnumValue> values, Dictionary<string, QualifiableType> typeDictionary) { m_rawName = rawName; typeDictionary[rawName] = this; m_stylizedName = Formatter.Prefix + Formatter.StylizeNameFromUnderscoreSeparators(rawName); m_isFlags = false; m_enumValues = values; } public override string ProjectedName { get { return m_stylizedName; } } public override string NativeName { get { return m_rawName; } } public override string ProjectedNameIncludingIndirection { get { return m_stylizedName; } } public List<EnumValue> Values { get { return m_enumValues; } } // Used for code generation. public override void OutputCode(Dictionary<string, QualifiableType> typeDictionary, Formatter idlFile) { idlFile.WriteIndent(); idlFile.Write("[version(VERSION)"); if (m_isFlags) { idlFile.Write(", flags"); } idlFile.Write("]"); idlFile.WriteLine(); idlFile.WriteLine("typedef enum " + m_stylizedName); idlFile.WriteLine("{"); idlFile.Indent(); for (int i = 0; i < m_enumValues.Count; i++) { bool isLast = i == m_enumValues.Count - 1; m_enumValues[i].OutputCode(isLast, m_isFlags, idlFile); } idlFile.Unindent(); idlFile.WriteLine("} " + m_stylizedName + ";"); idlFile.WriteLine(); } private string m_rawName; private string m_stylizedName; private List<EnumValue> m_enumValues; private bool m_isFlags; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Management.Monitoring.Autoscale; namespace Microsoft.WindowsAzure.Management.Monitoring.Autoscale { public partial class AutoscaleClient : ServiceClient<AutoscaleClient>, IAutoscaleClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private ISettingOperations _settings; /// <summary> /// Operations for managing the autoscale settings. /// </summary> public virtual ISettingOperations Settings { get { return this._settings; } } /// <summary> /// Initializes a new instance of the AutoscaleClient class. /// </summary> private AutoscaleClient() : base() { this._settings = new SettingOperations(this); this._apiVersion = "2013-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AutoscaleClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> public AutoscaleClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AutoscaleClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public AutoscaleClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AutoscaleClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private AutoscaleClient(HttpClient httpClient) : base(httpClient) { this._settings = new SettingOperations(this); this._apiVersion = "2013-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AutoscaleClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public AutoscaleClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AutoscaleClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public AutoscaleClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another AutoscaleClient /// instance /// </summary> /// <param name='client'> /// Instance of AutoscaleClient to clone to /// </param> protected override void Clone(ServiceClient<AutoscaleClient> client) { base.Clone(client); if (client is AutoscaleClient) { AutoscaleClient clonedClient = ((AutoscaleClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Insights { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// EventCategoriesOperations operations. /// </summary> internal partial class EventCategoriesOperations : Microsoft.Rest.IServiceOperations<InsightsClient>, IEventCategoriesOperations { /// <summary> /// Initializes a new instance of the EventCategoriesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal EventCategoriesOperations(InsightsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the InsightsClient /// </summary> public InsightsClient Client { get; private set; } /// <summary> /// get the list of available event categories supported in the Activity Log /// Service. The current list includes the following: Aministrative, Security, /// ServiceHealth, Alert, Recommendation, Policy. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<LocalizableString>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { string apiVersion = "2015-04-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/microsoft.insights/eventcategories").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<LocalizableString>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LocalizableString>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Generated from https://github.com/nuke-build/nuke/blob/master/source/Nuke.Common/Tools/Squirrel/Squirrel.json using JetBrains.Annotations; using Newtonsoft.Json; using Nuke.Common; using Nuke.Common.Execution; using Nuke.Common.Tooling; using Nuke.Common.Tools; using Nuke.Common.Utilities.Collections; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Nuke.Common.Tools.Squirrel { /// <summary> /// <p>Squirrel is both a set of tools and a library, to completely manage both installation and updating your Desktop Windows application, written in either C# or any other language (i.e., Squirrel can manage native C++ applications).</p> /// <p>For more details, visit the <a href="https://github.com/Squirrel/Squirrel.Windows">official website</a>.</p> /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class SquirrelTasks { /// <summary> /// Path to the Squirrel executable. /// </summary> public static string SquirrelPath => ToolPathResolver.TryGetEnvironmentExecutable("SQUIRREL_EXE") ?? ToolPathResolver.GetPackageExecutable("Squirrel.Windows", "Squirrel.exe"); public static Action<OutputType, string> SquirrelLogger { get; set; } = ProcessTasks.DefaultLogger; /// <summary> /// <p>Squirrel is both a set of tools and a library, to completely manage both installation and updating your Desktop Windows application, written in either C# or any other language (i.e., Squirrel can manage native C++ applications).</p> /// <p>For more details, visit the <a href="https://github.com/Squirrel/Squirrel.Windows">official website</a>.</p> /// </summary> public static IReadOnlyCollection<Output> Squirrel(string arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Func<string, string> outputFilter = null) { using var process = ProcessTasks.StartProcess(SquirrelPath, arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, SquirrelLogger, outputFilter); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p>Squirrel is both a set of tools and a library, to completely manage both installation and updating your Desktop Windows application, written in either C# or any other language (i.e., Squirrel can manage native C++ applications).</p> /// <p>For more details, visit the <a href="https://github.com/Squirrel/Squirrel.Windows">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>--baseUrl</c> via <see cref="SquirrelSettings.BaseUrl"/></li> /// <li><c>--bootstrapperExe</c> via <see cref="SquirrelSettings.BootstrapperExecutable"/></li> /// <li><c>--checkForUpdate</c> via <see cref="SquirrelSettings.CheckForUpdate"/></li> /// <li><c>--createShortcut</c> via <see cref="SquirrelSettings.CreateShortcut"/></li> /// <li><c>--download</c> via <see cref="SquirrelSettings.Download"/></li> /// <li><c>--framework-version</c> via <see cref="SquirrelSettings.FrameworkVersion"/></li> /// <li><c>--icon</c> via <see cref="SquirrelSettings.Icon"/></li> /// <li><c>--install</c> via <see cref="SquirrelSettings.Install"/></li> /// <li><c>--loadingGif</c> via <see cref="SquirrelSettings.LoadingGif"/></li> /// <li><c>--no-delta</c> via <see cref="SquirrelSettings.GenerateNoDelta"/></li> /// <li><c>--no-msi</c> via <see cref="SquirrelSettings.GenerateNoMsi"/></li> /// <li><c>--packagesDir</c> via <see cref="SquirrelSettings.PackagesDirectory"/></li> /// <li><c>--process-start-args</c> via <see cref="SquirrelSettings.ProcessStartArguments"/></li> /// <li><c>--processStart</c> via <see cref="SquirrelSettings.ProcessStart"/></li> /// <li><c>--processStartAndWait</c> via <see cref="SquirrelSettings.ProcessStartAndWait"/></li> /// <li><c>--releaseDir</c> via <see cref="SquirrelSettings.ReleaseDirectory"/></li> /// <li><c>--releasify</c> via <see cref="SquirrelSettings.Releasify"/></li> /// <li><c>--removeShortcut</c> via <see cref="SquirrelSettings.RemoveShortcut"/></li> /// <li><c>--setupIcon</c> via <see cref="SquirrelSettings.SetupIcon"/></li> /// <li><c>--shortcut-locations</c> via <see cref="SquirrelSettings.ShortcutLocations"/></li> /// <li><c>--signWithParams</c> via <see cref="SquirrelSettings.SignWithParameters"/></li> /// <li><c>--uninstall</c> via <see cref="SquirrelSettings.Uninstall"/></li> /// <li><c>--update</c> via <see cref="SquirrelSettings.Update"/></li> /// <li><c>--updateSelf</c> via <see cref="SquirrelSettings.UpdateSelf"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> Squirrel(SquirrelSettings toolSettings = null) { toolSettings = toolSettings ?? new SquirrelSettings(); using var process = ProcessTasks.StartProcess(toolSettings); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p>Squirrel is both a set of tools and a library, to completely manage both installation and updating your Desktop Windows application, written in either C# or any other language (i.e., Squirrel can manage native C++ applications).</p> /// <p>For more details, visit the <a href="https://github.com/Squirrel/Squirrel.Windows">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>--baseUrl</c> via <see cref="SquirrelSettings.BaseUrl"/></li> /// <li><c>--bootstrapperExe</c> via <see cref="SquirrelSettings.BootstrapperExecutable"/></li> /// <li><c>--checkForUpdate</c> via <see cref="SquirrelSettings.CheckForUpdate"/></li> /// <li><c>--createShortcut</c> via <see cref="SquirrelSettings.CreateShortcut"/></li> /// <li><c>--download</c> via <see cref="SquirrelSettings.Download"/></li> /// <li><c>--framework-version</c> via <see cref="SquirrelSettings.FrameworkVersion"/></li> /// <li><c>--icon</c> via <see cref="SquirrelSettings.Icon"/></li> /// <li><c>--install</c> via <see cref="SquirrelSettings.Install"/></li> /// <li><c>--loadingGif</c> via <see cref="SquirrelSettings.LoadingGif"/></li> /// <li><c>--no-delta</c> via <see cref="SquirrelSettings.GenerateNoDelta"/></li> /// <li><c>--no-msi</c> via <see cref="SquirrelSettings.GenerateNoMsi"/></li> /// <li><c>--packagesDir</c> via <see cref="SquirrelSettings.PackagesDirectory"/></li> /// <li><c>--process-start-args</c> via <see cref="SquirrelSettings.ProcessStartArguments"/></li> /// <li><c>--processStart</c> via <see cref="SquirrelSettings.ProcessStart"/></li> /// <li><c>--processStartAndWait</c> via <see cref="SquirrelSettings.ProcessStartAndWait"/></li> /// <li><c>--releaseDir</c> via <see cref="SquirrelSettings.ReleaseDirectory"/></li> /// <li><c>--releasify</c> via <see cref="SquirrelSettings.Releasify"/></li> /// <li><c>--removeShortcut</c> via <see cref="SquirrelSettings.RemoveShortcut"/></li> /// <li><c>--setupIcon</c> via <see cref="SquirrelSettings.SetupIcon"/></li> /// <li><c>--shortcut-locations</c> via <see cref="SquirrelSettings.ShortcutLocations"/></li> /// <li><c>--signWithParams</c> via <see cref="SquirrelSettings.SignWithParameters"/></li> /// <li><c>--uninstall</c> via <see cref="SquirrelSettings.Uninstall"/></li> /// <li><c>--update</c> via <see cref="SquirrelSettings.Update"/></li> /// <li><c>--updateSelf</c> via <see cref="SquirrelSettings.UpdateSelf"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> Squirrel(Configure<SquirrelSettings> configurator) { return Squirrel(configurator(new SquirrelSettings())); } /// <summary> /// <p>Squirrel is both a set of tools and a library, to completely manage both installation and updating your Desktop Windows application, written in either C# or any other language (i.e., Squirrel can manage native C++ applications).</p> /// <p>For more details, visit the <a href="https://github.com/Squirrel/Squirrel.Windows">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>--baseUrl</c> via <see cref="SquirrelSettings.BaseUrl"/></li> /// <li><c>--bootstrapperExe</c> via <see cref="SquirrelSettings.BootstrapperExecutable"/></li> /// <li><c>--checkForUpdate</c> via <see cref="SquirrelSettings.CheckForUpdate"/></li> /// <li><c>--createShortcut</c> via <see cref="SquirrelSettings.CreateShortcut"/></li> /// <li><c>--download</c> via <see cref="SquirrelSettings.Download"/></li> /// <li><c>--framework-version</c> via <see cref="SquirrelSettings.FrameworkVersion"/></li> /// <li><c>--icon</c> via <see cref="SquirrelSettings.Icon"/></li> /// <li><c>--install</c> via <see cref="SquirrelSettings.Install"/></li> /// <li><c>--loadingGif</c> via <see cref="SquirrelSettings.LoadingGif"/></li> /// <li><c>--no-delta</c> via <see cref="SquirrelSettings.GenerateNoDelta"/></li> /// <li><c>--no-msi</c> via <see cref="SquirrelSettings.GenerateNoMsi"/></li> /// <li><c>--packagesDir</c> via <see cref="SquirrelSettings.PackagesDirectory"/></li> /// <li><c>--process-start-args</c> via <see cref="SquirrelSettings.ProcessStartArguments"/></li> /// <li><c>--processStart</c> via <see cref="SquirrelSettings.ProcessStart"/></li> /// <li><c>--processStartAndWait</c> via <see cref="SquirrelSettings.ProcessStartAndWait"/></li> /// <li><c>--releaseDir</c> via <see cref="SquirrelSettings.ReleaseDirectory"/></li> /// <li><c>--releasify</c> via <see cref="SquirrelSettings.Releasify"/></li> /// <li><c>--removeShortcut</c> via <see cref="SquirrelSettings.RemoveShortcut"/></li> /// <li><c>--setupIcon</c> via <see cref="SquirrelSettings.SetupIcon"/></li> /// <li><c>--shortcut-locations</c> via <see cref="SquirrelSettings.ShortcutLocations"/></li> /// <li><c>--signWithParams</c> via <see cref="SquirrelSettings.SignWithParameters"/></li> /// <li><c>--uninstall</c> via <see cref="SquirrelSettings.Uninstall"/></li> /// <li><c>--update</c> via <see cref="SquirrelSettings.Update"/></li> /// <li><c>--updateSelf</c> via <see cref="SquirrelSettings.UpdateSelf"/></li> /// </ul> /// </remarks> public static IEnumerable<(SquirrelSettings Settings, IReadOnlyCollection<Output> Output)> Squirrel(CombinatorialConfigure<SquirrelSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) { return configurator.Invoke(Squirrel, SquirrelLogger, degreeOfParallelism, completeOnFailure); } } #region SquirrelSettings /// <summary> /// Used within <see cref="SquirrelTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] [Serializable] public partial class SquirrelSettings : ToolSettings { /// <summary> /// Path to the Squirrel executable. /// </summary> public override string ProcessToolPath => base.ProcessToolPath ?? SquirrelTasks.SquirrelPath; public override Action<OutputType, string> ProcessCustomLogger => SquirrelTasks.SquirrelLogger; /// <summary> /// Install the app whose package is in the specified directory. /// </summary> public virtual string Install { get; internal set; } /// <summary> /// Uninstall the app the same dir as Update.exe. /// </summary> public virtual bool? Uninstall { get; internal set; } /// <summary> /// Download the releases specified by the URL and write new results to stdout as JSON. /// </summary> public virtual bool? Download { get; internal set; } /// <summary> /// Check for one available update and writes new results to stdout as JSON. /// </summary> public virtual bool? CheckForUpdate { get; internal set; } /// <summary> /// Update the application to the latest remote version specified by URL. /// </summary> public virtual string Update { get; internal set; } /// <summary> /// Update or generate a releases directory with a given NuGet package. /// </summary> public virtual string Releasify { get; internal set; } /// <summary> /// Create a shortcut for the given executable name. /// </summary> public virtual string CreateShortcut { get; internal set; } /// <summary> /// Remove a shortcut for the given executable name. /// </summary> public virtual string RemoveShortcut { get; internal set; } /// <summary> /// Copy the currently executing Update.exe into the default location. /// </summary> public virtual string UpdateSelf { get; internal set; } /// <summary> /// Start an executable in the latest version of the app package. /// </summary> public virtual string ProcessStart { get; internal set; } /// <summary> /// Start an executable in the latest version of the app package. /// </summary> public virtual string ProcessStartAndWait { get; internal set; } /// <summary> /// Path to a release directory to use with releasify. /// </summary> public virtual string ReleaseDirectory { get; internal set; } /// <summary> /// Path to the NuGet Packages directory for C# apps. /// </summary> public virtual string PackagesDirectory { get; internal set; } /// <summary> /// Path to the Setup.exe to use as a template. /// </summary> public virtual string BootstrapperExecutable { get; internal set; } /// <summary> /// Path to an animated GIF to be displayed during installation. /// </summary> public virtual string LoadingGif { get; internal set; } /// <summary> /// Path to an ICO file that will be used for icon shortcuts. /// </summary> public virtual string Icon { get; internal set; } /// <summary> /// Path to an ICO file that will be used for the Setup executable's icon. /// </summary> public virtual string SetupIcon { get; internal set; } /// <summary> /// Sign the installer via SignTool.exe with the parameters given. /// </summary> public virtual string SignWithParameters { get; internal set; } /// <summary> /// Provides a base URL to prefix the RELEASES file packages with. /// </summary> public virtual string BaseUrl { get; internal set; } /// <summary> /// Arguments that will be used when starting executable. /// </summary> public virtual string ProcessStartArguments { get; internal set; } /// <summary> /// Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'. /// </summary> public virtual IReadOnlyList<string> ShortcutLocations => ShortcutLocationsInternal.AsReadOnly(); internal List<string> ShortcutLocationsInternal { get; set; } = new List<string>(); /// <summary> /// Don't generate an MSI package. /// </summary> public virtual bool? GenerateNoMsi { get; internal set; } /// <summary> /// Don't generate delta packages to save time /// </summary> public virtual bool? GenerateNoDelta { get; internal set; } /// <summary> /// Set the required .NET framework version, e.g. net461 /// </summary> public virtual string FrameworkVersion { get; internal set; } protected override Arguments ConfigureProcessArguments(Arguments arguments) { arguments .Add("--install={value}", Install) .Add("--uninstall", Uninstall) .Add("--download", Download) .Add("--checkForUpdate", CheckForUpdate) .Add("--update={value}", Update) .Add("--releasify={value}", Releasify) .Add("--createShortcut={value}", CreateShortcut) .Add("--removeShortcut={value}", RemoveShortcut) .Add("--updateSelf={value}", UpdateSelf) .Add("--processStart={value}", ProcessStart) .Add("--processStartAndWait={value}", ProcessStartAndWait) .Add("--releaseDir={value}", ReleaseDirectory) .Add("--packagesDir={value}", PackagesDirectory) .Add("--bootstrapperExe={value}", BootstrapperExecutable) .Add("--loadingGif={value}", LoadingGif) .Add("--icon={value}", Icon) .Add("--setupIcon={value}", SetupIcon) .Add("--signWithParams={value}", SignWithParameters) .Add("--baseUrl={value}", BaseUrl) .Add("--process-start-args={value}", ProcessStartArguments) .Add("--shortcut-locations={value}", ShortcutLocations, separator: ',') .Add("--no-msi", GenerateNoMsi) .Add("--no-delta", GenerateNoDelta) .Add("--framework-version={value}", FrameworkVersion); return base.ConfigureProcessArguments(arguments); } } #endregion #region SquirrelSettingsExtensions /// <summary> /// Used within <see cref="SquirrelTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class SquirrelSettingsExtensions { #region Install /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.Install"/></em></p> /// <p>Install the app whose package is in the specified directory.</p> /// </summary> [Pure] public static T SetInstall<T>(this T toolSettings, string install) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Install = install; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.Install"/></em></p> /// <p>Install the app whose package is in the specified directory.</p> /// </summary> [Pure] public static T ResetInstall<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Install = null; return toolSettings; } #endregion #region Uninstall /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.Uninstall"/></em></p> /// <p>Uninstall the app the same dir as Update.exe.</p> /// </summary> [Pure] public static T SetUninstall<T>(this T toolSettings, bool? uninstall) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Uninstall = uninstall; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.Uninstall"/></em></p> /// <p>Uninstall the app the same dir as Update.exe.</p> /// </summary> [Pure] public static T ResetUninstall<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Uninstall = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="SquirrelSettings.Uninstall"/></em></p> /// <p>Uninstall the app the same dir as Update.exe.</p> /// </summary> [Pure] public static T EnableUninstall<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Uninstall = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="SquirrelSettings.Uninstall"/></em></p> /// <p>Uninstall the app the same dir as Update.exe.</p> /// </summary> [Pure] public static T DisableUninstall<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Uninstall = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="SquirrelSettings.Uninstall"/></em></p> /// <p>Uninstall the app the same dir as Update.exe.</p> /// </summary> [Pure] public static T ToggleUninstall<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Uninstall = !toolSettings.Uninstall; return toolSettings; } #endregion #region Download /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.Download"/></em></p> /// <p>Download the releases specified by the URL and write new results to stdout as JSON.</p> /// </summary> [Pure] public static T SetDownload<T>(this T toolSettings, bool? download) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Download = download; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.Download"/></em></p> /// <p>Download the releases specified by the URL and write new results to stdout as JSON.</p> /// </summary> [Pure] public static T ResetDownload<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Download = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="SquirrelSettings.Download"/></em></p> /// <p>Download the releases specified by the URL and write new results to stdout as JSON.</p> /// </summary> [Pure] public static T EnableDownload<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Download = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="SquirrelSettings.Download"/></em></p> /// <p>Download the releases specified by the URL and write new results to stdout as JSON.</p> /// </summary> [Pure] public static T DisableDownload<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Download = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="SquirrelSettings.Download"/></em></p> /// <p>Download the releases specified by the URL and write new results to stdout as JSON.</p> /// </summary> [Pure] public static T ToggleDownload<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Download = !toolSettings.Download; return toolSettings; } #endregion #region CheckForUpdate /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.CheckForUpdate"/></em></p> /// <p>Check for one available update and writes new results to stdout as JSON.</p> /// </summary> [Pure] public static T SetCheckForUpdate<T>(this T toolSettings, bool? checkForUpdate) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CheckForUpdate = checkForUpdate; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.CheckForUpdate"/></em></p> /// <p>Check for one available update and writes new results to stdout as JSON.</p> /// </summary> [Pure] public static T ResetCheckForUpdate<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CheckForUpdate = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="SquirrelSettings.CheckForUpdate"/></em></p> /// <p>Check for one available update and writes new results to stdout as JSON.</p> /// </summary> [Pure] public static T EnableCheckForUpdate<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CheckForUpdate = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="SquirrelSettings.CheckForUpdate"/></em></p> /// <p>Check for one available update and writes new results to stdout as JSON.</p> /// </summary> [Pure] public static T DisableCheckForUpdate<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CheckForUpdate = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="SquirrelSettings.CheckForUpdate"/></em></p> /// <p>Check for one available update and writes new results to stdout as JSON.</p> /// </summary> [Pure] public static T ToggleCheckForUpdate<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CheckForUpdate = !toolSettings.CheckForUpdate; return toolSettings; } #endregion #region Update /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.Update"/></em></p> /// <p>Update the application to the latest remote version specified by URL.</p> /// </summary> [Pure] public static T SetUpdate<T>(this T toolSettings, string update) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Update = update; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.Update"/></em></p> /// <p>Update the application to the latest remote version specified by URL.</p> /// </summary> [Pure] public static T ResetUpdate<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Update = null; return toolSettings; } #endregion #region Releasify /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.Releasify"/></em></p> /// <p>Update or generate a releases directory with a given NuGet package.</p> /// </summary> [Pure] public static T SetReleasify<T>(this T toolSettings, string releasify) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Releasify = releasify; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.Releasify"/></em></p> /// <p>Update or generate a releases directory with a given NuGet package.</p> /// </summary> [Pure] public static T ResetReleasify<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Releasify = null; return toolSettings; } #endregion #region CreateShortcut /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.CreateShortcut"/></em></p> /// <p>Create a shortcut for the given executable name.</p> /// </summary> [Pure] public static T SetCreateShortcut<T>(this T toolSettings, string createShortcut) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CreateShortcut = createShortcut; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.CreateShortcut"/></em></p> /// <p>Create a shortcut for the given executable name.</p> /// </summary> [Pure] public static T ResetCreateShortcut<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.CreateShortcut = null; return toolSettings; } #endregion #region RemoveShortcut /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.RemoveShortcut"/></em></p> /// <p>Remove a shortcut for the given executable name.</p> /// </summary> [Pure] public static T SetRemoveShortcut<T>(this T toolSettings, string removeShortcut) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RemoveShortcut = removeShortcut; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.RemoveShortcut"/></em></p> /// <p>Remove a shortcut for the given executable name.</p> /// </summary> [Pure] public static T ResetRemoveShortcut<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.RemoveShortcut = null; return toolSettings; } #endregion #region UpdateSelf /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.UpdateSelf"/></em></p> /// <p>Copy the currently executing Update.exe into the default location.</p> /// </summary> [Pure] public static T SetUpdateSelf<T>(this T toolSettings, string updateSelf) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpdateSelf = updateSelf; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.UpdateSelf"/></em></p> /// <p>Copy the currently executing Update.exe into the default location.</p> /// </summary> [Pure] public static T ResetUpdateSelf<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.UpdateSelf = null; return toolSettings; } #endregion #region ProcessStart /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.ProcessStart"/></em></p> /// <p>Start an executable in the latest version of the app package.</p> /// </summary> [Pure] public static T SetProcessStart<T>(this T toolSettings, string processStart) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ProcessStart = processStart; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.ProcessStart"/></em></p> /// <p>Start an executable in the latest version of the app package.</p> /// </summary> [Pure] public static T ResetProcessStart<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ProcessStart = null; return toolSettings; } #endregion #region ProcessStartAndWait /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.ProcessStartAndWait"/></em></p> /// <p>Start an executable in the latest version of the app package.</p> /// </summary> [Pure] public static T SetProcessStartAndWait<T>(this T toolSettings, string processStartAndWait) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ProcessStartAndWait = processStartAndWait; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.ProcessStartAndWait"/></em></p> /// <p>Start an executable in the latest version of the app package.</p> /// </summary> [Pure] public static T ResetProcessStartAndWait<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ProcessStartAndWait = null; return toolSettings; } #endregion #region ReleaseDirectory /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.ReleaseDirectory"/></em></p> /// <p>Path to a release directory to use with releasify.</p> /// </summary> [Pure] public static T SetReleaseDirectory<T>(this T toolSettings, string releaseDirectory) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ReleaseDirectory = releaseDirectory; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.ReleaseDirectory"/></em></p> /// <p>Path to a release directory to use with releasify.</p> /// </summary> [Pure] public static T ResetReleaseDirectory<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ReleaseDirectory = null; return toolSettings; } #endregion #region PackagesDirectory /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.PackagesDirectory"/></em></p> /// <p>Path to the NuGet Packages directory for C# apps.</p> /// </summary> [Pure] public static T SetPackagesDirectory<T>(this T toolSettings, string packagesDirectory) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.PackagesDirectory = packagesDirectory; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.PackagesDirectory"/></em></p> /// <p>Path to the NuGet Packages directory for C# apps.</p> /// </summary> [Pure] public static T ResetPackagesDirectory<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.PackagesDirectory = null; return toolSettings; } #endregion #region BootstrapperExecutable /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.BootstrapperExecutable"/></em></p> /// <p>Path to the Setup.exe to use as a template.</p> /// </summary> [Pure] public static T SetBootstrapperExecutable<T>(this T toolSettings, string bootstrapperExecutable) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.BootstrapperExecutable = bootstrapperExecutable; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.BootstrapperExecutable"/></em></p> /// <p>Path to the Setup.exe to use as a template.</p> /// </summary> [Pure] public static T ResetBootstrapperExecutable<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.BootstrapperExecutable = null; return toolSettings; } #endregion #region LoadingGif /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.LoadingGif"/></em></p> /// <p>Path to an animated GIF to be displayed during installation.</p> /// </summary> [Pure] public static T SetLoadingGif<T>(this T toolSettings, string loadingGif) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.LoadingGif = loadingGif; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.LoadingGif"/></em></p> /// <p>Path to an animated GIF to be displayed during installation.</p> /// </summary> [Pure] public static T ResetLoadingGif<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.LoadingGif = null; return toolSettings; } #endregion #region Icon /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.Icon"/></em></p> /// <p>Path to an ICO file that will be used for icon shortcuts.</p> /// </summary> [Pure] public static T SetIcon<T>(this T toolSettings, string icon) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Icon = icon; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.Icon"/></em></p> /// <p>Path to an ICO file that will be used for icon shortcuts.</p> /// </summary> [Pure] public static T ResetIcon<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Icon = null; return toolSettings; } #endregion #region SetupIcon /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.SetupIcon"/></em></p> /// <p>Path to an ICO file that will be used for the Setup executable's icon.</p> /// </summary> [Pure] public static T SetSetupIcon<T>(this T toolSettings, string setupIcon) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.SetupIcon = setupIcon; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.SetupIcon"/></em></p> /// <p>Path to an ICO file that will be used for the Setup executable's icon.</p> /// </summary> [Pure] public static T ResetSetupIcon<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.SetupIcon = null; return toolSettings; } #endregion #region SignWithParameters /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.SignWithParameters"/></em></p> /// <p>Sign the installer via SignTool.exe with the parameters given.</p> /// </summary> [Pure] public static T SetSignWithParameters<T>(this T toolSettings, string signWithParameters) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.SignWithParameters = signWithParameters; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.SignWithParameters"/></em></p> /// <p>Sign the installer via SignTool.exe with the parameters given.</p> /// </summary> [Pure] public static T ResetSignWithParameters<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.SignWithParameters = null; return toolSettings; } #endregion #region BaseUrl /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.BaseUrl"/></em></p> /// <p>Provides a base URL to prefix the RELEASES file packages with.</p> /// </summary> [Pure] public static T SetBaseUrl<T>(this T toolSettings, string baseUrl) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.BaseUrl = baseUrl; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.BaseUrl"/></em></p> /// <p>Provides a base URL to prefix the RELEASES file packages with.</p> /// </summary> [Pure] public static T ResetBaseUrl<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.BaseUrl = null; return toolSettings; } #endregion #region ProcessStartArguments /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.ProcessStartArguments"/></em></p> /// <p>Arguments that will be used when starting executable.</p> /// </summary> [Pure] public static T SetProcessStartArguments<T>(this T toolSettings, string processStartArguments) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ProcessStartArguments = processStartArguments; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.ProcessStartArguments"/></em></p> /// <p>Arguments that will be used when starting executable.</p> /// </summary> [Pure] public static T ResetProcessStartArguments<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ProcessStartArguments = null; return toolSettings; } #endregion #region ShortcutLocations /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.ShortcutLocations"/> to a new list</em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T SetShortcutLocations<T>(this T toolSettings, params string[] shortcutLocations) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ShortcutLocationsInternal = shortcutLocations.ToList(); return toolSettings; } /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.ShortcutLocations"/> to a new list</em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T SetShortcutLocations<T>(this T toolSettings, IEnumerable<string> shortcutLocations) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ShortcutLocationsInternal = shortcutLocations.ToList(); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="SquirrelSettings.ShortcutLocations"/></em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T AddShortcutLocations<T>(this T toolSettings, params string[] shortcutLocations) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ShortcutLocationsInternal.AddRange(shortcutLocations); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="SquirrelSettings.ShortcutLocations"/></em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T AddShortcutLocations<T>(this T toolSettings, IEnumerable<string> shortcutLocations) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ShortcutLocationsInternal.AddRange(shortcutLocations); return toolSettings; } /// <summary> /// <p><em>Clears <see cref="SquirrelSettings.ShortcutLocations"/></em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T ClearShortcutLocations<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ShortcutLocationsInternal.Clear(); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="SquirrelSettings.ShortcutLocations"/></em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T RemoveShortcutLocations<T>(this T toolSettings, params string[] shortcutLocations) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(shortcutLocations); toolSettings.ShortcutLocationsInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="SquirrelSettings.ShortcutLocations"/></em></p> /// <p>Comma-separated string of shortcut locations, e.g. 'Desktop,StartMenu'.</p> /// </summary> [Pure] public static T RemoveShortcutLocations<T>(this T toolSettings, IEnumerable<string> shortcutLocations) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(shortcutLocations); toolSettings.ShortcutLocationsInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } #endregion #region GenerateNoMsi /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.GenerateNoMsi"/></em></p> /// <p>Don't generate an MSI package.</p> /// </summary> [Pure] public static T SetGenerateNoMsi<T>(this T toolSettings, bool? generateNoMsi) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoMsi = generateNoMsi; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.GenerateNoMsi"/></em></p> /// <p>Don't generate an MSI package.</p> /// </summary> [Pure] public static T ResetGenerateNoMsi<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoMsi = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="SquirrelSettings.GenerateNoMsi"/></em></p> /// <p>Don't generate an MSI package.</p> /// </summary> [Pure] public static T EnableGenerateNoMsi<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoMsi = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="SquirrelSettings.GenerateNoMsi"/></em></p> /// <p>Don't generate an MSI package.</p> /// </summary> [Pure] public static T DisableGenerateNoMsi<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoMsi = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="SquirrelSettings.GenerateNoMsi"/></em></p> /// <p>Don't generate an MSI package.</p> /// </summary> [Pure] public static T ToggleGenerateNoMsi<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoMsi = !toolSettings.GenerateNoMsi; return toolSettings; } #endregion #region GenerateNoDelta /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.GenerateNoDelta"/></em></p> /// <p>Don't generate delta packages to save time</p> /// </summary> [Pure] public static T SetGenerateNoDelta<T>(this T toolSettings, bool? generateNoDelta) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoDelta = generateNoDelta; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.GenerateNoDelta"/></em></p> /// <p>Don't generate delta packages to save time</p> /// </summary> [Pure] public static T ResetGenerateNoDelta<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoDelta = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="SquirrelSettings.GenerateNoDelta"/></em></p> /// <p>Don't generate delta packages to save time</p> /// </summary> [Pure] public static T EnableGenerateNoDelta<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoDelta = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="SquirrelSettings.GenerateNoDelta"/></em></p> /// <p>Don't generate delta packages to save time</p> /// </summary> [Pure] public static T DisableGenerateNoDelta<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoDelta = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="SquirrelSettings.GenerateNoDelta"/></em></p> /// <p>Don't generate delta packages to save time</p> /// </summary> [Pure] public static T ToggleGenerateNoDelta<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.GenerateNoDelta = !toolSettings.GenerateNoDelta; return toolSettings; } #endregion #region FrameworkVersion /// <summary> /// <p><em>Sets <see cref="SquirrelSettings.FrameworkVersion"/></em></p> /// <p>Set the required .NET framework version, e.g. net461</p> /// </summary> [Pure] public static T SetFrameworkVersion<T>(this T toolSettings, string frameworkVersion) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.FrameworkVersion = frameworkVersion; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="SquirrelSettings.FrameworkVersion"/></em></p> /// <p>Set the required .NET framework version, e.g. net461</p> /// </summary> [Pure] public static T ResetFrameworkVersion<T>(this T toolSettings) where T : SquirrelSettings { toolSettings = toolSettings.NewInstance(); toolSettings.FrameworkVersion = null; return toolSettings; } #endregion } #endregion }
using System; using System.Windows.Forms; // Form namespace au.util.comctl { internal partial class SimpleCalcForm : Form { private const string NUM_FORMAT = "{0:#,##0.######}"; private enum Operator { Add, Subtract, Multiply, Divide } #region Data Members private double _total; private Operator _op; #endregion #region Constructors public SimpleCalcForm() { InitializeComponent(); _total = 0; _op = Operator.Add; } #endregion // Constructors #region Properties /// <summary> /// Gets or sets the current value held by the simple calculator /// </summary> public double Value { get { return double.Parse(_txtNumber.Text); } set { _txtNumber.Text = string.Format(NUM_FORMAT, value); } } #endregion // Properties #region Methods /// <summary> /// Clear the current display value or reset the calculator to zero /// </summary> private void Clear() { if(_txtNumber.Text == "0") { _total = 0; _op = Operator.Add; } else _txtNumber.Text = "0"; } /// <summary> /// Perform queued operation /// </summary> private void Operate() { switch(_op) { case Operator.Add: _total += double.Parse(_txtNumber.Text); break; case Operator.Subtract: _total -= double.Parse(_txtNumber.Text); break; case Operator.Multiply: _total *= double.Parse(_txtNumber.Text); break; case Operator.Divide: _total /= double.Parse(_txtNumber.Text); break; } } /// <summary> /// Perform queued operation and queue the next operation /// </summary> /// <param name="op">Next operation</param> private void Operate(Operator op) { Operate(); _txtNumber.Text = "0"; _op = op; } /// <summary> /// Append a digit to the currently displayed value /// </summary> /// <param name="d">The digit to append</param> private void Digit(int d) { if(_txtNumber.Text == "0") _txtNumber.Text = d.ToString(); else if(_txtNumber.Text.IndexOf('.') > -1) _txtNumber.Text += d.ToString(); else { _txtNumber.Text = string.Format(NUM_FORMAT, Value * 10 + d); } } /// <summary> /// Place a decimal point at the end of the displayed number /// </summary> private void Decimal() { _txtNumber.Text += "."; } /// <summary> /// Evaluate the queued operation and place the result in the display /// </summary> private void Evaluate() { Operate(); _txtNumber.Text = string.Format(NUM_FORMAT, _total); _total = 0; _op = Operator.Add; } private void Backspace() { string tmp = _txtNumber.Text.Substring(0, _txtNumber.Text.Length - 1); if(tmp.IndexOf('.') > -1) _txtNumber.Text = tmp; else _txtNumber.Text = string.Format(NUM_FORMAT, double.Parse(tmp)); } #endregion // Methods #region Event Handlers private void SimpleCalcForm_KeyPress(object sender, KeyPressEventArgs e) { switch(e.KeyChar) { case 'c': Clear(); break; case 'C': Clear(); break; case '+': Operate(Operator.Add); break; case '-': Operate(Operator.Subtract); break; case '*': Operate(Operator.Multiply); break; case '/': Operate(Operator.Divide); break; case '0': Digit(0); break; case '1': Digit(1); break; case '2': Digit(2); break; case '3': Digit(3); break; case '4': Digit(4); break; case '5': Digit(5); break; case '6': Digit(6); break; case '7': Digit(7); break; case '8': Digit(8); break; case '9': Digit(9); break; case '.': Decimal(); break; case (char)8: Backspace(); break; case '=': Evaluate(); break; } } private void _btnClear_Click(object sender, EventArgs e) { Clear(); } private void _btnDivide_Click(object sender, EventArgs e) { Operate(Operator.Divide); } private void _btnMultiply_Click(object sender, EventArgs e) { Operate(Operator.Multiply); } private void _btnSubtract_Click(object sender, EventArgs e) { Operate(Operator.Subtract); } private void _btnAdd_Click(object sender, EventArgs e) { Operate(Operator.Add); } private void _btnEquals_Click(object sender, EventArgs e) { Evaluate(); } private void _btn9_Click(object sender, EventArgs e) { Digit(9); } private void _btn8_Click(object sender, EventArgs e) { Digit(8); } private void _btn7_Click(object sender, EventArgs e) { Digit(7); } private void _btn6_Click(object sender, EventArgs e) { Digit(6); } private void _btn5_Click(object sender, EventArgs e) { Digit(5); } private void _btn4_Click(object sender, EventArgs e) { Digit(4); } private void _btn3_Click(object sender, EventArgs e) { Digit(3); } private void _btn2_Click(object sender, EventArgs e) { Digit(2); } private void _btn1_Click(object sender, EventArgs e) { Digit(1); } private void _btn0_Click(object sender, EventArgs e) { Digit(0); } private void _btnDecimal_Click(object sender, EventArgs e) { Decimal(); } private void _btnOK_Click(object sender, EventArgs e) { Close(); } private void _btnCancel_Click(object sender, EventArgs e) { Close(); } #endregion // Event Handlers } }
#region File Description //----------------------------------------------------------------------------- // HeightmapCollision.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace HeightmapCollision { /// <summary> /// Sample showing how to use get the height of a programmatically generated /// heightmap. /// </summary> public class HeightmapCollisionGame : Microsoft.Xna.Framework.Game { #region Constants // This constant controls how quickly the sphere can move forward and backward const float SphereVelocity = 2; // how quickly the sphere can turn from side to side const float SphereTurnSpeed = .025f; // the radius of the sphere. We'll use this to keep the sphere above the ground, // and when computing how far the sphere has rolled. const float SphereRadius = 12.0f; // This vector controls how much the camera's position is offset from the // sphere. This value can be changed to move the camera further away from or // closer to the sphere. readonly Vector3 CameraPositionOffset = new Vector3(0, 40, 150); // This value controls the point the camera will aim at. This value is an offset // from the sphere's position. readonly Vector3 CameraTargetOffset = new Vector3(0, 30, 0); #endregion #region Fields GraphicsDeviceManager graphics; Model terrain; Matrix projectionMatrix; Matrix viewMatrix; Vector3 spherePosition; float sphereFacingDirection; Matrix sphereRollingMatrix = Matrix.Identity; Model sphere; HeightMapInfo heightMapInfo; #endregion #region Initialization public HeightmapCollisionGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { // now that the GraphicsDevice has been created, we can create the projection matrix. projectionMatrix = Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), GraphicsDevice.Viewport.AspectRatio, 1f, 10000); base.Initialize(); } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { terrain = Content.Load<Model>("terrain"); // The terrain processor attached a HeightMapInfo to the terrain model's // Tag. We'll save that to a member variable now, and use it to // calculate the terrain's heights later. heightMapInfo = terrain.Tag as HeightMapInfo; if (heightMapInfo == null) { string message = "The terrain model did not have a HeightMapInfo " + "object attached. Are you sure you are using the " + "TerrainProcessor?"; throw new InvalidOperationException(message); } sphere = Content.Load<Model>("sphere"); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); UpdateCamera(); base.Update(gameTime); } /// <summary> /// this function will calculate the camera's position and the position of /// its target. From those, we'll update the viewMatrix. /// </summary> private void UpdateCamera() { // The camera's position depends on the sphere's facing direction: when the // sphere turns, the camera needs to stay behind it. So, we'll calculate a // rotation matrix using the sphere's facing direction, and use it to // transform the two offset values that control the camera. Matrix cameraFacingMatrix = Matrix.CreateRotationY(sphereFacingDirection); Vector3 positionOffset = Vector3.Transform(CameraPositionOffset, cameraFacingMatrix); Vector3 targetOffset = Vector3.Transform(CameraTargetOffset, cameraFacingMatrix); // once we've transformed the camera's position offset vector, it's easy to // figure out where we think the camera should be. Vector3 cameraPosition = spherePosition + positionOffset; // We don't want the camera to go beneath the heightmap, so if the camera is // over the terrain, we'll move it up. if (heightMapInfo.IsOnHeightmap(cameraPosition)) { // we don't want the camera to go beneath the terrain's height + // a small offset. float minimumHeight = heightMapInfo.GetHeight(cameraPosition) + CameraPositionOffset.Y; if (cameraPosition.Y < minimumHeight) { cameraPosition.Y = minimumHeight; } } // next, we need to calculate the point that the camera is aiming it. That's // simple enough - the camera is aiming at the sphere, and has to take the // targetOffset into account. Vector3 cameraTarget = spherePosition + targetOffset; // with those values, we'll calculate the viewMatrix. viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { GraphicsDevice device = graphics.GraphicsDevice; device.Clear(Color.Black); DrawModel(terrain, Matrix.Identity); DrawModel(sphere, sphereRollingMatrix * Matrix.CreateTranslation(spherePosition)); // If there was any alpha blended translucent geometry in // the scene, that would be drawn here. base.Draw(gameTime); } /// <summary> /// Helper for drawing the terrain model. /// </summary> void DrawModel(Model model, Matrix worldMatrix) { Matrix[] boneTransforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(boneTransforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix; effect.View = viewMatrix; effect.Projection = projectionMatrix; effect.EnableDefaultLighting(); effect.PreferPerPixelLighting = true; // Set the fog to match the black background color effect.FogEnabled = true; effect.FogColor = Vector3.Zero; effect.FogStart = 1000; effect.FogEnd = 3200; } mesh.Draw(); } } #endregion #region Handle Input /// <summary> /// Handles input for quitting the game. /// </summary> private void HandleInput() { KeyboardState currentKeyboardState = Keyboard.GetState(); GamePadState currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.Buttons.Back == ButtonState.Pressed) { Exit(); } // Now move the sphere. First, we want to check to see if the sphere should // turn. turnAmount will be an accumulation of all the different possible // inputs. float turnAmount = -currentGamePadState.ThumbSticks.Left.X; if (currentKeyboardState.IsKeyDown(Keys.A) || currentKeyboardState.IsKeyDown(Keys.Left) || currentGamePadState.DPad.Left == ButtonState.Pressed) { turnAmount += 1; } if (currentKeyboardState.IsKeyDown(Keys.D) || currentKeyboardState.IsKeyDown(Keys.Right) || currentGamePadState.DPad.Right == ButtonState.Pressed) { turnAmount -= 1; } // clamp the turn amount between -1 and 1, and then use the finished // value to turn the sphere. turnAmount = MathHelper.Clamp(turnAmount, -1, 1); sphereFacingDirection += turnAmount * SphereTurnSpeed; // Next, we want to move the sphere forward or back. to do this, // we'll create a Vector3 and modify use the user's input to modify the Z // component, which corresponds to the forward direction. Vector3 movement = Vector3.Zero; movement.Z = -currentGamePadState.ThumbSticks.Left.Y; if (currentKeyboardState.IsKeyDown(Keys.W) || currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed) { movement.Z = -1; } if (currentKeyboardState.IsKeyDown(Keys.S) || currentKeyboardState.IsKeyDown(Keys.Down) || currentGamePadState.DPad.Down == ButtonState.Pressed) { movement.Z = 1; } // next, we'll create a rotation matrix from the sphereFacingDirection, and // use it to transform the vector. If we didn't do this, pressing "up" would // always move the ball along +Z. By transforming it, we can move in the // direction the sphere is "facing." Matrix sphereFacingMatrix = Matrix.CreateRotationY(sphereFacingDirection); Vector3 velocity = Vector3.Transform(movement, sphereFacingMatrix); velocity *= SphereVelocity; // Now we know how much the user wants to move. We'll construct a temporary // vector, newSpherePosition, which will represent where the user wants to // go. If that value is on the heightmap, we'll allow the move. Vector3 newSpherePosition = spherePosition + velocity; if (heightMapInfo.IsOnHeightmap(newSpherePosition)) { // finally, we need to see how high the terrain is at the sphere's new // position. GetHeight will give us that information, which is offset by // the size of the sphere. If we didn't offset by the size of the // sphere, it would be drawn halfway through the world, which looks // a little odd. newSpherePosition.Y = heightMapInfo.GetHeight(newSpherePosition) + SphereRadius; } else { newSpherePosition = spherePosition; } // now we need to roll the ball "forward." to do this, we first calculate // how far it has moved. float distanceMoved = Vector3.Distance(spherePosition, newSpherePosition); // The length of an arc on a circle or sphere is defined as L = theta * r, // where theta is the angle that defines the arc, and r is the radius of // the circle. // we know L, that's the distance the sphere has moved. we know r, that's // our constant "sphereRadius". We want to know theta - that will tell us // how much to rotate the sphere. we rearrange the equation to get... float theta = distanceMoved / SphereRadius; // now that we know how much to rotate the sphere, we have to figure out // whether it will roll forward or backward. We'll base this on the user's // input. int rollDirection = movement.Z > 0 ? 1 : -1; // finally, we'll roll it by rotating around the sphere's "right" vector. sphereRollingMatrix *= Matrix.CreateFromAxisAngle(sphereFacingMatrix.Right, theta * rollDirection); // once we've finished all computations, we can set spherePosition to the // new position that we calculated. spherePosition = newSpherePosition; } #endregion } #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (HeightmapCollisionGame game = new HeightmapCollisionGame()) { game.Run(); } } } #endregion }
// // X509CertificateStore.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013 Jeffrey Stedfast // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using Org.BouncyCastle.Security; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace MimeKit.Cryptography { /// <summary> /// A store for X.509 certificates and keys. /// </summary> public class X509CertificateStore : IX509Store { readonly Dictionary<X509Certificate, AsymmetricKeyParameter> keys; readonly HashSet<X509Certificate> unique; readonly List<X509Certificate> certs; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.X509CertificateStore"/> class. /// </summary> public X509CertificateStore () { keys = new Dictionary<X509Certificate, AsymmetricKeyParameter> (); unique = new HashSet<X509Certificate> (); certs = new List<X509Certificate> (); } /// <summary> /// Gets a read-only list of certificates currently in the store. /// </summary> /// <value>The certificates.</value> public IEnumerable<X509Certificate> Certificates { get { return certs; } } /// <summary> /// Gets the private key for the specified certificate. /// </summary> /// <returns>The private key on success; otherwise <c>null</c>.</returns> /// <param name="certificate">The certificate.</param> public AsymmetricKeyParameter GetPrivateKey (X509Certificate certificate) { AsymmetricKeyParameter key; if (!keys.TryGetValue (certificate, out key)) return null; return key; } /// <summary> /// Add the specified certificate. /// </summary> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public void Add (X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); if (unique.Add (certificate)) certs.Add (certificate); } /// <summary> /// Adds the specified range of certificates. /// </summary> /// <param name="certificates">The certificates.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificates"/> is <c>null</c>. /// </exception> public void AddRange (IEnumerable<X509Certificate> certificates) { if (certificates == null) throw new ArgumentNullException ("certificates"); foreach (var certificate in certificates) { if (unique.Add (certificate)) certs.Add (certificate); } } /// <summary> /// Remove the specified certificate. /// </summary> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public void Remove (X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); if (unique.Remove (certificate)) certs.Remove (certificate); } /// <summary> /// Removes the specified range of certificates. /// </summary> /// <param name="certificates">The certificates.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificates"/> is <c>null</c>. /// </exception> public void RemoveRange (IEnumerable<X509Certificate> certificates) { if (certificates == null) throw new ArgumentNullException ("certificates"); foreach (var certificate in certificates) { if (unique.Remove (certificate)) certs.Remove (certificate); } } /// <summary> /// Import the certificate(s) from the specified stream. /// </summary> /// <param name="stream">The stream to import.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the stream. /// </exception> public void Import (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); var parser = new X509CertificateParser (); foreach (X509Certificate certificate in parser.ReadCertificates (stream)) { if (unique.Add (certificate)) certs.Add (certificate); } } /// <summary> /// Import the certificate(s) from the specified file. /// </summary> /// <param name="fileName">The name of the file to import.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="fileName"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file could not be found. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the file. /// </exception> public void Import (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); using (var stream = File.OpenRead (fileName)) Import (stream); } /// <summary> /// Import the certificate(s) from the specified byte array. /// </summary> /// <param name="rawData">The raw certificate data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="rawData"/> is <c>null</c>. /// </exception> public void Import (byte[] rawData) { if (rawData == null) throw new ArgumentNullException ("rawData"); using (var stream = new MemoryStream (rawData, false)) Import (stream); } /// <summary> /// Import certificates and private keys from the specified stream. /// </summary> /// <param name="stream">The stream to import.</param> /// <param name="password">The password to unlock the stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the stream. /// </exception> public void Import (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ()); foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry (alias)) { var chain = pkcs12.GetCertificateChain (alias); var entry = pkcs12.GetKey (alias); for (int i = 0; i < chain.Length; i++) { if (unique.Add (chain[i].Certificate)) certs.Add (chain[i].Certificate); } if (entry.Key.IsPrivate) keys.Add (chain[0].Certificate, entry.Key); } else if (pkcs12.IsCertificateEntry (alias)) { var entry = pkcs12.GetCertificate (alias); if (unique.Add (entry.Certificate)) certs.Add (entry.Certificate); } } } /// <summary> /// Import certificates and private keys from the specified file. /// </summary> /// <param name="fileName">The name of the file to import.</param> /// <param name="password">The password to unlock the file.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="fileName"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// The specified file path is empty. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file could not be found. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to read the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the file. /// </exception> public void Import (string fileName, string password) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (string.IsNullOrEmpty (fileName)) throw new ArgumentException ("The specified path is empty.", "fileName"); using (var stream = File.OpenRead (fileName)) Import (stream, password); } /// <summary> /// Import certificates and private keys from the specified byte array. /// </summary> /// <param name="rawData">The raw certificate data.</param> /// <param name="password">The password to unlock the raw data.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="rawData"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> public void Import (byte[] rawData, string password) { if (rawData == null) throw new ArgumentNullException ("rawData"); using (var stream = new MemoryStream (rawData, false)) Import (stream, password); } /// <summary> /// Export the certificates to an unencrypted stream. /// </summary> /// <param name="stream">The output stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); foreach (var certificate in certs) { var encoded = certificate.GetEncoded (); stream.Write (encoded, 0, encoded.Length); } } /// <summary> /// Export the certificates to an unencrypted file. /// </summary> /// <param name="fileName">The file path to write to.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="fileName"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// The specified file path is empty. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// The specified path exceeds the maximum allowed path length of the system. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// A directory in the specified path does not exist. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to create the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (string.IsNullOrEmpty (fileName)) throw new ArgumentException ("The specified path is empty.", "fileName"); using (var file = File.Create (fileName)) { Export (file); } } /// <summary> /// Export the specified stream and password to a pkcs12-formatted file. /// </summary> /// <param name="stream">The output stream.</param> /// <param name="password">The password to use to lock the private keys.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var store = new Pkcs12Store (); foreach (var certificate in certs) { if (keys.ContainsKey (certificate)) continue; var entry = new X509CertificateEntry (certificate); var alias = certificate.GetCommonName (); store.SetCertificateEntry (alias, entry); } foreach (var kvp in keys) { var entry = new AsymmetricKeyEntry (kvp.Value); var cert = new X509CertificateEntry (kvp.Key); var chain = new List<X509CertificateEntry> (); var alias = kvp.Key.GetCommonName (); chain.Add (cert); store.SetKeyEntry (alias, entry, chain.ToArray ()); } store.Save (stream, password.ToCharArray (), new SecureRandom ()); } /// <summary> /// Export the specified stream and password to a pkcs12-formatted file. /// </summary> /// <param name="fileName">The file path to write to.</param> /// <param name="password">The password to use to lock the private keys.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="fileName"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// The specified file path is empty. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// The specified path exceeds the maximum allowed path length of the system. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// A directory in the specified path does not exist. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to create the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (string fileName, string password) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (string.IsNullOrEmpty (fileName)) throw new ArgumentException ("The specified path is empty.", "fileName"); if (password == null) throw new ArgumentNullException ("password"); using (var file = File.Create (fileName)) { Export (file, password); } } /// <summary> /// Gets an enumerator of matching <see cref="Org.BouncyCastle.X509.X509Certificate"/>s /// based on the specified selector. /// </summary> /// <returns>The matching certificates.</returns> /// <param name="selector">The match criteria.</param> public IEnumerable<X509Certificate> GetMatches (IX509Selector selector) { foreach (var certificate in certs) { if (selector == null || selector.Match (certificate)) yield return certificate; } yield break; } #region IX509Store implementation /// <summary> /// Gets a collection of matching <see cref="Org.BouncyCastle.X509.X509Certificate"/>s /// based on the specified selector. /// </summary> /// <returns>The matching certificates.</returns> /// <param name="selector">The match criteria.</param> ICollection IX509Store.GetMatches (IX509Selector selector) { var matches = new List<X509Certificate> (); foreach (var certificate in certs) { if (selector == null || selector.Match (certificate)) matches.Add (certificate); } return matches; } #endregion } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Alachisoft.NCache.Config.NewDom { /// /// <summary> /// @author numan_hanif /// </summary> public class DomHelper { public static Alachisoft.NCache.Config.Dom.CacheServerConfig convertToOldDom(Alachisoft.NCache.Config.NewDom.CacheServerConfig newDom) { Alachisoft.NCache.Config.Dom.CacheServerConfig oldDom = null; try { if (newDom != null) { oldDom = new Alachisoft.NCache.Config.Dom.CacheServerConfig(); if (newDom.CacheSettings != null) { oldDom.Name = newDom.CacheSettings.Name; oldDom.InProc = newDom.CacheSettings.InProc; oldDom.ConfigID = newDom.ConfigID; oldDom.LastModified = newDom.CacheSettings.LastModified; if (newDom.CacheSettings.Log != null) { oldDom.Log = newDom.CacheSettings.Log; } else { oldDom.Log = new Alachisoft.NCache.Config.Dom.Log(); } if (newDom.CacheSettings.PerfCounters != null) { oldDom.PerfCounters = newDom.CacheSettings.PerfCounters; } else { oldDom.PerfCounters = new Alachisoft.NCache.Config.Dom.PerfCounters(); } if (newDom.CacheSettings.QueryIndices != null) { oldDom.QueryIndices = newDom.CacheSettings.QueryIndices; } if (newDom.CacheSettings.Cleanup != null) { oldDom.Cleanup = newDom.CacheSettings.Cleanup; } else { oldDom.Cleanup = new Alachisoft.NCache.Config.Dom.Cleanup(); } if (newDom.CacheSettings.Storage != null) { oldDom.Storage = newDom.CacheSettings.Storage; } else { oldDom.Storage = new Alachisoft.NCache.Config.Dom.Storage(); } if (newDom.CacheSettings.EvictionPolicy != null) { oldDom.EvictionPolicy = newDom.CacheSettings.EvictionPolicy; } else { oldDom.EvictionPolicy = new Alachisoft.NCache.Config.Dom.EvictionPolicy(); } if (newDom.CacheSettings.CacheTopology != null) { oldDom.CacheType = newDom.CacheSettings.CacheType; } if (oldDom.CacheType.Equals("clustered-cache")) { if (newDom.CacheDeployment != null) { if (oldDom.Cluster == null) { oldDom.Cluster = new Alachisoft.NCache.Config.Dom.Cluster(); } string topology = newDom.CacheSettings.CacheTopology.Topology; if (topology != null) { topology = topology.ToLower(); if (topology.Equals("partitioned")) { topology = "partitioned-server"; } else if (topology.Equals("replicated")) { topology = "replicated-server"; } else if (topology.Equals("local")) { topology = "local-cache"; } } oldDom.Cluster.Topology = topology; oldDom.Cluster.OpTimeout = newDom.CacheSettings.CacheTopology.ClusterSettings.OpTimeout; oldDom.Cluster.StatsRepInterval = newDom.CacheSettings.CacheTopology.ClusterSettings.StatsRepInterval; oldDom.Cluster.UseHeartbeat = newDom.CacheSettings.CacheTopology.ClusterSettings.UseHeartbeat; if (oldDom.Cluster.Channel == null) { oldDom.Cluster.Channel = new Alachisoft.NCache.Config.Dom.Channel(); } oldDom.Cluster.Channel.TcpPort = newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.TcpPort; oldDom.Cluster.Channel.PortRange = newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.PortRange; oldDom.Cluster.Channel.ConnectionRetries = newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.ConnectionRetries; oldDom.Cluster.Channel.ConnectionRetryInterval = newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.ConnectionRetryInterval; oldDom.Cluster.Channel.InitialHosts = createInitialHosts(newDom.CacheDeployment.Servers.NodesList,newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.TcpPort); oldDom.Cluster.Channel.NumInitHosts = newDom.CacheDeployment.Servers.NodesList.Count; if (newDom.CacheDeployment.ClientNodes != null) { if (oldDom.ClientNodes == null) { oldDom.ClientNodes = new Alachisoft.NCache.Config.Dom.ClientNodes(); } oldDom.ClientNodes = newDom.CacheDeployment.ClientNodes; } } } if (newDom.CacheSettings.AutoLoadBalancing != null) { oldDom.AutoLoadBalancing = newDom.CacheSettings.AutoLoadBalancing; } oldDom.IsRunning = newDom.IsRunning; oldDom.IsRegistered = newDom.IsRegistered; oldDom.IsExpired = newDom.IsExpired; } } } catch (Exception ex) { throw new Exception("DomHelper.convertToOldDom" + ex.Message); } return oldDom; } public static Alachisoft.NCache.Config.NewDom.CacheServerConfig convertToNewDom(Alachisoft.NCache.Config.Dom.CacheServerConfig oldDom) { Alachisoft.NCache.Config.NewDom.CacheServerConfig newDom = null; try { if (oldDom != null) { newDom = new CacheServerConfig(); if (newDom.CacheSettings == null) { newDom.CacheSettings = new CacheServerConfigSetting(); } newDom.CacheSettings.Name = oldDom.Name; newDom.CacheSettings.InProc = oldDom.InProc; newDom.ConfigID = oldDom.ConfigID; newDom.CacheSettings.LastModified = oldDom.LastModified; if (oldDom.Log != null) { newDom.CacheSettings.Log = oldDom.Log; } else { newDom.CacheSettings.Log = new Alachisoft.NCache.Config.Dom.Log(); } if (oldDom.PerfCounters != null) { newDom.CacheSettings.PerfCounters = oldDom.PerfCounters; } else { newDom.CacheSettings.PerfCounters = new Alachisoft.NCache.Config.Dom.PerfCounters(); } if (oldDom.QueryIndices != null) { newDom.CacheSettings.QueryIndices = oldDom.QueryIndices; } if (oldDom.Cleanup != null) { newDom.CacheSettings.Cleanup = oldDom.Cleanup; } else { newDom.CacheSettings.Cleanup = new Alachisoft.NCache.Config.Dom.Cleanup(); } if (oldDom.Storage != null) { newDom.CacheSettings.Storage = oldDom.Storage; } else { newDom.CacheSettings.Storage = new Alachisoft.NCache.Config.Dom.Storage(); } if (oldDom.EvictionPolicy != null) { newDom.CacheSettings.EvictionPolicy = oldDom.EvictionPolicy; } else { newDom.CacheSettings.EvictionPolicy = oldDom.EvictionPolicy; } if (newDom.CacheSettings.CacheTopology == null) { newDom.CacheSettings.CacheTopology = new CacheTopology(); } newDom.CacheSettings.CacheType = oldDom.CacheType; if (oldDom.Cluster != null) { string topology = oldDom.Cluster.Topology; if (topology != null) { topology = topology.ToLower(); if (topology.Equals("partitioned-server")) { topology = "partitioned"; } else if (topology.Equals("replicated-server")) { topology = "replicated"; } else if (topology.Equals("local-cache")) { topology = "local-cache"; } } newDom.CacheSettings.CacheTopology.Topology = topology; if (oldDom.CacheType.Equals("clustered-cache")) { if (newDom.CacheDeployment == null) { newDom.CacheDeployment = new CacheDeployment(); } if (newDom.CacheSettings.CacheTopology.ClusterSettings == null) { newDom.CacheSettings.CacheTopology.ClusterSettings = new Cluster(); } newDom.CacheSettings.CacheTopology.ClusterSettings.OpTimeout = oldDom.Cluster.OpTimeout; newDom.CacheSettings.CacheTopology.ClusterSettings.StatsRepInterval = oldDom.Cluster.StatsRepInterval; newDom.CacheSettings.CacheTopology.ClusterSettings.UseHeartbeat = oldDom.Cluster.UseHeartbeat; if (newDom.CacheSettings.CacheTopology.ClusterSettings.Channel == null) { newDom.CacheSettings.CacheTopology.ClusterSettings.Channel = new Channel(); } if (oldDom.Cluster.Channel != null) { newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.TcpPort = oldDom.Cluster.Channel.TcpPort; newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.PortRange = oldDom.Cluster.Channel.PortRange; newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.ConnectionRetries = oldDom.Cluster.Channel.ConnectionRetries; newDom.CacheSettings.CacheTopology.ClusterSettings.Channel.ConnectionRetryInterval = oldDom.Cluster.Channel.ConnectionRetryInterval; } if (newDom.CacheDeployment.Servers == null) { newDom.CacheDeployment.Servers = new ServersNodes(); } #if !CLIENT newDom.CacheDeployment.Servers.NodesList = createServers(oldDom.Cluster.Channel.InitialHosts); #endif if (oldDom.ClientNodes != null) { if (newDom.CacheDeployment.ClientNodes == null) { newDom.CacheDeployment.ClientNodes = new Alachisoft.NCache.Config.Dom.ClientNodes(); } newDom.CacheDeployment.ClientNodes = oldDom.ClientNodes; } } } else { if (oldDom.CacheType != null) { if (oldDom.CacheType.Equals("local-cache")) { newDom.CacheSettings.CacheTopology.Topology = oldDom.CacheType; } newDom.CacheSettings.CacheTopology.ClusterSettings = null; } } if (oldDom.AutoLoadBalancing != null) { newDom.CacheSettings.AutoLoadBalancing = oldDom.AutoLoadBalancing; } newDom.IsRunning = oldDom.IsRunning; newDom.IsRegistered = oldDom.IsRegistered; newDom.IsExpired = oldDom.IsExpired; } } catch (Exception ex) { throw new Exception("DomHelper.convertToNewDom" + ex.Message); } return newDom; } #if !CLIENT private static ArrayList createServers(string l) { Global.Tokenizer tok = new Global.Tokenizer(l, ","); string t; Address addr; int port; ArrayList retval = new ArrayList(); Hashtable hosts = new Hashtable(); ServerNode node; //C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: int j = 0; while (tok.HasMoreTokens()) { try { t = tok.NextToken(); //C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: string host = t.Substring(0, (t.IndexOf((char) '[')) - (0)); host = host.Trim(); port = Convert.ToInt32(t.Substring(t.IndexOf((char) '[') + 1, (t.IndexOf((char) ']')) - (t.IndexOf((char) '[') + 1))); node = new ServerNode(host); retval.Add(node); //C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: j++; } catch (FormatException ex) { throw ex; } catch (Exception ex) { throw ex; } } return retval; } #endif private static string createInitialHosts(ArrayList nodes, int port) { string initialhost = ""; try { for (int index = 0; index < nodes.Count; index++) { ServerNode node = (ServerNode) nodes[index]; initialhost = initialhost + node.IP.ToString() + "[" + port + "]"; if (nodes.Count > 1 && index != nodes.Count - 1) { initialhost = initialhost + ","; } } } catch (Exception) { } return initialhost; } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Components.Playable; using IRTaktiks.Components.Scenario; using IRTaktiks.Components.Action; using System.Collections.Generic; using IRTaktiks.Components.Logic; namespace IRTaktiks.Components.Manager { /// <summary> /// Manager of attacks. /// </summary> public class AttackManager { #region Singleton /// <summary> /// The instance of the class. /// </summary> private static AttackManager InstanceField; /// <summary> /// The instance of the class. /// </summary> public static AttackManager Instance { get { if (InstanceField == null) InstanceField = new AttackManager(); return InstanceField; } } /// <summary> /// Private constructor. /// </summary> private AttackManager() { this.Random = new Random(); } #endregion #region Properties /// <summary> /// Random number generator. /// </summary> private Random Random; #endregion #region Construct /// <summary> /// Construct the list of the attacks based on attributes. /// </summary> /// <param name="unit">The unit that the attacks will be constructed.</param> /// <returns>The list of attacks.</returns> public List<Attack> Construct(Unit unit) { List<Attack> attacks = new List<Attack>(); #region Same attacks in all Jobs /* switch (unit.Attributes.Job) { case Job.Assasin: { return attacks; } case Job.Knight: { return attacks; } case Job.Monk: { return attacks; } case Job.Paladin: { return attacks; } case Job.Priest: { return attacks; } case Job.Wizard: { return attacks; } default: { return attacks; } } */ #endregion attacks.Add(new Attack(unit, "Short", Attack.AttackType.Short, Short)); attacks.Add(new Attack(unit, "Long", Attack.AttackType.Long, Long)); return attacks; } #endregion #region Attacks /// <summary> /// Cast the attack. /// (ATK - 0.3 * DEF) + (0.1 * (ATK - 0.3 * DEF)) /// </summary> /// <param name="command">attack casted.</param> /// <param name="caster">The caster of the attack.</param> /// <param name="target">The target of the attack.</param> /// <param name="position">The position of the target.</param> private void Short(Command command, Unit caster, Unit target, Vector2 position) { // Obtain the game instance. IRTGame game = caster.Game as IRTGame; // Effects on caster. caster.Time = 0; // Effects on target. if (target != null) { // Calcule the attack. double attack; attack = (caster.Attributes.Attack - 0.3f * target.Attributes.Defense); attack += this.Random.NextDouble() * 0.1f * attack; attack = attack < 1 ? 1 : attack; // Apply the hit and flee %. int percent = caster.Attributes.Hit - target.Attributes.Flee; // Limits of flee and hit. if (percent > 100) percent = 100; if (percent < 0) percent = 0; // Hit if (this.Random.Next(0, 100) <= percent) { target.Life -= (int)attack; Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8); AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Short, animationPosition); game.DamageManager.Queue(new Damage((int)attack, null, target.Position, Damage.DamageType.Harmful)); } // Miss else { game.DamageManager.Queue(new Damage("MISS", caster.Position, Damage.DamageType.Harmful)); } } } /// <summary> /// Cast the attack. /// (1.5 * HIT - 0.3 * DEF) + (0.1 * (1.5 * HIT - 0.3 * DEF)) /// </summary> /// <param name="command">attack casted.</param> /// <param name="caster">The caster of the attack.</param> /// <param name="target">The target of the attack.</param> /// <param name="position">The position of the target.</param> private void Long(Command command, Unit caster, Unit target, Vector2 position) { // Obtain the game instance. IRTGame game = caster.Game as IRTGame; // Effects on caster. caster.Time = 0; // Effects on target. if (target != null) { // Calcule the attack. double attack; attack = (1.5f * caster.Attributes.Hit - 0.3f * target.Attributes.Defense); attack += this.Random.NextDouble() * 0.1f * attack; attack = attack < 1 ? 1 : attack; // Apply the hit and flee %. int percent = caster.Attributes.Hit - target.Attributes.Flee; // Limits of flee and hit. if (percent > 100) percent = 100; if (percent < 0) percent = 0; // Hit if (this.Random.Next(0, 100) <= percent) { target.Life -= (int)attack; Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8); AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Long, animationPosition); game.DamageManager.Queue(new Damage((int)attack, null, target.Position, Damage.DamageType.Harmful)); } // Miss else { game.DamageManager.Queue(new Damage("MISS", caster.Position, Damage.DamageType.Harmful)); } } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // using System; using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Reflection { [Serializable] internal class MemberInfoSerializationHolder : ISerializable, IObjectReference { #region Staitc Public Members public static void GetSerializationInfo(SerializationInfo info, String name, RuntimeType reflectedClass, String signature, MemberTypes type) { GetSerializationInfo(info, name, reflectedClass, signature, null, type, null); } public static void GetSerializationInfo( SerializationInfo info, String name, RuntimeType reflectedClass, String signature, String signature2, MemberTypes type, Type[] genericArguments) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); String assemblyName = reflectedClass.Module.Assembly.FullName; String typeName = reflectedClass.FullName; info.SetType(typeof(MemberInfoSerializationHolder)); info.AddValue("Name", name, typeof(String)); info.AddValue("AssemblyName", assemblyName, typeof(String)); info.AddValue("ClassName", typeName, typeof(String)); info.AddValue("Signature", signature, typeof(String)); info.AddValue("Signature2", signature2, typeof(String)); info.AddValue("MemberType", (int)type); info.AddValue("GenericArguments", genericArguments, typeof(Type[])); } #endregion #region Private Data Members private String m_memberName; private RuntimeType m_reflectedType; // m_signature stores the ToString() representation of the member which is sometimes ambiguous. // Mulitple overloads of the same methods or properties can identical ToString(). // m_signature2 stores the SerializationToString() representation which should be unique for each member. // It is only written and used by post 4.0 CLR versions. private String m_signature; private String m_signature2; private MemberTypes m_memberType; private SerializationInfo m_info; #endregion #region Constructor internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); String assemblyName = info.GetString("AssemblyName"); String typeName = info.GetString("ClassName"); if (assemblyName == null || typeName == null) throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); Assembly assem = FormatterServices.LoadAssemblyFromString(assemblyName); m_reflectedType = assem.GetType(typeName, true, false) as RuntimeType; m_memberName = info.GetString("Name"); m_signature = info.GetString("Signature"); // Only v4.0 and later generates and consumes Signature2 m_signature2 = (string)info.GetValueNoThrow("Signature2", typeof(string)); m_memberType = (MemberTypes)info.GetInt32("MemberType"); m_info = info; } #endregion #region ISerializable [System.Security.SecurityCritical] // auto-generated public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method)); } #endregion #region IObjectReference [System.Security.SecurityCritical] // auto-generated public virtual Object GetRealObject(StreamingContext context) { if (m_memberName == null || m_reflectedType == null || m_memberType == 0) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState)); BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.OptionalParamBinding; switch (m_memberType) { #region case MemberTypes.Field: case MemberTypes.Field: { FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[]; if (fields.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); return fields[0]; } #endregion #region case MemberTypes.Event: case MemberTypes.Event: { EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[]; if (events.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); return events[0]; } #endregion #region case MemberTypes.Property: case MemberTypes.Property: { PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[]; if (properties.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); if (properties.Length == 1) return properties[0]; if (properties.Length > 1) { for (int i = 0; i < properties.Length; i++) { if (m_signature2 != null) { if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2)) return properties[i]; } else { if ((properties[i]).ToString().Equals(m_signature)) return properties[i]; } } } throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); } #endregion #region case MemberTypes.Constructor: case MemberTypes.Constructor: { if (m_signature == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature)); ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[]; if (constructors.Length == 1) return constructors[0]; if (constructors.Length > 1) { for (int i = 0; i < constructors.Length; i++) { if (m_signature2 != null) { if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2)) return constructors[i]; } else { if (constructors[i].ToString().Equals(m_signature)) return constructors[i]; } } } throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); } #endregion #region case MemberTypes.Method: case MemberTypes.Method: { MethodInfo methodInfo = null; if (m_signature == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature)); Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[]; MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[]; if (methods.Length == 1) methodInfo = methods[0]; else if (methods.Length > 1) { for (int i = 0; i < methods.Length; i++) { if (m_signature2 != null) { if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2)) { methodInfo = methods[i]; break; } } else { if (methods[i].ToString().Equals(m_signature)) { methodInfo = methods[i]; break; } } // Handle generic methods specially since the signature match above probably won't work (the candidate // method info hasn't been instantiated). If our target method is generic as well we can skip this. if (genericArguments != null && methods[i].IsGenericMethod) { if (methods[i].GetGenericArguments().Length == genericArguments.Length) { MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments); if (m_signature2 != null) { if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2)) { methodInfo = candidateMethod; break; } } else { if (candidateMethod.ToString().Equals(m_signature)) { methodInfo = candidateMethod; break; } } } } } } if (methodInfo == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); if (!methodInfo.IsGenericMethodDefinition) return methodInfo; if (genericArguments == null) return methodInfo; if (genericArguments[0] == null) return null; return methodInfo.MakeGenericMethod(genericArguments); } #endregion default: throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized")); } } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; namespace DotSpatial.Symbology.Forms { /// <summary> /// CharacterControl. /// </summary> [DefaultEvent("PopupClicked")] public class CharacterControl : VerticalScrollControl { #region Fields private readonly IWindowsFormsEditorService _editorService; private readonly ICharacterSymbol _symbol; private Size _cellSize; private bool _isPopup; private int _numColumns; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CharacterControl"/> class. /// </summary> public CharacterControl() { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="CharacterControl"/> class designed to edit the specific symbol. /// </summary> /// <param name="editorService">The editor service.</param> /// <param name="symbol">The character symbol.</param> public CharacterControl(IWindowsFormsEditorService editorService, ICharacterSymbol symbol) { _editorService = editorService; _symbol = symbol; Configure(); } #endregion #region Events /// <summary> /// Occurs when a magnification box is clicked. /// </summary> public event EventHandler PopupClicked; #endregion #region Properties /// <summary> /// Gets or sets the cell size. /// </summary> public Size CellSize { get { return _cellSize; } set { _cellSize = value; Invalidate(); } } /// <summary> /// Gets or sets t he document rectangle. This overrides underlying the behavior to hide it in the properties list for this control from serialization. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Rectangle DocumentRectangle { get { return base.DocumentRectangle; } set { base.DocumentRectangle = value; } } /// <summary> /// Gets or sets a value indicating whether this form should restructure the columns /// as it is resized so that all the columns are visible. /// </summary> public bool DynamicColumns { get; set; } /// <summary> /// Gets or sets a value indicating whether or not this item is selected. /// </summary> public bool IsSelected { get; set; } /// <summary> /// Gets or sets the number of columns. /// </summary> public int NumColumns { get { return _numColumns; } set { _numColumns = value; Invalidate(); } } /// <summary> /// Gets the number of rows, which is controlled by having to show 256 cells /// in the given number of columns. /// </summary> public int NumRows { get { if (_numColumns == 0) return 256; return (int)Math.Ceiling(256 / (double)_numColumns); } } /// <summary> /// Gets or sets the selected character. /// </summary> public byte SelectedChar { get; set; } /// <summary> /// Gets the string form of the selected character. /// </summary> public string SelectedString => ((char)(SelectedChar + (TypeSet * 256))).ToString(); /// <summary> /// Gets or sets the background color for the selection. /// </summary> public Color SelectionBackColor { get; set; } /// <summary> /// Gets or sets the Font Color for the selection. /// </summary> public Color SelectionForeColor { get; set; } /// <summary> /// Gets or sets the byte that describes the "larger" of the two bytes for a unicode set. /// The 256 character slots illustrate the sub-categories for those elements. /// </summary> public byte TypeSet { get; set; } #endregion #region Methods /// <summary> /// Initializes the character control. /// </summary> /// <param name="e">The paint event args.</param> protected override void OnInitialize(PaintEventArgs e) { DocumentRectangle = new Rectangle(0, 0, (_numColumns * _cellSize.Width) + 1, (NumRows * _cellSize.Height) + 1); if (DynamicColumns) { int newColumns = (Width - 20) / _cellSize.Width; if (newColumns != _numColumns) { e.Graphics.FillRectangle(Brushes.White, e.ClipRectangle); _numColumns = newColumns; Invalidate(); return; } } if (_numColumns == 0) _numColumns = 1; Font smallFont = new Font(Font.FontFamily, CellSize.Width * .8F, GraphicsUnit.Pixel); for (int i = 0; i < 256; i++) { int row = i / _numColumns; int col = i % _numColumns; string text = ((char)((TypeSet * 256) + i)).ToString(); e.Graphics.DrawString(text, smallFont, Brushes.Black, new PointF(col * _cellSize.Width, row * _cellSize.Height)); } for (int col = 0; col <= _numColumns; col++) { e.Graphics.DrawLine(Pens.Black, new PointF(col * _cellSize.Width, 0), new PointF(col * _cellSize.Width, NumRows * _cellSize.Height)); } for (int row = 0; row <= NumRows; row++) { e.Graphics.DrawLine(Pens.Black, new PointF(0, row * _cellSize.Height), new PointF(NumColumns * _cellSize.Width, row * _cellSize.Height)); } Brush backBrush = new SolidBrush(SelectionBackColor); Brush foreBrush = new SolidBrush(SelectionForeColor); if (IsSelected) { Rectangle sRect = GetSelectedRectangle(); e.Graphics.FillRectangle(backBrush, sRect); e.Graphics.DrawString(SelectedString, smallFont, foreBrush, new PointF(sRect.X, sRect.Y)); } if (_isPopup) { Rectangle pRect = GetPopupRectangle(); e.Graphics.FillRectangle(Brushes.Gray, new Rectangle(pRect.X + 2, pRect.Y + 2, pRect.Width, pRect.Height)); e.Graphics.FillRectangle(backBrush, pRect); e.Graphics.DrawRectangle(Pens.Black, pRect); Font bigFont = new Font(Font.FontFamily, CellSize.Width * 2.7F, GraphicsUnit.Pixel); e.Graphics.DrawString(SelectedString, bigFont, foreBrush, new PointF(pRect.X, pRect.Y)); } backBrush.Dispose(); foreBrush.Dispose(); } /// <summary> /// Handles the situation where a mouse up should show a magnified version of the character. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { if (_isPopup) { Rectangle pRect = GetPopupRectangle(); Rectangle cRect = DocumentToClient(pRect); if (cRect.Contains(e.Location)) { _isPopup = false; // make the popup vanish, but don't change the selection. cRect.Inflate(CellSize); Invalidate(cRect); OnPopupClicked(); return; } } if (e.X < 0) return; if (e.Y < 0) return; int col = (e.X + ControlRectangle.X) / _cellSize.Width; int row = (e.Y + ControlRectangle.Y) / _cellSize.Height; if (((_numColumns * row) + col) < 256) { IsSelected = true; SelectedChar = (byte)((_numColumns * row) + col); _isPopup = true; } Invalidate(); base.OnMouseUp(e); } /// <summary> /// Fires the PopupClicked event args, and closes a drop down editor if it exists. /// </summary> protected virtual void OnPopupClicked() { if (_editorService != null) { _symbol.Code = SelectedChar; _editorService.CloseDropDown(); } PopupClicked?.Invoke(this, EventArgs.Empty); } /// <summary> /// Occurs whenever this control is resized, and forces invalidation of the entire control because /// we are completely changing how the paging works. /// </summary> /// <param name="e">The event args.</param> protected override void OnResize(EventArgs e) { _isPopup = false; base.OnResize(e); Invalidate(); } private void Configure() { Font = new Font("DotSpatialSymbols", 18F, GraphicsUnit.Pixel); TypeSet = 0; _cellSize = new Size(22, 22); _numColumns = 16; DynamicColumns = true; SelectionBackColor = Color.CornflowerBlue; SelectionForeColor = Color.White; DocumentRectangle = new Rectangle(0, 0, _cellSize.Width * 16, _cellSize.Height * 16); ResetScroll(); } private Rectangle GetPopupRectangle() { int pr = SelectedChar / _numColumns; int pc = SelectedChar % _numColumns; if (pc == 0) pc = 1; if (pc == _numColumns - 1) pc = _numColumns - 2; if (pr == 0) pr = 1; if (pr == NumRows - 1) pr = NumRows - 2; return new Rectangle((pc - 1) * CellSize.Width, (pr - 1) * CellSize.Height, CellSize.Width * 3, CellSize.Height * 3); } private Rectangle GetSelectedRectangle() { int row = SelectedChar / _numColumns; int col = SelectedChar % _numColumns; return new Rectangle((col * _cellSize.Width) + 1, (row * _cellSize.Height) + 1, _cellSize.Width - 1, CellSize.Height - 1); } #endregion } }
using System; using System.Collections.Generic; namespace CocosSharp { #region Enums public enum CCScrollViewDirection { None = -1, Horizontal = 0, Vertical, Both } #endregion Enums public interface ICCScrollViewDelegate { void ScrollViewDidScroll(CCScrollView view); void ScrollViewDidZoom(CCScrollView view); } /** * ScrollView support for cocos2d for iphone. * It provides scroll view functionalities to cocos2d projects natively. */ public class CCScrollView : CCLayer { const float SCROLL_DEACCEL_RATE = 0.95f; const float SCROLL_DEACCEL_DIST = 1.0f; const float BOUNCE_DURATION = 0.15f; const float INSET_RATIO = 0.2f; const float MOVE_INCH = 7.0f / 160.0f; bool clippingToBounds; bool isTouchEnabled; float touchLength; float minScale; float maxScale; CCPoint minInset; CCPoint maxInset; List<CCTouch> touches; CCPoint scrollDistance; CCPoint touchPoint; CCSize viewSize; CCNode container; CCEventListener TouchListener; #region Properties public bool Bounceable { get ; set; } public bool Dragging { get; private set; } public bool IsTouchMoved { get; private set; } public CCScrollViewDirection Direction { get; set; } public ICCScrollViewDelegate Delegate { get; set; } public bool ClippingToBounds { get { return clippingToBounds; } set { clippingToBounds = value; ChildClippingMode = clippingToBounds ? CCClipMode.Bounds : CCClipMode.None; } } public bool TouchEnabled { get { return isTouchEnabled; } set { if (value != isTouchEnabled) { isTouchEnabled = value; if (isTouchEnabled) { // Register Touch Event var touchListener = new CCEventListenerTouchOneByOne(); touchListener.IsSwallowTouches = true; touchListener.OnTouchBegan = TouchBegan; touchListener.OnTouchMoved = TouchMoved; touchListener.OnTouchEnded = TouchEnded; touchListener.OnTouchCancelled = TouchCancelled; AddEventListener(touchListener); TouchListener = touchListener; } } else { Dragging = false; IsTouchMoved = false; touches.Clear(); RemoveEventListener(TouchListener); TouchListener = null; } } } public float MinScale { get { return minScale; } set { minScale = value; ZoomScale = ZoomScale; } } public float MaxScale { get { return maxScale; } set { maxScale = value; ZoomScale = ZoomScale; } } public float ZoomScale { get { return container.ScaleX; } set { if (container.ScaleX != value) { CCPoint center; if (touchLength == 0.0f) { center = new CCPoint(viewSize.Width * 0.5f, viewSize.Height * 0.5f); } else { center = touchPoint; } CCPoint oldCenter = container.Layer.ScreenToWorldspace(center); container.Scale = Math.Max(minScale, Math.Min(maxScale, value)); CCPoint newCenter = oldCenter; CCPoint offset = center - newCenter; if (Delegate != null) { Delegate.ScrollViewDidZoom(this); } SetContentOffset(container.Position + offset, false); } } } public CCPoint ContentOffset { get { return container.Position; } set { SetContentOffset(value); } } public CCPoint MinContainerOffset { get { return new CCPoint(viewSize.Width - container.ContentSize.Width * container.ScaleX, viewSize.Height - container.ContentSize.Height * container.ScaleY); } } public CCPoint MaxContainerOffset { get { return CCPoint.Zero; } } public override CCSize ContentSize { get { return container.ContentSize; } set { if (Container != null) { Container.ContentSize = value; UpdateInset(); } } } /** * size to clip. CCNode boundingBox uses contentSize directly. * It's semantically different what it actually means to common scroll views. * Hence, this scroll view will use a separate size property. */ public CCSize ViewSize { get { return viewSize; } set { viewSize = value; base.ContentSize = value; } } CCRect ViewRect { get { var rect = new CCRect (0, 0, viewSize.Width, viewSize.Height); return CCAffineTransform.Transform (rect, AffineWorldTransform); } } public CCNode Container { get { return container; } set { if (value == null) { return; } RemoveAllChildren(true); container = value; container.IgnoreAnchorPointForPosition = false; container.AnchorPoint = CCPoint.Zero; AddChild(container); ViewSize = viewSize; } } #endregion Properties #region Constructors public CCScrollView() : this (new CCSize(200, 200), null) { } public CCScrollView(CCSize size) : this(size, null) { } public CCScrollView(CCSize size, CCNode container) { if (container == null) { container = new CCLayer(); container.IgnoreAnchorPointForPosition = false; container.AnchorPoint = CCPoint.Zero; } container.Position = new CCPoint(0.0f, 0.0f); this.container = container; ViewSize = size; TouchEnabled = true; Delegate = null; Bounceable = true; ClippingToBounds = true; Direction = CCScrollViewDirection.Both; MinScale = MaxScale = 1.0f; touches = new List<CCTouch>(); touchLength = 0.0f; AddChild(container); } #endregion Constructors static float ConvertDistanceFromPointToInch(float pointDis) { float factor = 1.0f; //(CCDrawManager.SharedDrawManager.ScaleX + CCDrawManager.SharedDrawManager.ScaleY) / 2; return pointDis * factor / CCDevice.DPI; } /** * Determines if a given node's bounding box is in visible bounds * * @return YES if it is in visible bounds */ public bool IsNodeVisible(CCNode node) { CCPoint offset = ContentOffset; CCSize size = ViewSize; float scale = ZoomScale; var viewRect = new CCRect(-offset.X / scale, -offset.Y / scale, size.Width / scale, size.Height / scale); return viewRect.IntersectsRect(node.BoundingBox); } public void UpdateInset() { if (Container != null) { maxInset = MaxContainerOffset; maxInset = new CCPoint(maxInset.X + viewSize.Width * INSET_RATIO, maxInset.Y + viewSize.Height * INSET_RATIO); minInset = MinContainerOffset; minInset = new CCPoint(minInset.X - viewSize.Width * INSET_RATIO, minInset.Y - viewSize.Height * INSET_RATIO); } } public void SetContentOffset(CCPoint offset, bool animated=false) { if (animated) { //animate scrolling SetContentOffsetInDuration(offset, BOUNCE_DURATION); } else { //set the container position directly if (!Bounceable) { CCPoint minOffset = MinContainerOffset; CCPoint maxOffset = MaxContainerOffset; offset.X = Math.Max(minOffset.X, Math.Min(maxOffset.X, offset.X)); offset.Y = Math.Max(minOffset.Y, Math.Min(maxOffset.Y, offset.Y)); } container.Position = offset; if (Delegate != null) { Delegate.ScrollViewDidScroll(this); } } } /** * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) * You can override the animation duration with this method. * * @param offset new offset * @param animation duration */ public void SetContentOffsetInDuration(CCPoint offset, float dt) { CCMoveTo scroll = new CCMoveTo (dt, offset); CCCallFuncN expire = new CCCallFuncN(StoppedAnimatedScroll); container.RunAction(new CCSequence(scroll, expire)); Schedule(PerformedAnimatedScroll); } public void SetZoomScale(float value, bool animated=false) { if (animated) { SetZoomScaleInDuration(value, BOUNCE_DURATION); } else { ZoomScale = value; } } public void SetZoomScaleInDuration(float s, float dt) { if (dt > 0) { if (container.ScaleX != s) { CCActionTween scaleAction = new CCActionTween (dt, "zoomScale", container.ScaleX, s); RunAction(scaleAction); } } else { ZoomScale = s; } } /** * Provided to make scroll view compatible with SWLayer's pause method */ public void Pause(object sender) { container.Pause(); var children = container.Children; if (children != null) { foreach(CCNode child in children) { child.Pause(); } } } /** * Provided to make scroll view compatible with SWLayer's resume method */ public void Resume(object sender) { var children = container.Children; if (children != null) { foreach(CCNode child in children) { child.Resume(); } } container.Resume(); } #region Event handling /** override functions */ public virtual bool TouchBegan(CCTouch pTouch, CCEvent touchEvent) { if (!Visible) { return false; } var frame = ViewRect; //dispatcher does not know about clipping. reject touches outside visible bounds. if (touches.Count > 2 || IsTouchMoved || !frame.ContainsPoint(container.Layer.ScreenToWorldspace(pTouch.LocationOnScreen))) { return false; } if (!touches.Contains(pTouch)) { touches.Add(pTouch); } if (touches.Count == 1) { // scrolling touchPoint = Layer.ScreenToWorldspace(pTouch.LocationOnScreen); IsTouchMoved = false; Dragging = true; //Dragging started scrollDistance = CCPoint.Zero; touchLength = 0.0f; } else if (touches.Count == 2) { touchPoint = CCPoint.Midpoint(Layer.ScreenToWorldspace(touches[0].LocationOnScreen), Layer.ScreenToWorldspace(touches[1].LocationOnScreen)); touchLength = CCPoint.Distance(container.Layer.ScreenToWorldspace(touches[0].LocationOnScreen), container.Layer.ScreenToWorldspace(touches[1].LocationOnScreen)); Dragging = false; } return true; } public virtual void TouchMoved(CCTouch touch, CCEvent touchEvent) { if (!Visible) { return; } if (touches.Contains(touch)) { if (touches.Count == 1 && Dragging) {// scrolling CCPoint moveDistance, newPoint; //, maxInset, minInset; float newX, newY; var frame = ViewRect; newPoint = Layer.ScreenToWorldspace(touches[0].LocationOnScreen); moveDistance = newPoint - touchPoint; float dis = 0.0f; if (Direction == CCScrollViewDirection.Vertical) { dis = moveDistance.Y; } else if (Direction == CCScrollViewDirection.Horizontal) { dis = moveDistance.X; } else { dis = (float)Math.Sqrt(moveDistance.X * moveDistance.X + moveDistance.Y * moveDistance.Y); } if (!IsTouchMoved && Math.Abs(ConvertDistanceFromPointToInch(dis)) < MOVE_INCH) { //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y); return; } if (!IsTouchMoved) { moveDistance = CCPoint.Zero; } touchPoint = newPoint; IsTouchMoved = true; if (frame.ContainsPoint(touchPoint)) { switch (Direction) { case CCScrollViewDirection.Vertical: moveDistance = new CCPoint(0.0f, moveDistance.Y); break; case CCScrollViewDirection.Horizontal: moveDistance = new CCPoint(moveDistance.X, 0.0f); break; default: break; } newX = container.Position.X + moveDistance.X; newY = container.Position.Y + moveDistance.Y; scrollDistance = moveDistance; SetContentOffset(new CCPoint(newX, newY)); } } else if (touches.Count == 2 && !Dragging) { float len = CCPoint.Distance(Layer.ScreenToWorldspace(touches[0].LocationOnScreen), Layer.ScreenToWorldspace(touches[1].LocationOnScreen)); ZoomScale = ZoomScale * len / touchLength; } } } public virtual void TouchEnded(CCTouch touch, CCEvent touchEvent) { if (!Visible) { return; } if (touches.Contains(touch)) { if (touches.Count == 1 && IsTouchMoved) { Schedule(DeaccelerateScrolling); } touches.Remove(touch); } if (touches.Count == 0) { Dragging = false; IsTouchMoved = false; } } public virtual void TouchCancelled(CCTouch touch, CCEvent touchEvent) { if (!Visible) { return; } touches.Remove(touch); if (touches.Count == 0) { Dragging = false; IsTouchMoved = false; } } #endregion Event handling public override void AddChild(CCNode child, int zOrder, int tag) { child.IgnoreAnchorPointForPosition = false; // child.AnchorPoint = CCPoint.Zero; if (container != child) { container.AddChild(child, zOrder, tag); } else { base.AddChild(child, zOrder, tag); } } /** * Relocates the container at the proper offset, in bounds of max/min offsets. * * @param animated If YES, relocation is animated */ void RelocateContainer(bool animated) { CCPoint min = MinContainerOffset; CCPoint max = MaxContainerOffset; CCPoint oldPoint = container.Position; float newX = oldPoint.X; float newY = oldPoint.Y; if (Direction == CCScrollViewDirection.Both || Direction == CCScrollViewDirection.Horizontal) { newX = Math.Min(newX, max.X); newX = Math.Max(newX, min.X); } if (Direction == CCScrollViewDirection.Both || Direction == CCScrollViewDirection.Vertical) { newY = Math.Min(newY, max.Y); newY = Math.Max(newY, min.Y); } if (newY != oldPoint.Y || newX != oldPoint.X) { SetContentOffset(new CCPoint(newX, newY), animated); } } /** * implements auto-scrolling behavior. change SCROLL_DEACCEL_RATE as needed to choose * deacceleration speed. it must be less than 1.0f. * * @param dt delta */ void DeaccelerateScrolling(float dt) { if (Dragging) { Unschedule(DeaccelerateScrolling); return; } CCPoint maxInset, minInset; container.Position = container.Position + scrollDistance; if (Bounceable) { maxInset = this.maxInset; minInset = this.minInset; } else { maxInset = MaxContainerOffset; minInset = MinContainerOffset; } //check to see if offset lies within the inset bounds float newX = Math.Min(container.Position.X, maxInset.X); newX = Math.Max(newX, minInset.X); float newY = Math.Min(container.Position.Y, maxInset.Y); newY = Math.Max(newY, minInset.Y); scrollDistance = scrollDistance - new CCPoint(newX - container.Position.X, newY - container.Position.Y); scrollDistance = scrollDistance * SCROLL_DEACCEL_RATE; SetContentOffset(new CCPoint(newX, newY), false); if ((Math.Abs(scrollDistance.X) <= SCROLL_DEACCEL_DIST && Math.Abs(scrollDistance.Y) <= SCROLL_DEACCEL_DIST) || newY > maxInset.Y || newY < minInset.Y || newX > maxInset.X || newX < minInset.X || newX == maxInset.X || newX == minInset.X || newY == maxInset.Y || newY == minInset.Y) { Unschedule(DeaccelerateScrolling); RelocateContainer(true); } } /** * This method makes sure auto scrolling causes delegate to invoke its method */ void PerformedAnimatedScroll(float dt) { if (Dragging) { Unschedule(PerformedAnimatedScroll); return; } if (Delegate != null) { Delegate.ScrollViewDidScroll(this); } } /** * Expire animated scroll delegate calls */ void StoppedAnimatedScroll(CCNode node) { Unschedule(PerformedAnimatedScroll); // After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells. if (Delegate != null) { Delegate.ScrollViewDidScroll(this); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase { private enum Operation { Add, Set, Remove, Last, } [Fact] public void RandomOperationsTest() { int operationCount = this.RandomOperationsCount; var expected = new SortedDictionary<int, bool>(); var actual = ImmutableSortedDictionary<int, bool>.Empty; int seed = (int)DateTime.Now.Ticks; Debug.WriteLine("Using random seed {0}", seed); var random = new Random(seed); for (int iOp = 0; iOp < operationCount; iOp++) { switch ((Operation)random.Next((int)Operation.Last)) { case Operation.Add: int key; do { key = random.Next(); } while (expected.ContainsKey(key)); bool value = random.Next() % 2 == 0; Debug.WriteLine("Adding \"{0}\"={1} to the set.", key, value); expected.Add(key, value); actual = actual.Add(key, value); break; case Operation.Set: bool overwrite = expected.Count > 0 && random.Next() % 2 == 0; if (overwrite) { int position = random.Next(expected.Count); key = expected.Skip(position).First().Key; } else { do { key = random.Next(); } while (expected.ContainsKey(key)); } value = random.Next() % 2 == 0; Debug.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite); expected[key] = value; actual = actual.SetItem(key, value); break; case Operation.Remove: if (expected.Count > 0) { int position = random.Next(expected.Count); key = expected.Skip(position).First().Key; Debug.WriteLine("Removing element \"{0}\" from the set.", key); Assert.True(expected.Remove(key)); actual = actual.Remove(key); } break; } Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList()); } } [Fact] public void AddExistingKeySameValueTest() { AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft"); AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void AddExistingKeyDifferentValueTest() { AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void ToUnorderedTest() { var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n)))); var unsortedMap = sortedMap.ToImmutableDictionary(); Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap); Assert.Equal(sortedMap.Count, unsortedMap.Count); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList()); } [Fact] public void SortChangeTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("Johnny")); Assert.False(map.ContainsKey("johnny")); var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, newMap.Count); Assert.True(newMap.ContainsKey("Johnny")); Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive } [Fact] public void InitialBulkAddUniqueTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("c", "d"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); var actual = map.AddRange(uniqueEntries); Assert.Equal(2, actual.Count); } [Fact] public void InitialBulkAddWithExactDuplicatesTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("a", "b"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); var actual = map.AddRange(uniqueEntries); Assert.Equal(1, actual.Count); } [Fact] public void ContainsValueTest() { this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper()); } [Fact] public void InitialBulkAddWithKeyCollisionTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("a", "d"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); Assert.Throws<ArgumentException>(() => map.AddRange(uniqueEntries)); } [Fact] public void Create() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; var dictionary = ImmutableSortedDictionary.Create<string, string>(); Assert.Equal(0, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(pairs); Assert.Equal(1, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void ToImmutableSortedDictionary() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary(); Assert.Equal(1, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(keyComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant()); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void WithComparers() { var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1"); Assert.Same(Comparer<string>.Default, map.KeyComparer); Assert.True(map.ContainsKey("a")); Assert.False(map.ContainsKey("A")); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); var cultureComparer = StringComparer.CurrentCulture; map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(cultureComparer, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); } [Fact] public void WithComparersCollisions() { // First check where collisions have matching values. var map = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "1"); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(1, map.Count); Assert.True(map.ContainsKey("a")); Assert.Equal("1", map["a"]); // Now check where collisions have conflicting values. map = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "2").Add("b", "3"); Assert.Throws<ArgumentException>(() => map.WithComparers(StringComparer.OrdinalIgnoreCase)); // Force all values to be considered equal. map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(EverythingEqual<string>.Default, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("b")); } [Fact] public void CollisionExceptionMessageContainsKey() { var map = ImmutableSortedDictionary.Create<string, string>() .Add("firstKey", "1").Add("secondKey", "2"); var exception = Assert.Throws<ArgumentException>(() => map.Add("firstKey", "3")); Assert.Contains("firstKey", exception.Message); } [Fact] public void WithComparersEmptyCollection() { var map = ImmutableSortedDictionary.Create<string, string>(); Assert.Same(Comparer<string>.Default, map.KeyComparer); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } ////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces. public void EnumerationPerformance() { var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k); var timing = new TimeSpan[3]; var sw = new Stopwatch(); for (int j = 0; j < timing.Length; j++) { sw.Start(); for (int i = 0; i < 10000; i++) { foreach (var entry in dictionary) { } } timing[j] = sw.Elapsed; sw.Reset(); } string timingText = string.Join(Environment.NewLine, timing); Debug.WriteLine("Timing:{0}{1}", Environment.NewLine, timingText); } ////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces. public void EnumerationPerformance_Empty() { var dictionary = ImmutableSortedDictionary<int, int>.Empty; var timing = new TimeSpan[3]; var sw = new Stopwatch(); for (int j = 0; j < timing.Length; j++) { sw.Start(); for (int i = 0; i < 10000; i++) { foreach (var entry in dictionary) { } } timing[j] = sw.Elapsed; sw.Reset(); } string timingText = string.Join(Environment.NewLine, timing); Debug.WriteLine("Timing_Empty:{0}{1}", Environment.NewLine, timingText); } protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() { return ImmutableSortedDictionaryTest.Empty<TKey, TValue>(); } protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer) { return ImmutableSortedDictionary.Create<string, TValue>(comparer); } protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer; } internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root; } protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsValue(value)); Assert.True(map.Add(key, value).ContainsValue(value)); } private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.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.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/wrappers.proto</summary> public static partial class WrappersReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/wrappers.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static WrappersReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8SD2dvb2dsZS5wcm90", "b2J1ZiIcCgtEb3VibGVWYWx1ZRINCgV2YWx1ZRgBIAEoASIbCgpGbG9hdFZh", "bHVlEg0KBXZhbHVlGAEgASgCIhsKCkludDY0VmFsdWUSDQoFdmFsdWUYASAB", "KAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1", "ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEo", "DSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUS", "DQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEJ/", "ChNjb20uZ29vZ2xlLnByb3RvYnVmQg1XcmFwcGVyc1Byb3RvUAFaKmdpdGh1", "Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy93cmFwcGVyc6ABAfgBAaIC", "A0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.DoubleValue), global::Google.Protobuf.WellKnownTypes.DoubleValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FloatValue), global::Google.Protobuf.WellKnownTypes.FloatValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Int64Value), global::Google.Protobuf.WellKnownTypes.Int64Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.UInt64Value), global::Google.Protobuf.WellKnownTypes.UInt64Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Int32Value), global::Google.Protobuf.WellKnownTypes.Int32Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.UInt32Value), global::Google.Protobuf.WellKnownTypes.UInt32Value.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.BoolValue), global::Google.Protobuf.WellKnownTypes.BoolValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.StringValue), global::Google.Protobuf.WellKnownTypes.StringValue.Parser, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.BytesValue), global::Google.Protobuf.WellKnownTypes.BytesValue.Parser, new[]{ "Value" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Wrapper message for `double`. /// /// The JSON representation for `DoubleValue` is JSON number. /// </summary> public sealed partial class DoubleValue : pb::IMessage<DoubleValue> { private static readonly pb::MessageParser<DoubleValue> _parser = new pb::MessageParser<DoubleValue>(() => new DoubleValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DoubleValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DoubleValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DoubleValue(DoubleValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DoubleValue Clone() { return new DoubleValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private double value_; /// <summary> /// The double value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DoubleValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DoubleValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0D) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0D) { output.WriteRawTag(9); output.WriteDouble(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DoubleValue other) { if (other == null) { return; } if (other.Value != 0D) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 9: { Value = input.ReadDouble(); break; } } } } } /// <summary> /// Wrapper message for `float`. /// /// The JSON representation for `FloatValue` is JSON number. /// </summary> public sealed partial class FloatValue : pb::IMessage<FloatValue> { private static readonly pb::MessageParser<FloatValue> _parser = new pb::MessageParser<FloatValue>(() => new FloatValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FloatValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FloatValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FloatValue(FloatValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FloatValue Clone() { return new FloatValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private float value_; /// <summary> /// The float value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FloatValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FloatValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0F) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0F) { output.WriteRawTag(13); output.WriteFloat(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FloatValue other) { if (other == null) { return; } if (other.Value != 0F) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 13: { Value = input.ReadFloat(); break; } } } } } /// <summary> /// Wrapper message for `int64`. /// /// The JSON representation for `Int64Value` is JSON string. /// </summary> public sealed partial class Int64Value : pb::IMessage<Int64Value> { private static readonly pb::MessageParser<Int64Value> _parser = new pb::MessageParser<Int64Value>(() => new Int64Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Int64Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int64Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int64Value(Int64Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int64Value Clone() { return new Int64Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private long value_; /// <summary> /// The int64 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Int64Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Int64Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0L) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0L) { output.WriteRawTag(8); output.WriteInt64(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Int64Value other) { if (other == null) { return; } if (other.Value != 0L) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadInt64(); break; } } } } } /// <summary> /// Wrapper message for `uint64`. /// /// The JSON representation for `UInt64Value` is JSON string. /// </summary> public sealed partial class UInt64Value : pb::IMessage<UInt64Value> { private static readonly pb::MessageParser<UInt64Value> _parser = new pb::MessageParser<UInt64Value>(() => new UInt64Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UInt64Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt64Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt64Value(UInt64Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt64Value Clone() { return new UInt64Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private ulong value_; /// <summary> /// The uint64 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UInt64Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UInt64Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0UL) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0UL) { output.WriteRawTag(8); output.WriteUInt64(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UInt64Value other) { if (other == null) { return; } if (other.Value != 0UL) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadUInt64(); break; } } } } } /// <summary> /// Wrapper message for `int32`. /// /// The JSON representation for `Int32Value` is JSON number. /// </summary> public sealed partial class Int32Value : pb::IMessage<Int32Value> { private static readonly pb::MessageParser<Int32Value> _parser = new pb::MessageParser<Int32Value>(() => new Int32Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Int32Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int32Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int32Value(Int32Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Int32Value Clone() { return new Int32Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private int value_; /// <summary> /// The int32 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Int32Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Int32Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0) { output.WriteRawTag(8); output.WriteInt32(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Int32Value other) { if (other == null) { return; } if (other.Value != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadInt32(); break; } } } } } /// <summary> /// Wrapper message for `uint32`. /// /// The JSON representation for `UInt32Value` is JSON number. /// </summary> public sealed partial class UInt32Value : pb::IMessage<UInt32Value> { private static readonly pb::MessageParser<UInt32Value> _parser = new pb::MessageParser<UInt32Value>(() => new UInt32Value()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UInt32Value> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt32Value() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt32Value(UInt32Value other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UInt32Value Clone() { return new UInt32Value(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private uint value_; /// <summary> /// The uint32 value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UInt32Value); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UInt32Value other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != 0) { output.WriteRawTag(8); output.WriteUInt32(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UInt32Value other) { if (other == null) { return; } if (other.Value != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadUInt32(); break; } } } } } /// <summary> /// Wrapper message for `bool`. /// /// The JSON representation for `BoolValue` is JSON `true` and `false`. /// </summary> public sealed partial class BoolValue : pb::IMessage<BoolValue> { private static readonly pb::MessageParser<BoolValue> _parser = new pb::MessageParser<BoolValue>(() => new BoolValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BoolValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BoolValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BoolValue(BoolValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BoolValue Clone() { return new BoolValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private bool value_; /// <summary> /// The bool value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BoolValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BoolValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value != false) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value != false) { output.WriteRawTag(8); output.WriteBool(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BoolValue other) { if (other == null) { return; } if (other.Value != false) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Value = input.ReadBool(); break; } } } } } /// <summary> /// Wrapper message for `string`. /// /// The JSON representation for `StringValue` is JSON string. /// </summary> public sealed partial class StringValue : pb::IMessage<StringValue> { private static readonly pb::MessageParser<StringValue> _parser = new pb::MessageParser<StringValue>(() => new StringValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<StringValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StringValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StringValue(StringValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StringValue Clone() { return new StringValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private string value_ = ""; /// <summary> /// The string value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Value { get { return value_; } set { value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as StringValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(StringValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value.Length != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value.Length != 0) { output.WriteRawTag(10); output.WriteString(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(StringValue other) { if (other == null) { return; } if (other.Value.Length != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Value = input.ReadString(); break; } } } } } /// <summary> /// Wrapper message for `bytes`. /// /// The JSON representation for `BytesValue` is JSON string. /// </summary> public sealed partial class BytesValue : pb::IMessage<BytesValue> { private static readonly pb::MessageParser<BytesValue> _parser = new pb::MessageParser<BytesValue>(() => new BytesValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BytesValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BytesValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BytesValue(BytesValue other) : this() { value_ = other.value_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BytesValue Clone() { return new BytesValue(this); } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; private pb::ByteString value_ = pb::ByteString.Empty; /// <summary> /// The bytes value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Value { get { return value_; } set { value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BytesValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BytesValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Value != other.Value) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Value.Length != 0) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Value.Length != 0) { output.WriteRawTag(10); output.WriteBytes(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Value.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BytesValue other) { if (other == null) { return; } if (other.Value.Length != 0) { Value = other.Value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Value = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Cat { class CatTypeReconstructor : ConstraintSolver { public Constraint KindVarToConstraintVar(CatKind k) { Trace.Assert(k.IsKindVar()); return CreateVar(k.ToString().Substring(1)); } public Vector TypeVectorToConstraintVector(CatTypeVector x) { Vector vec = new Vector(); foreach (CatKind k in x.GetKinds()) vec.Insert(0, CatKindToConstraint(k)); return vec; } public Relation FxnTypeToRelation(CatFxnType ft) { Vector cons = TypeVectorToConstraintVector(ft.GetCons()); Vector prod = TypeVectorToConstraintVector(ft.GetProd()); Relation r = new Relation(cons, prod); return r; } public Constraint CatKindToConstraint(CatKind k) { if (k is CatTypeVector) { return TypeVectorToConstraintVector(k as CatTypeVector); } else if (k is CatFxnType) { return FxnTypeToRelation(k as CatFxnType); } else if (k.IsKindVar()) { return KindVarToConstraintVar(k); } else { return new Constant(k.ToIdString()); } } public CatTypeVector CatTypeVectorFromVec(Vector vec) { CatTypeVector ret = new CatTypeVector(); foreach (Constraint c in vec) ret.PushKindBottom(ConstraintToCatKind(c)); return ret; } public CatFxnType CatFxnTypeFromRelation(Relation rel) { CatTypeVector cons = CatTypeVectorFromVec(rel.GetLeft()); CatTypeVector prod = CatTypeVectorFromVec(rel.GetRight()); // TODO: add the boolean as a third value in the vector. // it becomes a variable when unknown, and is resolved otherwise. return new CatFxnType(cons, prod, false); } public CatKind ConstraintToCatKind(Constraint c) { if (c is ScalarVar) { return new CatTypeVar(c.ToString()); } else if (c is VectorVar) { return new CatStackVar(c.ToString()); } else if (c is Vector) { return CatTypeVectorFromVec(c as Vector); } else if (c is Relation) { return CatFxnTypeFromRelation(c as Relation); } else if (c is RecursiveRelation) { return new CatRecursiveType(); } else if (c is Constant) { // TODO: deal with CatCustomKinds return new CatSimpleTypeKind(c.ToString()); } else { throw new Exception("unhandled constraint " + c.ToString()); } } public CatFxnType LocalComposeTypes(CatFxnType left, CatFxnType right) { // Make sure that the variables on the left function and the variables // on the right function are different CatVarRenamer renamer = new CatVarRenamer(); left = renamer.Rename(left.AddImplicitRhoVariables()); renamer.ResetNames(); right = renamer.Rename(right.AddImplicitRhoVariables()); Log("=="); Log("Composing : " + left.ToString()); Log("with : " + right.ToString()); Log("Adding constraints"); Relation rLeft = FxnTypeToRelation(left); Relation rRight = FxnTypeToRelation(right); //TODO: remove //rLeft.UnrollRecursiveRelations(); //rRight.UnrollRecursiveRelations(); Relation result = new Relation(rLeft.GetLeft(), rRight.GetRight()); AddTopLevelConstraints(rLeft.GetRight(), rRight.GetLeft()); AddConstraint(CreateVar("result$"), result); Log("Constraints"); ComputeConstraintLists(); LogConstraints(); Log("Unifiers"); ComputeUnifiers(); foreach (string sVar in GetConstrainedVars()) { Constraint u = GetUnifierFor(sVar); Log("var: " + sVar + " = " + u); } Log("Composed Type"); Constraint c = GetResolvedUnifierFor("result$"); if (!(c is Relation)) throw new Exception("Resolved type is not a relation"); // TODO: remove // Relation r = c as Relation; // r.RollupRecursiveRelations(); CatKind k = ConstraintToCatKind(c); CatFxnType ft = k as CatFxnType; Log("raw type : " + ft.ToString()); Log("pretty type : " + ft.ToPrettyString()); Log("=="); CheckConstraintQueueEmpty(); // Check if the relation was valid, and thus the function type if (!ft.IsValid()) throw new Exception("invalid function type: " + ft.ToString()); return ft; } public static void OutputInferredType(CatFxnType ft) { Log("After rewriting"); Log(ft.ToPrettyString()); Log(""); } public static CatFxnType Infer(CatExpr f) { if (!Config.gbTypeChecking) return null; if (f.Count == 0) { if (Config.gbVerboseInference) Log("type is ( -> )"); return CatFxnType.Create("( -> )"); } else if (f.Count == 1) { Function x = f[0]; if (Config.gbVerboseInference) OutputInferredType(x.GetFxnType()); return x.GetFxnType(); } else { Function x = f[0]; CatFxnType ft = x.GetFxnType(); if (Config.gbVerboseInference) Log("initial term = " + x.GetName() + " : " + x.GetFxnTypeString()); for (int i = 1; i < f.Count; ++i) { if (ft == null) return ft; Function y = f[i]; if (Config.gbVerboseInference) { Log("Composing accumulated terms with next term"); string s = "previous terms = { "; for (int j = 0; j < i; ++j) s += f[j].GetName() + " "; Log(s + "} : " + ft.ToString()); Log("next term = " + y.GetName() + " : " + y.GetFxnTypeString()); } ft = ComposeTypes(ft, y.GetFxnType()); if (ft == null) return null; } return ft; } } public static CatFxnType ComposeTypes(CatFxnType left, CatFxnType right) { if (!Config.gbTypeChecking) return null; CatTypeReconstructor inferer = new CatTypeReconstructor(); return inferer.LocalComposeTypes(left, right); } } }
// // 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.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the virtual /// networks for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for /// more information) /// </summary> internal partial class NetworkOperations : IServiceOperations<NetworkManagementClient>, INetworkOperations { /// <summary> /// Initializes a new instance of the NetworkOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal NetworkOperations(NetworkManagementClient client) { this._client = client; } private NetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient. /// </summary> public NetworkManagementClient Client { get { return this._client; } } /// <summary> /// The Begin Setting Network Configuration operation asynchronously /// configures the virtual network. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Set Network Configuration /// 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> BeginSettingConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Configuration == null) { throw new ArgumentNullException("parameters.Configuration"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginSettingConfigurationAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/media"; 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("x-ms-version", "2015-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Configuration; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); // 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 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> /// The Get Network Configuration operation retrieves the network /// configuration file for the given subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Network Configuration operation response. /// </returns> public async Task<NetworkGetConfigurationResponse> GetConfigurationAsync(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>(); TracingAdapter.Enter(invocationId, this, "GetConfigurationAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/media"; 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("x-ms-version", "2015-04-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 NetworkGetConfigurationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new NetworkGetConfigurationResponse(); result.Configuration = responseContent; } 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> /// The List Virtual network sites operation retrieves the virtual /// networks configured for the subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response structure for the Network Operations List operation. /// </returns> public async Task<NetworkListResponse> ListAsync(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>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/virtualnetwork"; 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("x-ms-version", "2015-04-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 NetworkListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new NetworkListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement virtualNetworkSitesSequenceElement = responseDoc.Element(XName.Get("VirtualNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (virtualNetworkSitesSequenceElement != null) { foreach (XElement virtualNetworkSitesElement in virtualNetworkSitesSequenceElement.Elements(XName.Get("VirtualNetworkSite", "http://schemas.microsoft.com/windowsazure"))) { NetworkListResponse.VirtualNetworkSite virtualNetworkSiteInstance = new NetworkListResponse.VirtualNetworkSite(); result.VirtualNetworkSites.Add(virtualNetworkSiteInstance); XElement nameElement = virtualNetworkSitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; virtualNetworkSiteInstance.Name = nameInstance; } XElement labelElement = virtualNetworkSitesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; virtualNetworkSiteInstance.Label = labelInstance; } XElement idElement = virtualNetworkSitesElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; virtualNetworkSiteInstance.Id = idInstance; } XElement affinityGroupElement = virtualNetworkSitesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; virtualNetworkSiteInstance.AffinityGroup = affinityGroupInstance; } XElement locationElement = virtualNetworkSitesElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; virtualNetworkSiteInstance.Location = locationInstance; } XElement stateElement = virtualNetworkSitesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; virtualNetworkSiteInstance.State = stateInstance; } XElement addressSpaceElement = virtualNetworkSitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure")); if (addressSpaceElement != null) { NetworkListResponse.AddressSpace addressSpaceInstance = new NetworkListResponse.AddressSpace(); virtualNetworkSiteInstance.AddressSpace = addressSpaceInstance; XElement addressPrefixesSequenceElement = addressSpaceElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure")); if (addressPrefixesSequenceElement != null) { foreach (XElement addressPrefixesElement in addressPrefixesSequenceElement.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure"))) { addressSpaceInstance.AddressPrefixes.Add(addressPrefixesElement.Value); } } } XElement subnetsSequenceElement = virtualNetworkSitesElement.Element(XName.Get("Subnets", "http://schemas.microsoft.com/windowsazure")); if (subnetsSequenceElement != null) { foreach (XElement subnetsElement in subnetsSequenceElement.Elements(XName.Get("Subnet", "http://schemas.microsoft.com/windowsazure"))) { NetworkListResponse.Subnet subnetInstance = new NetworkListResponse.Subnet(); virtualNetworkSiteInstance.Subnets.Add(subnetInstance); XElement nameElement2 = subnetsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; subnetInstance.Name = nameInstance2; } XElement addressPrefixElement = subnetsElement.Element(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")); if (addressPrefixElement != null) { string addressPrefixInstance = addressPrefixElement.Value; subnetInstance.AddressPrefix = addressPrefixInstance; } XElement networkSecurityGroupElement = subnetsElement.Element(XName.Get("NetworkSecurityGroup", "http://schemas.microsoft.com/windowsazure")); if (networkSecurityGroupElement != null) { string networkSecurityGroupInstance = networkSecurityGroupElement.Value; subnetInstance.NetworkSecurityGroup = networkSecurityGroupInstance; } } } XElement dnsElement = virtualNetworkSitesElement.Element(XName.Get("Dns", "http://schemas.microsoft.com/windowsazure")); if (dnsElement != null) { XElement dnsServersSequenceElement = dnsElement.Element(XName.Get("DnsServers", "http://schemas.microsoft.com/windowsazure")); if (dnsServersSequenceElement != null) { foreach (XElement dnsServersElement in dnsServersSequenceElement.Elements(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure"))) { NetworkListResponse.DnsServer dnsServerInstance = new NetworkListResponse.DnsServer(); virtualNetworkSiteInstance.DnsServers.Add(dnsServerInstance); XElement nameElement3 = dnsServersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement3 != null) { string nameInstance3 = nameElement3.Value; dnsServerInstance.Name = nameInstance3; } XElement addressElement = dnsServersElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure")); if (addressElement != null) { string addressInstance = addressElement.Value; dnsServerInstance.Address = addressInstance; } } } } XElement gatewayElement = virtualNetworkSitesElement.Element(XName.Get("Gateway", "http://schemas.microsoft.com/windowsazure")); if (gatewayElement != null) { NetworkListResponse.Gateway gatewayInstance = new NetworkListResponse.Gateway(); virtualNetworkSiteInstance.Gateway = gatewayInstance; XElement profileElement = gatewayElement.Element(XName.Get("Profile", "http://schemas.microsoft.com/windowsazure")); if (profileElement != null) { string profileInstance = profileElement.Value; gatewayInstance.Profile = profileInstance; } XElement sitesSequenceElement = gatewayElement.Element(XName.Get("Sites", "http://schemas.microsoft.com/windowsazure")); if (sitesSequenceElement != null) { foreach (XElement sitesElement in sitesSequenceElement.Elements(XName.Get("LocalNetworkSite", "http://schemas.microsoft.com/windowsazure"))) { NetworkListResponse.LocalNetworkSite localNetworkSiteInstance = new NetworkListResponse.LocalNetworkSite(); gatewayInstance.Sites.Add(localNetworkSiteInstance); XElement nameElement4 = sitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement4 != null) { string nameInstance4 = nameElement4.Value; localNetworkSiteInstance.Name = nameInstance4; } XElement vpnGatewayAddressElement = sitesElement.Element(XName.Get("VpnGatewayAddress", "http://schemas.microsoft.com/windowsazure")); if (vpnGatewayAddressElement != null) { string vpnGatewayAddressInstance = vpnGatewayAddressElement.Value; localNetworkSiteInstance.VpnGatewayAddress = vpnGatewayAddressInstance; } XElement addressSpaceElement2 = sitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure")); if (addressSpaceElement2 != null) { NetworkListResponse.AddressSpace addressSpaceInstance2 = new NetworkListResponse.AddressSpace(); localNetworkSiteInstance.AddressSpace = addressSpaceInstance2; XElement addressPrefixesSequenceElement2 = addressSpaceElement2.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure")); if (addressPrefixesSequenceElement2 != null) { foreach (XElement addressPrefixesElement2 in addressPrefixesSequenceElement2.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure"))) { addressSpaceInstance2.AddressPrefixes.Add(addressPrefixesElement2.Value); } } } XElement connectionsSequenceElement = sitesElement.Element(XName.Get("Connections", "http://schemas.microsoft.com/windowsazure")); if (connectionsSequenceElement != null) { foreach (XElement connectionsElement in connectionsSequenceElement.Elements(XName.Get("Connection", "http://schemas.microsoft.com/windowsazure"))) { NetworkListResponse.Connection connectionInstance = new NetworkListResponse.Connection(); localNetworkSiteInstance.Connections.Add(connectionInstance); XElement typeElement = connectionsElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; connectionInstance.Type = typeInstance; } } } } } XElement vPNClientAddressPoolElement = gatewayElement.Element(XName.Get("VPNClientAddressPool", "http://schemas.microsoft.com/windowsazure")); if (vPNClientAddressPoolElement != null) { NetworkListResponse.VPNClientAddressPool vPNClientAddressPoolInstance = new NetworkListResponse.VPNClientAddressPool(); gatewayInstance.VPNClientAddressPool = vPNClientAddressPoolInstance; XElement addressPrefixesSequenceElement3 = vPNClientAddressPoolElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure")); if (addressPrefixesSequenceElement3 != null) { foreach (XElement addressPrefixesElement3 in addressPrefixesSequenceElement3.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure"))) { vPNClientAddressPoolInstance.AddressPrefixes.Add(addressPrefixesElement3.Value); } } } } } } } 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> /// The Set Network Configuration operation asynchronously configures /// the virtual network. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Set Network Configuration /// 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> public async Task<OperationStatusResponse> SetConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken) { NetworkManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "SetConfigurationAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.Networks.BeginSettingConfigurationAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using Gallio.Common.Xml; using Gallio.Common.Markup; using Gallio.Runtime.ProgressMonitoring; using Gallio.Runtime; using Gallio.Runner.Reports; using Path = System.IO.Path; namespace Gallio.Reports { /// <summary> /// <para> /// Generic XSLT report formatter. /// </para> /// <para> /// Recognizes the following options: /// <list type="bullet"> /// <listheader> /// <term>Option</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>AttachmentContentDisposition</term> /// <description>Overrides the default attachment content disposition for the format. /// The content disposition may be "Absent" to exclude attachments, "Link" to /// include attachments by reference to external files, or "Inline" to include attachments as /// inline content within the formatted document. Different formats use different /// default content dispositions.</description> /// </item> /// </list> /// </para> /// </summary> public class XsltReportFormatter : BaseReportFormatter { private readonly string extension; private readonly string contentType; private readonly DirectoryInfo resourceDirectory; private readonly string xsltPath; private readonly string[] resourcePaths; private XslCompiledTransform transform; /// <summary> /// Creates an XSLT report formatter. /// </summary> /// <param name="extension">The preferred extension without a '.'</param> /// <param name="contentType">The content type of the main report document.</param> /// <param name="resourceDirectory">The resource directory.</param> /// <param name="xsltPath">The path of the XSLT relative to the resource directory.</param> /// <param name="resourcePaths">The paths of the resources (such as images or CSS) to copy /// to the report directory relative to the resource directory.</param> /// <exception cref="ArgumentNullException">Thrown if any arguments are null.</exception> public XsltReportFormatter(string extension, string contentType, DirectoryInfo resourceDirectory, string xsltPath, string[] resourcePaths) { if (extension == null) throw new ArgumentNullException(@"extension"); if (contentType == null) throw new ArgumentNullException(@"contentType"); if (resourceDirectory == null) throw new ArgumentNullException(@"resourceDirectory"); if (xsltPath == null) throw new ArgumentNullException(@"xsltPath"); if (resourcePaths == null || Array.IndexOf(resourcePaths, null) >= 0) throw new ArgumentNullException(@"resourcePaths"); this.extension = extension; this.contentType = contentType; this.resourceDirectory = resourceDirectory; this.xsltPath = xsltPath; this.resourcePaths = resourcePaths; } /// <inheritdoc /> public override void Format(IReportWriter reportWriter, ReportFormatterOptions options, IProgressMonitor progressMonitor) { AttachmentContentDisposition attachmentContentDisposition = GetAttachmentContentDisposition(options); using (progressMonitor.BeginTask("Formatting report.", 10)) { progressMonitor.SetStatus("Applying XSL transform."); ApplyTransform(reportWriter, attachmentContentDisposition, options); progressMonitor.Worked(3); progressMonitor.SetStatus("Copying resources."); CopyResources(reportWriter); progressMonitor.Worked(2); progressMonitor.SetStatus(@""); if (attachmentContentDisposition == AttachmentContentDisposition.Link) { using (IProgressMonitor subProgressMonitor = progressMonitor.CreateSubProgressMonitor(5)) reportWriter.SaveReportAttachments(subProgressMonitor); } } } /// <summary> /// Gets the XSL transform. /// </summary> protected XslCompiledTransform Transform { get { if (transform == null) transform = LoadTransform(Path.Combine(resourceDirectory.FullName, xsltPath)); return transform; } } /// <summary> /// Applies the transform to produce a report. /// </summary> protected virtual void ApplyTransform(IReportWriter reportWriter, AttachmentContentDisposition attachmentContentDisposition, ReportFormatterOptions options) { XsltArgumentList arguments = new XsltArgumentList(); PopulateArguments(arguments, options, reportWriter.ReportContainer.ReportName); XPathDocument document = SerializeReportToXPathDocument(reportWriter, attachmentContentDisposition); string reportPath = reportWriter.ReportContainer.ReportName + @"." + extension; Encoding encoding = new UTF8Encoding(false); XslCompiledTransform transform = Transform; XmlWriterSettings settings = transform.OutputSettings.Clone(); settings.CheckCharacters = false; settings.Encoding = encoding; settings.CloseOutput = true; using (XmlWriter writer = XmlWriter.Create(reportWriter.ReportContainer.OpenWrite(reportPath, contentType, encoding), settings)) transform.Transform(document, arguments, writer); reportWriter.AddReportDocumentPath(reportPath); } /// <summary> /// Copies additional resources to the content path within the report. /// </summary> protected virtual void CopyResources(IReportWriter reportWriter) { foreach (string resourcePath in resourcePaths) { if (resourcePath.Length > 0) { string sourceContentPath = Path.Combine(resourceDirectory.FullName, resourcePath); string destContentPath = Path.Combine(reportWriter.ReportContainer.ReportName, resourcePath); ReportContainerUtils.CopyToReport(reportWriter.ReportContainer, sourceContentPath, destContentPath); } } } /// <summary> /// Populates the arguments for the XSL template processing. /// </summary> protected virtual void PopulateArguments(XsltArgumentList arguments, ReportFormatterOptions options, string reportName) { arguments.AddParam(@"resourceRoot", @"", reportName); } /// <summary> /// Loads the XSL transform. /// </summary> /// <param name="resolvedXsltPath">The full path of the XSLT.</param> /// <returns>The transform.</returns> protected virtual XslCompiledTransform LoadTransform(string resolvedXsltPath) { XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = false; settings.ValidationType = ValidationType.None; settings.CloseInput = true; settings.XmlResolver = GetContentResolver(); XslCompiledTransform transform = new XslCompiledTransform(); using (XmlReader reader = XmlReader.Create(resolvedXsltPath, settings)) transform.Load(reader); return transform; } private static XPathDocument SerializeReportToXPathDocument(IReportWriter reportWriter, AttachmentContentDisposition attachmentContentDisposition) { return XmlUtils.WriteToXPathDocument( xmlWriter => reportWriter.SerializeReport(xmlWriter, attachmentContentDisposition)); } private static XmlResolver GetContentResolver() { return new XmlUrlResolver(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: ChannelSinkStacks.cs ** ** Purpose: Defines the stack interfaces. ** ** ===========================================================*/ using System; using System.Collections; using System.IO; using System.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Metadata; using System.Security.Permissions; using System.Threading; namespace System.Runtime.Remoting.Channels { // interface for maintaining the sink stack // The formatter sink MUST provide this object. // No other sinks should have to check to see if this is null. [System.Runtime.InteropServices.ComVisible(true)] public interface IClientChannelSinkStack : IClientResponseChannelSinkStack { // Push a sink to the stack (it will be called on the way back to get // the response stream). [System.Security.SecurityCritical] // auto-generated_required void Push(IClientChannelSink sink, Object state); // Retrieve state previously pushed by sink. [System.Security.SecurityCritical] // auto-generated_required Object Pop(IClientChannelSink sink); } // IChannelSinkStack [System.Runtime.InteropServices.ComVisible(true)] public interface IClientResponseChannelSinkStack { // Call AsyncProcessResponse (on previous channel sink) [System.Security.SecurityCritical] // auto-generated_required void AsyncProcessResponse(ITransportHeaders headers, Stream stream); // Called by client formatter sink in AsyncProcessResponse once it has // deserialized the response message. [System.Security.SecurityCritical] // auto-generated_required void DispatchReplyMessage(IMessage msg); // If an exception happens on the async channel sink path, the // sink should call this method with the exception. [System.Security.SecurityCritical] // auto-generated_required void DispatchException(Exception e); } // interface IClientResponseChannelSinkStack [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(true)] public class ClientChannelSinkStack : IClientChannelSinkStack { private class SinkStack { public SinkStack PrevStack; public IClientChannelSink Sink; public Object State; } private SinkStack _stack = null; private IMessageSink _replySink = null; public ClientChannelSinkStack() { } // use this constructor when initiating an async call public ClientChannelSinkStack(IMessageSink replySink) { _replySink = replySink; } [System.Security.SecurityCritical] public void Push(IClientChannelSink sink, Object state) { SinkStack newStack = new SinkStack(); newStack.PrevStack = _stack; newStack.Sink = sink; newStack.State = state; _stack = newStack; } // Push // retrieve state previously pushed by sink [System.Security.SecurityCritical] public Object Pop(IClientChannelSink sink) { if (_stack == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Channel_PopOnEmptySinkStack")); } // find this sink on the stack do { if (_stack.Sink == sink) break; _stack = _stack.PrevStack; } while (_stack != null); if (_stack.Sink == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Channel_PopFromSinkStackWithoutPush")); } Object state = _stack.State; _stack = _stack.PrevStack; return state; } // Pop [System.Security.SecurityCritical] // auto-generated public void AsyncProcessResponse(ITransportHeaders headers, Stream stream) { // If the reply sink is null, this is a one way message, so we're not // going to process the reply path. if (_replySink != null) { if (_stack == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Channel_CantCallAPRWhenStackEmpty")); } IClientChannelSink sink = _stack.Sink; Object state = _stack.State; _stack = _stack.PrevStack; sink.AsyncProcessResponse(this, state, headers, stream); } } // AsyncProcessResponse // Client formatter sink should call this in AysncProcessResponse once // it has deserialized a message. [System.Security.SecurityCritical] // auto-generated public void DispatchReplyMessage(IMessage msg) { if (_replySink != null) _replySink.SyncProcessMessage(msg); } // DispatchReplyMessage [System.Security.SecurityCritical] // auto-generated public void DispatchException(Exception e) { DispatchReplyMessage(new ReturnMessage(e, null)); } // DispatchException } // ClientChannelSinkStack // interface for maintaining the sink stack // The transport sink MUST provide this object. // No other sinks should have to check to see if this is null. [System.Runtime.InteropServices.ComVisible(true)] public interface IServerChannelSinkStack : IServerResponseChannelSinkStack { // Push a sink to the stack (it will be called on the way back to get // the response stream). [System.Security.SecurityCritical] // auto-generated_required void Push(IServerChannelSink sink, Object state); // Retrieve state previously pushed by sink. [System.Security.SecurityCritical] // auto-generated_required Object Pop(IServerChannelSink sink); /// <internalonly/> // IMPORTANT: If a sink did a Push(), it must do a Pop() // before calling GetResponseStream inside of ProcessMessage. // On the way back, if it is determined that a asynchronous processing is // needed, a sink should call Store() instead of Pop() [System.Security.SecurityCritical] // auto-generated_required void Store(IServerChannelSink sink, Object state); /// <internalonly/> // Called by the server transport sink to complete the dispatch, if async // processing is being used. [System.Security.SecurityCritical] // auto-generated_required void StoreAndDispatch(IServerChannelSink sink, Object state); /// <internalonly/> // handles callback after message has been dispatched asynchronously [System.Security.SecurityCritical] // auto-generated_required void ServerCallback(IAsyncResult ar); } // IServerChannelSinkStack [System.Runtime.InteropServices.ComVisible(true)] public interface IServerResponseChannelSinkStack { /// <internalonly/> // Call AsyncProcessResponse (on previous channel sink) [System.Security.SecurityCritical] // auto-generated_required void AsyncProcessResponse(IMessage msg, ITransportHeaders headers, Stream stream); // Call GetResponseStream (on previous channel sink) [System.Security.SecurityCritical] // auto-generated_required Stream GetResponseStream(IMessage msg, ITransportHeaders headers); } // interface IServerResponseChannelSinkStack [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(true)] public class ServerChannelSinkStack : IServerChannelSinkStack { private class SinkStack { public SinkStack PrevStack; public IServerChannelSink Sink; public Object State; } private SinkStack _stack = null; private SinkStack _rememberedStack = null; // async callback support private IMessage _asyncMsg = null; private MethodInfo _asyncEnd = null; private Object _serverObject = null; private IMethodCallMessage _msg = null; [System.Security.SecurityCritical] public void Push(IServerChannelSink sink, Object state) { SinkStack newStack = new SinkStack(); newStack.PrevStack = _stack; newStack.Sink = sink; newStack.State = state; _stack = newStack; } // Push [System.Security.SecurityCritical] public Object Pop(IServerChannelSink sink) { if (_stack == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Channel_PopOnEmptySinkStack")); } // find this sink on the stack do { if (_stack.Sink == sink) break; _stack = _stack.PrevStack; } while (_stack != null); if (_stack.Sink == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Channel_PopFromSinkStackWithoutPush")); } Object state = _stack.State; _stack = _stack.PrevStack; return state; } // Pop [System.Security.SecurityCritical] // auto-generated public void Store(IServerChannelSink sink, Object state) { if (_stack == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Channel_StoreOnEmptySinkStack")); } // find this sink on the stack do { if (_stack.Sink == sink) break; _stack = _stack.PrevStack; } while (_stack != null); if (_stack.Sink == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Channel_StoreOnSinkStackWithoutPush")); } SinkStack remStack = new SinkStack(); remStack.PrevStack = _rememberedStack; remStack.Sink = sink; remStack.State = state; _rememberedStack = remStack; Pop(sink); } // Store [System.Security.SecurityCritical] // auto-generated public void StoreAndDispatch(IServerChannelSink sink, Object state) { Store(sink, state); FlipRememberedStack(); CrossContextChannel.DoAsyncDispatch(_asyncMsg, null); } // Store // Reverses remebered stack so that return message may be dispatched. private void FlipRememberedStack() { if (_stack != null) throw new RemotingException( Environment.GetResourceString( "Remoting_Channel_CantCallFRSWhenStackEmtpy")); while (_rememberedStack != null) { SinkStack newStack = new SinkStack(); newStack.PrevStack = _stack; newStack.Sink = _rememberedStack.Sink; newStack.State = _rememberedStack.State; _stack = newStack; _rememberedStack = _rememberedStack.PrevStack; } } // FlipRememberedStack [System.Security.SecurityCritical] // auto-generated public void AsyncProcessResponse(IMessage msg, ITransportHeaders headers, Stream stream) { if (_stack == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Channel_CantCallAPRWhenStackEmpty")); } IServerChannelSink sink = _stack.Sink; Object state = _stack.State; _stack = _stack.PrevStack; sink.AsyncProcessResponse(this, state, msg, headers, stream); } // AsyncProcessResponse [System.Security.SecurityCritical] // auto-generated public Stream GetResponseStream(IMessage msg, ITransportHeaders headers) { if (_stack == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Channel_CantCallGetResponseStreamWhenStackEmpty")); } // save state IServerChannelSink savedSink = _stack.Sink; Object savedState = _stack.State; _stack = _stack.PrevStack; Stream stream = savedSink.GetResponseStream(this, savedState, msg, headers); // restore state Push(savedSink, savedState); return stream; } // GetResponseStream // Store server that is going to be called back internal Object ServerObject { set { _serverObject = value; } } [System.Security.SecurityCritical] // auto-generated public void ServerCallback(IAsyncResult ar) { if (_asyncEnd != null) { RemotingMethodCachedData asyncEndCache = (RemotingMethodCachedData) InternalRemotingServices.GetReflectionCachedData(_asyncEnd); MethodInfo syncMI = (MethodInfo)_msg.MethodBase; RemotingMethodCachedData syncCache = (RemotingMethodCachedData) InternalRemotingServices.GetReflectionCachedData(syncMI); ParameterInfo[] paramList = asyncEndCache.Parameters; // construct list to pass into End Object[] parameters = new Object[paramList.Length]; parameters[paramList.Length - 1] = ar; // last parameter is the async result Object[] syncMsgArgs = _msg.Args; // copy out and ref parameters to the parameters list AsyncMessageHelper.GetOutArgs(syncCache.Parameters, syncMsgArgs, parameters); Object[] outArgs; StackBuilderSink s = new StackBuilderSink(_serverObject); Object returnValue = s.PrivateProcessMessage(_asyncEnd.MethodHandle, System.Runtime.Remoting.Messaging.Message.CoerceArgs(_asyncEnd, parameters, paramList), _serverObject, out outArgs); // The outArgs list is associated with the EndXXX method. We need to make sure // it is sized properly for the out args of the XXX method. if (outArgs != null) outArgs = ArgMapper.ExpandAsyncEndArgsToSyncArgs(syncCache, outArgs); s.CopyNonByrefOutArgsFromOriginalArgs(syncCache, syncMsgArgs, ref outArgs); IMessage retMessage = new ReturnMessage( returnValue, outArgs, _msg.ArgCount, Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext, _msg); AsyncProcessResponse(retMessage, null, null); } } // ServerCallback } // ServerChannelSinkStack // helper class for transforming [....] message parameter lists into its // async counterparts internal static class AsyncMessageHelper { internal static void GetOutArgs(ParameterInfo[] syncParams, Object[] syncArgs, Object[] endArgs) { int outCount = 0; for (int co = 0; co < syncParams.Length; co++) { if (syncParams[co].IsOut || syncParams[co].ParameterType.IsByRef) { endArgs[outCount++] = syncArgs[co]; } } } // GetOutArgs } // AsyncMessageHelper } // namespace System.Runtime.Remoting.Channels
using System; using System.Collections; using System.Collections.Generic; using FlatRedBall; using FlatRedBall.Graphics; #if FRB_MDX using Vector2 = Microsoft.DirectX.Vector2; #else using Vector2 = Microsoft.Xna.Framework.Vector2; #endif namespace FlatRedBall.Gui { /// <summary> /// Summary description for WindowArrayVisibilityListBox. /// </summary> public class WindowArrayVisibilityListBox : ListBox { #region Fields private List<Vector2> windowScls; #endregion #region Properties public override bool Visible { set { base.Visible = value; if(value == false) { foreach(CollapseItem item in mItems) ((WindowArray)item.ReferenceObject).Visible = value; } else { foreach(CollapseItem item in mItems) { if (this.GetHighlighted().Contains(item.Text)) { ((WindowArray)item.ReferenceObject).Visible = true; } else { ((WindowArray)item.ReferenceObject).Visible = false; } } } } } #endregion #region Delegates private void SelectWindowArrayVisibility(Window callingWindow) { int i = 0; foreach (CollapseItem item in this.mItems) { if (this.GetHighlighted().Contains(item.Text)) { Vector2 v = windowScls[i]; if (float.IsNaN(v.X) == false && float.IsNaN(v.Y) == false) { float newScaleX = v.X; float newScaleY = v.Y; if (float.IsNaN(v.X)) newScaleX = Parent.ScaleX; if (float.IsNaN(v.Y)) newScaleY = Parent.ScaleY; Parent.SetScaleTL(newScaleX, newScaleY, true); // parentWindow.X += v.X - parentWindow.ScaleX; // this.Parent.ScaleX = v.X; } ((WindowArray)item.ReferenceObject).Visible = true; } else { ((WindowArray)item.ReferenceObject).Visible = false; } i++; } if (this.NumberOfVisibleElements >= Items.Count) { ScrollBarVisible = false; } else { ScrollBarVisible = true; } } #endregion #region Methods #region Constructor public WindowArrayVisibilityListBox(Cursor cursor) : base(cursor) { Click += new GuiMessage(SelectWindowArrayVisibility); windowScls = new List<Vector2>(); } #endregion #region Public Methods public void AddWindowArray(string windowName, WindowArray windowArray, float ScaleX, float ScaleY) { base.AddItem(windowName, windowArray); windowScls.Add( new Vector2(ScaleX, ScaleY)); } public void AddWindowArray(string windowName, WindowArray windowArray) { AddWindowArray(windowName, windowArray, float.NaN, float.NaN); } public void AddWindowToCategory(IWindow windowToAdd, string category) { // If the window already exists in a category, then remove it // also remove the window from any WindowArrays that it belongs to foreach (CollapseItem collapseItem in mItems) { if (((WindowArray)collapseItem.ReferenceObject).Contains(windowToAdd)) { ((WindowArray)collapseItem.ReferenceObject).Remove(windowToAdd); } } ((WindowArray)GetObject(category)).Add(windowToAdd); SelectWindowArrayVisibility(this); } public string GetCategoryWindowBelongsTo(IWindow windowInQuestion) { foreach (CollapseItem collapseItem in mItems) { if (((WindowArray)collapseItem.ReferenceObject).Contains(windowInQuestion)) { return collapseItem.Text; } } return ""; } public bool IsWindowInCategory(IWindow windowToCheck, string category) { WindowArray windowArray = ((WindowArray)GetObject(category)); return windowArray != null && ((WindowArray)GetObject(category)).Contains(windowToCheck); } public override void HighlightItem(string itemToHighlight) { base.HighlightItem(itemToHighlight); SelectWindowArrayVisibility(this); } public override void RemoveWindow(IWindow windowToRemove) { base.RemoveWindow(windowToRemove); // also remove the window from any WindowArrays that it belongs to foreach (CollapseItem collapseItem in mItems) { if (((WindowArray)collapseItem.ReferenceObject).Contains(windowToRemove)) { ((WindowArray)collapseItem.ReferenceObject).Remove(windowToRemove); } } } public void SetCategoryScale(string category, float newScaleX, float newScaleY) { int index = -1; for (int i = 0; i < mItems.Count; i++) { if (mItems[i].Text == category) { index = i; break; } } if (index != -1) { windowScls[index] = new Vector2(newScaleX, newScaleY); } } #endregion #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace Dccelerator.UnFastReflection { /// <summary> /// Reflection Utilities. /// Contains useful methods for manipulating types and it's members (mostly properties) in simple and fast manner. /// Methods of this class works using Expression Threes to generate and compile delegates to accessing properties much more faster than reflection. /// It also used caching of properties paths. /// </summary> /// <remarks> /// Currently it invokes every property through delegate, to access nested properties. /// In future, I will generate and use delegate accessing full requested property path at one call. /// </remarks> /// <seealso cref="RUtils{TType}"/> public static class RUtils //todo: generate and use delegate accessing full requested property path at one call. { /// <summary> /// Returns number of inheritance generator from <paramref name="parent"/> to <paramref name="child"/> type. /// </summary> /// <returns> /// Returns 0, if <paramref name="parent"/> is interface, and it can be assigranble from <paramref name="child"/>. /// Othrewise returns number of ingeritrance iterations fro <paramref name="parent"/> to <paramref name="child"/>. /// </returns> /// <exception cref="ArgumentNullException">When <paramref name="parent"/> or <paramref name="child"/> is null</exception> /// <exception cref="InvalidOperationException">When <paramref name="parent"/> and <paramref name="child"/> arguments are not siblings.</exception> public static int GetGenerationNumberTo(this Type parent, Type child) { if (parent == null) throw new ArgumentNullException(nameof(parent)); if (child == null) throw new ArgumentNullException(nameof(child)); if (!parent.IsAssignableFrom(child)) throw new InvalidOperationException($"Type '{parent}' is not parent of type '{child}'"); if (parent.GetInfo().IsInterface) return 0; var sum = 0; do { if (parent == child) return sum; child = child.GetInfo().BaseType; sum++; } while (child != null); return sum; } public static PropertyInfo MostClosedPropertyNamed(string name, Type type) { return type.MostClosedPropertyNamed(name); } public static PropertyInfo MostClosedPropertyNamed(this Type type, string name) { return type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) .Where(x => x.Name == name) .MostClosedPropertyTo(type); } public static PropertyInfo MostClosedPropertyTo(Type type, IEnumerable<PropertyInfo> props) { return props.MostClosedPropertyTo(type); } public static PropertyInfo MostClosedPropertyTo(this IEnumerable<PropertyInfo> props, Type type) { Dictionary<Type, PropertyInfo> declarationMapping; try { declarationMapping = props.ToDictionary(x => x.DeclaringType, x => x); } catch (Exception e) { Log.TraceEvent(TraceEventType.Error, e.ToString()); throw; } if (!declarationMapping.Any()) return null; var curType = type; do { if (declarationMapping.TryGetValue(curType, out PropertyInfo closestProperty)) return closestProperty; } while ((curType = curType.GetInfo().BaseType) != null); var error = $"Seems that passed properties doesn't belong to type '{type.FullName}'. " + $"\nPassed props {{" + $"\n\t{string.Join("\n,", declarationMapping.Select(x => $"\"{x.Key.FullName}\": \"{x.Value.Name}\""))}}}"; Log.TraceEvent(TraceEventType.Critical, error); throw new Exception(error); } /// <summary> /// Returns an structure for manipulating property what placed on <paramref name="path"/>, if we start looking from specified <paramref name="contextType"/>. /// Is will return null, when path is wrong. /// </summary> /// <param name="contextType"></param> //todo: documentation /// <param name="path"></param> /// <returns></returns> public static PropertyPath GetPropertyPath(this Type contextType, string path) { var identity = new PropIdentity(contextType, path); if (_propertyPaths.TryGetValue(identity, out var propertyPath)) return propertyPath; propertyPath = make_property_path(identity); if (!_propertyPaths.TryAdd(identity, propertyPath)) propertyPath = _propertyPaths[identity]; return propertyPath; } /// <summary> /// Returns value of property placed on <paramref name="path"/> with started point at <paramref name="context"/>. /// </summary> /// <param name="context">Object that has property on passed <paramref name="path"/></param> /// <param name="path">Path to requested property</param> /// <param name="value">Value</param> public static bool TryGet<T>(this T context, string path, out object value) { return RUtils<T>.TryGet(context, path, out value); } /// <summary> /// Returns value of property placed on <paramref name="path"/> with started point at <paramref name="context"/>. /// </summary> /// <param name="context">Object that has property on passed <paramref name="path"/></param> /// <param name="path">Path to requested property</param> /// <param name="value">Value</param> public static bool TryGet(this object context, string path, out object value) { if (context == null || path == null) { value = null; return false; } var type = context.GetType(); var prop = GetPropertyPath(type, path); if (prop != null) { try { value = prop.Get(context); return true; } catch (Exception e) { Log.TraceEvent(TraceEventType.Error, $"Can't get value from path {type.FullName}.{path}\n\n{e}"); value = null; return false; } } Log.TraceEvent(TraceEventType.Warning, $"There is no property or field {type.FullName}.{path}"); value = null; return false; } public static object Get<T>(this T context, string path) { return RUtils<T>.Get(context, path); } public static object Get(this object context, string path) { if (context == null || path == null) return null; var type = context.GetType(); var propertyPath = GetPropertyPath(type, path); if (propertyPath != null) return propertyPath.Get(context); Log.TraceEvent(TraceEventType.Warning, $"There is no property or field {type.FullName}.{path}"); return null; } public static bool TrySet<T>(this T context, string path, object value) { if (context == null || string.IsNullOrWhiteSpace(path)) return false; return RUtils<T>.TrySet(context, path, value); } public static bool TrySet(this object context, string path, object value) { if (context == null || path == null) return false; var type = context.GetType(); var prop = GetPropertyPath(type, path); if (prop != null) { try { prop.Set(context, value); return true; } catch (Exception e) { Log.TraceEvent(TraceEventType.Error, $"Can't set value '{value}' on path {type.FullName}.{path}\n\n{e}"); return false; } } Log.TraceEvent(TraceEventType.Warning, $"There is no property or field {type.FullName}.{path}"); return false; } public static void Set<T>(this T context, string path, object value) { RUtils<T>.Set(context, path, value); } public static void Set(this object context, string path, object value) { if (context == null || path == null) return; PropertyPath propertyPath; if ((propertyPath = GetPropertyPath(context.GetType(), path)) != null) { propertyPath.Set(context, value); } } #region private class PropIdentity { public readonly string Path; public readonly Type Type; readonly int _hashCode; public PropIdentity(Type type, string path) { Type = type; Path = path; var h = 13; h *= 7 + Path.GetHashCode(); h *= 7 + Type.GetHashCode(); _hashCode = h; } public override int GetHashCode() { return _hashCode; } public override bool Equals(object obj) { return Equals(obj as PropIdentity); } public bool Equals(PropIdentity other) { return other != null && other.Path == Path && other.Type == Type; } } static readonly ConcurrentDictionary<PropIdentity, PropertyPath> _propertyPaths = new ConcurrentDictionary<PropIdentity, PropertyPath>(); static PropertyPath make_property_path( PropIdentity identity) { var neighborInfo = typeof (RUtils<>).MakeGenericType(identity.Type); var neighborMethod = neighborInfo.GetMethod("make_property_path", BindingFlags.Static | BindingFlags.NonPublic); return (PropertyPath) neighborMethod?.Invoke(null, new object[] {identity.Path}); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows; using TypeVisualiser.Geometry; using TypeVisualiser.Properties; namespace TypeVisualiser.Model { /// <summary> /// A model class that describes the line between the subject and an association /// </summary> internal class ConnectionLine : IComparable, IComparable<ConnectionLine>, IDiagramContent, INotifyPropertyChanged { private Point from; private Func<Area, ProximityTestResult> isOverlapping; private DiagramElement parent1; private DiagramElement parent2; private DiagramElement primaryParent; // This is either parent1 or parent2 private Point to; private Point toLineEnd; internal ConnectionLine() { Thickness = 2; Id = Guid.NewGuid().ToString(); } public event PropertyChangedEventHandler PropertyChanged; public static IConnectorBuilder ConnectorBuilder { get; set; } public double Distance { get; set; } /// <summary> /// Gets the exit angle. /// 0 = Pointing right (used to point at the left side of a rectangle) /// 90 = Pointing down (used to point at the top side of a rectangle) /// 180 = Pointing left (used to point at the right side of a rectangle) /// 270 = Pointing up (used to point at the bottom side of a rectangle) /// </summary> public double ExitAngle { get; set; } /// <summary> /// Gets or sets the From point. This is the beginning of the line. The From end is aligned to the diagram subject usually. /// </summary> public Point From { get { return this.from; } set { this.from = value; RaisePropertyChanged("From"); } } /// <summary> /// Used only for debug purposes /// The north oriented angle of the line from the pov of the 'to' end. /// </summary> public double FromAngle { get; set; } public string Id { get; private set; } public IDiagramContent PointingAt { get { return this.primaryParent.DiagramContent; } } public string Style { get; set; } public double Thickness { get; set; } /// <summary> /// Gets or sets the To position of the connection. /// This is the ultimate end of the connection line including the arrow head. The arrow head is aligned to this point, where the line end is /// aligned to the <see cref="ToLineEnd"/>. /// </summary> public Point To { get { return this.to; } set { this.to = value; RaisePropertyChanged("To"); } } /// <summary> /// Used only for debug purposes /// The north oriented angle of the line from the pov of the 'from' end. /// </summary> public double ToAngle { get; set; } /// <summary> /// Gets or sets the To Line End position. /// This is the end of the straight line portion of the connection and the begining of the arrow head. The arrow head tip is aligned to the /// <see cref="To"/> point not this point. /// </summary> public Point ToLineEnd { get { return this.toLineEnd; } set { this.toLineEnd = value; RaisePropertyChanged("ToLineEnd"); } } public string ToolTip { get; private set; } /// <summary> /// Finds the best connection location. /// </summary> /// <param name="fromArea">From visual.</param> /// <param name="destinationArea">To visual.</param> /// <param name="isOverlappingWithOtherControls">A function delegate to find out if a proposed area is overlapping with other controls.</param> /// <returns>A pair of points, from and to</returns> public static ConnectionLine FindBestConnectionRoute( Area fromArea, Area destinationArea, Func<Area, ProximityTestResult> isOverlappingWithOtherControls) { ConnectionLine result = ConnectorBuilder.CalculateBestConnection(fromArea, destinationArea, isOverlappingWithOtherControls); return result; } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "ConnectionRoute ({0:F1},{1:F1}) {4:F1}deg to ({2:F1},{3:F1}) {5:F1}deg", From.X, From.Y, To.X, To.Y, FromAngle, ToAngle); } /// <summary> /// Adjusts the coordinates after canvas expansion. /// If the diagram content needs to adjust itself after being repositioned when the canvas is expanded. /// </summary> /// <param name="horizontalExpandedBy">The horizontalExpandedBy adjustment.</param> /// <param name="verticalExpandedBy">The verticalExpandedBy adjustment.</param> public void AdjustCoordinatesAfterCanvasExpansion(double horizontalExpandedBy, double verticalExpandedBy) { From = new Point(From.X + horizontalExpandedBy, From.Y + verticalExpandedBy); To = new Point(To.X + horizontalExpandedBy, To.Y + verticalExpandedBy); } public int CompareTo(object obj) { return CompareTo((ConnectionLine)obj); } public int CompareTo(ConnectionLine other) { if (other == null) { throw new ArgumentNullResourceException("other", Resources.General_Given_Parameter_Cannot_Be_Null); } return Distance.CompareTo(other.Distance); } /// <summary> /// Notifies the data context (represented by this Diagram Content) that a previously registered position-dependent diagram element has moved. /// </summary> /// <param name="dependentElement">The dependent element.</param> /// <returns> /// A result containing information if layout changes are required with new suggested values. /// </returns> public ParentHasMovedNotificationResult NotifyDiagramContentParentHasMoved(DiagramElement dependentElement) { ConnectionLine route = FindBestConnectionRoute(this.parent1.Area, this.parent2.Area, this.isOverlapping); ClonePropertiesIntoThisInstance(route); return new ParentHasMovedNotificationResult(route.From); } /// <summary> /// Gives a data context for a diagram element the opportunity to listen to parent events when the <see cref="DiagramElement"/> is created. /// </summary> /// <param name="dependentElements">This object is dependent on the position of these elements</param> /// <param name="isOverlappingFunction">The delegate function to determine if a proposed position overlaps with any existing elements.</param> public void RegisterPositionDependency(IEnumerable<DiagramElement> dependentElements, Func<Area, ProximityTestResult> isOverlappingFunction) { this.isOverlapping = isOverlappingFunction; List<DiagramElement> elements = dependentElements.ToList(); this.parent1 = elements.FirstOrDefault(); this.parent2 = elements.Skip(1).FirstOrDefault(); if (SetToolTipText(this.parent1)) { return; } SetToolTipText(this.parent2); } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } private void ClonePropertiesIntoThisInstance(ConnectionLine cloneSource) { From = cloneSource.From; To = cloneSource.To; ToLineEnd = cloneSource.ToLineEnd; ToAngle = cloneSource.ToAngle; FromAngle = cloneSource.FromAngle; ExitAngle = cloneSource.ExitAngle; Distance = cloneSource.Distance; // Must not clone the Id, the clone is intended to seemlessly replace the original. // Style = cloneSource.Style; // Don't clone style or thickness these are already set appropriately for the new type based on usage // Thickness = cloneSource.Thickness; ToolTip = cloneSource.ToolTip; } private bool SetToolTipText(DiagramElement parent) { if (parent != null) { var association = parent.DiagramContent as Association; // Must be association to include parents and fields. if (association != null && !(association is SubjectAssociation)) // Must not be the main subject but rather the element being pointed at. { this.primaryParent = parent; ToolTip = association.Name; return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; namespace System { public partial class Exception : ISerializable { partial void RestoreRemoteStackTrace(SerializationInfo info, StreamingContext context) { _remoteStackTraceString = info.GetString("RemoteStackTraceString"); // Do not rename (binary serialization) // Get the WatsonBuckets that were serialized - this is particularly // done to support exceptions going across AD transitions. // // We use the no throw version since we could be deserializing a pre-V4 // exception object that may not have this entry. In such a case, we would // get null. _watsonBuckets = (byte[]?)info.GetValueNoThrow("WatsonBuckets", typeof(byte[])); // Do not rename (binary serialization) // If we are constructing a new exception after a cross-appdomain call... if (context.State == StreamingContextStates.CrossAppDomain) { // ...this new exception may get thrown. It is logically a re-throw, but // physically a brand-new exception. Since the stack trace is cleared // on a new exception, the "_remoteStackTraceString" is provided to // effectively import a stack trace from a "remote" exception. So, // move the _stackTraceString into the _remoteStackTraceString. Note // that if there is an existing _remoteStackTraceString, it will be // preserved at the head of the new string, so everything works as // expected. // Even if this exception is NOT thrown, things will still work as expected // because the StackTrace property returns the concatenation of the // _remoteStackTraceString and the _stackTraceString. _remoteStackTraceString += _stackTraceString; _stackTraceString = null; } } private IDictionary CreateDataContainer() { if (IsImmutableAgileException(this)) return new EmptyReadOnlyDictionaryInternal(); else return new ListDictionaryInternal(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsImmutableAgileException(Exception e); #if FEATURE_COMINTEROP // // Exception requires anything to be added into Data dictionary is serializable // This wrapper is made serializable to satisfy this requirement but does NOT serialize // the object and simply ignores it during serialization, because we only need // the exception instance in the app to hold the error object alive. // Once the exception is serialized to debugger, debugger only needs the error reference string // [Serializable] internal class __RestrictedErrorObject { // Hold the error object instance but don't serialize/deserialize it [NonSerialized] private readonly object _realErrorObject; internal __RestrictedErrorObject(object errorObject) { _realErrorObject = errorObject; } public object RealErrorObject { get { return _realErrorObject; } } } internal void AddExceptionDataForRestrictedErrorInfo( string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object? restrictedErrorObject, bool hasrestrictedLanguageErrorObject = false) { IDictionary dict = Data; if (dict != null) { dict.Add("RestrictedDescription", restrictedError); dict.Add("RestrictedErrorReference", restrictedErrorReference); dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid); // Keep the error object alive so that user could retrieve error information // using Data["RestrictedErrorReference"] dict.Add("__RestrictedErrorObject", restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject)); dict.Add("__HasRestrictedLanguageErrorObject", hasrestrictedLanguageErrorObject); } } internal bool TryGetRestrictedLanguageErrorObject(out object? restrictedErrorObject) { restrictedErrorObject = null; if (Data != null && Data.Contains("__HasRestrictedLanguageErrorObject")) { if (Data.Contains("__RestrictedErrorObject")) { if (Data["__RestrictedErrorObject"] is __RestrictedErrorObject restrictedObject) restrictedErrorObject = restrictedObject.RealErrorObject; } return (bool)Data["__HasRestrictedLanguageErrorObject"]!; } return false; } #endif // FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] private static extern IRuntimeMethodInfo GetMethodFromStackTrace(object stackTrace); private MethodBase? GetExceptionMethodFromStackTrace() { Debug.Assert(_stackTrace != null, "_stackTrace shouldn't be null when this method is called"); IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace!); // Under certain race conditions when exceptions are re-used, this can be null if (method == null) return null; return RuntimeType.GetMethodBase(method); } public MethodBase? TargetSite { get { if (_exceptionMethod != null) { return _exceptionMethod; } if (_stackTrace == null) { return null; } _exceptionMethod = GetExceptionMethodFromStackTrace(); return _exceptionMethod; } } // Returns the stack trace as a string. If no stack trace is // available, null is returned. public virtual string? StackTrace { get { string? stackTraceString = _stackTraceString; string? remoteStackTraceString = _remoteStackTraceString; // if no stack trace, try to get one if (stackTraceString != null) { return remoteStackTraceString + stackTraceString; } if (_stackTrace == null) { return remoteStackTraceString; } return remoteStackTraceString + GetStackTrace(this); } } private static string GetStackTrace(Exception e) { // Do not include a trailing newline for backwards compatibility return new StackTrace(e, fNeedFileInfo: true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } private string? CreateSourceName() { StackTrace st = new StackTrace(this, fNeedFileInfo: false); if (st.FrameCount > 0) { StackFrame sf = st.GetFrame(0)!; MethodBase method = sf.GetMethod()!; Module module = method.Module; if (!(module is RuntimeModule rtModule)) { if (module is System.Reflection.Emit.ModuleBuilder moduleBuilder) rtModule = moduleBuilder.InternalModule; else throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject); } return rtModule.GetRuntimeAssembly().GetSimpleName(); } return null; } // This method will clear the _stackTrace of the exception object upon deserialization // to ensure that references from another AD/Process dont get accidentally used. [OnDeserialized] private void OnDeserialized(StreamingContext context) { _stackTrace = null; // We wont serialize or deserialize the IP for Watson bucketing since // we dont know where the deserialized object will be used in. // Using it across process or an AppDomain could be invalid and result // in AV in the runtime. // // Hence, we set it to zero when deserialization takes place. _ipForWatsonBuckets = UIntPtr.Zero; } // This is used by the runtime when re-throwing a managed exception. It will // copy the stack trace to _remoteStackTraceString. internal void InternalPreserveStackTrace() { // Make sure that the _source field is initialized if Source is not overriden. // We want it to contain the original faulting point. _ = Source; string? tmpStackTraceString = StackTrace; if (!string.IsNullOrEmpty(tmpStackTraceString)) { _remoteStackTraceString = tmpStackTraceString + Environment.NewLineConst; } _stackTrace = null; _stackTraceString = null; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PrepareForForeignExceptionRaise(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetStackTracesDeepCopy(Exception exception, out byte[]? currentStackTrace, out object[]? dynamicMethodArray); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SaveStackTracesFromDeepCopy(Exception exception, byte[]? currentStackTrace, object[]? dynamicMethodArray); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern uint GetExceptionCount(); // This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the // exception, just before the exception is "rethrown". internal void RestoreDispatchState(in DispatchState dispatchState) { // Restore only for non-preallocated exceptions if (!IsImmutableAgileException(this)) { // When restoring back the fields, we again create a copy and set reference to them // in the exception object. This will ensure that when this exception is thrown and these // fields are modified, then EDI's references remain intact. // byte[]? stackTraceCopy = (byte[]?)dispatchState.StackTrace?.Clone(); object[]? dynamicMethodsCopy = (object[]?)dispatchState.DynamicMethods?.Clone(); // Watson buckets and remoteStackTraceString fields are captured and restored without any locks. It is possible for them to // get out of sync without violating overall integrity of the system. _watsonBuckets = dispatchState.WatsonBuckets; _ipForWatsonBuckets = dispatchState.IpForWatsonBuckets; _remoteStackTraceString = dispatchState.RemoteStackTrace; // The binary stack trace and references to dynamic methods have to be restored under a lock to guarantee integrity of the system. SaveStackTracesFromDeepCopy(this, stackTraceCopy, dynamicMethodsCopy); _stackTraceString = null; // Marks the TES state to indicate we have restored foreign exception // dispatch information. PrepareForForeignExceptionRaise(); } } private MethodBase? _exceptionMethod; // Needed for serialization. internal string? _message; private IDictionary? _data; private readonly Exception? _innerException; private string? _helpURL; private byte[]? _stackTrace; private byte[]? _watsonBuckets; private string? _stackTraceString; // Needed for serialization. private string? _remoteStackTraceString; #pragma warning disable CA1823, 414 // Fields are not used from managed. // _dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of the exception. We do this because // the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed // unless a System.Resolver object roots it. private readonly object[]? _dynamicMethods; private string? _source; // Mainly used by VB. private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing private readonly IntPtr _xptrs; // Internal EE stuff private readonly int _xcode = _COMPlusExceptionCode; // Internal EE stuff #pragma warning restore CA1823, 414 // @MANAGED: HResult is used from within the EE! Rename with care - check VM directory private int _HResult; // HResult // See src\inc\corexcep.h's EXCEPTION_COMPLUS definition: private const int _COMPlusExceptionCode = unchecked((int)0xe0434352); // Win32 exception code for COM+ exceptions private string? SerializationRemoteStackTraceString => _remoteStackTraceString; private object? SerializationWatsonBuckets => _watsonBuckets; private string? SerializationStackTraceString { get { string? stackTraceString = _stackTraceString; if (stackTraceString == null && _stackTrace != null) { stackTraceString = GetStackTrace(this); } return stackTraceString; } } // This piece of infrastructure exists to help avoid deadlocks // between parts of mscorlib that might throw an exception while // holding a lock that are also used by mscorlib's ResourceManager // instance. As a special case of code that may throw while holding // a lock, we also need to fix our asynchronous exceptions to use // Win32 resources as well (assuming we ever call a managed // constructor on instances of them). We should grow this set of // exception messages as we discover problems, then move the resources // involved to native code. internal enum ExceptionMessageKind { ThreadAbort = 1, ThreadInterrupted = 2, OutOfMemory = 3 } // See comment on ExceptionMessageKind internal static string GetMessageFromNativeResources(ExceptionMessageKind kind) { string? retMesg = null; GetMessageFromNativeResources(kind, new StringHandleOnStack(ref retMesg)); return retMesg!; } [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg); internal readonly struct DispatchState { public readonly byte[]? StackTrace; public readonly object[]? DynamicMethods; public readonly string? RemoteStackTrace; public readonly UIntPtr IpForWatsonBuckets; public readonly byte[]? WatsonBuckets; public DispatchState( byte[]? stackTrace, object[]? dynamicMethods, string? remoteStackTrace, UIntPtr ipForWatsonBuckets, byte[]? watsonBuckets) { StackTrace = stackTrace; DynamicMethods = dynamicMethods; RemoteStackTrace = remoteStackTrace; IpForWatsonBuckets = ipForWatsonBuckets; WatsonBuckets = watsonBuckets; } } internal DispatchState CaptureDispatchState() { GetStackTracesDeepCopy(this, out byte[]? stackTrace, out object[]? dynamicMethods); return new DispatchState(stackTrace, dynamicMethods, _remoteStackTraceString, _ipForWatsonBuckets, _watsonBuckets); } [StackTraceHidden] internal void SetCurrentStackTrace() { // If this is a preallocated singleton exception, silently skip the operation, // regardless of the value of throwIfHasExistingStack. if (IsImmutableAgileException(this)) { return; } // Check to see if the exception already has a stack set in it. if (_stackTrace != null || _stackTraceString != null || _remoteStackTraceString != null) { ThrowHelper.ThrowInvalidOperationException(); } // Store the current stack trace into the "remote" stack trace, which was originally introduced to support // remoting of exceptions cross app-domain boundaries, and is thus concatenated into Exception.StackTrace // when it's retrieved. var sb = new StringBuilder(256); new StackTrace(fNeedFileInfo: true).ToString(System.Diagnostics.StackTrace.TraceFormat.TrailingNewLine, sb); sb.AppendLine(SR.Exception_EndStackTraceFromPreviousThrow); _remoteStackTraceString = sb.ToString(); } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using Orleans.Runtime; using Orleans.Streams; namespace Orleans.Providers.Streams.Common { internal class CacheBucket { // For backpressure detection we maintain a histogram of 10 buckets. // Every bucket records how many items are in the cache in that bucket // and how many cursors are poinmting to an item in that bucket. // We update the NumCurrentItems when we add and remove cache item (potentially opening or removing a bucket) // We update NumCurrentCursors every time we move a cursor // If the first (most outdated bucket) has at least one cursor pointing to it, we say we are under back pressure (in a full cache). internal int NumCurrentItems { get; private set; } internal int NumCurrentCursors { get; private set; } internal void UpdateNumItems(int val) { NumCurrentItems = NumCurrentItems + val; } internal void UpdateNumCursors(int val) { NumCurrentCursors = NumCurrentCursors + val; } } internal class SimpleQueueCacheItem { internal IBatchContainer Batch; internal bool DeliveryFailure; internal StreamSequenceToken SequenceToken; internal CacheBucket CacheBucket; } /// <summary> /// A queue cache that keeps items in memory /// </summary> public class SimpleQueueCache : IQueueCache { private readonly LinkedList<SimpleQueueCacheItem> cachedMessages; private readonly int maxCacheSize; private readonly ILogger logger; private readonly List<CacheBucket> cacheCursorHistogram; // for backpressure detection private const int NUM_CACHE_HISTOGRAM_BUCKETS = 10; private readonly int CACHE_HISTOGRAM_MAX_BUCKET_SIZE; /// <summary> /// Number of items in the cache /// </summary> public int Size => cachedMessages.Count; /// <summary> /// The limit of the maximum number of items that can be added /// </summary> public int GetMaxAddCount() { return CACHE_HISTOGRAM_MAX_BUCKET_SIZE; } /// <summary> /// SimpleQueueCache Constructor /// </summary> /// <param name="cacheSize"></param> /// <param name="logger"></param> public SimpleQueueCache(int cacheSize, ILogger logger) { cachedMessages = new LinkedList<SimpleQueueCacheItem>(); maxCacheSize = cacheSize; this.logger = logger; cacheCursorHistogram = new List<CacheBucket>(); CACHE_HISTOGRAM_MAX_BUCKET_SIZE = Math.Max(cacheSize / NUM_CACHE_HISTOGRAM_BUCKETS, 1); // we have 10 buckets } /// <summary> /// Returns true if this cache is under pressure. /// </summary> public virtual bool IsUnderPressure() { return cacheCursorHistogram.Count >= NUM_CACHE_HISTOGRAM_BUCKETS; } /// <summary> /// Ask the cache if it has items that can be purged from the cache /// (so that they can be subsequently released them the underlying queue). /// </summary> /// <param name="purgedItems"></param> public virtual bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems) { purgedItems = null; if (cachedMessages.Count == 0) return false; // empty cache if (cacheCursorHistogram.Count == 0) return false; // no cursors yet - zero consumers basically yet. if (cacheCursorHistogram[0].NumCurrentCursors > 0) return false; // consumers are still active in the oldest bucket - fast path var allItems = new List<IBatchContainer>(); while (cacheCursorHistogram.Count > 0 && cacheCursorHistogram[0].NumCurrentCursors == 0) { List<IBatchContainer> items = DrainBucket(cacheCursorHistogram[0]); allItems.AddRange(items); cacheCursorHistogram.RemoveAt(0); // remove the last bucket } purgedItems = allItems; if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("TryPurgeFromCache: purged {PurgedItemsCount} items from cache.", purgedItems.Count); } return true; } private List<IBatchContainer> DrainBucket(CacheBucket bucket) { var itemsToRelease = new List<IBatchContainer>(bucket.NumCurrentItems); // walk all items in the cache starting from last // and remove from the cache the oness that reside in the given bucket until we jump to a next bucket while (bucket.NumCurrentItems > 0) { SimpleQueueCacheItem item = cachedMessages.Last.Value; if (item.CacheBucket.Equals(bucket)) { if (!item.DeliveryFailure) { itemsToRelease.Add(item.Batch); } bucket.UpdateNumItems(-1); cachedMessages.RemoveLast(); } else { // this item already points into the next bucket, so stop. break; } } return itemsToRelease; } /// <summary> /// Add a list of message to the cache /// </summary> /// <param name="msgs"></param> public virtual void AddToCache(IList<IBatchContainer> msgs) { if (msgs == null) throw new ArgumentNullException(nameof(msgs)); if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("AddToCache: added {ItemCount} items to cache.", msgs.Count); } foreach (var message in msgs) { Add(message, message.SequenceToken); } } /// <summary> /// Acquire a stream message cursor. This can be used to retrieve messages from the /// cache starting at the location indicated by the provided token. /// </summary> /// <param name="streamId"></param> /// <param name="token"></param> /// <returns></returns> public virtual IQueueCacheCursor GetCacheCursor(StreamId streamId, StreamSequenceToken token) { var cursor = new SimpleQueueCacheCursor(this, streamId, logger); InitializeCursor(cursor, token); return cursor; } internal void InitializeCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken sequenceToken) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("InitializeCursor: {Cursor} to sequenceToken {SequenceToken}", cursor, sequenceToken); } // Nothing in cache, unset token, and wait for more data. if (cachedMessages.Count == 0) { UnsetCursor(cursor, sequenceToken); return; } // if no token is provided, set token to item at end of cache sequenceToken = sequenceToken ?? cachedMessages.First?.Value?.SequenceToken; // If sequenceToken is too new to be in cache, unset token, and wait for more data. if (sequenceToken.Newer(cachedMessages.First.Value.SequenceToken)) { UnsetCursor(cursor, sequenceToken); return; } LinkedListNode<SimpleQueueCacheItem> lastMessage = cachedMessages.Last; // Check to see if offset is too old to be in cache if (sequenceToken.Older(lastMessage.Value.SequenceToken)) { throw new QueueCacheMissException(sequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken); } // Now the requested sequenceToken is set and is also within the limits of the cache. // Find first message at or below offset // Events are ordered from newest to oldest, so iterate from start of list until we hit a node at a previous offset, or the end. LinkedListNode<SimpleQueueCacheItem> node = cachedMessages.First; while (node != null && node.Value.SequenceToken.Newer(sequenceToken)) { // did we get to the end? if (node.Next == null) // node is the last message break; // if sequenceId is between the two, take the higher if (node.Next.Value.SequenceToken.Older(sequenceToken)) break; node = node.Next; } // return cursor from start. SetCursor(cursor, node); } internal void RefreshCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken sequenceToken) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("RefreshCursor: {RefreshCursor} to sequenceToken {SequenceToken}", cursor, sequenceToken); } // set if unset if (!cursor.IsSet) { InitializeCursor(cursor, cursor.SequenceToken ?? sequenceToken); } } /// <summary> /// Acquires the next message in the cache at the provided cursor /// </summary> /// <param name="cursor"></param> /// <param name="batch"></param> /// <returns></returns> internal bool TryGetNextMessage(SimpleQueueCacheCursor cursor, out IBatchContainer batch) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("TryGetNextMessage: {Cursor}", cursor); } batch = null; if (!cursor.IsSet) return false; // If we are at the end of the cache unset cursor and move offset one forward if (cursor.Element == cachedMessages.First) { UnsetCursor(cursor, null); } else // Advance to next: { AdvanceCursor(cursor, cursor.Element.Previous); } batch = cursor.Element?.Value.Batch; return (batch != null); } private void AdvanceCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("UpdateCursor: {Cursor} to item {Item}", cursor, item.Value.Batch); } cursor.Element.Value.CacheBucket.UpdateNumCursors(-1); // remove from prev bucket cursor.Set(item); cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket } internal void SetCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("SetCursor: {Cursor} to item {Item}", cursor, item.Value.Batch); } cursor.Set(item); cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket } internal void UnsetCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken token) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("UnsetCursor: {Cursor}", cursor); } if (cursor.IsSet) { cursor.Element.Value.CacheBucket.UpdateNumCursors(-1); } cursor.UnSet(token); } private void Add(IBatchContainer batch, StreamSequenceToken sequenceToken) { if (batch == null) throw new ArgumentNullException(nameof(batch)); // this should never happen, but just in case if (Size >= maxCacheSize) throw new CacheFullException(); CacheBucket cacheBucket; if (cacheCursorHistogram.Count == 0) { cacheBucket = new CacheBucket(); cacheCursorHistogram.Add(cacheBucket); } else { cacheBucket = cacheCursorHistogram[cacheCursorHistogram.Count - 1]; // last one } if (cacheBucket.NumCurrentItems == CACHE_HISTOGRAM_MAX_BUCKET_SIZE) // last bucket is full, open a new one { cacheBucket = new CacheBucket(); cacheCursorHistogram.Add(cacheBucket); } // Add message to linked list var item = new SimpleQueueCacheItem { Batch = batch, SequenceToken = sequenceToken, CacheBucket = cacheBucket }; cachedMessages.AddFirst(new LinkedListNode<SimpleQueueCacheItem>(item)); cacheBucket.UpdateNumItems(1); } } }
// 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: Capture synchronization semantics for asynchronous callbacks ** ** ===========================================================*/ namespace System.Threading { using Microsoft.Win32.SafeHandles; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [Flags] enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 }; #endif #if FEATURE_COMINTEROP && FEATURE_APPX // // This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx. // I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed. // [FriendAccessAllowed] [SecurityCritical] internal class WinRTSynchronizationContextFactoryBase { [SecurityCritical] public virtual SynchronizationContext Create(object coreDispatcher) {return null;} } #endif //FEATURE_COMINTEROP #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)] #endif public class SynchronizationContext { #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT SynchronizationContextProperties _props = SynchronizationContextProperties.None; #endif public SynchronizationContext() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT // helper delegate to statically bind to Wait method private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); static Type s_cachedPreparedType1; static Type s_cachedPreparedType2; static Type s_cachedPreparedType3; static Type s_cachedPreparedType4; static Type s_cachedPreparedType5; // protected so that only the derived sync context class can enable these flags [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] protected void SetWaitNotificationRequired() { // // Prepare the method so that it can be called in a reliable fashion when a wait is needed. // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing // preparing the method here does is to ensure there is no failure point before the method execution begins. // // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain. // So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets // our cache be much faster than a more general cache might be. This is important, because this // is a *very* hot code path for many WPF and WinForms apps. // Type type = this.GetType(); if (s_cachedPreparedType1 != type && s_cachedPreparedType2 != type && s_cachedPreparedType3 != type && s_cachedPreparedType4 != type && s_cachedPreparedType5 != type) { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; } public bool IsWaitNotificationRequired() { return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } #endif public virtual void Send(SendOrPostCallback d, Object state) { d(state); } public virtual void Post(SendOrPostCallback d, Object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> public virtual void OperationStarted() { } /// <summary> /// Optional override for subclasses, for responding to notification that operation has completed. /// </summary> public virtual void OperationCompleted() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT // Method called when the CLR does a wait operation [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles"); } Contract.EndContractBlock(); return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } // Static helper to which the above method can delegate to in order to get the default // COM behavior. [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected static extern int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); #endif #if FEATURE_CORECLR [System.Security.SecurityCritical] public static void SetSynchronizationContext(SynchronizationContext syncContext) { Thread.CurrentThread.SynchronizationContext = syncContext; } [System.Security.SecurityCritical] public static void SetThreadStaticContext(SynchronizationContext syncContext) { Thread.CurrentThread.SynchronizationContext = syncContext; } public static SynchronizationContext Current { get { SynchronizationContext context = Thread.CurrentThread.SynchronizationContext; #if FEATURE_APPX if (context == null && AppDomain.IsAppXModel()) context = GetWinRTContext(); #endif return context; } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Current; // SC never flows } } #else //FEATURE_CORECLR // set SynchronizationContext on the current thread [System.Security.SecurityCritical] // auto-generated_required public static void SetSynchronizationContext(SynchronizationContext syncContext) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.SynchronizationContext = syncContext; ec.SynchronizationContextNoFlow = syncContext; } // Get the current SynchronizationContext on the current thread public static SynchronizationContext Current { get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext(); } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext(); } } private static SynchronizationContext GetThreadLocalContext() { SynchronizationContext context = null; #if FEATURE_APPX if (context == null && AppDomain.IsAppXModel()) context = GetWinRTContext(); #endif return context; } #endif //FEATURE_CORECLR #if FEATURE_APPX [SecuritySafeCritical] private static SynchronizationContext GetWinRTContext() { Contract.Assert(Environment.IsWinRTSupported); Contract.Assert(AppDomain.IsAppXModel()); // // We call into the VM to get the dispatcher. This is because: // // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly // into processes that don't need it (for performance reasons). // // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. // object dispatcher = GetWinRTDispatcherForCurrentThread(); if (dispatcher != null) return GetWinRTSynchronizationContextFactory().Create(dispatcher); return null; } [SecurityCritical] static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; [SecurityCritical] private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { // // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because // we can do very little with WinRT stuff in mscorlib. // WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory; if (factory == null) { Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true); s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true); } return factory; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SecurityCritical] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Interface)] private static extern object GetWinRTDispatcherForCurrentThread(); #endif //FEATURE_APPX // helper to Clone this SynchronizationContext, public virtual SynchronizationContext CreateCopy() { // the CLR dummy has an empty clone function - no member data return new SynchronizationContext(); } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [System.Security.SecurityCritical] // auto-generated private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } #endif } }
using System; using System.Collections.Generic; using System.Text; using Platform.Runtime; using System.Data.Common; using System.Runtime.InteropServices; using System.ServiceModel; using System.Runtime.Serialization; using System.Web.Services; using System.Web.UI; /* * High performance automated object model * Created by an automatic tool * */ namespace Platform.Module.UndoRedo.Services.Packages { /// <summary> /// Defines the contract for the UndoRedoGroup class /// </summary> [ComVisible(true)] [Guid("16bc4334-706b-d0b7-fb99-7a3342166ff0")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IUndoRedoGroup { bool Exists { get; } System.Int64 Id { get; set; } System.String EntryName { get; set; } System.String UndoRedoEntityType { get; set; } System.Int64 UndoRedoRecordId { get; set; } void Read(System.Int64 __Id, System.String __UndoRedoEntityType); void Reload(); void Create(); void Update(); void Delete(); void CopyWithKeysFrom(UndoRedoGroup _object); void CopyWithKeysTo(UndoRedoGroup _object); void CopyFrom(UndoRedoGroup _object); void CopyTo(UndoRedoGroup _object); } /// <summary> /// Defines the contract for all the service-based types which can /// apply servicing on Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup type. /// </summary> [ComVisible(true)] [Guid("9577a647-1e13-02a4-8c12-18783d52560d")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [ServiceContract(Namespace="http://services.msd.com")] public interface IUndoRedoGroupService { string Uri { get; set; } [OperationContract] bool Exists(UndoRedoGroup _UndoRedoGroup); [OperationContract] UndoRedoGroup Read(System.Int64 __Id, System.String __UndoRedoEntityType); [OperationContract] UndoRedoGroup Reload(UndoRedoGroup _UndoRedoGroup); [OperationContract] UndoRedoGroup Create(System.Int64 __Id, System.String __UndoRedoEntityType); [OperationContract] void Delete(System.Int64 __Id, System.String __UndoRedoEntityType); [OperationContract] void UpdateObject(UndoRedoGroup _UndoRedoGroup); [OperationContract] void CreateObject(UndoRedoGroup _UndoRedoGroup); [OperationContract] void DeleteObject(UndoRedoGroup _UndoRedoGroup); [OperationContract] void Undo(); [OperationContract] void Redo(); [OperationContract] UndoRedoGroupCollection SearchByEntityType(System.String UndoRedoEntityType ); [OperationContract] UndoRedoGroupCollection SearchByEntityTypePaged(System.String UndoRedoEntityType , long PagingStart, long PagingCount); [OperationContract] long SearchByEntityTypeCount(System.String UndoRedoEntityType ); } /// <summary> /// WCF and default implementation of a service object for Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup type. /// </summary> [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("216659dc-ee3f-6856-39a6-2949ab623b08")] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext=false, IncludeExceptionDetailInFaults = true, AddressFilterMode=AddressFilterMode.Any, Namespace="http://services.msd.com")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] sealed public class UndoRedoGroupService : IUndoRedoGroupService { /// <summary> /// Not supported. Throws a NotSupportedException on get or set. /// </summary> public string Uri { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } [WebMethod] public bool Exists(UndoRedoGroup _UndoRedoGroup) { return _UndoRedoGroup.Exists; } [WebMethod] public UndoRedoGroup Read(System.Int64 __Id, System.String __UndoRedoEntityType) { return new UndoRedoGroup(__Id, __UndoRedoEntityType); } [WebMethod] public UndoRedoGroup Reload(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Reload(); return _UndoRedoGroup; } [WebMethod] public UndoRedoGroup Create(System.Int64 __Id, System.String __UndoRedoEntityType) { return UndoRedoGroup.CreateUndoRedoGroup(__Id, __UndoRedoEntityType); } [WebMethod] public void Delete(System.Int64 __Id, System.String __UndoRedoEntityType) { UndoRedoGroup.DeleteUndoRedoGroup(__Id, __UndoRedoEntityType); } [WebMethod] public void UpdateObject(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Update(); } [WebMethod] public void CreateObject(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Create(); } [WebMethod] public void DeleteObject(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Delete(); } [WebMethod] public void Undo() { UndoRedoGroup.Undo(); } [WebMethod] public void Redo() { UndoRedoGroup.Redo(); } [WebMethod] public UndoRedoGroupCollection SearchByEntityType(System.String UndoRedoEntityType ) { return UndoRedoGroup.SearchByEntityType(UndoRedoEntityType ); } [WebMethod] public UndoRedoGroupCollection SearchByEntityTypePaged(System.String UndoRedoEntityType , long PagingStart, long PagingCount) { return UndoRedoGroup.SearchByEntityTypePaged(UndoRedoEntityType , PagingStart, PagingCount); } [WebMethod] public long SearchByEntityTypeCount(System.String UndoRedoEntityType ) { return UndoRedoGroup.SearchByEntityTypeCount(UndoRedoEntityType ); } } /// <summary> /// Provides the implementation of Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup model that acts as DAL for /// a database table. /// </summary> [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("e141a570-ef42-154a-9fb9-8958583f92a9")] [DataContract] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] [Serializable] public class UndoRedoGroup : IUndoRedoGroup, IHierarchyData, global::Platform.Runtime.Data.IModelHierachyData { #region Servicing support // Synchronized replication [NonSerialized] static List<IUndoRedoGroupService> replicationServices = null; // Scaling proxy objects (using 1 object you get forwarding) [NonSerialized] static List<IUndoRedoGroupService> scalingServices = null; // static IServiceSelectionAlgorithm serviceSelectionAlgorithm = null; // Failover scenario [NonSerialized] static List<IUndoRedoGroupService> failoverServices = null; #endregion #region Connection provider and DbConnection selection support [NonSerialized] static string classConnectionString = null; [NonSerialized] string instanceConnectionString = null; [System.Xml.Serialization.XmlIgnoreAttribute] public static string ClassConnectionString { get { if (!String.IsNullOrEmpty(classConnectionString)) return classConnectionString; if (global::System.Configuration.ConfigurationManager.ConnectionStrings["Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup"] != null) classConnectionString = global::System.Configuration.ConfigurationManager.ConnectionStrings["Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup"].ConnectionString; if (!String.IsNullOrEmpty(classConnectionString)) return classConnectionString; if (!String.IsNullOrEmpty(Platform.Module.Packages.ConnectionString)) return Platform.Module.Packages.ConnectionString; throw new InvalidOperationException("The sql connection string has not been set up in any level"); } set { classConnectionString = value; } } [System.Xml.Serialization.XmlIgnoreAttribute] public string ConnectionString { get { if (!String.IsNullOrEmpty(instanceConnectionString)) return instanceConnectionString; return ClassConnectionString; } set { instanceConnectionString = value; } } [NonSerialized] static global::Platform.Runtime.SqlProviderType classSqlProviderType = global::Platform.Runtime.SqlProviderType.NotSpecified; [NonSerialized] global::Platform.Runtime.SqlProviderType instanceSqlProviderType = global::Platform.Runtime.SqlProviderType.NotSpecified; [System.Xml.Serialization.XmlIgnoreAttribute] public static global::Platform.Runtime.SqlProviderType ClassSqlProviderType { get { if (classSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return classSqlProviderType; classSqlProviderType = global::Platform.Runtime.Sql.GetProviderConfiguration("Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup.ProviderType"); if (classSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return classSqlProviderType; if (global::Platform.Module.Packages.SqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return Platform.Module.Packages.SqlProviderType; throw new InvalidOperationException("The sql provider type has not been set up in any level"); } set { classSqlProviderType = value; } } [System.Xml.Serialization.XmlIgnoreAttribute] public global::Platform.Runtime.SqlProviderType InstanceSqlProviderType { get { if (instanceSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return instanceSqlProviderType; return ClassSqlProviderType; } set { instanceSqlProviderType = value; } } [NonSerialized] private static global::Platform.Runtime.IConnectionProvider instanceConnectionProvider; [NonSerialized] private static global::Platform.Runtime.IConnectionProvider classConnectionProvider; [System.Xml.Serialization.XmlIgnoreAttribute] public global::Platform.Runtime.IConnectionProvider InstanceConnectionProvider { get { if (String.IsNullOrEmpty(ConnectionString) || InstanceSqlProviderType == Platform.Runtime.SqlProviderType.NotSpecified) return ClassConnectionProvider; if (instanceConnectionProvider == null) { instanceConnectionProvider = Platform.Runtime.Sql.CreateProvider(InstanceSqlProviderType, ConnectionString); } return instanceConnectionProvider; } } [System.Xml.Serialization.XmlIgnoreAttribute] public static global::Platform.Runtime.IConnectionProvider ClassConnectionProvider { get { if (String.IsNullOrEmpty(ClassConnectionString) || ClassSqlProviderType == Platform.Runtime.SqlProviderType.NotSpecified) return Platform.Module.Packages.ConnectionProvider; if (classConnectionProvider == null) { classConnectionProvider = Platform.Runtime.Sql.CreateProvider(ClassSqlProviderType, ClassConnectionString); } return classConnectionProvider; } } [System.Xml.Serialization.XmlIgnoreAttribute] public global::Platform.Runtime.IConnectionProvider ConnectionProvider { get { if (InstanceConnectionProvider != null) return InstanceConnectionProvider; return ClassConnectionProvider; } } #endregion #region Data row consistency and state RowState __databaseState = RowState.Empty; bool __hasBeenReadOnce = false; #endregion #region Main implementation - Properties, Relations, CRUD System.Int64 _Id; // Key member [DataMember] [global::System.ComponentModel.Bindable(true)] public System.Int64 Id { get { return _Id; } set { if (_Id != value) __hasBeenReadOnce = false; _Id = value; } } System.String _EntryName; [DataMember] [global::System.ComponentModel.Bindable(true)] public System.String EntryName { get { return _EntryName; } set { _EntryName = value; } } System.String _UndoRedoEntityType; // Key member [DataMember] [global::System.ComponentModel.Bindable(true)] public System.String UndoRedoEntityType { get { return _UndoRedoEntityType; } set { if (_UndoRedoEntityType != value) __hasBeenReadOnce = false; _UndoRedoEntityType = value; } } System.Int64 _UndoRedoRecordId; [DataMember] [global::System.ComponentModel.Bindable(true)] public System.Int64 UndoRedoRecordId { get { return _UndoRedoRecordId; } set { _UndoRedoRecordId = value; } } public static UndoRedoGroupCollection SearchByEntityType(System.String _UndoRedoEntityType) { UndoRedoGroupCollection _UndoRedoGroupCollection = new UndoRedoGroupCollection(); // sql read using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString)) { dbconn.Open(); DbCommand command = ClassConnectionProvider.GetDatabaseCommand("UnReGrSeByEnTy", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _UndoRedoEntityType = ClassConnectionProvider.Escape(_UndoRedoEntityType); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), -1); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); ClassConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); while (dr.Read()) { UndoRedoGroup o = new UndoRedoGroup(); o.__databaseState = RowState.Initialized; o._Id = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int64)); o._EntryName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntryName"], typeof(System.String)); o._UndoRedoEntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoEntityType"], typeof(System.String)); o._UndoRedoRecordId = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoRecordId"], typeof(System.Int64)); _UndoRedoGroupCollection.Add(o); } dr.Close(); } return _UndoRedoGroupCollection; } public static UndoRedoGroupCollection SearchByEntityTypePaged(System.String _UndoRedoEntityType, long PagingStart, long PagingCount) { UndoRedoGroupCollection _UndoRedoGroupCollection = new UndoRedoGroupCollection(); // sql read using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString)) { dbconn.Open(); DbCommand command = ClassConnectionProvider.GetDatabaseCommand("UnReGrSeByEnTyPaged", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _UndoRedoEntityType = ClassConnectionProvider.Escape(_UndoRedoEntityType); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), -1); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); DbParameter __param_PagingStart = ClassConnectionProvider.GetDatabaseParameter("PagingStart", PagingStart); command.Parameters.Add(__param_PagingStart); DbParameter __param_PagingCount = ClassConnectionProvider.GetDatabaseParameter("PagingCount", PagingCount); command.Parameters.Add(__param_PagingCount); ClassConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (ClassSqlProviderType == global::Platform.Runtime.SqlProviderType.SqlServer) { while (PagingStart > 0 && dr.Read()) --PagingStart; } while (PagingCount > 0 && dr.Read()) { UndoRedoGroup o = new UndoRedoGroup(); o.__databaseState = RowState.Initialized; o._Id = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int64)); o._EntryName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntryName"], typeof(System.String)); o._UndoRedoEntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoEntityType"], typeof(System.String)); o._UndoRedoRecordId = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoRecordId"], typeof(System.Int64)); _UndoRedoGroupCollection.Add(o); --PagingCount; } dr.Close(); } return _UndoRedoGroupCollection; } public static long SearchByEntityTypeCount(System.String _UndoRedoEntityType) { long count = 0; // sql read using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString)) { dbconn.Open(); DbCommand command = ClassConnectionProvider.GetDatabaseCommand("UnReGrSeByEnTyCount", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _UndoRedoEntityType = ClassConnectionProvider.Escape(_UndoRedoEntityType); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), -1); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); ClassConnectionProvider.OnBeforeExecuted(command); count = (int)command.ExecuteScalar(); if (count < 0) count = 0; } return count; } public bool Exists { get { if (!__hasBeenReadOnce) Exist(); return __databaseState == RowState.Initialized; } } public UndoRedoGroup() {} public UndoRedoGroup(System.Int64 __Id, System.String __UndoRedoEntityType) { Read(__Id, __UndoRedoEntityType); } #region CRUD void Exist() { // sql read - should be changed to specific exist implementation using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReGrRead", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int64), -1); param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(_Id); command.Parameters.Add(param_Id); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), 128); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { __databaseState = RowState.Initialized; } else { __databaseState = RowState.Empty; } __hasBeenReadOnce = true; dr.Close(); } } public void Read(System.Int64 __Id, System.String __UndoRedoEntityType) { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].Read(__Id, __UndoRedoEntityType); return; } // Get a service via an algorithm // int nextIndex = serviceSelectionAlgorithm.Pick(scalingServices, "UnReGr"); // Perfect for read operations, but not for write // scalingServices[nextIndex].Read(__Id, __UndoRedoEntityType); // return; throw new NotImplementedException(); } try { // sql read using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReGrRead", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _Id = __Id; DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int64), -1); param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(__Id); command.Parameters.Add(param_Id); _UndoRedoEntityType = __UndoRedoEntityType; DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), 128); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(__UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { _Id = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int64)); _EntryName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntryName"], typeof(System.String)); _UndoRedoEntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoEntityType"], typeof(System.String)); _UndoRedoRecordId = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoRecordId"], typeof(System.Int64)); __databaseState = RowState.Initialized; } else { __databaseState = RowState.Empty; } __hasBeenReadOnce = true; dr.Close(); } } catch (Exception ex) { if (failoverServices != null) { bool foundFailsafe = false; for (int n = 0; n < failoverServices.Count; ++n) { try { failoverServices[n].Read(__Id, __UndoRedoEntityType); foundFailsafe = true; break; } catch { // Do not request again from failed services failoverServices.RemoveAt(n); --n; } } if (failoverServices.Count == 0) failoverServices = null; if (!foundFailsafe) throw ex; } else throw ex; } } public void Reload() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].Reload(this); return; } // Get a service via an algorithm // int nextIndex = serviceSelectionAlgorithm.GetNext(scalingServices, "UnReGr"); // Perfect for read operations, but not for write // return scalingServices[nextIndex].Reload(); throw new NotImplementedException(); } try { // sql read using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReGrRead", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int64), -1); param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(_Id); command.Parameters.Add(param_Id); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), 128); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { _Id = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int64)); _EntryName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntryName"], typeof(System.String)); _UndoRedoEntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoEntityType"], typeof(System.String)); _UndoRedoRecordId = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoRecordId"], typeof(System.Int64)); __databaseState = RowState.Initialized; } else { __databaseState = RowState.Empty; } __hasBeenReadOnce = true; dr.Close(); } } catch (Exception ex) { if (failoverServices != null) { bool foundFailsafe = false; for (int n = 0; n < failoverServices.Count; ++n) { try { failoverServices[n].Reload(this); foundFailsafe = true; break; } catch { // Do not request again from failed services failoverServices.RemoveAt(n); --n; } } if (failoverServices.Count == 0) failoverServices = null; if (!foundFailsafe) throw ex; } else throw ex; } } public void Create() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].CreateObject(this); return; } // Create/Update/Delete supports scaling only by synchronizing // scalingServices[0].CreateObject(this); // scalingServices[0].SynchronizeTo(scalingServices); throw new NotImplementedException(); } try { if (!Exists) { // Mark undo if possible /* if (IsUndoRedoSupported) MarkUndo(this, true, false, false); //*/ // sql create using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReGrCreate", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_EntryName = ClassConnectionProvider.GetDatabaseParameter("EntryName", typeof(System.String), 128); param_EntryName.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntryName); command.Parameters.Add(param_EntryName); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), 128); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); DbParameter param_UndoRedoRecordId = ClassConnectionProvider.GetDatabaseParameter("UndoRedoRecordId", typeof(System.Int64), -1); param_UndoRedoRecordId.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoRecordId); command.Parameters.Add(param_UndoRedoRecordId); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { _Id = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int64)); _EntryName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntryName"], typeof(System.String)); _UndoRedoEntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoEntityType"], typeof(System.String)); _UndoRedoRecordId = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["UndoRedoRecordId"], typeof(System.Int64)); } __databaseState = RowState.Initialized; } } else Update(); } catch (Exception) { // Failsafe scenarios cannot be used for create/update/delete // Must be handled as an error throw; } // Everything went ok; now replicate in a synchronous way if (replicationServices != null) { // this is only for write/delete operations for (int n = 0; n < replicationServices.Count; ++n) { try { replicationServices[n].CreateObject(this); } catch { // Do not request again from failed services replicationServices.RemoveAt(n); --n; } } if (replicationServices.Count == 0) replicationServices = null; } } static public UndoRedoGroup CreateUndoRedoGroup(System.Int64 __Id, System.String __UndoRedoEntityType) { UndoRedoGroup o = new UndoRedoGroup(__Id, __UndoRedoEntityType); if (!o.Exists) o.Create(); return o; } public void Update() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].UpdateObject(this); return; } // Create/Update/Delete supports scaling only by synchronizing // scalingServices[0].UpdateObject(this); throw new NotImplementedException(); } try { if (!Exists) { this.Create(); return; } // Mark undo if possible /* if (IsUndoRedoSupported) MarkUndo(this, false, false, true); //*/ // sql update using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReGrUpdate", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int64), -1); param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(_Id); command.Parameters.Add(param_Id); DbParameter param_EntryName = ClassConnectionProvider.GetDatabaseParameter("EntryName", typeof(System.String), 128); param_EntryName.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntryName); command.Parameters.Add(param_EntryName); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), 128); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); DbParameter param_UndoRedoRecordId = ClassConnectionProvider.GetDatabaseParameter("UndoRedoRecordId", typeof(System.Int64), -1); param_UndoRedoRecordId.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoRecordId); command.Parameters.Add(param_UndoRedoRecordId); command.ExecuteNonQuery(); } } catch (Exception) { // Failsafe scenarios cannot be used for create/update/delete // Must be handled as an error throw; } // Everything went ok; now replicate in a synchronous way if (replicationServices != null) { // this is only for write/delete operations for (int n = 0; n < replicationServices.Count; ++n) { try { replicationServices[n].UpdateObject(this); } catch { // Do not request again from failed services replicationServices.RemoveAt(n); --n; } } if (replicationServices.Count == 0) replicationServices = null; } } public void Delete() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].DeleteObject(this); return; } // Create/Update/Delete supports scaling only by synchronizing // scalingServices[0].DeleteObject(this); throw new NotImplementedException(); } try { if (!Exists) return; // Mark undo if possible /* if (IsUndoRedoSupported) MarkUndo(this, false, true, false); //*/ // sql-delete using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReGrDelete", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int64), -1); param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(_Id); command.Parameters.Add(param_Id); DbParameter param_UndoRedoEntityType = ClassConnectionProvider.GetDatabaseParameter("UndoRedoEntityType", typeof(System.String), 128); param_UndoRedoEntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_UndoRedoEntityType); command.Parameters.Add(param_UndoRedoEntityType); command.ExecuteNonQuery(); __databaseState = RowState.Empty; } } catch (Exception) { // Failsafe scenarios cannot be used for create/update/delete // Must be handled as an error throw; } // Everything went ok; now replicate in a synchronous way if (replicationServices != null) { // this is only for write/delete operations for (int n = 0; n < replicationServices.Count; ++n) { try { replicationServices[n].DeleteObject(this); } catch { // Do not request again from failed services replicationServices.RemoveAt(n); --n; } } if (replicationServices.Count == 0) replicationServices = null; } } static public void DeleteUndoRedoGroup(System.Int64 __Id, System.String __UndoRedoEntityType) { UndoRedoGroup o = new UndoRedoGroup(__Id, __UndoRedoEntityType); if (o.Exists) o.Delete(); } #endregion #region Copying instances public void CopyWithKeysFrom(UndoRedoGroup _object) { _Id = _object._Id; _EntryName = _object._EntryName; _UndoRedoEntityType = _object._UndoRedoEntityType; _UndoRedoRecordId = _object._UndoRedoRecordId; } public void CopyWithKeysTo(UndoRedoGroup _object) { _object._Id = _Id; _object._EntryName = _EntryName; _object._UndoRedoEntityType = _UndoRedoEntityType; _object._UndoRedoRecordId = _UndoRedoRecordId; } static public void CopyWithKeysObject(UndoRedoGroup _objectFrom, UndoRedoGroup _objectTo) { _objectFrom.CopyWithKeysTo(_objectTo); } public void CopyFrom(UndoRedoGroup _object) { _EntryName = _object._EntryName; _UndoRedoRecordId = _object._UndoRedoRecordId; } public void CopyTo(UndoRedoGroup _object) { _object._EntryName = _EntryName; _object._UndoRedoRecordId = _UndoRedoRecordId; } static public void CopyObject(UndoRedoGroup _objectFrom, UndoRedoGroup _objectTo) { _objectFrom.CopyTo(_objectTo); } #endregion #region Undo / Redo functionality /* private static bool isUndoRedoSupported = false; private static bool isUndoRedoSupportedHasBeenLoaded = false; private static long undoRedoMaximumObjects = -1; public static bool IsUndoRedoSupported { get { if (!isUndoRedoSupportedHasBeenLoaded) { // Load options undo entity once isUndoRedoSupportedHasBeenLoaded = true; Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions options = new Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions(typeof(UndoRedoGroup).FullName); if (!options.Exists) { undoRedoMaximumObjects = options.ItemsAllowed = 1000; options.IsEnabled = true; options.Create(); isUndoRedoSupported = true; } else { isUndoRedoSupported = options.IsEnabled; undoRedoMaximumObjects = options.ItemsAllowed; } } return isUndoRedoSupported; } set { isUndoRedoSupportedHasBeenLoaded = true; isUndoRedoSupported = value; Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions options = new Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions(typeof(UndoRedoGroup).FullName); if (!options.Exists) { undoRedoMaximumObjects = options.ItemsAllowed = 1000; } options.IsEnabled = isUndoRedoSupported; options.Update(); } } static void MarkUndo(UndoRedoGroup _object, bool IsCreatedUndoDeletes, bool IsDeletedUndoCreates, bool IsUpdatedUndoUpdates) { // Delete already undone entries (steps that have been undone but not redone) UndoRedoGroupUndoRedoCollection allUndidAndNotRedoneEntries = UndoRedoGroupUndoRedo.GetAllFilterByIsUndone(true); for(int n = 0; n < allUndidAndNotRedoneEntries.Count; ++n) allUndidAndNotRedoneEntries[n].Delete(); // Create one undo entry UndoRedoGroupUndoRedo _urobject = new UndoRedoGroupUndoRedo(); // Enumerate all properties and add them to the UndoRedo object _urobject.Id = _object._Id; _urobject.EntryName = _object._EntryName; _urobject.UndoRedoEntityType = _object._UndoRedoEntityType; _urobject.UndoRedoRecordId = _object._UndoRedoRecordId; _urobject.IsCreatedUndoDeletes = IsCreatedUndoDeletes; _urobject.IsDeletedUndoCreates = IsDeletedUndoCreates; _urobject.IsUpdatedUndoUpdates = IsUpdatedUndoUpdates; _urobject.Create(); // Add this to all groups if needed Platform.Module.UndoRedo.Services.Packages.Grouping.GroupEntry(typeof(UndoRedoGroup).FullName, _urobject.UndoRedoId); // Check if we have too many - if yes delete the oldest entry long count = UndoRedoGroupUndoRedo.GetAllWithNoFilterCount(true) - undoRedoMaximumObjects; if (count > 0) { UndoRedoGroupUndoRedoCollection allOldUndoEntries = UndoRedoGroupUndoRedo.GetAllWithNoFilterOppositeSortingPaged(true, 0, count); for(int n = 0; n < allOldUndoEntries.Count; ++n) allOldUndoEntries[n].Delete(); } } static public void Undo() { // Load the last undo, and execute it UndoRedoGroupUndoRedoCollection firstUndoEntries = UndoRedoGroupUndoRedo.GetAllFilterByIsUndonePaged(false, 0, 1); if (firstUndoEntries.Count < 1) return; UndoRedoGroupUndoRedo _urobject = firstUndoEntries[0]; UndoRedoGroup _object = new UndoRedoGroup(); _object._Id = _urobject.Id; _object._EntryName = _urobject.EntryName; _object._UndoRedoEntityType = _urobject.UndoRedoEntityType; _object._UndoRedoRecordId = _urobject.UndoRedoRecordId; _urobject.IsUndone = true; _urobject.Update(); // Do the opposite action if (_urobject.IsDeletedUndoCreates || _urobject.IsUpdatedUndoUpdates) _object.Create(); // Create or update store else if (_urobject.IsCreatedUndoDeletes) _object.Delete(); // Delete } static public void Redo() { // Get the last already undone and load it UndoRedoGroupUndoRedoCollection firstEntryToRedoEntries = UndoRedoGroupUndoRedo.GetAllFilterByIsUndoneOppositeOrderPaged(true, 0, 1); if (firstEntryToRedoEntries.Count < 1) return; UndoRedoGroupUndoRedo _urobject = firstEntryToRedoEntries[0]; UndoRedoGroup _object = new UndoRedoGroup(); _object._Id = _urobject.Id; _object._EntryName = _urobject.EntryName; _object._UndoRedoEntityType = _urobject.UndoRedoEntityType; _object._UndoRedoRecordId = _urobject.UndoRedoRecordId; _urobject.IsUndone = false; _urobject.Update(); // Do the opposite action if (_urobject.IsDeletedUndoCreates) _object.Delete(); // Delete again else if (_urobject.IsCreatedUndoDeletes || _urobject.IsUpdatedUndoUpdates) _object.Create(); // Create or update again } //*/ // Undo redo enabled //* static public void Undo() { throw new NotImplementedException("This feature is not implemented in this class."); } static public void Redo() { throw new NotImplementedException("This feature is not implemented in this class."); } //*/ // Undo redo disabled #endregion #endregion #region IHierarchyData Members IHierarchicalEnumerable IHierarchyData.GetChildren() { string selectedProperty = (__level < __childProperties.Length ? __childProperties[__level] : __childProperties[__childProperties.Length - 1]); global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty); if (pi == null) throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName); IHierarchicalEnumerable dataSource = pi.GetValue(this, null) as IHierarchicalEnumerable; foreach (IHierarchyData ihd in dataSource) { global::Platform.Runtime.Data.IModelHierachyData imhd = ihd as global::Platform.Runtime.Data.IModelHierachyData; if (imhd != null) { imhd.Level = __level + 1; imhd.ParentProperties = __parentProperties; imhd.ChildProperties = __childProperties; } } return dataSource; } IHierarchyData IHierarchyData.GetParent() { string selectedProperty = (__level < __parentProperties.Length ? __parentProperties[__level] : __parentProperties[__parentProperties.Length - 1]); global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty); if (pi == null) throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName); IHierarchyData data = pi.GetValue(this, null) as IHierarchyData; global::Platform.Runtime.Data.IModelHierachyData imhd = data as global::Platform.Runtime.Data.IModelHierachyData; if (imhd != null) { imhd.Level = __level - 1; imhd.ParentProperties = __parentProperties; imhd.ChildProperties = __childProperties; } return data; } bool IHierarchyData.HasChildren { get { string selectedProperty = (__level < __childProperties.Length ? __childProperties[__level] : __childProperties[__childProperties.Length - 1]); global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty); if (pi == null) throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName); IHierarchicalEnumerable value = pi.GetValue(this, null) as IHierarchicalEnumerable; bool exists = false; foreach(IHierarchyData ihd in value) { exists = true; break; } return exists; } } object IHierarchyData.Item { get { return this; } } string IHierarchyData.Path { get { return ""; } } string IHierarchyData.Type { get { return this.GetType().FullName; } } #endregion #region Platform.Runtime.Data.IHierarchyData explicit Members [NonSerialized] string[] __childProperties = null; [NonSerialized] string[] __parentProperties = null; [NonSerialized] int __level = -1; string[] Platform.Runtime.Data.IModelHierachyData.ChildProperties { get { return __childProperties; } set { __childProperties = value; } } string[] Platform.Runtime.Data.IModelHierachyData.ParentProperties { get { return __parentProperties; } set { __parentProperties = value; } } int Platform.Runtime.Data.IModelHierachyData.Level { get { return __level; } set { __level = value; } } #endregion } /// <summary> /// Defines the contract for the UndoRedoGroupCollection class /// </summary> [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("e9566d43-4eb0-59b1-500f-5b6df45a572a")] public interface IUndoRedoGroupCollection : IEnumerable<UndoRedoGroup> { int IndexOf(UndoRedoGroup item); void Insert(int index, UndoRedoGroup item); void RemoveAt(int index); UndoRedoGroup this[int index] { get; set; } void Add(UndoRedoGroup item); void Clear(); bool Contains(UndoRedoGroup item); void CopyTo(UndoRedoGroup[] array, int arrayIndex); int Count { get; } bool IsReadOnly { get; } bool Remove(UndoRedoGroup item); } /// <summary> /// Provides the implementation of the class that represents a list of Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup /// </summary> [ClassInterface(ClassInterfaceType.None)] [Guid("970710d7-7511-edcb-0e50-828564fd0ffa")] [DataContract] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] [Serializable] public class UndoRedoGroupCollection : IUndoRedoGroupCollection, IList<UndoRedoGroup>, IHierarchicalEnumerable { List<UndoRedoGroup> _list = new List<UndoRedoGroup>(); public static implicit operator List<UndoRedoGroup>(UndoRedoGroupCollection collection) { return collection._list; } #region IList<UndoRedoGroup> Members public int IndexOf(UndoRedoGroup item) { return _list.IndexOf(item); } public void Insert(int index, UndoRedoGroup item) { _list.Insert(index, item); } public void RemoveAt(int index) { _list.RemoveAt(index); } public UndoRedoGroup this[int index] { get { return _list[index]; } set { _list[index] = value; } } #endregion #region ICollection<UndoRedoGroup> Members public void Add(UndoRedoGroup item) { _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(UndoRedoGroup item) { return _list.Contains(item); } public void CopyTo(UndoRedoGroup[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(UndoRedoGroup item) { return _list.Remove(item); } #endregion #region IEnumerable<UndoRedoGroup> Members public IEnumerator<UndoRedoGroup> GetEnumerator() { return _list.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } #endregion #region IHierarchicalEnumerable Members public IHierarchyData GetHierarchyData(object enumeratedItem) { return enumeratedItem as IHierarchyData; } #endregion } namespace Web { /// <summary> /// The WebService service provider that allows to create web services /// that share Platform.Module.UndoRedo.Services.Packages.UndoRedoGroup objects. /// </summary> /// <example> /// You can use that in the header of an asmx file like this: /// <%@ WebService Language="C#" Class="Platform.Module.UndoRedo.Services.Packages.Web.UndoRedoGroupWebService" %> /// </example> [WebService(Namespace="http://services.msd.com")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] [ComVisible(false)] sealed public class UndoRedoGroupWebService : WebService, IUndoRedoGroupService { /// <summary> /// Gets the Uri if the service. Setting property is not supported. /// </summary> public string Uri { get { return "http://services.msd.com"; } set { throw new NotSupportedException(); } } [WebMethod] public bool Exists(UndoRedoGroup _UndoRedoGroup) { return _UndoRedoGroup.Exists; } [WebMethod] public UndoRedoGroup Read(System.Int64 __Id, System.String __UndoRedoEntityType) { return new UndoRedoGroup(__Id, __UndoRedoEntityType); } [WebMethod] public UndoRedoGroup Reload(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Reload(); return _UndoRedoGroup; } [WebMethod] public UndoRedoGroup Create(System.Int64 __Id, System.String __UndoRedoEntityType) { return UndoRedoGroup.CreateUndoRedoGroup(__Id, __UndoRedoEntityType); } [WebMethod] public void Delete(System.Int64 __Id, System.String __UndoRedoEntityType) { UndoRedoGroup.DeleteUndoRedoGroup(__Id, __UndoRedoEntityType); } [WebMethod] public void UpdateObject(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Update(); } [WebMethod] public void CreateObject(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Create(); } [WebMethod] public void DeleteObject(UndoRedoGroup _UndoRedoGroup) { _UndoRedoGroup.Delete(); } [WebMethod] public void Undo() { UndoRedoGroup.Undo(); } [WebMethod] public void Redo() { UndoRedoGroup.Redo(); } [WebMethod] public UndoRedoGroupCollection SearchByEntityType(System.String UndoRedoEntityType ) { return UndoRedoGroup.SearchByEntityType(UndoRedoEntityType ); } [WebMethod] public UndoRedoGroupCollection SearchByEntityTypePaged(System.String UndoRedoEntityType , long PagingStart, long PagingCount) { return UndoRedoGroup.SearchByEntityTypePaged(UndoRedoEntityType , PagingStart, PagingCount); } [WebMethod] public long SearchByEntityTypeCount(System.String UndoRedoEntityType ) { return UndoRedoGroup.SearchByEntityTypeCount(UndoRedoEntityType ); } } /// <summary> /// The WebService client service /// </summary> [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Web.Services.WebServiceBindingAttribute(Name="UndoRedoGroupWebServiceSoap", Namespace="http://services.msd.com")] [System.Xml.Serialization.XmlIncludeAttribute(typeof(MarshalByRefObject))] [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("3e068013-510b-2258-f4e7-913393dd2144")] sealed public class UndoRedoGroupWebServiceClient : System.Web.Services.Protocols.SoapHttpClientProtocol, IUndoRedoGroupService { static string globalUrl; /// <summary> /// By setting this value, all the subsequent clients that using the default /// constructor will point to the service that this url points to. /// </summary> static public string GlobalUrl { get { return globalUrl; } set { globalUrl = value; } } /// <summary> /// Initializes a web service client using the url as the service endpoint. /// </summary> /// <param name="url">The service url that the object will point to</param> public UndoRedoGroupWebServiceClient(string url) { this.Url = url; } /// <summary> /// Initializes a web service client without a specific service url. /// If the GlobalUrl value is set, is been used as the Url. /// </summary> public UndoRedoGroupWebServiceClient() { if (!String.IsNullOrEmpty(globalUrl)) this.Url = globalUrl; } /// <summary> /// Allows the service to set the Uri for COM compatibility. Is the same with Url property. /// </summary> public string Uri { get { return this.Url; } set { this.Url = value; } } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Exists", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool Exists(UndoRedoGroup _UndoRedoGroup) { object[] results = this.Invoke("Exists", new object[] {_UndoRedoGroup}); return ((bool)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Read", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoGroup Read(System.Int64 __Id, System.String __UndoRedoEntityType) { object[] results = this.Invoke("Read", new object[] {__Id, __UndoRedoEntityType}); return ((UndoRedoGroup)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Reload", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoGroup Reload(UndoRedoGroup _UndoRedoGroup) { object[] results = this.Invoke("Reload", new object[] {_UndoRedoGroup}); return ((UndoRedoGroup)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Create", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoGroup Create(System.Int64 __Id, System.String __UndoRedoEntityType) { object[] results = this.Invoke("Create", new object[] {__Id, __UndoRedoEntityType}); return ((UndoRedoGroup)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Delete", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Delete(System.Int64 __Id, System.String __UndoRedoEntityType) { this.Invoke("Delete", new object[] {__Id, __UndoRedoEntityType}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/UpdateObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void UpdateObject(UndoRedoGroup _UndoRedoGroup) { this.Invoke("UpdateObject", new object[] {_UndoRedoGroup}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/CreateObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void CreateObject(UndoRedoGroup _UndoRedoGroup) { this.Invoke("CreateObject", new object[] {_UndoRedoGroup}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/DeleteObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void DeleteObject(UndoRedoGroup _UndoRedoGroup) { this.Invoke("DeleteObject", new object[] {_UndoRedoGroup}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Undo", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Undo() { this.Invoke("Undo", new object[] {}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Redo", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Redo() { this.Invoke("Redo", new object[] {}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByEntityType", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoGroupCollection SearchByEntityType(System.String UndoRedoEntityType ) { object[] results = this.Invoke("SearchByEntityType", new object[] {UndoRedoEntityType}); return ((UndoRedoGroupCollection)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByEntityTypePaged", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoGroupCollection SearchByEntityTypePaged(System.String UndoRedoEntityType , long PagingStart, long PagingCount) { object[] results = this.Invoke("SearchByEntityTypePaged", new object[] {UndoRedoEntityType,PagingStart,PagingCount}); return ((UndoRedoGroupCollection)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByEntityTypeCount", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public long SearchByEntityTypeCount(System.String UndoRedoEntityType ) { object[] results = this.Invoke("SearchByEntityTypeCount", new object[] {UndoRedoEntityType}); return ((long)(results[0])); } } } // namespace Web } // namespace Platform.Module.UndoRedo.Services.Packages
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var syntaxKindsMissing = new HashSet<SyntaxKind>(); // AllInOneCSharpCode has no deconstruction or declaration expression syntaxKindsMissing.Add(SyntaxKind.SingleVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ParenthesizedVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ForEachVariableStatement); syntaxKindsMissing.Add(SyntaxKind.DeclarationExpression); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsMissing); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true)); } } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using (var workspace = await TestWorkspace.CreateCSharpAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular)) { var currentProject = workspace.CurrentSolution.Projects.Single(); var additionalDocId = DocumentId.CreateNewId(currentProject.Id); var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")); currentProject = newSln.Projects.Single(); var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId); AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.State); AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var sourceDocument = currentProject.Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer); diagnosticService.GetDiagnosticDescriptors(projectOpt: null); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool OpenFileOnly(Workspace workspace) => false; public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); } private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); } public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } } }
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using UnityEngine; namespace Game {public class World : MonoBehaviour{ public static int frame; void Update () { Update(Time.deltaTime, this); frame++; } public bool JustEntered = true; public void Start() { bobbies = ( (new Cons<Bob>(new Bob("1"),(new Cons<Bob>(new Bob("2"),(new Cons<Bob>(new Bob("3"),(new Empty<Bob>()).ToList<Bob>())).ToList<Bob>())).ToList<Bob>())).ToList<Bob>()).ToList<Bob>(); MainCamera = new MainCamera(); } public MainCamera MainCamera; public List<Bob> __bobbies; public List<Bob> bobbies{ get { return __bobbies; } set{ __bobbies = value; foreach(var e in value){if(e.JustEntered){ e.JustEntered = false; } } } } System.DateTime init_time = System.DateTime.Now; public void Update(float dt, World world) { var t = System.DateTime.Now; MainCamera.Update(dt, world); for(int x0 = 0; x0 < bobbies.Count; x0++) { bobbies[x0].Update(dt, world); } } } public class Bob{ public int frame; public bool JustEntered = true; private System.String nameBob; public int ID; public Bob(System.String nameBob) {JustEntered = false; frame = World.frame; UnityBob = UnityBob.Find(nameBob); } public System.Collections.Generic.List<UnityEngine.Vector3> Checkpoints{ get { return UnityBob.Checkpoints; } } public BobAnimation CurrentAnimation{ set{UnityBob.CurrentAnimation = value; } } public UnityEngine.Vector3 Forward{ get { return UnityBob.Forward; } } public System.Boolean IsHit{ get { return UnityBob.IsHit; } } public System.Boolean MouseHover{ get { return UnityBob.MouseHover; } set{UnityBob.MouseHover = value; } } public UnityEngine.Vector3 Position{ get { return UnityBob.Position; } set{UnityBob.Position = value; } } public System.Boolean Quit{ set{UnityBob.Quit = value; } } public System.Boolean Selected{ get { return UnityBob.Selected; } set{UnityBob.Selected = value; } } public UnityBob UnityBob; public UnityEngine.Vector3 Velocity{ get { return UnityBob.Velocity; } set{UnityBob.Velocity = value; } } public System.Boolean enabled{ get { return UnityBob.enabled; } set{UnityBob.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityBob.gameObject; } } public UnityEngine.HideFlags hideFlags{ get { return UnityBob.hideFlags; } set{UnityBob.hideFlags = value; } } public System.Boolean isActiveAndEnabled{ get { return UnityBob.isActiveAndEnabled; } } public System.String name{ get { return UnityBob.name; } set{UnityBob.name = value; } } public System.String tag{ get { return UnityBob.tag; } set{UnityBob.tag = value; } } public UnityEngine.Transform transform{ get { return UnityBob.transform; } } public System.Boolean useGUILayout{ get { return UnityBob.useGUILayout; } set{UnityBob.useGUILayout = value; } } public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); } public void Rule0(float dt, World world) { Position = (Position) + ((Velocity) * (dt)); } int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(UnityEngine.Input.GetMouseButtonDown(0))) { s1 = -1; return; }else { goto case 0; } case 0: Selected = IsHit; s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: MouseHover = IsHit; s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: if(!(((!(Selected)) || (true)))) { s3 = -1; return; }else { goto case 0; } case 0: if(!(Selected)) { goto case 2; }else { if(true) { goto case 3; }else { s3 = 0; return; } } case 2: Velocity = Vector3.zero; CurrentAnimation = BobAnimation.Idle; s3 = -1; return; case 3: Velocity = ((Velocity) + (((Forward) * (dt)))); CurrentAnimation = BobAnimation.Walk; s3 = -1; return; default: return;}} } public class MainCamera{ public int frame; public bool JustEntered = true; public int ID; public MainCamera() {JustEntered = false; frame = World.frame; UnityCamera = UnityCamera.Find(); PlusSpeed = 2f; MinusSpeed = -2f; MaxVelocity = 8f; } public UnityEngine.Vector3 Backward{ get { return UnityCamera.Backward; } } public UnityEngine.Vector3 Down{ get { return UnityCamera.Down; } } public UnityEngine.Vector3 Forward{ get { return UnityCamera.Forward; } } public System.Single MaxVelocity; public System.Single MinusSpeed; public System.Single PlusSpeed; public UnityEngine.Vector3 Position{ get { return UnityCamera.Position; } set{UnityCamera.Position = value; } } public UnityEngine.Quaternion Rotation{ get { return UnityCamera.Rotation; } set{UnityCamera.Rotation = value; } } public UnityCamera UnityCamera; public UnityEngine.Vector3 Up{ get { return UnityCamera.Up; } } public System.Boolean enabled{ get { return UnityCamera.enabled; } set{UnityCamera.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityCamera.gameObject; } } public UnityEngine.HideFlags hideFlags{ get { return UnityCamera.hideFlags; } set{UnityCamera.hideFlags = value; } } public System.Boolean isActiveAndEnabled{ get { return UnityCamera.isActiveAndEnabled; } } public System.String name{ get { return UnityCamera.name; } set{UnityCamera.name = value; } } public System.String tag{ get { return UnityCamera.tag; } set{UnityCamera.tag = value; } } public UnityEngine.Transform transform{ get { return UnityCamera.transform; } } public System.Boolean useGUILayout{ get { return UnityCamera.useGUILayout; } set{UnityCamera.useGUILayout = value; } } public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); this.Rule5(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: if(!(UnityEngine.Input.GetKey(KeyCode.W))) { s0 = -1; return; }else { goto case 0; } case 0: Rotation = ((((UnityEngine.Quaternion.Euler(0f,0f,0f)) * (UnityCamera.Rotation))) * (UnityEngine.Quaternion.Euler(MinusSpeed,0f,0f))); s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(UnityEngine.Input.GetKey(KeyCode.S))) { s1 = -1; return; }else { goto case 0; } case 0: Rotation = ((((UnityEngine.Quaternion.Euler(0f,0f,0f)) * (UnityCamera.Rotation))) * (UnityEngine.Quaternion.Euler(PlusSpeed,0f,0f))); s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: if(!(UnityEngine.Input.GetKey(KeyCode.D))) { s2 = -1; return; }else { goto case 0; } case 0: Rotation = ((((UnityEngine.Quaternion.Euler(0f,PlusSpeed,0f)) * (UnityCamera.Rotation))) * (UnityEngine.Quaternion.Euler(0f,0f,0f))); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: if(!(UnityEngine.Input.GetKey(KeyCode.A))) { s3 = -1; return; }else { goto case 0; } case 0: Rotation = ((((UnityEngine.Quaternion.Euler(0f,MinusSpeed,0f)) * (UnityCamera.Rotation))) * (UnityEngine.Quaternion.Euler(0f,0f,0f))); s3 = -1; return; default: return;}} int s4=-1; public void Rule4(float dt, World world){ switch (s4) { case -1: if(!(UnityEngine.Input.GetKey(KeyCode.Space))) { s4 = -1; return; }else { goto case 0; } case 0: Position = ((Position) + (((((Backward) * (dt))) * (MaxVelocity)))); s4 = -1; return; default: return;}} int s5=-1; public void Rule5(float dt, World world){ switch (s5) { case -1: if(!(UnityEngine.Input.GetKey(KeyCode.LeftShift))) { s5 = -1; return; }else { goto case 0; } case 0: Position = ((Position) + (((((Forward) * (dt))) * (MaxVelocity)))); s5 = -1; return; default: return;}} } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Reactive.Disposables; #nullable enable namespace Avalonia.Collections { /// <summary> /// Defines extension methods for working with <see cref="AvaloniaList{T}"/>s. /// </summary> public static class AvaloniaListExtensions { /// <summary> /// Invokes an action for each item in a collection and subsequently each item added or /// removed from the collection. /// </summary> /// <typeparam name="T">The type of the collection items.</typeparam> /// <param name="collection">The collection.</param> /// <param name="added"> /// An action called initially for each item in the collection and subsequently for each /// item added to the collection. The parameters passed are the index in the collection and /// the item. /// </param> /// <param name="removed"> /// An action called for each item removed from the collection. The parameters passed are /// the index in the collection and the item. /// </param> /// <param name="reset"> /// An action called when the collection is reset. /// </param> /// <param name="weakSubscription"> /// Indicates if a weak subscription should be used to track changes to the collection. /// </param> /// <returns>A disposable used to terminate the subscription.</returns> public static IDisposable ForEachItem<T>( this IAvaloniaReadOnlyList<T> collection, Action<T> added, Action<T> removed, Action reset, bool weakSubscription = false) { return collection.ForEachItem((_, i) => added(i), (_, i) => removed(i), reset, weakSubscription); } /// <summary> /// Invokes an action for each item in a collection and subsequently each item added or /// removed from the collection. /// </summary> /// <typeparam name="T">The type of the collection items.</typeparam> /// <param name="collection">The collection.</param> /// <param name="added"> /// An action called initially for each item in the collection and subsequently for each /// item added to the collection. The parameters passed are the index in the collection and /// the item. /// </param> /// <param name="removed"> /// An action called for each item removed from the collection. The parameters passed are /// the index in the collection and the item. /// </param> /// <param name="reset"> /// An action called when the collection is reset. This will be followed by calls to /// <paramref name="added"/> for each item present in the collection after the reset. /// </param> /// <param name="weakSubscription"> /// Indicates if a weak subscription should be used to track changes to the collection. /// </param> /// <returns>A disposable used to terminate the subscription.</returns> public static IDisposable ForEachItem<T>( this IAvaloniaReadOnlyList<T> collection, Action<int, T> added, Action<int, T> removed, Action reset, bool weakSubscription = false) { void Add(int index, IList items) { foreach (T item in items) { added(index++, item); } } void Remove(int index, IList items) { for (var i = items.Count - 1; i >= 0; --i) { removed(index + i, (T)items[i]); } } NotifyCollectionChangedEventHandler handler = (_, e) => { switch (e.Action) { case NotifyCollectionChangedAction.Add: Add(e.NewStartingIndex, e.NewItems); break; case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Replace: Remove(e.OldStartingIndex, e.OldItems); int newIndex = e.NewStartingIndex; if(newIndex > e.OldStartingIndex) { newIndex -= e.OldItems.Count; } Add(newIndex, e.NewItems); break; case NotifyCollectionChangedAction.Remove: Remove(e.OldStartingIndex, e.OldItems); break; case NotifyCollectionChangedAction.Reset: if (reset == null) { throw new InvalidOperationException( "Reset called on collection without reset handler."); } reset(); Add(0, (IList)collection); break; } }; Add(0, (IList)collection); if (weakSubscription) { return collection.WeakSubscribe(handler); } else { collection.CollectionChanged += handler; return Disposable.Create(() => collection.CollectionChanged -= handler); } } [Obsolete("Causes memory leaks. Use DynamicData or similar instead.")] public static IAvaloniaReadOnlyList<TDerived> CreateDerivedList<TSource, TDerived>( this IAvaloniaReadOnlyList<TSource> collection, Func<TSource, TDerived> select) { var result = new AvaloniaList<TDerived>(); collection.ForEachItem( (i, item) => result.Insert(i, select(item)), (i, item) => result.RemoveAt(i), () => result.Clear()); return result; } /// <summary> /// Listens for property changed events from all items in a collection. /// </summary> /// <typeparam name="T">The type of the collection items.</typeparam> /// <param name="collection">The collection.</param> /// <param name="callback">A callback to call for each property changed event.</param> /// <returns>A disposable used to terminate the subscription.</returns> public static IDisposable TrackItemPropertyChanged<T>( this IAvaloniaReadOnlyList<T> collection, Action<Tuple<object, PropertyChangedEventArgs>> callback) { List<INotifyPropertyChanged> tracked = new List<INotifyPropertyChanged>(); PropertyChangedEventHandler handler = (s, e) => { callback(Tuple.Create(s, e)); }; collection.ForEachItem( x => { var inpc = x as INotifyPropertyChanged; if (inpc != null) { inpc.PropertyChanged += handler; tracked.Add(inpc); } }, x => { var inpc = x as INotifyPropertyChanged; if (inpc != null) { inpc.PropertyChanged -= handler; tracked.Remove(inpc); } }, () => throw new NotSupportedException("Collection reset not supported.")); return Disposable.Create(() => { foreach (var i in tracked) { i.PropertyChanged -= handler; } }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace AwesomeNamespace { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for StorageAccountsOperations. /// </summary> public static partial class StorageAccountsOperationsExtensions { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// </param> /// <param name='type'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this IStorageAccountsOperations operations, string name, string type = "Microsoft.Storage/storageAccounts", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(name, type, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='location'> /// Resource location /// </param> /// <param name='accountType'> /// Gets or sets the account type. Possible values include: 'Standard_LRS', /// 'Standard_ZRS', 'Standard_GRS', 'Standard_RAGRS', 'Premium_LRS' /// </param> /// <param name='tags'> /// Resource tags /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> CreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, string location, AccountType accountType, IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, location, accountType, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> GetPropertiesAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='tags'> /// Resource tags /// </param> /// <param name='accountType'> /// Gets or sets the account type. Note that StandardZRS and PremiumLRS /// accounts cannot be changed to other account types, and other account types /// cannot be changed to StandardZRS or PremiumLRS. Possible values include: /// 'Standard_LRS', 'Standard_ZRS', 'Standard_GRS', 'Standard_RAGRS', /// 'Premium_LRS' /// </param> /// <param name='customDomain'> /// User domain assigned to the storage account. Name is the CNAME source. Only /// one custom domain is supported per storage account at this time. To clear /// the existing custom domain, use an empty string for the custom domain name /// property. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> UpdateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, IDictionary<string, string> tags = default(IDictionary<string, string>), AccountType? accountType = default(AccountType?), CustomDomain customDomain = default(CustomDomain), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, tags, accountType, customDomain, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> ListKeysAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListAsync(this IStorageAccountsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this IStorageAccountsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='keyName'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> RegenerateKeyAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, string keyName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, keyName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='location'> /// Resource location /// </param> /// <param name='accountType'> /// Gets or sets the account type. Possible values include: 'Standard_LRS', /// 'Standard_ZRS', 'Standard_GRS', 'Standard_RAGRS', 'Premium_LRS' /// </param> /// <param name='tags'> /// Resource tags /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> BeginCreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, string location, AccountType accountType, IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, location, accountType, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; namespace System { // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. public static class BitConverter { public static readonly bool IsLittleEndian = GetIsLittleEndian(); private static unsafe bool GetIsLittleEndian() { int i = 1; return *((byte*)&i) == 1; } // Converts a Boolean into an array of bytes with length one. public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)1 : (byte)0); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts a short into an array of bytes with length // two. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed (byte* b = bytes) *((short*)b) = value; return bytes; } // Converts an int into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed (byte* b = bytes) *((int*)b) = value; return bytes; } // Converts a long into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed (byte* b = bytes) *((long*)b) = value; return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } // Converts a float into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } // Converts a double into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } // Converts an array of bytes into a char. public static char ToChar(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (char)ToInt16(value, startIndex); } // Converts an array of bytes into a short. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe short ToInt16(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 2 == 0) { // data is aligned return *((short*)pbyte); } else if (IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)); } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } // Converts an array of bytes into an int. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe int ToInt32(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 4 == 0) { // data is aligned return *((int*)pbyte); } else if (IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } // Converts an array of bytes into a long. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe long ToInt64(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 8 == 0) { // data is aligned return *((long*)pbyte); } else if (IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } // Converts an array of bytes into an ushort. // [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (ushort)ToInt16(value, startIndex); } // Converts an array of bytes into an uint. // [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (uint)ToInt32(value, startIndex); } // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (ulong)ToInt64(value, startIndex); } // Converts an array of bytes into a float. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static float ToSingle(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); int val = ToInt32(value, startIndex); return *(float*)&val; } // Converts an array of bytes into a double. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static double ToDouble(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static char GetHexValue(int i) { Debug.Assert(i >= 0 && i < 16, "i is out of range."); if (i < 10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static string ToString(byte[] value, int startIndex, int length) { if (value == null) ThrowValueArgumentNull(); if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) ThrowStartIndexArgumentOutOfRange(); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive); if (startIndex > value.Length - length) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (int.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3))); } int chArrayLength = length * 3; const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation unsafe { if (chArrayLength < StackLimit) { char* chArrayPtr = stackalloc char[chArrayLength]; return ToString(value, startIndex, length, chArrayPtr, chArrayLength); } else { fixed (char* chArrayPtr = new char[chArrayLength]) return ToString(value, startIndex, length, chArrayPtr, chArrayLength); } } } private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength) { Debug.Assert(length > 0); Debug.Assert(chArrayLength == length * 3); char* p = chArray; int endIndex = startIndex + length; for (int i = startIndex; i < endIndex; i++) { byte b = value[i]; *p++ = GetHexValue(b >> 4); *p++ = GetHexValue(b & 0xF); *p++ = '-'; } // We don't need the last '-' character return new string(chArray, 0, chArrayLength - 1); } // Converts an array of bytes into a String. public static string ToString(byte[] value) { if (value == null) ThrowValueArgumentNull(); Contract.Ensures(Contract.Result<string>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } // Converts an array of bytes into a String. public static string ToString(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); Contract.Ensures(Contract.Result<string>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if (startIndex < 0) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 1) ThrowStartIndexArgumentOutOfRange(); // differs from other overloads, which throw base ArgumentException Contract.EndContractBlock(); return value[startIndex] != 0; } [SecuritySafeCritical] public static unsafe long DoubleToInt64Bits(double value) { return *((long*)&value); } [SecuritySafeCritical] public static unsafe double Int64BitsToDouble(long value) { return *((double*)&value); } private static void ThrowValueArgumentNull() { throw new ArgumentNullException("value"); } private static void ThrowStartIndexArgumentOutOfRange() { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } private static void ThrowValueArgumentTooSmall() { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall, "value"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public static class SequenceEqualTests { private const int DuplicateFactor = 8; // // SequenceEqual // public static IEnumerable<object[]> SequenceEqualData(int[] counts) { foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4))) { foreach (object[] right in Sources.Ranges(new[] { (int)left[1] })) { yield return new object[] { left[0], right[0], right[1] }; } } } public static IEnumerable<object[]> SequenceEqualUnequalSizeData(int[] counts) { foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4))) { foreach (object[] right in Sources.Ranges(new[] { 1, ((int)left[1] - 1) / 2 + 1, (int)left[1] * 2 + 1 }.Distinct())) { yield return new object[] { left[0], left[1], right[0], right[1] }; } } } public static IEnumerable<object[]> SequenceEqualUnequalData(int[] counts) { foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4))) { Func<int, IEnumerable<int>> items = x => new[] { 0, x / 8, x / 2, x * 7 / 8, x - 1 }.Distinct(); foreach (object[] right in Sources.Ranges(new[] { (int)left[1] }, items)) { yield return new object[] { left[0], right[0], right[1], right[2] }; } } } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })] public static void SequenceEqual(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { _ = count; ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; Assert.True(leftQuery.SequenceEqual(rightQuery)); Assert.True(rightQuery.SequenceEqual(leftQuery)); Assert.True(leftQuery.SequenceEqual(leftQuery)); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { SequenceEqual(left, right, count); } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })] public static void SequenceEqual_CustomComparator(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; Assert.True(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(leftQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor))); ParallelQuery<int> repeating = Enumerable.Range(0, (count + (DuplicateFactor - 1)) / DuplicateFactor).SelectMany(x => Enumerable.Range(0, DuplicateFactor)).Take(count).AsParallel().AsOrdered(); Assert.True(leftQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(rightQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(repeating.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(repeating.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor))); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { SequenceEqual_CustomComparator(left, right, count); } [Theory] [MemberData(nameof(SequenceEqualUnequalSizeData), new[] { 0, 4, 16 })] public static void SequenceEqual_UnequalSize(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { _ = leftCount; _ = rightCount; ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; Assert.False(leftQuery.SequenceEqual(rightQuery)); Assert.False(rightQuery.SequenceEqual(leftQuery)); Assert.False(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(2))); Assert.False(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(2))); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualUnequalSizeData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_UnequalSize_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { SequenceEqual_UnequalSize(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(SequenceEqualUnequalData), new[] { 1, 2, 16 })] public static void SequenceEqual_Unequal(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item) { _ = count; ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item.Select(x => x == item ? -1 : x); Assert.False(leftQuery.SequenceEqual(rightQuery)); Assert.False(rightQuery.SequenceEqual(leftQuery)); Assert.True(leftQuery.SequenceEqual(leftQuery)); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualUnequalData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_Unequal_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item) { SequenceEqual_Unequal(left, right, count, item); } [Fact] public static void SequenceEqual_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] public static void SequenceEqual_OperationCanceledException() { AssertThrows.EventuallyCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler))); AssertThrows.EventuallyCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler))); } [Fact] public static void SequenceEqual_AggregateException_Wraps_OperationCanceledException() { AssertThrows.OtherTokenCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler))); AssertThrows.OtherTokenCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler))); AssertThrows.SameTokenNotCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler))); AssertThrows.SameTokenNotCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler))); } [Fact] public static void SequenceEqual_OperationCanceledException_PreCanceled() { AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2))); AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2), new ModularCongruenceComparer(1))); AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source)); AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source, new ModularCongruenceComparer(1))); } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 4 })] public static void SequenceEqual_AggregateException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { _ = count; AssertThrows.Wrapped<DeliberateTestException>(() => left.Item.SequenceEqual(right.Item, new FailingEqualityComparer<int>())); } [Fact] // Should not get the same setting from both operands. public static void SequenceEqual_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).SequenceEqual(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).SequenceEqual(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void SequenceEqual_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1))); AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null)); AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null, EqualityComparer<int>.Default)); } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })] public static void SequenceEqual_DisposeException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { _ = count; ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; AssertThrows.Wrapped<TestDisposeException>(() => leftQuery.SequenceEqual(new DisposeExceptionEnumerable<int>(rightQuery).AsParallel())); AssertThrows.Wrapped<TestDisposeException>(() => new DisposeExceptionEnumerable<int>(leftQuery).AsParallel().SequenceEqual(rightQuery)); } private class DisposeExceptionEnumerable<T> : IEnumerable<T> { private IEnumerable<T> _enumerable; public DisposeExceptionEnumerable(IEnumerable<T> enumerable) { _enumerable = enumerable; } public IEnumerator<T> GetEnumerator() { return new DisposeExceptionEnumerator(_enumerable.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class DisposeExceptionEnumerator : IEnumerator<T> { private IEnumerator<T> _enumerator; public DisposeExceptionEnumerator(IEnumerator<T> enumerator) { _enumerator = enumerator; } public T Current { get { return _enumerator.Current; } } public void Dispose() { throw new TestDisposeException(); } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } } } private class TestDisposeException : Exception { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Xml; using System.Collections; namespace System.Data.Common { internal sealed class DateTimeOffsetStorage : DataStorage { private static readonly DateTimeOffset s_defaultValue = DateTimeOffset.MinValue; private DateTimeOffset[] _values; internal DateTimeOffsetStorage(DataColumn column) : base(column, typeof(DateTimeOffset), s_defaultValue, StorageType.DateTimeOffset) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Min: DateTimeOffset min = DateTimeOffset.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { min = (DateTimeOffset.Compare(_values[record], min) < 0) ? _values[record] : min; hasData = true; } } if (hasData) { return min; } return _nullValue; case AggregateType.Max: DateTimeOffset max = DateTimeOffset.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { max = (DateTimeOffset.Compare(_values[record], max) >= 0) ? _values[record] : max; hasData = true; } } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null; case AggregateType.Count: int count = 0; for (int i = 0; i < records.Length; i++) { if (HasValue(records[i])) { count++; } } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(DateTimeOffset)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { DateTimeOffset valueNo1 = _values[recordNo1]; DateTimeOffset valueNo2 = _values[recordNo2]; if (valueNo1 == s_defaultValue || valueNo2 == s_defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) { return bitCheck; } } return DateTimeOffset.Compare(valueNo1, valueNo2); } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { return (HasValue(recordNo) ? 1 : 0); } DateTimeOffset valueNo1 = _values[recordNo]; if ((s_defaultValue == valueNo1) && !HasValue(recordNo)) { return -1; } return DateTimeOffset.Compare(valueNo1, (DateTimeOffset)value); } public override object ConvertValue(object value) { if (_nullValue != value) { if (null != value) { value = ((DateTimeOffset)value); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { DateTimeOffset value = _values[record]; if ((value != s_defaultValue) || HasValue(record)) { return value; } return _nullValue; } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = s_defaultValue; SetNullBit(record, true); } else { _values[record] = (DateTimeOffset)value; SetNullBit(record, false); } } public override void SetCapacity(int capacity) { DateTimeOffset[] newValues = new DateTimeOffset[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } public override object ConvertXmlToObject(string s) { return XmlConvert.ToDateTimeOffset(s); } public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((DateTimeOffset)value); } protected override object GetEmptyStorage(int recordCount) { return new DateTimeOffset[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { DateTimeOffset[] typedStore = (DateTimeOffset[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, !HasValue(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (DateTimeOffset[])store; SetNullStorage(nullbits); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Batch.Tests.Helpers; using Microsoft.Azure.Management.Batch; using Microsoft.Azure.Management.Batch.Models; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Microsoft.Azure.Batch.Tests { public class InMemoryAccountTests { [Fact] public void AccountCreateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Create(null, "bar", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("foo", null, new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("foo", "bar", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("invalid+", "account", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "invalid%", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "INVALID", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "/invalid", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "s", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "account_name_that_is_too_long", new BatchAccountCreateParameters())); } [Fact] public void AccountCreateAsyncValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'accountname', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = Task.Factory.StartNew(() => client.BatchAccount.CreateWithHttpMessagesAsync( "foo", "accountname", new BatchAccountCreateParameters { Location = "South Central US", Tags = tags })).Unwrap().GetAwaiter().GetResult(); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Put, handler.Requests[0].Method); Assert.NotNull(handler.Requests[0].Headers.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Body.Location); Assert.NotEmpty(result.Body.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.Body.ProvisioningState); Assert.Equal(2, result.Body.Tags.Count); } [Fact] public void CreateAccountWithAutoStorageAsyncValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var utcNow = DateTime.UtcNow; string resourceId = "abc123"; var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'accountname', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'autoStorage' :{ 'storageAccountId' : '//storageAccount1', 'lastKeySync': '" + utcNow.ToString("o") + @"', 'authenticationMode': 'BatchAccountManagedIdentity', 'NodeIdentityReference': { 'resourceId': '" + resourceId + @"' } } }, }") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { okResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.Create("resourceGroupName", "accountname", new BatchAccountCreateParameters { Location = "South Central US", AutoStorage = new AutoStorageBaseProperties() { StorageAccountId = "//storageAccount1", AuthenticationMode = AutoStorageAuthenticationMode.BatchAccountManagedIdentity, NodeIdentityReference = new ComputeNodeIdentityReference(resourceId) } });; // Validate result Assert.Equal("//storageAccount1", result.AutoStorage.StorageAccountId); Assert.Equal(AutoStorageAuthenticationMode.BatchAccountManagedIdentity, result.AutoStorage.AuthenticationMode); Assert.Equal(resourceId, result.AutoStorage.NodeIdentityReference.ResourceId); Assert.Equal(utcNow, result.AutoStorage.LastKeySync); } [Fact] public void AccountUpdateWithAutoStorageValidateMessage() { var utcNow = DateTime.UtcNow; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'autoStorage' : { 'storageAccountId' : '//StorageAccountId', 'lastKeySync': '" + utcNow.ToString("o") + @"', } }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.BatchAccount.Update("foo", "acctname", new BatchAccountUpdateParameters { Tags = tags, }); // Validate headers - User-Agent for certs, Authorization for tokens //Assert.Equal(HttpMethod.Patch, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState); Assert.Equal("//StorageAccountId", result.AutoStorage.StorageAccountId); Assert.Equal(utcNow, result.AutoStorage.LastKeySync); Assert.Equal(2, result.Tags.Count); } [Fact] public void AccountCreateSyncValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'accountname', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.BatchAccount.Create("foo", "accountname", new BatchAccountCreateParameters("westus") { Tags = tags, AutoStorage = new AutoStorageBaseProperties() { StorageAccountId = "//storageAccount1" } }); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState); Assert.Equal(2, result.Tags.Count); } [Fact] public void AccountUpdateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.BatchAccount.Update("foo", "acctname", new BatchAccountUpdateParameters { Tags = tags, AutoStorage = new AutoStorageBaseProperties() { StorageAccountId = "//StorageAccountId" } }); // Validate headers - User-Agent for certs, Authorization for tokens Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState); Assert.Equal(2, result.Tags.Count); } [Fact] public void AccountUpdateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Update(null, null, new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("foo", null, new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("foo", "bar", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("rg", "invalid%", new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("rg", "/invalid", new BatchAccountUpdateParameters())); } [Fact] public void AccountDeleteValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse, okResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); client.BatchAccount.Delete("resGroup", "acctname"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); } [Fact] public void AccountDeleteNotFoundValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(@"") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, notFoundResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); var result = Assert.Throws<CloudException>(() => Task.Factory.StartNew(() => client.BatchAccount.DeleteWithHttpMessagesAsync( "resGroup", "acctname")).Unwrap().GetAwaiter().GetResult()); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); Assert.Equal(HttpStatusCode.NotFound, result.Response.StatusCode); } [Fact] public void AccountDeleteOkValidateMessage() { var noContentResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"") }; noContentResponse.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(noContentResponse); var client = BatchTestHelper.GetBatchManagementClient(handler); client.BatchAccount.Delete("resGroup", "acctname"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); } [Fact] public void AccountDeleteThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("foo", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete(null, "bar")); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("rg", "invalid%")); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("rg", "/invalid")); } [Fact] public void AccountGetValidateResponse() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.Get("foo", "acctname"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.Equal("acctname", result.Name); Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname", result.Id); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(20, result.DedicatedCoreQuota); Assert.Equal(50, result.LowPriorityCoreQuota); Assert.Equal(100, result.PoolQuota); Assert.Equal(200, result.ActiveJobAndJobScheduleQuota); Assert.True(result.Tags.ContainsKey("tag1")); } [Fact] public void AccountGetThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("foo", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Get(null, "bar")); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("rg", "invalid%")); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("rg", "/invalid")); } [Fact] public void AccountListValidateMessage() { var allSubsResponseEmptyNextLink = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctname1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname1.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : '' }") }; var allSubsResponseNonemptyNextLink = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname1.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname?$skipToken=opaqueStringThatYouShouldntCrack' } ") }; var allSubsResponseNonemptyNextLink1 = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname1.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname?$skipToken=opaqueStringThatYouShouldntCrack' } ") }; allSubsResponseEmptyNextLink.Headers.Add("x-ms-request-id", "1"); allSubsResponseNonemptyNextLink.Headers.Add("x-ms-request-id", "1"); allSubsResponseNonemptyNextLink1.Headers.Add("x-ms-request-id", "1"); // all accounts under sub and empty next link var handler = new RecordedDelegatingHandler(allSubsResponseEmptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = Task.Factory.StartNew(() => client.BatchAccount.ListWithHttpMessagesAsync()) .Unwrap() .GetAwaiter() .GetResult(); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode); // Validate result Assert.Equal(2, result.Body.Count()); var account1 = result.Body.ElementAt(0); var account2 = result.Body.ElementAt(1); Assert.Equal("West US", account1.Location); Assert.Equal("acctname", account1.Name); Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname", account1.Id); Assert.Equal("/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctname1", account2.Id); Assert.NotEmpty(account1.AccountEndpoint); Assert.Equal(20, account1.DedicatedCoreQuota); Assert.Equal(50, account1.LowPriorityCoreQuota); Assert.Equal(100, account1.PoolQuota); Assert.Equal(200, account2.ActiveJobAndJobScheduleQuota); Assert.True(account1.Tags.ContainsKey("tag1")); // all accounts under sub and a non-empty nextLink handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK }; client = BatchTestHelper.GetBatchManagementClient(handler); var result1 = client.BatchAccount.List(); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // all accounts under sub with a non-empty nextLink response handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink1) { StatusCodeToReturn = HttpStatusCode.OK }; client = BatchTestHelper.GetBatchManagementClient(handler); result1 = client.BatchAccount.ListNext(result1.NextPageLink); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); } [Fact] public void AccountListByResourceGroupValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctname.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'dedicatedCoreQuota' : '20', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctname1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctname1.batch.core.windows.net/', 'provisioningState' : 'Failed', 'dedicatedCoreQuota' : '10', 'lowPriorityCoreQuota' : '50', 'poolQuota' : '50', 'activeJobAndJobScheduleQuota' : '100' }, 'tags' : { 'tag1' : 'value for tag1' } } ], 'nextLink' : 'originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack' }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.List(); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal(2, result.Count()); var account1 = result.ElementAt(0); var account2 = result.ElementAt(1); Assert.Equal("West US", account1.Location); Assert.Equal("acctname", account1.Name); Assert.Equal( @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname", account1.Id); Assert.Equal(@"http://acctname.batch.core.windows.net/", account1.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, account1.ProvisioningState); Assert.Equal(20, account1.DedicatedCoreQuota); Assert.Equal(50, account1.LowPriorityCoreQuota); Assert.Equal(100, account1.PoolQuota); Assert.Equal(200, account1.ActiveJobAndJobScheduleQuota); Assert.Equal("South Central US", account2.Location); Assert.Equal("acctname1", account2.Name); Assert.Equal(@"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname1", account2.Id); Assert.Equal(@"http://acctname1.batch.core.windows.net/", account2.AccountEndpoint); Assert.Equal(ProvisioningState.Failed, account2.ProvisioningState); Assert.Equal(10, account2.DedicatedCoreQuota); Assert.Equal(50, account2.LowPriorityCoreQuota); Assert.Equal(50, account2.PoolQuota); Assert.Equal(100, account2.ActiveJobAndJobScheduleQuota); Assert.Equal(2, account1.Tags.Count); Assert.True(account1.Tags.ContainsKey("tag2")); Assert.Equal(1, account2.Tags.Count); Assert.True(account2.Tags.ContainsKey("tag1")); Assert.Equal(@"originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack", result.NextPageLink); } [Fact] public void AccountListNextThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.BatchAccount.ListNext(null)); } [Fact] public void AccountKeysListValidateMessage() { var primaryKeyString = "primary key string which is alot longer than this"; var secondaryKeyString = "secondary key string which is alot longer than this"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'primary' : 'primary key string which is alot longer than this', 'secondary' : 'secondary key string which is alot longer than this', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.GetKeys("foo", "acctname"); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.NotEmpty(result.Primary); Assert.Equal(primaryKeyString, result.Primary); Assert.NotEmpty(result.Secondary); Assert.Equal(secondaryKeyString, result.Secondary); } [Fact] public void AccountKeysListThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.GetKeys("foo", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.GetKeys(null, "bar")); } [Fact] public void AccountKeysRegenerateValidateMessage() { var primaryKeyString = "primary key string which is alot longer than this"; var secondaryKeyString = "secondary key string which is alot longer than this"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'primary' : 'primary key string which is alot longer than this', 'secondary' : 'secondary key string which is alot longer than this', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.RegenerateKey( "foo", "acctname", AccountKeyType.Primary); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.NotEmpty(result.Primary); Assert.Equal(primaryKeyString, result.Primary); Assert.NotEmpty(result.Secondary); Assert.Equal(secondaryKeyString, result.Secondary); } [Fact] public void AccountKeysRegenerateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey(null, "bar", AccountKeyType.Primary)); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("foo", null, AccountKeyType.Primary)); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("rg", "invalid%", AccountKeyType.Primary)); } [Fact] public void ListOutboundNetworkDependenciesEndpointsValidateResponse() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'category': 'Azure Batch', 'endpoints': [ { 'domainName': 'japaneast.batch.azure.com', 'description': 'Applicable to all Azure Batch pools.', 'endpointDetails': [ { 'port': 443 } ] } ] }, { 'category': 'Azure Storage', 'endpoints': [ { 'domainName': 'sampleautostorageaccountname.blob.core.windows.net', 'description': 'AutoStorage endpoint for this Batch account. Applicable to all Azure Batch pools under this account.', 'endpointDetails': [ { 'port': 443 } ] } ] } ] }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); IPage<OutboundEnvironmentEndpoint> result = client.BatchAccount.ListOutboundNetworkDependenciesEndpoints("default-azurebatch-japaneast", "sampleacct"); Assert.Equal(2, result.Count()); OutboundEnvironmentEndpoint endpoint = result.ElementAt(0); Assert.Equal("Azure Batch", endpoint.Category); Assert.Equal("japaneast.batch.azure.com", endpoint.Endpoints[0].DomainName); Assert.Equal("Applicable to all Azure Batch pools.", endpoint.Endpoints[0].Description); Assert.Equal(443, endpoint.Endpoints[0].EndpointDetails[0].Port); endpoint = result.ElementAt(1); Assert.Equal("Azure Storage", endpoint.Category); Assert.Equal("sampleautostorageaccountname.blob.core.windows.net", endpoint.Endpoints[0].DomainName); Assert.Equal("AutoStorage endpoint for this Batch account. Applicable to all Azure Batch pools under this account.", endpoint.Endpoints[0].Description); Assert.Equal(443, endpoint.Endpoints[0].EndpointDetails[0].Port); } [Fact] public void UserAssignedIdentitiesShouldSubstituteForBatchAccountIdentityUserAssignedIdentitiesValue() { string principalId = "TestPrincipal"; string tenantId = "TestTenant"; BatchAccountIdentityUserAssignedIdentitiesValue testIdentity = new BatchAccountIdentityUserAssignedIdentitiesValue(); BatchAccountIdentity identity = new BatchAccountIdentity(ResourceIdentityType.UserAssigned, principalId, tenantId, new Dictionary<string, BatchAccountIdentityUserAssignedIdentitiesValue> { { "", testIdentity } }); Assert.True(testIdentity is UserAssignedIdentities); Assert.Equal(principalId, identity.PrincipalId); Assert.Equal(tenantId, identity.TenantId); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using System; //using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.HSSF.Record.Aggregates; using NPOI.SS; using NPOI.SS.Formula; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula.Udf; using NPOI.SS.UserModel; /** * Internal POI use only * * @author Josh Micich */ internal class HSSFEvaluationWorkbook : IFormulaRenderingWorkbook, IEvaluationWorkbook, IFormulaParsingWorkbook { private HSSFWorkbook _uBook; private NPOI.HSSF.Model.InternalWorkbook _iBook; public static HSSFEvaluationWorkbook Create(NPOI.SS.UserModel.IWorkbook book) { if (book == null) { return null; } return new HSSFEvaluationWorkbook((HSSFWorkbook)book); } private HSSFEvaluationWorkbook(HSSFWorkbook book) { _uBook = book; _iBook = book.Workbook; } public int GetExternalSheetIndex(String sheetName) { int sheetIndex = _uBook.GetSheetIndex(sheetName); return _iBook.CheckExternSheet(sheetIndex); } public int GetExternalSheetIndex(String workbookName, String sheetName) { return _iBook.GetExternalSheetIndex(workbookName, sheetName); } public ExternalName GetExternalName(int externSheetIndex, int externNameIndex) { return _iBook.GetExternalName(externSheetIndex, externNameIndex); } public NameXPtg GetNameXPtg(String name) { return _iBook.GetNameXPtg(name, _uBook.GetUDFFinder()); } public IEvaluationName GetName(String name,int sheetIndex) { for (int i = 0; i < _iBook.NumNames; i++) { NameRecord nr = _iBook.GetNameRecord(i); if (nr.SheetNumber == sheetIndex + 1 && name.Equals(nr.NameText, StringComparison.OrdinalIgnoreCase)) { return new Name(nr, i); } } return sheetIndex == -1 ? null : GetName(name, -1); } public int GetSheetIndex(IEvaluationSheet evalSheet) { HSSFSheet sheet = ((HSSFEvaluationSheet)evalSheet).HSSFSheet; return _uBook.GetSheetIndex(sheet); } public int GetSheetIndex(String sheetName) { return _uBook.GetSheetIndex(sheetName); } public String GetSheetName(int sheetIndex) { return _uBook.GetSheetName(sheetIndex); } public IEvaluationSheet GetSheet(int sheetIndex) { return new HSSFEvaluationSheet((HSSFSheet)_uBook.GetSheetAt(sheetIndex)); } public int ConvertFromExternSheetIndex(int externSheetIndex) { return _iBook.GetSheetIndexFromExternSheetIndex(externSheetIndex); } public ExternalSheet GetExternalSheet(int externSheetIndex) { return _iBook.GetExternalSheet(externSheetIndex); } public String ResolveNameXText(NameXPtg n) { return _iBook.ResolveNameXText(n.SheetRefIndex, n.NameIndex); } public String GetSheetNameByExternSheet(int externSheetIndex) { return _iBook.FindSheetNameFromExternSheet(externSheetIndex); } public String GetNameText(NamePtg namePtg) { return _iBook.GetNameRecord(namePtg.Index).NameText; } public IEvaluationName GetName(NamePtg namePtg) { int ix = namePtg.Index; return new Name(_iBook.GetNameRecord(ix), ix); } public Ptg[] GetFormulaTokens(IEvaluationCell evalCell) { ICell cell = ((HSSFEvaluationCell)evalCell).HSSFCell; //if (false) //{ // // re-parsing the formula text also works, but is a waste of time // // It is useful from time to time to run all unit tests with this code // // to make sure that all formulas POI can evaluate can also be parsed. // return FormulaParser.Parse(cell.CellFormula, _uBook, FormulaType.CELL, _uBook.GetSheetIndex(cell.Sheet)); //} FormulaRecordAggregate fr = (FormulaRecordAggregate)((HSSFCell)cell).CellValueRecord; return fr.FormulaTokens; } public UDFFinder GetUDFFinder() { return _uBook.GetUDFFinder(); } private class Name : IEvaluationName { private NameRecord _nameRecord; private int _index; public Name(NameRecord nameRecord, int index) { _nameRecord = nameRecord; _index = index; } public Ptg[] NameDefinition { get{ return _nameRecord.NameDefinition; } } public String NameText { get{ return _nameRecord.NameText; } } public bool HasFormula { get{ return _nameRecord.HasFormula; } } public bool IsFunctionName { get{ return _nameRecord.IsFunctionName; } } public bool IsRange { get { return _nameRecord.HasFormula; // TODO - is this right? } } public NamePtg CreatePtg() { return new NamePtg(_index); } } public SpreadsheetVersion GetSpreadsheetVersion() { return SpreadsheetVersion.EXCEL97; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using mshtml; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Mshtml; using System.Diagnostics; namespace OpenLiveWriter.PostEditor.PostHtmlEditing { /// <summary> /// Utility for pretty printing and range of HTML content from the DOM. /// </summary> public class FormattedHtmlPrinter { private FormattedHtmlPrinter() { } public static String ToFormattedHtml(MshtmlMarkupServices markupServices, MarkupRange bounds) { StringBuilder sb = new StringBuilder(); HtmlWriter xmlWriter = new HtmlWriter(sb); PrintHtml(xmlWriter, markupServices, bounds); return sb.ToString(); } private static void PrintHtml(HtmlWriter writer, MshtmlMarkupServices MarkupServices, MarkupRange bounds) { //create a range to span a single position while walking the doc MarkupRange range = MarkupServices.CreateMarkupRange(); range.Start.MoveToPointer(bounds.Start); range.End.MoveToPointer(bounds.Start); //create a context that can be reused while walking the document. MarkupContext context = new MarkupContext(); //move the range.End to the right and print out each element along the way range.End.Right(true, context); while (context.Context != _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_None && range.Start.IsLeftOf(bounds.End)) { string text = null; if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text) { //if this is a text context, then get the text that is between the start and end points. text = range.HtmlText; //the range.HtmlText operation sometimes returns the outer tags for a text node, //so we need to strip the tags. //FIXME: if the Right/Left operations returned the available text value, this wouldn't be necessary. if (text != null) text = StripSurroundingTags(text); } else if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope) { string htmlText = range.HtmlText; if (context.Element.innerHTML == null && htmlText != null && htmlText.IndexOf("&nbsp;") != -1) { //HACK: Under these conditions, there was a was an invisible NBSP char in the //document that is not detectable by walking through the document with MarkupServices. //So, we force the text of the element to be the &nbsp; char to ensure that the //whitespace that was visible in the editor is visible in the final document. text = "&nbsp;"; } } //print the context. printContext(writer, context, text, range); //move the start element to the spot where the end currently is so tht there is //only ever a single difference in position range.Start.MoveToPointer(range.End); //move the end to the next position range.End.Right(true, context); } } private static string trimHtmlText(string html) { return Regex.Replace(html, @"\s+", " "); } /// <summary> /// Utility for printing the correct XHTML for a given MarkupContext. /// </summary> /// <param name="writer"></param> /// <param name="context"></param> /// <param name="text"></param> private static void printContext(HtmlWriter writer, MarkupContext context, string text, MarkupRange range) { switch (context.Context) { case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope: printElementStart(writer, context.Element); if (HtmlLinebreakStripper.IsPreserveWhitespaceTag(context.Element.tagName)) { // <pre> was losing whitespace using the normal markup pointer traversal method writer.WriteString(BalanceHtml(context.Element.innerHTML)); printElementEnd(writer, context.Element); range.End.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd); break; } else { if (text != null) writer.WriteString(trimHtmlText(text)); break; } case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope: if (text != null) writer.WriteString(trimHtmlText(text)); printElementEnd(writer, context.Element); break; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_None: break; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_NoScope: if (context.Element is IHTMLCommentElement || context.Element is IHTMLUnknownElement) { //bugfix: 1777 - comments should just be inserted raw. string html = context.Element.outerHTML; // bugfix: 534222 - embed tag markup generation issues if (html != null && html.ToUpper(CultureInfo.InvariantCulture) != "</EMBED>") writer.WriteString(html); } else { printElementStart(writer, context.Element); if (text == null && context.Element.innerHTML != null) { //Avoid MSHTML bug: in some cases (like title or script elements), MSHTML improperly //reports a tag as being NoScope, even through it clearly has a start and end tag with //text in between. To cover this case, we look for text in a noscope element, and add //it to the XML stream if it is detected. writer.WriteString(context.Element.innerHTML); } printElementEnd(writer, context.Element); } break; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text: if (text != null) writer.WriteString(trimHtmlText(text)); break; default: break; } } private static string BalanceHtml(string html) { StringBuilder sb = new StringBuilder(html.Length + 10); SimpleHtmlParser parser = new SimpleHtmlParser(html); Element el; while (null != (el = parser.Next())) { if (el is BeginTag) { BeginTag bt = (BeginTag)el; if (!ElementFilters.RequiresEndTag(bt.Name)) bt.Complete = true; } sb.Append(el.ToString()); } return sb.ToString(); } /// <summary> /// Utility for properly printing the end tag for an element. /// This utility takes care of including/suppressing end tags for empty nodes properly. /// </summary> /// <param name="writer"></param> /// <param name="element"></param> private static void printElementEnd(HtmlWriter writer, IHTMLElement element) { // No tagName, no end tag. if (string.IsNullOrEmpty(element.tagName)) { return; } if (ElementFilters.RequiresEndTag(element)) { writer.WriteEndElement(true); } else { writer.WriteEndElement(false); } } /// <summary> /// Utility for properly printing the start tag for an element. /// This utility takes care of including/suppresing attributes and namespaces properly. /// </summary> /// <param name="writer"></param> /// <param name="element"></param> private static void printElementStart(HtmlWriter writer, IHTMLElement element) { string tagName = element.tagName; // If there is no tag name, this is mostly an artificial tag reported by mshtml, // and not really present in the markup // (e.g HTMLTableCaptionClass) if (string.IsNullOrEmpty(tagName)) { return; } //XHTML tags are all lowercase tagName = tagName.ToLower(CultureInfo.InvariantCulture); //this is a standard HTML tag, so just write it out. writer.WriteStartElement(tagName); IHTMLDOMNode node = element as IHTMLDOMNode; IHTMLAttributeCollection attrs = node.attributes as IHTMLAttributeCollection; if (attrs != null) { foreach (IHTMLDOMAttribute attr in attrs) { string attrName = attr.nodeName as string; if (attr.specified) { string attrNameLower = attrName.ToLower(CultureInfo.InvariantCulture); //get the raw attribute value (so that IE doesn't try to expand out paths in the value). string attrValue = element.getAttribute(attrName, 2) as string; if (attrValue == null) { //IE won't return some attributes (like class) using IHTMLElement.getAttribute(), //so if the value is null, try to get the value directly from the DOM Attribute. //Note: we can't use the DOM value by default, because IE will rewrite the value //to contain a fully-qualified path on some attribures (like src and href). attrValue = attr.nodeValue as string; if (attrValue == null) { if ((attrNameLower == "hspace" || attrNameLower == "vspace") && attr.nodeValue is int) { attrValue = ((int)attr.nodeValue).ToString(CultureInfo.InvariantCulture); } else if (attrNameLower == "style") { //Avoid bug: Images that are resized with the editor insert a STYLE attribute. //IE won't return the style attribute using the standard API, so we have to grab //it from the style object attrValue = element.style.cssText; } else if (attrNameLower == "colspan") { attrValue = (element as IHTMLTableCell).colSpan.ToString(CultureInfo.InvariantCulture); } else if (attrNameLower == "rowspan") { attrValue = (element as IHTMLTableCell).rowSpan.ToString(CultureInfo.InvariantCulture); } else if (attrNameLower == "align" && attr.nodeValue is int) { // This is not documented anywhere. Just discovered the values empirically on IE7 (Vista). switch ((int)attr.nodeValue) { case 1: attrValue = "left"; break; case 2: attrValue = "center"; break; case 3: attrValue = "right"; break; case 4: attrValue = "texttop"; break; case 5: attrValue = "absmiddle"; break; case 6: attrValue = "baseline"; break; case 7: attrValue = "absbottom"; break; case 8: attrValue = "bottom"; break; case 9: attrValue = "middle"; break; case 10: attrValue = "top"; break; } } } Debug.WriteLineIf(attrValue != null && attrName != "id", String.Format(CultureInfo.InvariantCulture, "{0}.{1} attribute value not retreived", tagName, attrName), element.outerHTML); } // Minimized attributes are not allowed, according // to section 4.5 of XHTML 1.0 specification. // TODO: Deal with simple values that are not strings if (attrValue == null && attrNameLower != "id") attrValue = attrName; if (attrName != null && attrValue != null) { //write out this attribute. writer.WriteAttributeString(attrName, attrValue); } } } } } /// <summary> /// Strips the tags that a surrounding a string (ex: <b><i>text</i></b> becomes text) /// </summary> /// <param name="text">a string of text zero or one surrounding tags</param> /// <returns></returns> private static string StripSurroundingTags(string text) { int index = text.IndexOf('<'); if (index != -1) { //this HTML text fragment is surrounded by tags, but shouldn't be //fix bug 486877 by trimming whitespace before/after the tags, so it doesn't creep in. text = text.Trim(); index = text.IndexOf('<'); //reset the index of the tag } while (index != -1) { int index2 = text.IndexOf('>', index); text = text.Remove(index, index2 - index + 1); index = text.IndexOf('<'); } return text; } } class HtmlWriter { private StringBuilder sb; private Stack openElements = new Stack(); public HtmlWriter(StringBuilder sb) { this.sb = sb; } public void WriteAttributeString(String name, String val) { GetCurrentElementPrinter().WriteElementAttribute(sb, name, val); } public void WriteStartElement(String name) { HtmlElementPrinter currentPrinter = null; if (openElements.Count > 0) { currentPrinter = GetCurrentElementPrinter(); } HtmlElementPrinter elementPrinter = new HtmlElementPrinter(name, openElements.Count, currentPrinter); if (currentPrinter != null) currentPrinter.BeforeAddChildElement(sb, name); elementPrinter.WriteElementStart(sb); openElements.Push(elementPrinter); } private HtmlElementPrinter GetCurrentElementPrinter() { return (HtmlElementPrinter)openElements.Peek(); } public void WriteString(String str) { if (openElements.Count > 0) GetCurrentElementPrinter().WriteString(sb, str); else sb.Append(str); } public void WriteEndElement(bool requiresEndTag) { HtmlElementPrinter elementPrinter = (HtmlElementPrinter)openElements.Pop(); elementPrinter.WriteElementEnd(sb, requiresEndTag); } /// <summary> /// Look up table holding the names of all block-formatted tags. /// </summary> private static Hashtable BlockTagNames { get { if (_blockTagNames == null) { _blockTagNames = new Hashtable(); _blockTagNames["div"] = "div"; _blockTagNames["p"] = "p"; _blockTagNames["pre"] = "pre"; _blockTagNames["br"] = "br"; _blockTagNames["h1"] = "h1"; _blockTagNames["h2"] = "h2"; _blockTagNames["h3"] = "h3"; _blockTagNames["h4"] = "h4"; _blockTagNames["h5"] = "h5"; _blockTagNames["h6"] = "h6"; _blockTagNames["hr"] = "hr"; _blockTagNames["blockquote"] = "blockquote"; _blockTagNames["table"] = "table"; _blockTagNames["tr"] = "tr"; _blockTagNames["td"] = "td"; _blockTagNames["th"] = "th"; _blockTagNames["ul"] = "ul"; _blockTagNames["ol"] = "ol"; _blockTagNames["li"] = "li"; } return _blockTagNames; } } private static Hashtable _blockTagNames; /// <summary> /// Manages the incremental printing of an HTML element. /// </summary> private class HtmlElementPrinter { private enum START_TAG_STATE { NONE, OPENED, CLOSED }; private START_TAG_STATE startTagState = START_TAG_STATE.NONE; private String tagName; private int stackDepth; private HtmlElementPrinter parentElementPrinter; private ElementIndentStrategy indentStrategy; private int childCount; public HtmlElementPrinter(String tagName, int stackDepth, HtmlElementPrinter parentElementPrinter) { this.tagName = tagName; this.stackDepth = stackDepth; this.parentElementPrinter = parentElementPrinter; //create the appropriate indentation stategy for this element this.indentStrategy = CreateIndentStrategy(tagName, this); } public HtmlElementPrinter getParent() { return parentElementPrinter; } public void WriteElementStart(StringBuilder sb) { startTagState = START_TAG_STATE.OPENED; ApplyStartIndentStrategy(sb, stackDepth); sb.Append("<"); sb.Append(tagName); } public void WriteElementAttribute(StringBuilder sb, String attrName, String attrValue) { Debug.Assert(Regex.IsMatch(attrName, "^[a-zA-Z-]+$"), "Illegal attribute name: " + attrName); sb.Append(" "); sb.Append(attrName); sb.Append("=\""); sb.Append(HtmlUtils.EscapeEntities(attrValue)); sb.Append("\""); } public void WriteElementEnd(StringBuilder sb, bool requiresEndTag) { if (startTagState == START_TAG_STATE.OPENED && !requiresEndTag) { sb.Append(" /"); CloseStartElement(sb); } else { CloseStartElement(sb); ApplyEndIndentStrategy(sb, stackDepth); sb.Append("</"); sb.Append(tagName); sb.Append(">"); if (BlockTagNames.ContainsKey(tagName)) { sb.Append("\r\n"); } } } public void BeforeAddChildElement(StringBuilder sb, String tagName) { CloseStartElement(sb); childCount++; } public void WriteString(StringBuilder sb, String str) { CloseStartElement(sb); sb.Append(str); } public int ChildCount { get { return childCount; } } private void CloseStartElement(StringBuilder sb) { if (startTagState == START_TAG_STATE.OPENED) { sb.Append(">"); startTagState = START_TAG_STATE.CLOSED; } } protected virtual void ApplyStartIndentStrategy(StringBuilder sb, int depth) { indentStrategy.ApplyStartIndent(sb, depth); } protected virtual void ApplyEndIndentStrategy(StringBuilder sb, int depth) { indentStrategy.ApplyEndIndent(sb, depth); } private static ElementIndentStrategy CreateIndentStrategy(String tagName, HtmlElementPrinter printer) { if (BlockTagNames.ContainsKey(tagName)) return new BlockElementIndentStrategy(printer); else return new ElementIndentStrategy(printer); } } /// <summary> /// Standard indentation strategy that only indents when a tag starts on a newline /// </summary> private class ElementIndentStrategy { protected HtmlElementPrinter elementPrinter; public ElementIndentStrategy(HtmlElementPrinter elementPrinter) { this.elementPrinter = elementPrinter; } public virtual void ApplyStartIndent(StringBuilder sb, int depth) { bool isStartOfLine = sb.Length == 0 || sb[sb.Length - 1] == '\n'; if (isStartOfLine) WriteIndent(sb, depth); } public virtual void ApplyEndIndent(StringBuilder sb, int depth) { bool isStartOfLine = sb.Length == 0 || sb[sb.Length - 1] == '\n'; if (isStartOfLine) WriteIndent(sb, depth); } protected void WriteIndent(StringBuilder sb, int depth) { for (int i = 0; i < depth; i++) { sb.Append(" "); } } } /// <summary> /// Indentation strategy that forces a line break and indent before the element starts. /// </summary> private class BlockElementIndentStrategy : ElementIndentStrategy { private bool forceVisualLeadingLineBreak = true; public BlockElementIndentStrategy(HtmlElementPrinter elementPrinter) : base(elementPrinter) { //if this element is is the very first content in the parent element, then supress //adding the visual line break so that we don't end up with extra whitespace. HtmlElementPrinter parent = elementPrinter.getParent(); if (parent != null) forceVisualLeadingLineBreak = parent.ChildCount > 0; } public override void ApplyStartIndent(StringBuilder sb, int depth) { bool isStartOfLine = sb.Length == 0 || sb[sb.Length - 1] == '\n'; //force a line break so this tag can be indented. if (!isStartOfLine) { sb.Append("\r\n"); } if (forceVisualLeadingLineBreak && sb.Length > 0) { //add an additional line break to mirror the visual breaks //shown when the HTML is rendered in a browser sb.Append("\r\n"); } WriteIndent(sb, depth); } } } }
using System; using System.Net; using IvionWebSoft; namespace WebIrc { /// <summary> /// Takes an URL and returns an IRC-printable title. /// </summary> public class WebToIrc { public double Threshold { get; set; } public bool ParseMedia { get; set; } public ChanHandler Chan { get; private set; } public DanboHandler Danbo { get; private set; } public GelboHandler Gelbo { get; private set; } public WikipediaHandler Wiki { get; private set; } public CookieContainer Cookies { get { return urlFetcher.Cookies; } } internal static UrlTitleComparer UrlTitle { get; private set; } readonly WebUriFetcher urlFetcher; // Pre-HTML junctions. (These usually get their info from APIs) readonly Func<TitlingRequest, TitlingResult>[] preHtmlHandlers; // Instructions for various URLs, how much to get and what to do with it. readonly UrlLoadInstructions[] urlInstructions; static WebToIrc() { UrlTitle = new UrlTitleComparer(); } public WebToIrc() { Chan = new ChanHandler(); Danbo = new DanboHandler(); Gelbo = new GelboHandler(); Wiki = new WikipediaHandler(); urlFetcher = new WebUriFetcher() { Cookies = new CookieContainer(), MaxSizeNonHtml = SizeConstants.NonHtmlDefault }; preHtmlHandlers = new Func<TitlingRequest, TitlingResult>[] { Danbo.HandleRequest, Gelbo.HandleRequest, Chan.HandleRequest }; // Generic instructions, for all URLs not matched by // previous instructions. var generic = new UrlLoadInstructions( uri => true, SizeConstants.HtmlDefault, true, GenericHandler ); urlInstructions = new UrlLoadInstructions[] { UrlLoadInstructions.Youtube, UrlLoadInstructions.Twitter, Wiki.LoadInstructions, generic }; } public TitlingResult WebInfo(string uriString) { if (uriString == null) throw new ArgumentNullException(nameof(uriString)); Uri uri; try { uri = new Uri(uriString); } catch (UriFormatException ex) { return TitlingResult.Failure(uriString, ex); } return WebInfo(uri); } public TitlingResult WebInfo(Uri uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); if (!uri.IsAbsoluteUri) throw new ArgumentException("Uri must be absolute: " + uri, nameof(uri)); if (TitlingRequest.IsSchemeSupported(uri)) return WebInfo( new TitlingRequest(uri) ); else { var ex = new NotSupportedException("Unsupported scheme: " + uri.Scheme); return TitlingResult.Failure(uri.OriginalString, ex); } } public TitlingResult WebInfo(TitlingRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); // TitlingRequest ensures that what we get passed is an absolute URI with a scheme we support. Most // importantly this relieves the individual handlers of checking for those conditions. foreach (var handler in preHtmlHandlers) { var result = handler(request); if (result != null) return result; } foreach (var instruction in urlInstructions) { if (instruction.Match(request.Uri)) { // Set options as per instructions. urlFetcher.MaxSizeHtml = instruction.FetchSize; urlFetcher.FollowMetaRefreshes = instruction.FollowMetaRefreshes; var result = urlFetcher.Load(request.Uri); request.Resource = result.Page; // HTML handling. if (result.IsHtml) { return HandleHtml( request, result.Page, instruction.Handler ?? GenericHandler ); } // Media/Binary handling. if (ParseMedia && result.Bytes.Success) { return BinaryHandler.BinaryToIrc(request, result.Bytes); } return request.CreateResult(false); } } throw new InvalidOperationException( "Reached end of method, this should not happen. There should be a catch-all in urlInstructions."); } static TitlingResult HandleHtml( TitlingRequest request, HtmlPage page, Func<TitlingRequest, string, TitlingResult> handler) { const int maxTitleLength = 1024; ReportCharsets(request, page); string htmlTitle = WebTools.GetTitle(page.Content); if (string.IsNullOrWhiteSpace(htmlTitle)) { request.AddMessage("No <title> found, or title element was empty/whitespace."); return request.CreateResult(false); } if (htmlTitle.Length > maxTitleLength) { request.AddMessage("HTML title length was in excess of 1024 characters, assuming spam."); return request.CreateResult(false); } // If defined and not of ridiculous length make it available to TitleBuilder. request.IrcTitle.HtmlTitle = htmlTitle; return handler(request, page.Content); } static void ReportCharsets(TitlingRequest req, HtmlPage page) { var encInfo = string.Format("(HTTP) \"{0}\" -> {1} ; (HTML) \"{2}\" -> {3}", page.HeadersCharset, page.EncHeaders, page.HtmlCharset, page.EncHtml); req.AddMessage(encInfo); } // To conform to the signature we accept the HTML document. We don't need it. TitlingResult GenericHandler(TitlingRequest req, string htmlDoc) { // Because the similarity can only be 1 max, allow all titles to be printed if Threshold is set to 1 or // higher. The similarity would always be equal to or less than 1. if (Threshold >= 1) return req.CreateResult(true); // If Threshold is set to 0 that would still mean that titles that had 0 similarity with their URLs would // get printed. Set to a negative value to never print any title. if (Threshold < 0) return req.CreateResult(false); double urlTitleSimilarity = UrlTitle.Similarity(req.Url, req.IrcTitle.HtmlTitle); req.AddMessage( string.Format("URL-Title Similarity: {0} [Threshold: {1}]", urlTitleSimilarity, Threshold) ); if (urlTitleSimilarity <= Threshold) return req.CreateResult(true); return req.CreateResult(false); } } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap04 : YsMap { public override int MapIndex => 4; protected override int RandomEncounterChance => 10; protected override int RandomEncounterExtraCount => 0; public YserMap04() { MapEvent01 = FnTELPORTN_01; MapEvent02 = FnTELEMESG_02; MapEvent03 = FnTOSOLDQU_03; MapEvent04 = FnGATEMESG_04; MapEvent05 = FnNPCCHATA_05; MapEvent06 = FnNPCCHATB_06; MapEvent07 = FnITEMAENC_07; MapEvent08 = FnTELPORTN_08; MapEvent09 = FnITEMBENC_09; MapEvent0A = FnITEMCENC_0A; MapEvent0B = FnITEMDENC_0B; MapEvent0D = FnTRAPDORA_0D; MapEvent0E = FnTRAPDORB_0E; MapEvent0F = FnTRAPDORC_0F; MapEvent10 = FnTRAPDORD_10; MapEvent11 = FnTRAPDORE_11; MapEvent12 = FnTRAPDORF_12; MapEvent13 = FnTRAPDORG_13; MapEvent14 = FnTRAPDORH_14; MapEvent15 = FnTRAPDOR_15; MapEvent16 = FnTRAPDORJ_16; MapEvent17 = FnTRAPDORK_17; MapEvent18 = FnTRAPDORL_18; MapEvent19 = FnTRAPDORM_19; MapEvent1A = FnTRAPDORN_1A; MapEvent1B = FnTUFMNSTR_1B; MapEvent1E = FnGOLDENCA_1E; MapEvent1F = FnGOLDBENC_1F; MapEvent20 = FnGOLDCENC_20; } // === Strings ================================================ private const string String03FC = "There is a teleport in the north wall to the Hall of Doors."; private const string String0438 = "The gateway leads to the SOLDIERS QUARTERS."; private const string String0464 = "You encounter a Human Thief."; private const string String0481 = "King Cleowyn long sought the buried secrets of a great wizard whose castle lies buried inside this mountain. "; private const string String04EF = "The king died most horribly, it is said. His anguished death scream was heard across the island, but no one ever found his body. The dead wizard may have claimed the body, but no one knows for sure."; private const string String05B6 = "The Human Thief cadges some money from you and runs away."; private const string String05F0 = "You encounter an Elf Barbarian."; private const string String0610 = "Two levels down is a most strange area. Six small rooms are accessible to anyone, but there is a large area I have not been able to reach. A wizard told me I should study my runes to solve the mystery of this area."; private const string String06E7 = "The Elf Barbarian is busy tending her many wounds and ignores you."; private const string String072A = "Monsters jump out of the shadows."; private const string String074C = "Monsters snarl as you approach a pile of weapons."; private const string String077E = "Unclean spirits shriek as they attack."; private const string String07A5 = "Incubi surround you as you approach a weapon on the floor."; private const string String07E0 = "Skeletons attack you."; private const string String07F6 = "Skeletons guard a precious hoard."; private const string String0818 = "The dead arise as you draw near."; private const string String0839 = "Your movement disturbs the dead who have guarded King Cleowyn's Treasury."; private const string String0883 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String08D3 = "A trapdoor in the floor opens."; private const string String08F2 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0942 = "A trapdoor in the floor opens."; private const string String0961 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String09B1 = "A trapdoor in the floor opens."; private const string String09D0 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0A20 = "A trapdoor in the floor opens."; private const string String0A3F = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0A8F = "A trapdoor in the floor opens."; private const string String0AAE = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0AFE = "A trapdoor in the floor opens."; private const string String0B1D = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0B6D = "A trapdoor in the floor opens."; private const string String0B8C = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0BDC = "A trapdoor in the floor opens."; private const string String0BFB = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0C4B = "A trapdoor in the floor opens."; private const string String0C6A = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0CBA = "A trapdoor in the floor opens."; private const string String0CD9 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0D29 = "A trapdoor in the floor opens."; private const string String0D48 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0D98 = "A trapdoor in the floor opens."; private const string String0DB7 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0E07 = "A trapdoor in the floor opens."; private const string String0E26 = "You detect a trapdoor in the floor, but not in time to prevent falling through!"; private const string String0E76 = "A trapdoor in the floor opens."; private const string String0E95 = "Ghosts haunt the empty room."; private const string String0EB2 = "Spirits of the dead guard King Cleowyn's gold."; private const string String0EE1 = "Bones of dead guards and one-time thieves rise to challenge you."; private const string String0F22 = "Skeletons of dead guards and the thieves they killed stand between you and Cleowyn's gold."; private const string String0F7D = "Spiders drop from the ceiling."; private const string String0F9C = "Spider webs envelop a pile of gold pieces on the floor."; // === Functions ================================================ private void FnTELPORTN_01(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x04, 0x5F, 0x01, type); L001E: return; // RETURN; } private void FnTELEMESG_02(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String03FC); // There is a teleport in the north wall to the Hall of Doors. L0010: return; // RETURN; } private void FnTOSOLDQU_03(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x06, 0x4F, 0x00, type); L001D: return; // RETURN; } private void FnGATEMESG_04(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0438); // The gateway leads to the SOLDIERS QUARTERS. L0010: return; // RETURN; } private void FnNPCCHATA_05(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0464); // You encounter a Human Thief. L0010: ShowPortrait(player, 0x0022); L001D: Compare(GetRandom(0x000F), 0x0009); L002D: if (JumpAbove) goto L004B; L002F: ShowMessage(player, doMsgs, String0481); // King Cleowyn long sought the buried secrets of a great wizard whose castle lies buried inside this mountain. L003C: ShowMessage(player, doMsgs, String04EF); // The king died most horribly, it is said. His anguished death scream was heard across the island, but no one ever found his body. The dead wizard may have claimed the body, but no one knows for sure. L0049: goto L006A; L004B: ModifyGold(player, 0xFFFF38BA); L005D: ShowMessage(player, doMsgs, String05B6); // The Human Thief cadges some money from you and runs away. L006A: return; // RETURN; } private void FnNPCCHATB_06(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String05F0); // You encounter an Elf Barbarian. L0010: ShowPortrait(player, 0x0018); L001D: Compare(GetRandom(0x000F), 0x0007); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String0610); // Two levels down is a most strange area. Six small rooms are accessible to anyone, but there is a large area I have not been able to reach. A wizard told me I should study my runes to solve the mystery of this area. L003C: goto L004B; L003E: ShowMessage(player, doMsgs, String06E7); // The Elf Barbarian is busy tending her many wounds and ignores you. L004B: return; // RETURN; } private void FnITEMAENC_07(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryWeapons), 0x0001); L0017: if (JumpNotEqual) goto L0048; L0019: ShowMessage(player, doMsgs, String072A); // Monsters jump out of the shadows. L0026: AddTreasure(player, 0x0064, 0x00, 0x00, 0x00, 0xCE, 0xB5); L0046: goto L008B; L0048: AddTreasure(player, 0x1770, 0x00, 0x00, 0xCE, 0x42, 0x0A); L0069: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryWeapons, 0x01); L007E: ShowMessage(player, doMsgs, String074C); // Monsters snarl as you approach a pile of weapons. L008B: Compare(PartyCount(player), 0x0001); L0096: if (JumpEqual) goto L00A5; L0098: Compare(PartyCount(player), 0x0002); L00A3: if (JumpNotEqual) goto L00CB; L00A5: AddEncounter(player, 0x01, 0x19); L00B7: AddEncounter(player, 0x02, 0x1E); L00C9: goto L0125; L00CB: AddEncounter(player, 0x01, 0x1B); L00DD: AddEncounter(player, 0x02, 0x1A); L00EF: AddEncounter(player, 0x03, 0x19); L0101: AddEncounter(player, 0x05, 0x1E); L0113: AddEncounter(player, 0x06, 0x1E); L0125: return; // RETURN; } private void FnTELPORTN_08(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x01, 0x04, 0x5F, 0x01, type); L001E: return; // RETURN; } private void FnITEMBENC_09(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryWeapons2), 0x0001); L0017: if (JumpNotEqual) goto L0048; L0019: ShowMessage(player, doMsgs, String077E); // Unclean spirits shriek as they attack. L0026: AddTreasure(player, 0x0190, 0x00, 0x00, 0x00, 0xB5, 0xCB); L0046: goto L008A; L0048: AddTreasure(player, 0x0BB8, 0x00, 0x00, 0x00, 0x8A, 0x3B); L0068: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryWeapons2, 0x01); L007D: ShowMessage(player, doMsgs, String07A5); // Incubi surround you as you approach a weapon on the floor. L008A: Compare(PartyCount(player), 0x0001); L0095: if (JumpNotEqual) goto L00BE; L0097: AddEncounter(player, 0x01, 0x24); L00A9: AddEncounter(player, 0x02, 0x24); L00BB: goto L0181; L00BE: Compare(PartyCount(player), 0x0002); L00C9: if (JumpNotEqual) goto L0115; L00CB: AddEncounter(player, 0x01, 0x23); L00DD: AddEncounter(player, 0x02, 0x23); L00EF: AddEncounter(player, 0x03, 0x23); L0101: AddEncounter(player, 0x04, 0x25); L0113: goto L0181; L0115: AddEncounter(player, 0x01, 0x28); L0127: AddEncounter(player, 0x02, 0x28); L0139: AddEncounter(player, 0x03, 0x27); L014B: AddEncounter(player, 0x04, 0x27); L015D: AddEncounter(player, 0x05, 0x26); L016F: AddEncounter(player, 0x06, 0x26); L0181: return; // RETURN; } private void FnITEMCENC_0A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold4), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: AddTreasure(player, 0x0064, 0x00, 0x00, 0x00, 0x00, 0xCE); L0038: ShowMessage(player, doMsgs, String07E0); // Skeletons attack you. L0045: goto L008B; L0047: AddTreasure(player, 0x0BB8, 0x00, 0xCC, 0x39, 0x8C, 0x1C); L0069: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold4, 0x01); L007E: ShowMessage(player, doMsgs, String07F6); // Skeletons guard a precious hoard. L008B: Compare(PartyCount(player), 0x0001); L0096: if (JumpNotEqual) goto L00BF; L0098: AddEncounter(player, 0x01, 0x03); L00AA: AddEncounter(player, 0x02, 0x02); L00BC: goto L01DA; L00BF: Compare(PartyCount(player), 0x0002); L00CA: if (JumpNotEqual) goto L0105; L00CC: AddEncounter(player, 0x01, 0x03); L00DE: AddEncounter(player, 0x02, 0x01); L00F0: AddEncounter(player, 0x03, 0x03); L0102: goto L01DA; L0105: Compare(PartyCount(player), 0x0003); L0110: if (JumpNotEqual) goto L016E; L0112: AddEncounter(player, 0x01, 0x04); L0124: AddEncounter(player, 0x02, 0x02); L0136: AddEncounter(player, 0x03, 0x04); L0148: AddEncounter(player, 0x04, 0x03); L015A: AddEncounter(player, 0x06, 0x01); L016C: goto L01DA; L016E: AddEncounter(player, 0x01, 0x04); L0180: AddEncounter(player, 0x02, 0x04); L0192: AddEncounter(player, 0x03, 0x03); L01A4: AddEncounter(player, 0x04, 0x03); L01B6: AddEncounter(player, 0x05, 0x02); L01C8: AddEncounter(player, 0x06, 0x02); L01DA: return; // RETURN; } private void FnITEMDENC_0B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold5), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: ShowMessage(player, doMsgs, String0818); // The dead arise as you draw near. L0026: AddTreasure(player, 0x0096, 0x00, 0x00, 0x00, 0x00, 0xB6); L0045: goto L0089; L0047: AddTreasure(player, 0x09C4, 0x00, 0x00, 0x00, 0xC2, 0x76); L0067: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold5, 0x01); L007C: ShowMessage(player, doMsgs, String0839); // Your movement disturbs the dead who have guarded King Cleowyn's Treasury. L0089: Compare(PartyCount(player), 0x0001); L0094: if (JumpNotEqual) goto L00BD; L0096: AddEncounter(player, 0x01, 0x08); L00A8: AddEncounter(player, 0x02, 0x0D); L00BA: goto L016E; L00BD: Compare(PartyCount(player), 0x0002); L00C8: if (JumpNotEqual) goto L0102; L00CA: AddEncounter(player, 0x01, 0x09); L00DC: AddEncounter(player, 0x02, 0x0E); L00EE: AddEncounter(player, 0x03, 0x06); L0100: goto L016E; L0102: AddEncounter(player, 0x01, 0x0B); L0114: AddEncounter(player, 0x02, 0x0A); L0126: AddEncounter(player, 0x03, 0x05); L0138: AddEncounter(player, 0x04, 0x06); L014A: AddEncounter(player, 0x05, 0x12); L015C: AddEncounter(player, 0x06, 0x13); L016E: return; // RETURN; } private void FnTRAPDORA_0D(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0005); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008D; L0063: ShowMessage(player, doMsgs, String0883); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0x85, 0x01, type); L008B: goto L00B5; L008D: ShowMessage(player, doMsgs, String08D3); // A trapdoor in the floor opens. L009A: TeleportParty(player, 0x02, 0x01, 0x85, 0x01, type); L00B5: return; // RETURN; } private void FnTRAPDORB_0E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0005); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008D; L0063: ShowMessage(player, doMsgs, String08F2); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0x86, 0x01, type); L008B: goto L00B5; L008D: ShowMessage(player, doMsgs, String0942); // A trapdoor in the floor opens. L009A: TeleportParty(player, 0x02, 0x01, 0x86, 0x01, type); L00B5: return; // RETURN; } private void FnTRAPDORC_0F(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0006); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008D; L0063: ShowMessage(player, doMsgs, String0961); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0x98, 0x02, type); L008B: goto L00B5; L008D: ShowMessage(player, doMsgs, String09B1); // A trapdoor in the floor opens. L009A: TeleportParty(player, 0x02, 0x01, 0x98, 0x02, type); L00B5: return; // RETURN; } private void FnTRAPDORD_10(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0006); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008C; L0063: ShowMessage(player, doMsgs, String09D0); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0xA6, 0x00, type); L008A: goto L00B3; L008C: ShowMessage(player, doMsgs, String0A20); // A trapdoor in the floor opens. L0099: TeleportParty(player, 0x02, 0x01, 0xA6, 0x00, type); L00B3: return; // RETURN; } private void FnTRAPDORE_11(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0007); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0077; L004E: ShowMessage(player, doMsgs, String0A3F); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, 0xA8, 0x00, type); L0075: goto L009E; L0077: ShowMessage(player, doMsgs, String0A8F); // A trapdoor in the floor opens. L0084: TeleportParty(player, 0x02, 0x01, 0xA8, 0x00, type); L009E: return; // RETURN; } private void FnTRAPDORF_12(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0008); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0078; L004E: ShowMessage(player, doMsgs, String0AAE); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, 0xB5, 0x02, type); L0076: goto L00A0; L0078: ShowMessage(player, doMsgs, String0AFE); // A trapdoor in the floor opens. L0085: TeleportParty(player, 0x02, 0x01, 0xB5, 0x02, type); L00A0: return; // RETURN; } private void FnTRAPDORG_13(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0005); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008D; L0063: ShowMessage(player, doMsgs, String0B1D); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0xC7, 0x01, type); L008B: goto L00B5; L008D: ShowMessage(player, doMsgs, String0B6D); // A trapdoor in the floor opens. L009A: TeleportParty(player, 0x02, 0x01, 0xC7, 0x01, type); L00B5: return; // RETURN; } private void FnTRAPDORH_14(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0009); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0077; L004E: ShowMessage(player, doMsgs, String0B8C); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, 0xCF, 0x00, type); L0075: goto L009E; L0077: ShowMessage(player, doMsgs, String0BDC); // A trapdoor in the floor opens. L0084: TeleportParty(player, 0x02, 0x01, 0xCF, 0x00, type); L009E: return; // RETURN; } private void FnTRAPDOR_15(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0006); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008C; L0063: ShowMessage(player, doMsgs, String0BFB); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0xD6, 0x00, type); L008A: goto L00B3; L008C: ShowMessage(player, doMsgs, String0C4B); // A trapdoor in the floor opens. L0099: TeleportParty(player, 0x02, 0x01, 0xD6, 0x00, type); L00B3: return; // RETURN; } private void FnTRAPDORJ_16(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x000A); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0078; L004E: ShowMessage(player, doMsgs, String0C6A); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, 0xD8, 0x03, type); L0076: goto L00A0; L0078: ShowMessage(player, doMsgs, String0CBA); // A trapdoor in the floor opens. L0085: TeleportParty(player, 0x02, 0x01, 0xD8, 0x03, type); L00A0: return; // RETURN; } private void FnTRAPDORK_17(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0006); L0012: if (JumpNotBelow) goto L0063; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L0063; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L0063; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBD, 0xBD); L004C: if (JumpNotEqual) goto L0063; L004E: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L0061: if (JumpEqual) goto L008D; L0063: ShowMessage(player, doMsgs, String0CD9); // You detect a trapdoor in the floor, but not in time to prevent falling through! L0070: TeleportParty(player, 0x02, 0x01, 0xE9, 0x03, type); L008B: goto L00B5; L008D: ShowMessage(player, doMsgs, String0D29); // A trapdoor in the floor opens. L009A: TeleportParty(player, 0x02, 0x01, 0xE9, 0x03, type); L00B5: return; // RETURN; } private void FnTRAPDORL_18(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x000B); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0077; L004E: ShowMessage(player, doMsgs, String0D48); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, 0xEB, 0x00, type); L0075: goto L009E; L0077: ShowMessage(player, doMsgs, String0D98); // A trapdoor in the floor opens. L0084: TeleportParty(player, 0x02, 0x01, 0xEB, 0x00, type); L009E: return; // RETURN; } private void FnTRAPDORM_19(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x0008); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0077; L004E: ShowMessage(player, doMsgs, String0DB7); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, YsIndexes.ItemRanbowGemYellow, 0x00, type); L0075: goto L009E; L0077: ShowMessage(player, doMsgs, String0E07); // A trapdoor in the floor opens. L0084: TeleportParty(player, 0x02, 0x01, YsIndexes.ItemRanbowGemYellow, 0x00, type); L009E: return; // RETURN; } private void FnTRAPDORN_1A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0D), 0x000A); L0012: if (JumpNotBelow) goto L004E; L0014: RefreshCompareFlags(HasUsedSpell(player, type, ref doMsgs, 0x17)); L0022: if (JumpNotEqual) goto L004E; L0024: ax = HasUsedItem(player, type, ref doMsgs, 0xA2, 0xA2); L0037: if (JumpNotEqual) goto L004E; L0039: ax = HasUsedItem(player, type, ref doMsgs, 0xBE, 0xBE); L004C: if (JumpEqual) goto L0078; L004E: ShowMessage(player, doMsgs, String0E26); // You detect a trapdoor in the floor, but not in time to prevent falling through! L005B: TeleportParty(player, 0x02, 0x01, 0xF7, 0x02, type); L0076: goto L00A0; L0078: ShowMessage(player, doMsgs, String0E76); // A trapdoor in the floor opens. L0085: TeleportParty(player, 0x02, 0x01, 0xF7, 0x02, type); L00A0: return; // RETURN; } private void FnTUFMNSTR_1B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpEqual) goto L001D; L0010: Compare(PartyCount(player), 0x0002); L001B: if (JumpNotEqual) goto L0043; L001D: AddEncounter(player, 0x01, 0x1A); L002F: AddEncounter(player, 0x02, 0x1A); L0041: goto L009D; L0043: AddEncounter(player, 0x01, 0x1D); L0055: AddEncounter(player, 0x02, 0x1D); L0067: AddEncounter(player, 0x03, 0x1C); L0079: AddEncounter(player, 0x04, 0x1E); L008B: AddEncounter(player, 0x05, 0x1E); L009D: return; // RETURN; } private void FnGOLDENCA_1E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold), 0x0001); L0017: if (JumpNotEqual) goto L0046; L0019: ShowMessage(player, doMsgs, String0E95); // Ghosts haunt the empty room. L0026: AddTreasure(player, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x73); L0044: goto L0087; L0046: AddTreasure(player, 0x0FA0, 0x00, 0x00, 0x00, 0x00, 0xCE); L0065: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold, 0x01); L007A: ShowMessage(player, doMsgs, String0EB2); // Spirits of the dead guard King Cleowyn's gold. L0087: Compare(PartyCount(player), 0x0001); L0092: if (JumpEqual) goto L00A1; L0094: Compare(PartyCount(player), 0x0002); L009F: if (JumpNotEqual) goto L00C7; L00A1: AddEncounter(player, 0x01, 0x0F); L00B3: AddEncounter(player, 0x02, 0x10); L00C5: goto L010F; L00C7: AddEncounter(player, 0x01, 0x10); L00D9: AddEncounter(player, 0x02, 0x11); L00EB: AddEncounter(player, 0x03, 0x11); L00FD: AddEncounter(player, 0x04, 0x10); L010F: return; // RETURN; } private void FnGOLDBENC_1F(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold2), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: ShowMessage(player, doMsgs, String0EE1); // Bones of dead guards and one-time thieves rise to challenge you. L0026: AddTreasure(player, 0x00FA, 0x00, 0x00, 0x00, 0x00, 0xB5); L0045: goto L0088; L0047: AddTreasure(player, 0x1388, 0x00, 0x00, 0x00, 0x00, 0xCB); L0066: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold2, 0x01); L007B: ShowMessage(player, doMsgs, String0F22); // Skeletons of dead guards and the thieves they killed stand between you and Cleowyn's gold. L0088: Compare(PartyCount(player), 0x0001); L0093: if (JumpNotEqual) goto L00BC; L0095: AddEncounter(player, 0x01, 0x03); L00A7: AddEncounter(player, 0x02, 0x02); L00B9: goto L01D7; L00BC: Compare(PartyCount(player), 0x0002); L00C7: if (JumpNotEqual) goto L0102; L00C9: AddEncounter(player, 0x01, 0x03); L00DB: AddEncounter(player, 0x02, 0x01); L00ED: AddEncounter(player, 0x03, 0x03); L00FF: goto L01D7; L0102: Compare(PartyCount(player), 0x0003); L010D: if (JumpNotEqual) goto L016B; L010F: AddEncounter(player, 0x01, 0x04); L0121: AddEncounter(player, 0x02, 0x02); L0133: AddEncounter(player, 0x03, 0x04); L0145: AddEncounter(player, 0x04, 0x03); L0157: AddEncounter(player, 0x06, 0x01); L0169: goto L01D7; L016B: AddEncounter(player, 0x01, 0x04); L017D: AddEncounter(player, 0x02, 0x04); L018F: AddEncounter(player, 0x03, 0x03); L01A1: AddEncounter(player, 0x04, 0x03); L01B3: AddEncounter(player, 0x05, 0x02); L01C5: AddEncounter(player, 0x06, 0x02); L01D7: return; // RETURN; } private void FnGOLDCENC_20(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold3), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: ShowMessage(player, doMsgs, String0F7D); // Spiders drop from the ceiling. L0026: AddTreasure(player, 0x00C8, 0x00, 0x00, 0x00, 0x00, 0xCE); L0045: goto L0088; L0047: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0x00, 0xBD); L0066: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagTreasuryKingsGold3, 0x01); L007B: ShowMessage(player, doMsgs, String0F9C); // Spider webs envelop a pile of gold pieces on the floor. L0088: Compare(PartyCount(player), 0x0001); L0093: if (JumpNotEqual) goto L00BC; L0095: AddEncounter(player, 0x01, 0x16); L00A7: AddEncounter(player, 0x02, 0x16); L00B9: goto L015B; L00BC: Compare(PartyCount(player), 0x0002); L00C7: if (JumpNotEqual) goto L0101; L00C9: AddEncounter(player, 0x01, 0x17); L00DB: AddEncounter(player, 0x02, 0x16); L00ED: AddEncounter(player, 0x03, 0x17); L00FF: goto L015B; L0101: AddEncounter(player, 0x01, 0x16); L0113: AddEncounter(player, 0x02, 0x16); L0125: AddEncounter(player, 0x03, 0x17); L0137: AddEncounter(player, 0x04, 0x17); L0149: AddEncounter(player, 0x05, 0x18); L015B: return; // RETURN; } } }
//------------------------------------------------------------------------------ // <copyright file="ReferenceConverter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.ComponentModel { using Microsoft.Win32; using System.Collections; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Serialization.Formatters; using System.Security.Permissions; /// <devdoc> /// <para>Provides a type converter to convert object references to and from various /// other representations.</para> /// </devdoc> [HostProtection(SharedState = true)] public class ReferenceConverter : TypeConverter { private static readonly string none = SR.GetString(SR.toStringNone); private Type type; /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.ReferenceConverter'/> class. /// </para> /// </devdoc> public ReferenceConverter(Type type) { this.type = type; } /// <internalonly/> /// <devdoc> /// <para>Gets a value indicating whether this converter can convert an object in the /// given source type to a reference object using the specified context.</para> /// </devdoc> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string) && context != null) { return true; } return base.CanConvertFrom(context, sourceType); } /// <internalonly/> /// <devdoc> /// <para>Converts the given object to the reference type.</para> /// </devdoc> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string text = ((string)value).Trim(); if (!String.Equals(text, none) && context != null) { // Try the reference service first. // IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { object obj = refSvc.GetReference(text); if (obj != null) { return obj; } } // Now try IContainer // IContainer cont = context.Container; if (cont != null) { object obj = cont.Components[text]; if (obj != null) { return obj; } } } return null; } return base.ConvertFrom(context, culture, value); } /// <internalonly/> /// <devdoc> /// <para>Converts the given value object to the reference type /// using the specified context and arguments.</para> /// </devdoc> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (value != null) { // Try the reference service first. // if (context != null) { IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { string name = refSvc.GetName(value); if (name != null) { return name; } } } #if !MOBILE // Now see if this is an IComponent. // if (!Marshal.IsComObject(value) && value is IComponent) { IComponent comp = (IComponent)value; ISite site = comp.Site; if (site != null) { string name = site.Name; if (name != null) { return name; } } } // Couldn't find it. return String.Empty; #endif } return none; } return base.ConvertTo(context, culture, value, destinationType); } /// <internalonly/> /// <devdoc> /// <para>Gets a collection of standard values for the reference data type.</para> /// </devdoc> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { object[] components = null; if (context != null) { ArrayList list = new ArrayList(); list.Add(null); // Try the reference service first. // IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { object[] objs = refSvc.GetReferences(type); int count = objs.Length; for (int i = 0; i < count; i++) { if (IsValueAllowed(context, objs[i])) list.Add(objs[i]); } } else { // Now try IContainer. // IContainer cont = context.Container; if (cont != null) { ComponentCollection objs = cont.Components; foreach(IComponent obj in objs) { if (obj != null && type.IsInstanceOfType(obj) && IsValueAllowed(context, obj)) { list.Add(obj); } } } } components = list.ToArray(); Array.Sort(components, 0, components.Length, new ReferenceComparer(this)); } return new StandardValuesCollection(components); } /// <internalonly/> /// <devdoc> /// <para>Gets a value indicating whether the list of standard values returned from /// <see cref='System.ComponentModel.ReferenceConverter.GetStandardValues'/> is an exclusive list. </para> /// </devdoc> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } /// <internalonly/> /// <devdoc> /// <para>Gets a value indicating whether this object supports a standard set of values /// that can be picked from a list.</para> /// </devdoc> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } /// <devdoc> /// <para>Gets a value indicating whether a particular value can be added to /// the standard values collection.</para> /// </devdoc> protected virtual bool IsValueAllowed(ITypeDescriptorContext context, object value) { return true; } /// <devdoc> /// IComparer object used for sorting references /// </devdoc> private class ReferenceComparer : IComparer { private ReferenceConverter converter; public ReferenceComparer(ReferenceConverter converter) { this.converter = converter; } public int Compare(object item1, object item2) { String itemName1 = converter.ConvertToString(item1); String itemName2 = converter.ConvertToString(item2); return string.Compare(itemName1, itemName2, false, CultureInfo.InvariantCulture); } } } }
// SharpMath - C# Mathematical Library // Copyright (c) 2012 Morten Bakkedal // This code is published under the MIT License. using System; using System.Diagnostics; using System.Globalization; namespace SharpMath { [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{ToString(),nq}")] public struct Complex : IEquatable<Complex> { private double re, im; static Complex() { I = new Complex(0.0, 1.0); } public Complex(double re, double im) { this.re = re; this.im = im; } public override string ToString() { if (im == 0.0) { return re.ToString(CultureInfo.InvariantCulture); } else if (im > 0.0) { return re.ToString(CultureInfo.InvariantCulture) + "+i" + im.ToString(CultureInfo.InvariantCulture); } else { return re.ToString(CultureInfo.InvariantCulture) + "-i" + (-im).ToString(CultureInfo.InvariantCulture); } } public override int GetHashCode() { unchecked { // Add the hash code of the pair as here: // http://stackoverflow.com/questions/892618/create-a-hashcode-of-two-numbers return (23 * 31 + re.GetHashCode()) * 31 + im.GetHashCode(); } } public bool Equals(Complex other) { return this == (Complex)other; } public override bool Equals(object other) { if (!(other is Complex)) { return false; } return Equals((Complex)other); } public static implicit operator Complex(double a) { return new Complex(a, 0.0); } public static explicit operator double(Complex z) { return z.re; } public static Complex operator +(Complex z1, Complex z2) { return new Complex(z1.re + z2.re, z1.im + z2.im); } public static Complex operator +(Complex z, double a) { return new Complex(z.re + a, z.im); } public static Complex operator +(double a, Complex z) { return new Complex(a + z.re, z.im); } public static Complex operator -(Complex z) { return new Complex(-z.re, -z.im); } public static Complex operator -(Complex z1, Complex z2) { return new Complex(z1.re - z2.re, z1.im - z2.im); } public static Complex operator -(Complex z, double a) { return new Complex(z.re - a, z.im); } public static Complex operator -(double a, Complex z) { return new Complex(a - z.re, -z.im); } public static Complex operator *(Complex z1, Complex z2) { return new Complex(z1.re * z2.re - z1.im * z2.im, z1.im * z2.re + z1.re * z2.im); } public static Complex operator *(Complex z, double a) { return new Complex(z.re * a, z.im * a); } public static Complex operator *(double a, Complex z) { return new Complex(a * z.re, a * z.im); } public static Complex operator /(Complex z1, Complex z2) { double c = z2.re * z2.re + z2.im * z2.im; return new Complex((z1.re * z2.re + z1.im * z2.im) / c, (z1.im * z2.re - z1.re * z2.im) / c); } public static Complex operator /(Complex z, double a) { return new Complex(z.re / a, z.im / a); } public static Complex operator /(double a, Complex z) { double c = z.re * z.re + z.im * z.im; return new Complex(a * z.re / c, -a * z.im / c); } public static bool operator ==(Complex z1, Complex z2) { return z1.re == z2.re && z1.im == z2.im; } public static bool operator !=(Complex z1, Complex z2) { return !(z1 == z2); } public static double Re(Complex z) { return z.re; } public static double Im(Complex z) { return z.im; } public static Complex Polar(double r, double theta) { return new Complex(r * Math.Cos(theta), r * Math.Sin(theta)); } public static Complex Conjugate(Complex z) { return new Complex(z.re, -z.im); } public static double Abs(Complex z) { return Math.Sqrt(z.re * z.re + z.im * z.im); } public static Complex Exp(Complex z) { double c = Math.Exp(z.re); if (z.im == 0.0) { return new Complex(c, 0.0); } else { return new Complex(c * Math.Cos(z.im), c * Math.Sin(z.im)); } } public static Complex Sqr(Complex z) { return new Complex(z.re * z.re - z.im * z.im, 2.0 * z.re * z.im); } /// <summary> /// Computes the principal square root. Discontinuity at the negative real axis. /// </summary> public static Complex Sqrt(Complex z) { // Using this identity: // http://en.wikipedia.org/w/index.php?title=Square_root&oldid=500359963#Algebraic_formula if (z.im != 0.0) { double c = Complex.Abs(z) + z.re; return new Complex(Math.Sqrt(0.5 * c), z.im / Math.Sqrt(2.0 * c)); } else if (z.re >= 0.0) { return new Complex(Math.Sqrt(z.re), 0.0); } else { return new Complex(0.0, Math.Sqrt(-z.re)); } } public static double Arg(Complex z) { if (z.re > 0.0 || z.im != 0.0) { return 2.0 * Math.Atan2(z.im, Abs(z) + z.re); } else if (z.re < 0.0 && z.im == 0.0) { return Math.PI; } else { return double.NaN; } } public static Complex Log(Complex z) { return new Complex(0.5 * Math.Log(z.re * z.re + z.im * z.im), Arg(z)); } public static Complex I { get; private set; } } }
using newtelligence.DasBlog.Runtime; namespace newtelligence.DasBlog.Web.Services.InstantArticle { using System; using System.Xml; using System.Xml.Serialization; [XmlType(Namespace="", IncludeInSchema=false)] [XmlRoot("rss", Namespace= "http://purl.org/rss/1.0/modules/content/")] public class IARoot { [XmlNamespaceDeclarations] public XmlSerializerNamespaces Namespaces; private string version; private IAChannelCollection channels; public IARoot() { Namespaces = new XmlSerializerNamespaces(); channels = new IAChannelCollection(); version = "2.0"; } [XmlAttribute("version")] public string Version { get { return version; } set { version = value; } } [XmlElement("channel")] public IAChannelCollection Channels { get { return channels; } set { channels = value; } } } [XmlRoot("channel")] public class IAChannel { IAItemCollection items = new IAItemCollection(); [XmlElement("title")] public string Title { get; set; } [XmlElement("link")] public string Link { get; set; } [XmlElement("description", IsNullable=false)] public string Description { get; set; } [XmlElement("pubDate")] public string PubDate { get; set; } [XmlElement("lastBuildDate")] public string LastBuildDate { get; set; } [XmlElement("language")] public string Language { get; set; } [XmlElement("generator")] public string Generator { get; set; } [XmlElement("docs")] public string Docs { get; set; } [XmlElement("item")] public IAItemCollection Items { get { return items; } set { items = value; } } public IAChannel() { Generator = "newtelligence dasBlog "+GetType().Assembly.GetName().Version; } } [XmlRoot("item")] public class IAItem { [XmlElement("title")] public string Title { get; set; } [XmlElement("pubDate")] public string PubDate { get; set; } [XmlElement("link")] public string Link { get; set; } [XmlElement("guid")] public string Guid { get; set; } [XmlElement("description")] public string Description { get; set; } [XmlAnyElement] public XmlElement[] anyElements; } /// <summary> /// A collection of elements of type RssItem /// </summary> public class IAItemCollection: System.Collections.CollectionBase { /// <summary> /// Initializes a new empty instance of the RssItemCollection class. /// </summary> public IAItemCollection() { // empty } /// <summary> /// Initializes a new instance of the RssItemCollection class, containing elements /// copied from an array. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the new RssItemCollection. /// </param> public IAItemCollection(IAItem[] items) { this.AddRange(items); } /// <summary> /// Initializes a new instance of the RssItemCollection class, containing elements /// copied from another instance of RssItemCollection /// </summary> /// <param name="items"> /// The RssItemCollection whose elements are to be added to the new RssItemCollection. /// </param> public IAItemCollection(IAItemCollection items) { this.AddRange(items); } /// <summary> /// Adds the elements of an array to the end of this RssItemCollection. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the end of this RssItemCollection. /// </param> public virtual void AddRange(IAItem[] items) { foreach (IAItem item in items) { this.List.Add(item); } } /// <summary> /// Adds the elements of another RssItemCollection to the end of this RssItemCollection. /// </summary> /// <param name="items"> /// The RssItemCollection whose elements are to be added to the end of this RssItemCollection. /// </param> public virtual void AddRange(IAItemCollection items) { foreach (IAItem item in items) { this.List.Add(item); } } /// <summary> /// Adds an instance of type RssItem to the end of this RssItemCollection. /// </summary> /// <param name="value"> /// The RssItem to be added to the end of this RssItemCollection. /// </param> public virtual void Add(IAItem value) { this.List.Add(value); } /// <summary> /// Determines whether a specfic RssItem value is in this RssItemCollection. /// </summary> /// <param name="value"> /// The RssItem value to locate in this RssItemCollection. /// </param> /// <returns> /// true if value is found in this RssItemCollection; /// false otherwise. /// </returns> public virtual bool Contains(IAItem value) { return this.List.Contains(value); } /// <summary> /// Return the zero-based index of the first occurrence of a specific value /// in this RssItemCollection /// </summary> /// <param name="value"> /// The RssItem value to locate in the RssItemCollection. /// </param> /// <returns> /// The zero-based index of the first occurrence of the _ELEMENT value if found; /// -1 otherwise. /// </returns> public virtual int IndexOf(IAItem value) { return this.List.IndexOf(value); } /// <summary> /// Inserts an element into the RssItemCollection at the specified index /// </summary> /// <param name="index"> /// The index at which the RssItem is to be inserted. /// </param> /// <param name="value"> /// The RssItem to insert. /// </param> public virtual void Insert(int index, IAItem value) { this.List.Insert(index, value); } /// <summary> /// Gets or sets the RssItem at the given index in this RssItemCollection. /// </summary> public virtual IAItem this[int index] { get { return (IAItem) this.List[index]; } set { this.List[index] = value; } } /// <summary> /// Removes the first occurrence of a specific RssItem from this RssItemCollection. /// </summary> /// <param name="value"> /// The RssItem value to remove from this RssItemCollection. /// </param> public virtual void Remove(IAItem value) { this.List.Remove(value); } /// <summary> /// Type-specific enumeration class, used by RssItemCollection.GetEnumerator. /// </summary> public class Enumerator: System.Collections.IEnumerator { private System.Collections.IEnumerator wrapped; public Enumerator(IAItemCollection collection) { this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator(); } public IAItem Current { get { return (IAItem) (this.wrapped.Current); } } object System.Collections.IEnumerator.Current { get { return (IAItem) (this.wrapped.Current); } } public bool MoveNext() { return this.wrapped.MoveNext(); } public void Reset() { this.wrapped.Reset(); } } /// <summary> /// Returns an enumerator that can iterate through the elements of this RssItemCollection. /// </summary> /// <returns> /// An object that implements System.Collections.IEnumerator. /// </returns> public new virtual IAItemCollection.Enumerator GetEnumerator() { return new IAItemCollection.Enumerator(this); } } /// <summary> /// A collection of elements of type RssChannel /// </summary> public class IAChannelCollection: System.Collections.CollectionBase { /// <summary> /// Initializes a new empty instance of the RssChannelCollection class. /// </summary> public IAChannelCollection() { // empty } /// <summary> /// Initializes a new instance of the RssChannelCollection class, containing elements /// copied from an array. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the new RssChannelCollection. /// </param> public IAChannelCollection(IAChannel[] items) { this.AddRange(items); } /// <summary> /// Initializes a new instance of the RssChannelCollection class, containing elements /// copied from another instance of RssChannelCollection /// </summary> /// <param name="items"> /// The RssChannelCollection whose elements are to be added to the new RssChannelCollection. /// </param> public IAChannelCollection(IAChannelCollection items) { this.AddRange(items); } /// <summary> /// Adds the elements of an array to the end of this RssChannelCollection. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the end of this RssChannelCollection. /// </param> public virtual void AddRange(IAChannel[] items) { foreach (IAChannel item in items) { this.List.Add(item); } } /// <summary> /// Adds the elements of another RssChannelCollection to the end of this RssChannelCollection. /// </summary> /// <param name="items"> /// The RssChannelCollection whose elements are to be added to the end of this RssChannelCollection. /// </param> public virtual void AddRange(IAChannelCollection items) { foreach (IAChannel item in items) { this.List.Add(item); } } /// <summary> /// Adds an instance of type RssChannel to the end of this RssChannelCollection. /// </summary> /// <param name="value"> /// The RssChannel to be added to the end of this RssChannelCollection. /// </param> public virtual void Add(IAChannel value) { this.List.Add(value); } /// <summary> /// Determines whether a specfic RssChannel value is in this RssChannelCollection. /// </summary> /// <param name="value"> /// The RssChannel value to locate in this RssChannelCollection. /// </param> /// <returns> /// true if value is found in this RssChannelCollection; /// false otherwise. /// </returns> public virtual bool Contains(IAChannel value) { return this.List.Contains(value); } /// <summary> /// Return the zero-based index of the first occurrence of a specific value /// in this RssChannelCollection /// </summary> /// <param name="value"> /// The RssChannel value to locate in the RssChannelCollection. /// </param> /// <returns> /// The zero-based index of the first occurrence of the _ELEMENT value if found; /// -1 otherwise. /// </returns> public virtual int IndexOf(IAChannel value) { return this.List.IndexOf(value); } /// <summary> /// Inserts an element into the RssChannelCollection at the specified index /// </summary> /// <param name="index"> /// The index at which the RssChannel is to be inserted. /// </param> /// <param name="value"> /// The RssChannel to insert. /// </param> public virtual void Insert(int index, IAChannel value) { this.List.Insert(index, value); } /// <summary> /// Gets or sets the RssChannel at the given index in this RssChannelCollection. /// </summary> public virtual IAChannel this[int index] { get { return (IAChannel) this.List[index]; } set { this.List[index] = value; } } /// <summary> /// Removes the first occurrence of a specific RssChannel from this RssChannelCollection. /// </summary> /// <param name="value"> /// The RssChannel value to remove from this RssChannelCollection. /// </param> public virtual void Remove(IAChannel value) { this.List.Remove(value); } /// <summary> /// Type-specific enumeration class, used by RssChannelCollection.GetEnumerator. /// </summary> public class Enumerator: System.Collections.IEnumerator { private System.Collections.IEnumerator wrapped; public Enumerator(IAChannelCollection collection) { this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator(); } public IAChannel Current { get { return (IAChannel) (this.wrapped.Current); } } object System.Collections.IEnumerator.Current { get { return (IAChannel) (this.wrapped.Current); } } public bool MoveNext() { return this.wrapped.MoveNext(); } public void Reset() { this.wrapped.Reset(); } } /// <summary> /// Returns an enumerator that can iterate through the elements of this RssChannelCollection. /// </summary> /// <returns> /// An object that implements System.Collections.IEnumerator. /// </returns> public new virtual IAChannelCollection.Enumerator GetEnumerator() { return new IAChannelCollection.Enumerator(this); } } }
/* * Copyright (c) Contributors, VPGsim Project http://fernseed.usu.edu/ * 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 VPGsim 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.Net; using System.IO; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace vpgSoilModule { public class vpgSoilModule : IvpgSoilModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); bool m_enabled = true; bool m_localFiles = true; string m_soilXPath = "addon-modules/vpgsim/soil/DefaultSoilX.txt"; string m_soilYPath = "addon-modules/vpgsim/soil/DefaultSoilY.txt"; string m_soilZPath = "addon-modules/vpgsim/soil/DefaultSoilZ.txt"; private Vector3[] m_soilType = new Vector3[256 * 256]; public void Initialise(Scene scene, IConfigSource config) { IConfig vpgSoilConfig = config.Configs["vpgSoil"]; if (vpgSoilConfig != null) { m_enabled = vpgSoilConfig.GetBoolean("enabled", true); m_localFiles = vpgSoilConfig.GetBoolean("local_files", true); m_soilXPath = vpgSoilConfig.GetString("soil_x_path", "addon-modules/vpgsim/soil/DefaultSoilX.txt"); m_soilYPath = vpgSoilConfig.GetString("soil_y_path", "addon-modules/vpgsim/soil/DefaultSoilY.txt"); m_soilZPath = vpgSoilConfig.GetString("soil_z_path", "addon-modules/vpgsim/soil/DefaultSoilZ.txt"); } if (m_enabled) { scene.RegisterModuleInterface<IvpgSoilModule>(this); GenerateSoilType(); } } public void PostInitialise() { } public void Close() { } public string Name { get { return "vpgSoilModule"; } } public bool IsSharedModule { get { return false; } } public Vector3 SoilType(int x, int y, int z) { Vector3 type = new Vector3(0f, 0f, 0f); if (x < 0) x = 0; if (x > 255) x = 255; if (y < 0) y = 0; if (y > 255) y = 255; if (m_soilType != null) { type = m_soilType[y * 256 + x]; } return type; } /// <summary> /// Calculate the soil type across the region. /// </summary> private void GenerateSoilType() { string[] soilX = new string[256*256]; string[] soilY = new string[256*256]; string[] soilZ = new string[256*256]; if (m_localFiles) //Read from a local file { if (System.IO.File.Exists(m_soilXPath)) { soilX = System.IO.File.ReadAllLines(m_soilXPath); m_log.Info("[vpgSoil] Loaded Soil.X values from " + m_soilXPath); } else { m_log.Info("[vpgSoil] " + m_soilXPath + " not found. Loaded default values for Soil.X"); for(int index=0; index<256*256; index++) { soilX[index] = "0.5"; //If no soil values are available, use 0.5 } } if (System.IO.File.Exists(m_soilYPath)) { soilY = System.IO.File.ReadAllLines(m_soilYPath); m_log.Info("[vpgSoil] Loaded Soil.Y values from " + m_soilYPath); } else { m_log.Info("[vpgSoil] " + m_soilYPath + " not found. Loaded default values for Soil.Y"); for(int index=0; index<256*256; index++) { soilY[index] = "0.5"; //If no soil values are available, use 0.5 } } if (System.IO.File.Exists(m_soilZPath)) { soilZ = System.IO.File.ReadAllLines(m_soilZPath); m_log.Info("[vpgSoil] Loaded Soil.Z values from " + m_soilZPath); } else { m_log.Info("[vpgSoil] " + m_soilZPath + " not found. Loaded default values for Soil.Z"); for(int index=0; index<256*256; index++) { soilZ[index] = "0.5"; //If no soil values are available, use 0.5 } } } else //read from a url { WebRequest soilUrl = WebRequest.Create(m_soilXPath); try { StreamReader urlData = new StreamReader(soilUrl.GetResponse().GetResponseStream()); int lineCounter = 0; string line; while ((line = urlData.ReadLine()) != null) { soilX[lineCounter] = line; lineCounter++; } m_log.Info("[vpgSoil] Loaded Soil.X values from " + m_soilXPath); } catch //failed to get the data for some reason { m_log.Info("[vpgSoil] " + m_soilXPath + " not found. Loaded default values for Soil.X"); for(int index=0; index<256*256; index++) { soilX[index] = "0.5"; //If no soil values are available, use 0.5 } } soilUrl = WebRequest.Create(m_soilYPath); try { StreamReader urlData = new StreamReader(soilUrl.GetResponse().GetResponseStream()); int lineCounter = 0; string line; while ((line = urlData.ReadLine()) != null) { soilY[lineCounter] = line; lineCounter++; } m_log.Info("[vpgSoil] Loaded Soil.Y values from " + m_soilYPath); } catch //failed to get the data for some reason { m_log.Info("[vpgSoil] " + m_soilYPath + " not found. Loaded default values for Soil.Y"); for(int index=0; index<256*256; index++) { soilY[index] = "0.5"; //If no soil values are available, use 0.5 } } soilUrl = WebRequest.Create(m_soilZPath); try { StreamReader urlData = new StreamReader(soilUrl.GetResponse().GetResponseStream()); int lineCounter = 0; string line; while ((line = urlData.ReadLine()) != null) { soilZ[lineCounter] = line; lineCounter++; } m_log.Info("[vpgSoil] Loaded Soil.Z values from " + m_soilZPath); } catch //failed to get the data for some reason { m_log.Info("[vpgSoil] " + m_soilZPath + " not found. Loaded default values for Soil.Z"); for(int index=0; index<256*256; index++) { soilZ[index] = "0.5"; //If no soil values are available, use 0.5 } } } for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { int index = y * 256 + x; m_soilType[index] = new Vector3(Convert.ToSingle(soilX[index]), Convert.ToSingle(soilY[index]), Convert.ToSingle(soilZ[index])); } } } } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion; using GitVersionCore.Tests; using LibGit2Sharp; using NUnit.Framework; [TestFixture] public class FeatureBranchScenarios { [Test] public void ShouldInheritIncrementCorrectlyWithMultiplePossibleParentsAndWeirdlyNamedDevelopBranch() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("development"); Commands.Checkout(fixture.Repository, "development"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "development"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-JIRA-124.1+2"); } } [Test] public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly() { var config = new Config { Branches = { { "unstable", new BranchConfig { Increment = IncrementStrategy.Minor, Regex = "unstable"} } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("unstable"); Commands.Checkout(fixture.Repository, "unstable"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "unstable"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver(config, "1.1.0-JIRA-124.1+2"); } } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffDevelop() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.1.0-JIRA-123.1+5"); } } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffMaster() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-JIRA-123.1+5"); } } [Test] public void TestFeatureBranch() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature-test"); Commands.Checkout(fixture.Repository, "feature-test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } } [Test] public void TestFeaturesBranch() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("features/test"); Commands.Checkout(fixture.Repository, "features/test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } } [Test] public void WhenTwoFeatureBranchPointToTheSameCommit() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/feature1"); Commands.Checkout(fixture.Repository, "feature/feature1"); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("feature/feature2"); Commands.Checkout(fixture.Repository, "feature/feature2"); fixture.AssertFullSemver("0.1.0-feature2.1+1"); } } [Test] public void ShouldBePossibleToMergeDevelopForALongRunningBranchWhereDevelopAndMasterAreEqual() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("v1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/longrunning"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "master"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); fixture.Repository.ApplyTag("v1.1.0"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); var configuration = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; fixture.AssertFullSemver(configuration, "1.2.0-longrunning.2"); } } [TestCase("alpha", "JIRA-123", "alpha")] [TestCase("useBranchName", "JIRA-123", "JIRA-123")] [TestCase("alpha.{BranchName}", "JIRA-123", "alpha.JIRA-123")] public void ShouldUseConfiguredTag(string tag, string featureName, string preReleaseTagName) { var config = new Config { Branches = { { "feature", new BranchConfig { Tag = tag } } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); var featureBranchName = string.Format("feature/{0}", featureName); fixture.Repository.CreateBranch(featureBranchName); Commands.Checkout(fixture.Repository, featureBranchName); fixture.Repository.MakeCommits(5); var expectedFullSemVer = string.Format("1.0.1-{0}.1+5", preReleaseTagName); fixture.AssertFullSemver(config, expectedFullSemVer); } } [Test] public void BranchCreatedAfterFinishReleaseShouldInheritAndIncrementFromLastMasterCommitTag() { using (var fixture = new BaseGitFlowRepositoryFixture("0.1.0")) { //validate current version fixture.AssertFullSemver("0.2.0-alpha.1"); fixture.Repository.CreateBranch("release/0.2.0"); Commands.Checkout(fixture.Repository, "release/0.2.0"); //validate release version fixture.AssertFullSemver("0.2.0-beta.1+0"); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.ApplyTag("0.2.0"); //validate master branch version fixture.AssertFullSemver("0.2.0"); fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.Branches.Remove("release/2.0.0"); fixture.Repository.MakeACommit(); //validate develop branch version after merging release 0.2.0 to master and develop (finish release) fixture.AssertFullSemver("0.3.0-alpha.1"); //create a feature branch from develop fixture.BranchTo("feature/TEST-1"); fixture.Repository.MakeACommit(); //I'm not entirely sure what the + value should be but I know the semvar major/minor/patch should be 0.3.0 fixture.AssertFullSemver("0.3.0-TEST-1.1+2"); } } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchCreated() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+1"); } } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+2"); } } public class WhenMasterMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "1.0.1+1"); // create a feature branch from master and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver(config, "1.0.1-test.1+1"); } } [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into master fixture.Checkout("master"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver(config, "1.0.1+2"); // create a feature branch from master and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver(config, "1.0.1-test.1+2"); } } } public class WhenFeatureBranchHasNoConfig { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+1"); } } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+2"); } } // ReSharper disable once MemberHidesStaticFromOuterClass public class WhenMasterMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "1.0.1+1"); // create a misnamed feature branch (i.e. it uses the default config) from master and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver(config, "1.0.1-misnamed.1+1"); } } [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into master fixture.Checkout("master"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver(config, "1.0.1+2"); // create a misnamed feature branch (i.e. it uses the default config) from master and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver(config, "1.0.1-misnamed.1+2"); } } } } [Test] public void PickUpVersionFromMasterMarkedWithIsTracksReleaseBranches() { var config = new Config { VersioningMode = VersioningMode.ContinuousDelivery, Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { Tag = "pre", TracksReleaseBranches = true, } }, { "release", new BranchConfig() { IsReleaseBranch = true, Tag = "rc", } } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.MakeACommit(); // create a release branch and tag a release fixture.BranchTo("release/0.10.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver(config, "0.10.0-rc.1+2"); // switch to master and verify the version fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "0.10.1-pre.1+1"); // create a feature branch from master and verify the version fixture.BranchTo("MyFeatureD"); fixture.AssertFullSemver(config, "0.10.1-MyFeatureD.1+1"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class VirtualMachineExtensionsOperationsExtensions { /// <summary> /// The operation to create or update the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be create or /// updated. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='extensionParameters'> /// Parameters supplied to the Create Virtual Machine Extension operation. /// </param> public static VirtualMachineExtension CreateOrUpdate(this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, VirtualMachineExtension extensionParameters) { return Task.Factory.StartNew(s => ((IVirtualMachineExtensionsOperations)s).CreateOrUpdateAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to create or update the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be create or /// updated. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='extensionParameters'> /// Parameters supplied to the Create Virtual Machine Extension operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualMachineExtension> CreateOrUpdateAsync( this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, VirtualMachineExtension extensionParameters, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// The operation to create or update the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be create or /// updated. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='extensionParameters'> /// Parameters supplied to the Create Virtual Machine Extension operation. /// </param> public static VirtualMachineExtension BeginCreateOrUpdate(this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, VirtualMachineExtension extensionParameters) { return Task.Factory.StartNew(s => ((IVirtualMachineExtensionsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to create or update the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be create or /// updated. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='extensionParameters'> /// Parameters supplied to the Create Virtual Machine Extension operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualMachineExtension> BeginCreateOrUpdateAsync( this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, VirtualMachineExtension extensionParameters, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// The operation to delete the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be deleted. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> public static void Delete(this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName) { Task.Factory.StartNew(s => ((IVirtualMachineExtensionsOperations)s).DeleteAsync(resourceGroupName, vmName, vmExtensionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to delete the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be deleted. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The operation to delete the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be deleted. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> public static void BeginDelete(this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName) { Task.Factory.StartNew(s => ((IVirtualMachineExtensionsOperations)s).BeginDeleteAsync(resourceGroupName, vmName, vmExtensionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to delete the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine where the extension should be deleted. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The operation to get the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine containing the extension. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. /// </param> public static VirtualMachineExtension Get(this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, string expand = default(string)) { return Task.Factory.StartNew(s => ((IVirtualMachineExtensionsOperations)s).GetAsync(resourceGroupName, vmName, vmExtensionName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to get the extension. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine containing the extension. /// </param> /// <param name='vmExtensionName'> /// The name of the virtual machine extension. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualMachineExtension> GetAsync( this IVirtualMachineExtensionsOperations operations, string resourceGroupName, string vmName, string vmExtensionName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vmName, vmExtensionName, expand, null, cancellationToken).ConfigureAwait(false); return _result.Body; } } }
using Discord.Rest; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; namespace Discord.WebSocket { /// <summary> /// Represents a WebSocket-based direct-message channel. /// </summary> [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class SocketDMChannel : SocketChannel, IDMChannel, ISocketPrivateChannel, ISocketMessageChannel { private readonly MessageCache _messages; /// <summary> /// Gets the recipient of the channel. /// </summary> public SocketUser Recipient { get; } /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>(); /// <summary> /// Gets a collection that is the current logged-in user and the recipient. /// </summary> public new IReadOnlyCollection<SocketUser> Users => ImmutableArray.Create(Discord.CurrentUser, Recipient); internal SocketDMChannel(DiscordSocketClient discord, ulong id, SocketGlobalUser recipient) : base(discord, id) { Recipient = recipient; recipient.GlobalUser.AddRef(); if (Discord.MessageCacheSize > 0) _messages = new MessageCache(Discord); } internal static SocketDMChannel Create(DiscordSocketClient discord, ClientState state, Model model) { var entity = new SocketDMChannel(discord, model.Id, discord.GetOrCreateUser(state, model.Recipients.Value[0])); entity.Update(state, model); return entity; } internal override void Update(ClientState state, Model model) { Recipient.Update(state, model.Recipients.Value[0]); } /// <inheritdoc /> public Task CloseAsync(RequestOptions options = null) => ChannelHelper.DeleteAsync(this, Discord, options); //Messages /// <inheritdoc /> public SocketMessage GetCachedMessage(ulong id) => _messages?.Get(id); /// <summary> /// Gets the message associated with the given <paramref name="id"/>. /// </summary> /// <param name="id">TThe ID of the message.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// The message gotten from either the cache or the download, or <c>null</c> if none is found. /// </returns> public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null) { IMessage msg = _messages?.Get(id); if (msg == null) msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false); return msg; } /// <summary> /// Gets the last N messages from this message channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(ulong, Direction, int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="fromMessageId">The ID of the starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(IMessage, Direction, int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="fromMessage">The starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit); /// <inheritdoc /> public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Discord, options); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// <inheritdoc /> public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// <inheritdoc /> public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options); /// <inheritdoc /> public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options); /// <inheritdoc /> public Task TriggerTypingAsync(RequestOptions options = null) => ChannelHelper.TriggerTypingAsync(this, Discord, options); /// <inheritdoc /> public IDisposable EnterTypingState(RequestOptions options = null) => ChannelHelper.EnterTypingState(this, Discord, options); internal void AddMessage(SocketMessage msg) => _messages?.Add(msg); internal SocketMessage RemoveMessage(ulong id) => _messages?.Remove(id); //Users /// <summary> /// Gets a user in this channel from the provided <paramref name="id"/>. /// </summary> /// <param name="id">The snowflake identifier of the user.</param> /// <returns> /// A <see cref="SocketUser"/> object that is a recipient of this channel; otherwise <c>null</c>. /// </returns> public new SocketUser GetUser(ulong id) { if (id == Recipient.Id) return Recipient; else if (id == Discord.CurrentUser.Id) return Discord.CurrentUser; else return null; } /// <summary> /// Returns the recipient user. /// </summary> public override string ToString() => $"@{Recipient}"; private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)"; internal new SocketDMChannel Clone() => MemberwiseClone() as SocketDMChannel; //SocketChannel /// <inheritdoc /> internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users; /// <inheritdoc /> internal override SocketUser GetUserInternal(ulong id) => GetUser(id); //IDMChannel /// <inheritdoc /> IUser IDMChannel.Recipient => Recipient; //ISocketPrivateChannel /// <inheritdoc /> IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => ImmutableArray.Create(Recipient); //IPrivateChannel /// <inheritdoc /> IReadOnlyCollection<IUser> IPrivateChannel.Recipients => ImmutableArray.Create<IUser>(Recipient); //IMessageChannel /// <inheritdoc /> async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetMessageAsync(id, options).ConfigureAwait(false); else return GetCachedMessage(id); } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options); /// <inheritdoc /> async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IChannel /// <inheritdoc /> string IChannel.Name => $"@{Recipient}"; /// <inheritdoc /> Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IUser>(GetUser(id)); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Dns { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RecordSetsOperations operations. /// </summary> public partial interface IRecordSetsOperations { /// <summary> /// Updates a record set within a DNS zone. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='zoneName'> /// The name of the DNS zone (without a terminating dot). /// </param> /// <param name='relativeRecordSetName'> /// The name of the record set, relative to the name of the zone. /// </param> /// <param name='recordType'> /// The type of DNS record in this record set. Possible values include: /// 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' /// </param> /// <param name='parameters'> /// Parameters supplied to the Update operation. /// </param> /// <param name='ifMatch'> /// The etag of the record set. Omit this value to always overwrite the /// current record set. Specify the last-seen etag value to prevent /// accidentally overwritting concurrent changes. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecordSet>> UpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a record set within a DNS zone. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='zoneName'> /// The name of the DNS zone (without a terminating dot). /// </param> /// <param name='relativeRecordSetName'> /// The name of the record set, relative to the name of the zone. /// </param> /// <param name='recordType'> /// The type of DNS record in this record set. Record sets of type SOA /// can be updated but not created (they are created when the DNS zone /// is created). Possible values include: 'A', 'AAAA', 'CNAME', 'MX', /// 'NS', 'PTR', 'SOA', 'SRV', 'TXT' /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate operation. /// </param> /// <param name='ifMatch'> /// The etag of the record set. Omit this value to always overwrite the /// current record set. Specify the last-seen etag value to prevent /// accidentally overwritting any concurrent changes. /// </param> /// <param name='ifNoneMatch'> /// Set to '*' to allow a new record set to be created, but to prevent /// updating an existing record set. Other values will be ignored. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecordSet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a record set from a DNS zone. This operation cannot be /// undone. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='zoneName'> /// The name of the DNS zone (without a terminating dot). /// </param> /// <param name='relativeRecordSetName'> /// The name of the record set, relative to the name of the zone. /// </param> /// <param name='recordType'> /// The type of DNS record in this record set. Record sets of type SOA /// cannot be deleted (they are deleted when the DNS zone is deleted). /// Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', /// 'SOA', 'SRV', 'TXT' /// </param> /// <param name='ifMatch'> /// The etag of the record set. Omit this value to always delete the /// current record set. Specify the last-seen etag value to prevent /// accidentally deleting any concurrent changes. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a record set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='zoneName'> /// The name of the DNS zone (without a terminating dot). /// </param> /// <param name='relativeRecordSetName'> /// The name of the record set, relative to the name of the zone. /// </param> /// <param name='recordType'> /// The type of DNS record in this record set. Possible values include: /// 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecordSet>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the record sets of a specified type in a DNS zone. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='zoneName'> /// The name of the DNS zone (without a terminating dot). /// </param> /// <param name='recordType'> /// The type of record sets to enumerate. Possible values include: 'A', /// 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' /// </param> /// <param name='top'> /// The maximum number of record sets to return. If not specified, /// returns up to 100 record sets. /// </param> /// <param name='recordsetnamesuffix'> /// The suffix label of the record set name that has to be used to /// filter the record set enumerations. If this parameter is specified, /// Enumeration will return only records that end with /// .&lt;recordSetNameSuffix&gt; /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeWithHttpMessagesAsync(string resourceGroupName, string zoneName, RecordType recordType, int? top = default(int?), string recordsetnamesuffix = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all record sets in a DNS zone. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='zoneName'> /// The name of the DNS zone (without a terminating dot). /// </param> /// <param name='top'> /// The maximum number of record sets to return. If not specified, /// returns up to 100 record sets. /// </param> /// <param name='recordsetnamesuffix'> /// The suffix label of the record set name that has to be used to /// filter the record set enumerations. If this parameter is specified, /// Enumeration will return only records that end with /// .&lt;recordSetNameSuffix&gt; /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecordSet>>> ListByDnsZoneWithHttpMessagesAsync(string resourceGroupName, string zoneName, int? top = default(int?), string recordsetnamesuffix = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the record sets of a specified type in a DNS zone. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all record sets in a DNS zone. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecordSet>>> ListByDnsZoneNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }