context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SAP2SharePointWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PhotonHandler.cs" company="Exit Games GmbH"> // Part of: Photon Unity Networking // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if UNITY_5 && (!UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 && !UNITY_5_3) || UNITY_6 #define UNITY_MIN_5_4 #endif using System; using System.Collections; using System.Diagnostics; using ExitGames.Client.Photon; using UnityEngine; using Debug = UnityEngine.Debug; using Hashtable = ExitGames.Client.Photon.Hashtable; using SupportClassPun = ExitGames.Client.Photon.SupportClass; /// <summary> /// Internal Monobehaviour that allows Photon to run an Update loop. /// </summary> internal class PhotonHandler : Photon.MonoBehaviour { public static PhotonHandler SP; public int updateInterval; // time [ms] between consecutive SendOutgoingCommands calls public int updateIntervalOnSerialize; // time [ms] between consecutive RunViewUpdate calls (sending syncs, etc) private int nextSendTickCount = 0; private int nextSendTickCountOnSerialize = 0; private static bool sendThreadShouldRun; private static Stopwatch timerToStopConnectionInBackground; protected internal static bool AppQuits; protected internal static Type PingImplementation = null; protected void Awake() { if (SP != null && SP != this && SP.gameObject != null) { GameObject.DestroyImmediate(SP.gameObject); } SP = this; DontDestroyOnLoad(this.gameObject); this.updateInterval = 1000 / PhotonNetwork.sendRate; this.updateIntervalOnSerialize = 1000 / PhotonNetwork.sendRateOnSerialize; PhotonHandler.StartFallbackSendAckThread(); } #if UNITY_MIN_5_4 protected void Start() { UnityEngine.SceneManagement.SceneManager.sceneLoaded += (scene, loadingMode) => { PhotonNetwork.networkingPeer.NewSceneLoaded(); PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); }; } #else /// <summary>Called by Unity after a new level was loaded.</summary> protected void OnLevelWasLoaded(int level) { PhotonNetwork.networkingPeer.NewSceneLoaded(); PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); } #endif /// <summary>Called by Unity when the application is closed. Disconnects.</summary> protected void OnApplicationQuit() { PhotonHandler.AppQuits = true; PhotonHandler.StopFallbackSendAckThread(); PhotonNetwork.Disconnect(); } /// <summary> /// Called by Unity when the application gets paused (e.g. on Android when in background). /// </summary> /// <remarks> /// Some versions of Unity will give false values for pause on Android (and possibly on other platforms). /// Sets a disconnect timer when PhotonNetwork.BackgroundTimeout > 0.001f. /// </remarks> /// <param name="pause"></param> protected void OnApplicationPause(bool pause) { if (PhotonNetwork.BackgroundTimeout > 0.001f) { if (timerToStopConnectionInBackground == null) { timerToStopConnectionInBackground = new Stopwatch(); } timerToStopConnectionInBackground.Reset(); if (pause) { timerToStopConnectionInBackground.Start(); } else { timerToStopConnectionInBackground.Stop(); } } } /// <summary>Called by Unity when the play mode ends. Used to cleanup.</summary> protected void OnDestroy() { //Debug.Log("OnDestroy on PhotonHandler."); PhotonHandler.StopFallbackSendAckThread(); //PhotonNetwork.Disconnect(); } protected void Update() { if (PhotonNetwork.networkingPeer == null) { Debug.LogError("NetworkPeer broke!"); return; } if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated || PhotonNetwork.connectionStateDetailed == ClientState.Disconnected || PhotonNetwork.offlineMode) { return; } // the messageQueue might be paused. in that case a thread will send acknowledgements only. nothing else to do here. if (!PhotonNetwork.isMessageQueueRunning) { return; } bool doDispatch = true; while (PhotonNetwork.isMessageQueueRunning && doDispatch) { // DispatchIncomingCommands() returns true of it found any command to dispatch (event, result or state change) UnityEngine.Profiling.Profiler.BeginSample("DispatchIncomingCommands"); doDispatch = PhotonNetwork.networkingPeer.DispatchIncomingCommands(); UnityEngine.Profiling.Profiler.EndSample(); } int currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); // avoiding Environment.TickCount, which could be negative on long-running platforms if (PhotonNetwork.isMessageQueueRunning && currentMsSinceStart > this.nextSendTickCountOnSerialize) { PhotonNetwork.networkingPeer.RunViewUpdate(); this.nextSendTickCountOnSerialize = currentMsSinceStart + this.updateIntervalOnSerialize; this.nextSendTickCount = 0; // immediately send when synchronization code was running } currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); if (currentMsSinceStart > this.nextSendTickCount) { bool doSend = true; while (PhotonNetwork.isMessageQueueRunning && doSend) { // Send all outgoing commands UnityEngine.Profiling.Profiler.BeginSample("SendOutgoingCommands"); doSend = PhotonNetwork.networkingPeer.SendOutgoingCommands(); UnityEngine.Profiling.Profiler.EndSample(); } this.nextSendTickCount = currentMsSinceStart + this.updateInterval; } } protected void OnJoinedRoom() { PhotonNetwork.networkingPeer.LoadLevelIfSynced(); } protected void OnCreatedRoom() { PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); } public static void StartFallbackSendAckThread() { #if !UNITY_WEBGL if (sendThreadShouldRun) { return; } sendThreadShouldRun = true; SupportClassPun.CallInBackground(FallbackSendAckThread); // thread will call this every 100ms until method returns false #endif } public static void StopFallbackSendAckThread() { #if !UNITY_WEBGL sendThreadShouldRun = false; #endif } public static bool FallbackSendAckThread() { if (sendThreadShouldRun && PhotonNetwork.networkingPeer != null) { // check if the client should disconnect after some seconds in background if (timerToStopConnectionInBackground != null && PhotonNetwork.BackgroundTimeout > 0.001f) { if (timerToStopConnectionInBackground.ElapsedMilliseconds > PhotonNetwork.BackgroundTimeout * 1000) { return sendThreadShouldRun; } } PhotonNetwork.networkingPeer.SendAcksOnly(); } return sendThreadShouldRun; } #region Photon Cloud Ping Evaluation private const string PlayerPrefsKey = "PUNCloudBestRegion"; internal static CloudRegionCode BestRegionCodeCurrently = CloudRegionCode.none; // default to none internal static CloudRegionCode BestRegionCodeInPreferences { get { string prefsRegionCode = PlayerPrefs.GetString(PlayerPrefsKey, ""); if (!string.IsNullOrEmpty(prefsRegionCode)) { CloudRegionCode loadedRegion = Region.Parse(prefsRegionCode); return loadedRegion; } return CloudRegionCode.none; } set { if (value == CloudRegionCode.none) { PlayerPrefs.DeleteKey(PlayerPrefsKey); } else { PlayerPrefs.SetString(PlayerPrefsKey, value.ToString()); } } } internal protected static void PingAvailableRegionsAndConnectToBest() { SP.StartCoroutine(SP.PingAvailableRegionsCoroutine(true)); } internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest) { BestRegionCodeCurrently = CloudRegionCode.none; while (PhotonNetwork.networkingPeer.AvailableRegions == null) { if (PhotonNetwork.connectionStateDetailed != ClientState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != ClientState.ConnectedToNameServer) { Debug.LogError("Call ConnectToNameServer to ping available regions."); yield break; // break if we don't connect to the nameserver at all } Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null)); yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping) } if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0) { Debug.LogError("No regions available. Are you sure your appid is valid and setup?"); yield break; // break if we don't get regions at all } PhotonPingManager pingManager = new PhotonPingManager(); foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions) { SP.StartCoroutine(pingManager.PingSocket(region)); } while (!pingManager.Done) { yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping) } Region best = pingManager.BestRegion; PhotonHandler.BestRegionCodeCurrently = best.Code; PhotonHandler.BestRegionCodeInPreferences = best.Code; Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest); if (connectToBest) { PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code); } } #endregion }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Avalonia.Platform.Interop; using static Avalonia.OpenGL.GlConsts; namespace Avalonia.OpenGL { public delegate IntPtr GlGetProcAddressDelegate(string procName); public unsafe class GlInterface : GlBasicInfoInterface<GlInterface.GlContextInfo> { public string Version { get; } public string Vendor { get; } public string Renderer { get; } public GlContextInfo ContextInfo { get; } public class GlContextInfo { public GlVersion Version { get; } public HashSet<string> Extensions { get; } public GlContextInfo(GlVersion version, HashSet<string> extensions) { Version = version; Extensions = extensions; } public static GlContextInfo Create(GlVersion version, Func<string, IntPtr> getProcAddress) { var basicInfoInterface = new GlBasicInfoInterface(getProcAddress); var exts = basicInfoInterface.GetExtensions(); return new GlContextInfo(version, new HashSet<string>(exts)); } } private GlInterface(GlContextInfo info, Func<string, IntPtr> getProcAddress) : base(getProcAddress, info) { ContextInfo = info; Version = GetString(GlConsts.GL_VERSION); Renderer = GetString(GlConsts.GL_RENDERER); Vendor = GetString(GlConsts.GL_VENDOR); } public GlInterface(GlVersion version, Func<string, IntPtr> getProcAddress) : this( GlContextInfo.Create(version, getProcAddress), getProcAddress) { } public GlInterface(GlVersion version, Func<Utf8Buffer, IntPtr> n) : this(version, ConvertNative(n)) { } public static GlInterface FromNativeUtf8GetProcAddress(GlVersion version, Func<Utf8Buffer, IntPtr> getProcAddress) => new GlInterface(version, getProcAddress); public T GetProcAddress<T>(string proc) => Marshal.GetDelegateForFunctionPointer<T>(GetProcAddress(proc)); // ReSharper disable UnassignedGetOnlyAutoProperty public delegate int GlGetError(); [GlEntryPoint("glGetError")] public GlGetError GetError { get; } public delegate void GlClearStencil(int s); [GlEntryPoint("glClearStencil")] public GlClearStencil ClearStencil { get; } public delegate void GlClearColor(float r, float g, float b, float a); [GlEntryPoint("glClearColor")] public GlClearColor ClearColor { get; } public delegate void GlClear(int bits); [GlEntryPoint("glClear")] public GlClear Clear { get; } public delegate void GlViewport(int x, int y, int width, int height); [GlEntryPoint("glViewport")] public GlViewport Viewport { get; } [GlEntryPoint("glFlush")] public Action Flush { get; } [GlEntryPoint("glFinish")] public Action Finish { get; } public delegate IntPtr GlGetString(int v); [GlEntryPoint("glGetString")] public GlGetString GetStringNative { get; } public string GetString(int v) { var ptr = GetStringNative(v); if (ptr != IntPtr.Zero) return Marshal.PtrToStringAnsi(ptr); return null; } public delegate void GlGetIntegerv(int name, out int rv); [GlEntryPoint("glGetIntegerv")] public GlGetIntegerv GetIntegerv { get; } public delegate void GlGenFramebuffers(int count, int[] res); [GlEntryPoint("glGenFramebuffers")] public GlGenFramebuffers GenFramebuffers { get; } public delegate void GlDeleteFramebuffers(int count, int[] framebuffers); [GlEntryPoint("glDeleteFramebuffers")] public GlDeleteFramebuffers DeleteFramebuffers { get; } public delegate void GlBindFramebuffer(int target, int fb); [GlEntryPoint("glBindFramebuffer")] public GlBindFramebuffer BindFramebuffer { get; } public delegate int GlCheckFramebufferStatus(int target); [GlEntryPoint("glCheckFramebufferStatus")] public GlCheckFramebufferStatus CheckFramebufferStatus { get; } public delegate void GlBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter); [GlMinVersionEntryPoint("glBlitFramebuffer", 3, 0)] public GlBlitFramebuffer BlitFramebuffer { get; } public delegate void GlGenRenderbuffers(int count, int[] res); [GlEntryPoint("glGenRenderbuffers")] public GlGenRenderbuffers GenRenderbuffers { get; } public delegate void GlDeleteRenderbuffers(int count, int[] renderbuffers); [GlEntryPoint("glDeleteRenderbuffers")] public GlDeleteTextures DeleteRenderbuffers { get; } public delegate void GlBindRenderbuffer(int target, int fb); [GlEntryPoint("glBindRenderbuffer")] public GlBindRenderbuffer BindRenderbuffer { get; } public delegate void GlRenderbufferStorage(int target, int internalFormat, int width, int height); [GlEntryPoint("glRenderbufferStorage")] public GlRenderbufferStorage RenderbufferStorage { get; } public delegate void GlFramebufferRenderbuffer(int target, int attachment, int renderbufferTarget, int renderbuffer); [GlEntryPoint("glFramebufferRenderbuffer")] public GlFramebufferRenderbuffer FramebufferRenderbuffer { get; } public delegate void GlGenTextures(int count, int[] res); [GlEntryPoint("glGenTextures")] public GlGenTextures GenTextures { get; } public delegate void GlBindTexture(int target, int fb); [GlEntryPoint("glBindTexture")] public GlBindTexture BindTexture { get; } public delegate void GlActiveTexture(int texture); [GlEntryPoint("glActiveTexture")] public GlActiveTexture ActiveTexture { get; } public delegate void GlDeleteTextures(int count, int[] textures); [GlEntryPoint("glDeleteTextures")] public GlDeleteTextures DeleteTextures { get; } public delegate void GlTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, IntPtr data); [GlEntryPoint("glTexImage2D")] public GlTexImage2D TexImage2D { get; } public delegate void GlCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height); [GlEntryPoint("glCopyTexSubImage2D")] public GlCopyTexSubImage2D CopyTexSubImage2D { get; } public delegate void GlTexParameteri(int target, int name, int value); [GlEntryPoint("glTexParameteri")] public GlTexParameteri TexParameteri { get; } public delegate void GlFramebufferTexture2D(int target, int attachment, int texTarget, int texture, int level); [GlEntryPoint("glFramebufferTexture2D")] public GlFramebufferTexture2D FramebufferTexture2D { get; } public delegate int GlCreateShader(int shaderType); [GlEntryPoint("glCreateShader")] public GlCreateShader CreateShader { get; } public delegate void GlShaderSource(int shader, int count, IntPtr strings, IntPtr lengths); [GlEntryPoint("glShaderSource")] public GlShaderSource ShaderSource { get; } public void ShaderSourceString(int shader, string source) { using (var b = new Utf8Buffer(source)) { var ptr = b.DangerousGetHandle(); var len = new IntPtr(b.ByteLen); ShaderSource(shader, 1, new IntPtr(&ptr), new IntPtr(&len)); } } public delegate void GlCompileShader(int shader); [GlEntryPoint("glCompileShader")] public GlCompileShader CompileShader { get; } public delegate void GlGetShaderiv(int shader, int name, int* parameters); [GlEntryPoint("glGetShaderiv")] public GlGetShaderiv GetShaderiv { get; } public delegate void GlGetShaderInfoLog(int shader, int maxLength, out int length, void*infoLog); [GlEntryPoint("glGetShaderInfoLog")] public GlGetShaderInfoLog GetShaderInfoLog { get; } public unsafe string CompileShaderAndGetError(int shader, string source) { ShaderSourceString(shader, source); CompileShader(shader); int compiled; GetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (compiled != 0) return null; int logLength; GetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength == 0) logLength = 4096; var logData = new byte[logLength]; int len; fixed (void* ptr = logData) GetShaderInfoLog(shader, logLength, out len, ptr); return Encoding.UTF8.GetString(logData,0, len); } public delegate int GlCreateProgram(); [GlEntryPoint("glCreateProgram")] public GlCreateProgram CreateProgram { get; } public delegate void GlAttachShader(int program, int shader); [GlEntryPoint("glAttachShader")] public GlAttachShader AttachShader { get; } public delegate void GlLinkProgram(int program); [GlEntryPoint("glLinkProgram")] public GlLinkProgram LinkProgram { get; } public delegate void GlGetProgramiv(int program, int name, int* parameters); [GlEntryPoint("glGetProgramiv")] public GlGetProgramiv GetProgramiv { get; } public delegate void GlGetProgramInfoLog(int program, int maxLength, out int len, void* infoLog); [GlEntryPoint("glGetProgramInfoLog")] public GlGetProgramInfoLog GetProgramInfoLog { get; } public unsafe string LinkProgramAndGetError(int program) { LinkProgram(program); int compiled; GetProgramiv(program, GL_LINK_STATUS, &compiled); if (compiled != 0) return null; int logLength; GetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); var logData = new byte[logLength]; int len; fixed (void* ptr = logData) GetProgramInfoLog(program, logLength, out len, ptr); return Encoding.UTF8.GetString(logData,0, len); } public delegate void GlBindAttribLocation(int program, int index, IntPtr name); [GlEntryPoint("glBindAttribLocation")] public GlBindAttribLocation BindAttribLocation { get; } public void BindAttribLocationString(int program, int index, string name) { using (var b = new Utf8Buffer(name)) BindAttribLocation(program, index, b.DangerousGetHandle()); } public delegate void GlGenBuffers(int len, int[] rv); [GlEntryPoint("glGenBuffers")] public GlGenBuffers GenBuffers { get; } public int GenBuffer() { var rv = new int[1]; GenBuffers(1, rv); return rv[0]; } public delegate void GlBindBuffer(int target, int buffer); [GlEntryPoint("glBindBuffer")] public GlBindBuffer BindBuffer { get; } public delegate void GlBufferData(int target, IntPtr size, IntPtr data, int usage); [GlEntryPoint("glBufferData")] public GlBufferData BufferData { get; } public delegate int GlGetAttribLocation(int program, IntPtr name); [GlEntryPoint("glGetAttribLocation")] public GlGetAttribLocation GetAttribLocation { get; } public int GetAttribLocationString(int program, string name) { using (var b = new Utf8Buffer(name)) return GetAttribLocation(program, b.DangerousGetHandle()); } public delegate void GlVertexAttribPointer(int index, int size, int type, int normalized, int stride, IntPtr pointer); [GlEntryPoint("glVertexAttribPointer")] public GlVertexAttribPointer VertexAttribPointer { get; } public delegate void GlEnableVertexAttribArray(int index); [GlEntryPoint("glEnableVertexAttribArray")] public GlEnableVertexAttribArray EnableVertexAttribArray { get; } public delegate void GlUseProgram(int program); [GlEntryPoint("glUseProgram")] public GlUseProgram UseProgram { get; } public delegate void GlDrawArrays(int mode, int first, IntPtr count); [GlEntryPoint("glDrawArrays")] public GlDrawArrays DrawArrays { get; } public delegate void GlDrawElements(int mode, int count, int type, IntPtr indices); [GlEntryPoint("glDrawElements")] public GlDrawElements DrawElements { get; } public delegate int GlGetUniformLocation(int program, IntPtr name); [GlEntryPoint("glGetUniformLocation")] public GlGetUniformLocation GetUniformLocation { get; } public int GetUniformLocationString(int program, string name) { using (var b = new Utf8Buffer(name)) return GetUniformLocation(program, b.DangerousGetHandle()); } public delegate void GlUniform1f(int location, float falue); [GlEntryPoint("glUniform1f")] public GlUniform1f Uniform1f { get; } public delegate void GlUniformMatrix4fv(int location, int count, bool transpose, void* value); [GlEntryPoint("glUniformMatrix4fv")] public GlUniformMatrix4fv UniformMatrix4fv { get; } public delegate void GlEnable(int what); [GlEntryPoint("glEnable")] public GlEnable Enable { get; } public delegate void GlDeleteBuffers(int count, int[] buffers); [GlEntryPoint("glDeleteBuffers")] public GlDeleteBuffers DeleteBuffers { get; } public delegate void GlDeleteProgram(int program); [GlEntryPoint("glDeleteProgram")] public GlDeleteProgram DeleteProgram { get; } public delegate void GlDeleteShader(int shader); [GlEntryPoint("glDeleteShader")] public GlDeleteShader DeleteShader { get; } // ReSharper restore UnassignedGetOnlyAutoProperty } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using DotVVM.Framework.Controls.Infrastructure; using DotVVM.Framework.Hosting; using DotVVM.Framework.Runtime; namespace DotVVM.Framework.Controls { /// <summary> /// Contains child controls of a <see cref="DotvvmControl"/>. /// </summary> public class DotvvmControlCollection : IList<DotvvmControl> { private DotvvmControl parent; private List<DotvvmControl> controls = new List<DotvvmControl>(); private LifeCycleEventType lastLifeCycleEvent; private bool isInvokingEvent; private int uniqueIdCounter = 0; /// <summary> /// Initializes a new instance of the <see cref="DotvvmControlCollection"/> class. /// </summary> public DotvvmControlCollection(DotvvmControl parent) { this.parent = parent; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> public IEnumerator<DotvvmControl> GetEnumerator() { return controls.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <exception cref="System.InvalidOperationException"></exception> public void Add(DotvvmControl item) { Insert(controls.Count, item); } /// <summary> /// Adds an item to the child collection, but does not create unique ids, does not invoke missing events, ... Intended for internal use only. /// </summary> internal void AddUnchecked(DotvvmControl item) { controls.Add(item); item.Parent = parent; SetLifecycleRequirements(item); } /// <summary> /// Adds items to the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <param name="items">An enumeration of objects to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <exception cref="System.InvalidOperationException"></exception> public void Add(IEnumerable<DotvvmControl> items) { foreach (var item in items) { controls.Add(item); SetParent(item); } } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> public void Clear() { foreach (var item in controls) { item.Parent = null; } controls.Clear(); uniqueIdCounter = 0; } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <returns> /// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. /// </returns> public bool Contains(DotvvmControl item) { return item.Parent == parent && controls.Contains(item); } /// <summary> /// Copies the controls to the specified array. /// </summary> public void CopyTo(DotvvmControl[] array, int arrayIndex) { controls.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <returns> /// true if <paramref name="item" /> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />. /// </returns> public bool Remove(DotvvmControl item) { if (item.Parent == parent) { item.Parent = null; controls.Remove(item); return true; } return false; } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> public int Count => controls.Count; /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </summary> public bool IsReadOnly => false; /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1" />. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1" />.</param> /// <returns> /// The index of <paramref name="item" /> if found in the list; otherwise, -1. /// </returns> public int IndexOf(DotvvmControl item) { return controls.IndexOf(item); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item" /> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param> public void Insert(int index, DotvvmControl item) { controls.Insert(index, item); SetParent(item); } /// <summary> /// Inserts items to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="items" /> should be inserted.</param> /// <param name="items">An enumeration of objects to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param> public void Insert(int index, IEnumerable<DotvvmControl> items) { items = items.ToArray(); controls.InsertRange(index, items); foreach (var item in items) { SetParent(item); } } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1" /> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> public void RemoveAt(int index) { var item = controls[index]; item.Parent = null; controls.RemoveAt(index); } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public DotvvmControl this[int index] { get { return controls[index]; } set { controls[index].Parent = null; controls[index] = value; SetParent(value); } } /// <summary> /// Sets the parent to the specified control. /// </summary> private void SetParent(DotvvmControl item) { if (item.Parent != null && item.Parent != parent && IsInParentsChildren(item)) { throw new DotvvmControlException(parent, "The control cannot be added to the collection " + "because it already has a different parent! Remove it from the original collection first."); } item.Parent = parent; if (!item.properties.Contains(Internal.UniqueIDProperty) && parent.properties.TryGet(Internal.UniqueIDProperty, out var parentId) && parentId is not null) { AssignUniqueIds(item, parentId); } SetLifecycleRequirements(item); ValidateParentsLifecycleEvents(); } private void SetLifecycleRequirements(DotvvmControl item) { // Iterates through all parents and ORs the LifecycleRequirements var updatedLastEvent = lastLifeCycleEvent; { DotvvmControl? currentParent = parent; bool lifecycleEventUpdatingDisabled = false; while (currentParent != null && (item.LifecycleRequirements & ~currentParent.LifecycleRequirements) != ControlLifecycleRequirements.None) { // set parent's Requirements to match the OR of all children currentParent.LifecycleRequirements |= item.LifecycleRequirements; // if the parent has greater last lifecycle event, update local if (!lifecycleEventUpdatingDisabled && currentParent.Children.lastLifeCycleEvent > updatedLastEvent) updatedLastEvent = currentParent.Children.lastLifeCycleEvent; // but don't update it, when the ancestor is invoking this event if (!lifecycleEventUpdatingDisabled && currentParent.Children.isInvokingEvent) lifecycleEventUpdatingDisabled = true; currentParent = GetClosestDotvvmControlAncestor(currentParent); } if (!lifecycleEventUpdatingDisabled && currentParent != null && currentParent.Children.lastLifeCycleEvent > updatedLastEvent) updatedLastEvent = currentParent.Children.lastLifeCycleEvent; } // update ancestor's last event if (updatedLastEvent > lastLifeCycleEvent) { DotvvmControl? currentParent = parent; while (currentParent != null &&!currentParent.Children.isInvokingEvent && currentParent.Children.lastLifeCycleEvent < updatedLastEvent) { currentParent.Children.lastLifeCycleEvent = updatedLastEvent; currentParent = GetClosestDotvvmControlAncestor(currentParent); } } if (lastLifeCycleEvent > LifeCycleEventType.None) item.Children.InvokeMissedPageLifeCycleEvents(lastLifeCycleEvent, isMissingInvoke: true); } void AssignUniqueIds(DotvvmControl item, object parentId) { Debug.Assert(parent.properties.Contains(Internal.UniqueIDProperty)); Debug.Assert(!item.properties.Contains(Internal.UniqueIDProperty)); Debug.Assert(parentId is string); var id = parentId.ToString() + "a" + uniqueIdCounter.ToString(); uniqueIdCounter++; item.properties.Set(Internal.UniqueIDProperty, id); foreach (var c in item.Children.controls) { if (!c.properties.Contains(Internal.UniqueIDProperty)) item.Children.AssignUniqueIds(c, id); } } [Conditional("DEBUG")] internal void ValidateParentsLifecycleEvents() { // check if all ancestors have the flags if (!parent.GetAllAncestors(onlyWhenInChildren: true).OfType<DotvvmControl>().All(c => (c.LifecycleRequirements & parent.LifecycleRequirements) == parent.LifecycleRequirements)) throw new Exception("Internal bug in Lifecycle events."); } private IDotvvmRequestContext? GetContext() { DotvvmBindableObject? c = parent; while (c != null) { if (c.properties.TryGet(Internal.RequestContextProperty, out var context)) return (IDotvvmRequestContext?)context; c = c.Parent; } // when not found, fallback to this slow method: return (IDotvvmRequestContext?)parent.GetValue(Internal.RequestContextProperty); } /// <summary> /// Invokes missed page life cycle events on the control. /// </summary> private void InvokeMissedPageLifeCycleEvents(LifeCycleEventType targetEventType, bool isMissingInvoke) { // just a quick check to save GetValue call if (lastLifeCycleEvent >= targetEventType || parent.LifecycleRequirements == ControlLifecycleRequirements.None) return; var context = GetContext(); if (context == null) throw new DotvvmControlException(parent, "InvokeMissedPageLifeCycleEvents must be called on a control rooted in a view."); DotvvmControl lastProcessedControl = parent; try { InvokeMissedPageLifeCycleEvent(context, targetEventType, isMissingInvoke, ref lastProcessedControl); } catch (DotvvmInterruptRequestExecutionException) { throw; } catch (Exception ex) { if (ex is IDotvvmException { RelatedControl: not null }) throw; if (ex is DotvvmExceptionBase dotvvmException) { dotvvmException.RelatedControl = lastProcessedControl; throw; } else { var eventType = lastLifeCycleEvent + 1; var baseException = ex.GetBaseException(); var controlType = lastProcessedControl.GetType().Name; throw new DotvvmControlException(lastProcessedControl, $"Unhandled {baseException.GetType().Name} occurred in {controlType}.{eventType}: {baseException.Message}", ex); } } } private void InvokeMissedPageLifeCycleEvent(IDotvvmRequestContext context, LifeCycleEventType targetEventType, bool isMissingInvoke, ref DotvvmControl lastProcessedControl) { ValidateParentsLifecycleEvents(); isInvokingEvent = true; for (var eventType = lastLifeCycleEvent + 1; eventType <= targetEventType; eventType++) { // get ControlLifecycleRequirements flag for the event var reqflag = (1 << ((int)eventType - 1)); if (isMissingInvoke) reqflag = reqflag << 5; // abort when control does not require that if ((parent.LifecycleRequirements & (ControlLifecycleRequirements)reqflag) == 0) { lastLifeCycleEvent = eventType; continue; } lastProcessedControl = parent; switch (eventType) { case LifeCycleEventType.PreInit: parent.OnPreInit(context); break; case LifeCycleEventType.Init: parent.OnInit(context); break; case LifeCycleEventType.Load: parent.OnLoad(context); break; case LifeCycleEventType.PreRender: parent.OnPreRender(context); break; case LifeCycleEventType.PreRenderComplete: parent.OnPreRenderComplete(context); break; default: throw new ArgumentOutOfRangeException(nameof(eventType), eventType, null); } lastLifeCycleEvent = eventType; foreach (var child in controls) { child.Children.InvokeMissedPageLifeCycleEvent(context, eventType, isMissingInvoke && eventType == targetEventType, ref lastProcessedControl); } } isInvokingEvent = false; } /// <summary> /// Invokes the specified method on all controls in the page control tree. /// </summary> public static void InvokePageLifeCycleEventRecursive(DotvvmControl rootControl, LifeCycleEventType eventType) { rootControl.Children.InvokeMissedPageLifeCycleEvents(eventType, isMissingInvoke: false); } private static DotvvmControl? GetClosestDotvvmControlAncestor(DotvvmControl control) { var currentParent = control.Parent; while (currentParent != null && !(currentParent is DotvvmControl)) { currentParent = currentParent.Parent; } return (DotvvmControl?)currentParent; } private static bool IsInParentsChildren(DotvvmControl item) { return item.Parent is DotvvmControl control && control.Children.Contains(item); } /// <summary> /// Determines whether the control has only white space content. /// </summary> public bool HasOnlyWhiteSpaceContent() { if (controls.Count == 0) return true; foreach (var c in controls) { if (c is not Infrastructure.RawLiteral lit || !lit.IsWhitespace) 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.Windows.Controls.Page.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.Windows.Controls { public partial class Page : System.Windows.FrameworkElement, System.Windows.IWindowService, System.Windows.Markup.IAddChild { #region Methods and constructors protected override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeBounds) { return default(System.Windows.Size); } protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint) { return default(System.Windows.Size); } protected virtual new void OnTemplateChanged(ControlTemplate oldTemplate, ControlTemplate newTemplate) { } protected sealed override void OnVisualParentChanged(System.Windows.DependencyObject oldParent) { } public Page() { } public bool ShouldSerializeShowsNavigationUI() { return default(bool); } public bool ShouldSerializeTitle() { return default(bool); } public bool ShouldSerializeWindowHeight() { return default(bool); } public bool ShouldSerializeWindowTitle() { return default(bool); } public bool ShouldSerializeWindowWidth() { return default(bool); } void System.Windows.Markup.IAddChild.AddChild(Object obj) { } void System.Windows.Markup.IAddChild.AddText(string str) { } #endregion #region Properties and indexers public System.Windows.Media.Brush Background { get { return default(System.Windows.Media.Brush); } set { } } public Object Content { get { return default(Object); } set { } } public System.Windows.Media.FontFamily FontFamily { get { return default(System.Windows.Media.FontFamily); } set { } } public double FontSize { get { return default(double); } set { } } public System.Windows.Media.Brush Foreground { get { return default(System.Windows.Media.Brush); } set { } } public bool KeepAlive { get { return default(bool); } set { } } internal protected override System.Collections.IEnumerator LogicalChildren { get { return default(System.Collections.IEnumerator); } } public System.Windows.Navigation.NavigationService NavigationService { get { return default(System.Windows.Navigation.NavigationService); } } public bool ShowsNavigationUI { get { return default(bool); } set { } } double System.Windows.IWindowService.Height { get { return default(double); } set { } } string System.Windows.IWindowService.Title { get { return default(string); } set { } } bool System.Windows.IWindowService.UserResized { get { return default(bool); } } double System.Windows.IWindowService.Width { get { return default(double); } set { } } public ControlTemplate Template { get { return default(ControlTemplate); } set { } } public string Title { get { return default(string); } set { } } public double WindowHeight { get { return default(double); } set { } } public string WindowTitle { get { return default(string); } set { } } public double WindowWidth { get { return default(double); } set { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty BackgroundProperty; public readonly static System.Windows.DependencyProperty ContentProperty; public readonly static System.Windows.DependencyProperty FontFamilyProperty; public readonly static System.Windows.DependencyProperty FontSizeProperty; public readonly static System.Windows.DependencyProperty ForegroundProperty; public readonly static System.Windows.DependencyProperty KeepAliveProperty; public readonly static System.Windows.DependencyProperty TemplateProperty; public readonly static System.Windows.DependencyProperty TitleProperty; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Management.Automation; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements update-typeData command. /// </summary> [Cmdlet(VerbsData.Update, "TypeData", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, DefaultParameterSetName = FileParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113421")] public class UpdateTypeDataCommand : UpdateData { #region dynamic type set // Dynamic type set name and type data set name private const string DynamicTypeSet = "DynamicTypeSet"; private const string TypeDataSet = "TypeDataSet"; private static object s_notSpecified = new object(); private static bool HasBeenSpecified(object obj) { return !System.Object.ReferenceEquals(obj, s_notSpecified); } private PSMemberTypes _memberType; private bool _isMemberTypeSet = false; /// <summary> /// The member type of to be added. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] [ValidateSet(System.Management.Automation.Runspaces.TypeData.NoteProperty, System.Management.Automation.Runspaces.TypeData.AliasProperty, System.Management.Automation.Runspaces.TypeData.ScriptProperty, System.Management.Automation.Runspaces.TypeData.CodeProperty, System.Management.Automation.Runspaces.TypeData.ScriptMethod, System.Management.Automation.Runspaces.TypeData.CodeMethod, IgnoreCase = true)] public PSMemberTypes MemberType { set { _memberType = value; _isMemberTypeSet = true; } get { return _memberType; } } private string _memberName; /// <summary> /// The name of the new member. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string MemberName { set { _memberName = value; } get { return _memberName; } } private object _value1 = s_notSpecified; /// <summary> /// First value of the new member. The meaning of this value /// changes according to the member type. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] public object Value { set { _value1 = value; } get { return _value1; } } private object _value2; /// <summary> /// Second value of the new member. The meaning of this value /// changes according to the member type. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public object SecondValue { set { _value2 = value; } get { return _value2; } } private Type _typeConverter; /// <summary> /// The type converter to be added. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TypeConverter { set { _typeConverter = value; } get { return _typeConverter; } } private Type _typeAdapter; /// <summary> /// The type adapter to be added. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TypeAdapter { set { _typeAdapter = value; } get { return _typeAdapter; } } /// <summary> /// SerializationMethod. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string SerializationMethod { set { _serializationMethod = value; } get { return _serializationMethod; } } /// <summary> /// TargetTypeForDeserialization. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TargetTypeForDeserialization { set { _targetTypeForDeserialization = value; } get { return _targetTypeForDeserialization; } } /// <summary> /// SerializationDepth. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] [ValidateRange(0, int.MaxValue)] public int SerializationDepth { set { _serializationDepth = value; } get { return _serializationDepth; } } /// <summary> /// DefaultDisplayProperty. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string DefaultDisplayProperty { set { _defaultDisplayProperty = value; } get { return _defaultDisplayProperty; } } /// <summary> /// InheritPropertySerializationSet. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public bool? InheritPropertySerializationSet { set { _inheritPropertySerializationSet = value; } get { return _inheritPropertySerializationSet; } } /// <summary> /// StringSerializationSource. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string StringSerializationSource { set { _stringSerializationSource = value; } get { return _stringSerializationSource; } } /// <summary> /// DefaultDisplayPropertySet. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] DefaultDisplayPropertySet { set { _defaultDisplayPropertySet = value; } get { return _defaultDisplayPropertySet; } } /// <summary> /// DefaultKeyPropertySet. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] DefaultKeyPropertySet { set { _defaultKeyPropertySet = value; } get { return _defaultKeyPropertySet; } } /// <summary> /// PropertySerializationSet. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] PropertySerializationSet { set { _propertySerializationSet = value; } get { return _propertySerializationSet; } } // These members are represented as NoteProperty in types.ps1xml private string _serializationMethod; private Type _targetTypeForDeserialization; private int _serializationDepth = int.MinValue; private string _defaultDisplayProperty; private bool? _inheritPropertySerializationSet; // These members are represented as AliasProperty in types.ps1xml private string _stringSerializationSource; // These members are represented as PropertySet in types.ps1xml private string[] _defaultDisplayPropertySet; private string[] _defaultKeyPropertySet; private string[] _propertySerializationSet; private string _typeName; /// <summary> /// The type name we want to update on. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = DynamicTypeSet)] [ArgumentToTypeNameTransformationAttribute()] [ValidateNotNullOrEmpty] public string TypeName { set { _typeName = value; } get { return _typeName; } } private bool _force = false; /// <summary> /// True if we should overwrite a possibly existing member. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [Parameter(ParameterSetName = TypeDataSet)] public SwitchParameter Force { set { _force = value; } get { return _force; } } #endregion dynamic type set #region strong type data set private TypeData[] _typeData; /// <summary> /// The TypeData instances. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = TypeDataSet)] public TypeData[] TypeData { set { _typeData = value; } get { return _typeData; } } #endregion strong type data set /// <summary> /// This method verify if the Type Table is shared and cannot be updated. /// </summary> protected override void BeginProcessing() { if (Context.TypeTable.isShared) { var ex = new InvalidOperationException(TypesXmlStrings.SharedTypeTableCannotBeUpdated); this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedTypeTable", ErrorCategory.InvalidOperation, null)); } } /// <summary> /// This method implements the ProcessRecord method for update-typeData command. /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case FileParameterSet: ProcessTypeFiles(); break; case DynamicTypeSet: ProcessDynamicType(); break; case TypeDataSet: ProcessStrongTypeData(); break; } } /// <summary> /// This method implements the EndProcessing method for update-typeData command. /// </summary> protected override void EndProcessing() { this.Context.TypeTable.ClearConsolidatedMembers(); } #region strong typeData private void ProcessStrongTypeData() { string action = UpdateDataStrings.UpdateTypeDataAction; string target = UpdateDataStrings.UpdateTypeDataTarget; foreach (TypeData item in _typeData) { // If type contains no members at all, report the error and skip it if (!EnsureTypeDataIsNotEmpty(item)) { continue; } TypeData type = item.Copy(); // Set property IsOverride to be true if -Force parameter is specified if (_force) { type.IsOverride = true; } string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, type.TypeName); if (ShouldProcess(formattedTarget, action)) { try { var errors = new ConcurrentBag<string>(); this.Context.TypeTable.Update(type, errors, false); // Write out errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } else { // Update successfully, we add the TypeData into cache if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } } } #endregion strong typeData #region dynamic type processing /// <summary> /// Process the dynamic type update. /// </summary> private void ProcessDynamicType() { if (string.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } TypeData type = new TypeData(_typeName) { IsOverride = _force }; GetMembers(type.Members); if (_typeConverter != null) { type.TypeConverter = _typeConverter; } if (_typeAdapter != null) { type.TypeAdapter = _typeAdapter; } if (_serializationMethod != null) { type.SerializationMethod = _serializationMethod; } if (_targetTypeForDeserialization != null) { type.TargetTypeForDeserialization = _targetTypeForDeserialization; } if (_serializationDepth != int.MinValue) { type.SerializationDepth = (uint)_serializationDepth; } if (_defaultDisplayProperty != null) { type.DefaultDisplayProperty = _defaultDisplayProperty; } if (_inheritPropertySerializationSet != null) { type.InheritPropertySerializationSet = _inheritPropertySerializationSet.Value; } if (_stringSerializationSource != null) { type.StringSerializationSource = _stringSerializationSource; } if (_defaultDisplayPropertySet != null) { PropertySetData defaultDisplayPropertySet = new PropertySetData(_defaultDisplayPropertySet); type.DefaultDisplayPropertySet = defaultDisplayPropertySet; } if (_defaultKeyPropertySet != null) { PropertySetData defaultKeyPropertySet = new PropertySetData(_defaultKeyPropertySet); type.DefaultKeyPropertySet = defaultKeyPropertySet; } if (_propertySerializationSet != null) { PropertySetData propertySerializationSet = new PropertySetData(_propertySerializationSet); type.PropertySerializationSet = propertySerializationSet; } // If the type contains no members at all, report the error and return if (!EnsureTypeDataIsNotEmpty(type)) { return; } // Load the resource strings string action = UpdateDataStrings.UpdateTypeDataAction; string target = UpdateDataStrings.UpdateTypeDataTarget; string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, _typeName); if (ShouldProcess(formattedTarget, action)) { try { var errors = new ConcurrentBag<string>(); this.Context.TypeTable.Update(type, errors, false); // Write out errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } else { // Update successfully, we add the TypeData into cache if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } } /// <summary> /// Get the members for the TypeData. /// </summary> /// <returns></returns> private void GetMembers(Dictionary<string, TypeMemberData> members) { if (!_isMemberTypeSet) { // If the MemberType is not specified, the MemberName, Value, and SecondValue parameters // should not be specified either if (_memberName != null || HasBeenSpecified(_value1) || _value2 != null) { ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); } return; } switch (MemberType) { case PSMemberTypes.NoteProperty: NotePropertyData note = GetNoteProperty(); members.Add(note.Name, note); break; case PSMemberTypes.AliasProperty: AliasPropertyData alias = GetAliasProperty(); members.Add(alias.Name, alias); break; case PSMemberTypes.ScriptProperty: ScriptPropertyData scriptProperty = GetScriptProperty(); members.Add(scriptProperty.Name, scriptProperty); break; case PSMemberTypes.CodeProperty: CodePropertyData codeProperty = GetCodeProperty(); members.Add(codeProperty.Name, codeProperty); break; case PSMemberTypes.ScriptMethod: ScriptMethodData scriptMethod = GetScriptMethod(); members.Add(scriptMethod.Name, scriptMethod); break; case PSMemberTypes.CodeMethod: CodeMethodData codeMethod = GetCodeMethod(); members.Add(codeMethod.Name, codeMethod); break; default: ThrowTerminatingError(NewError("CannotUpdateMemberType", UpdateDataStrings.CannotUpdateMemberType, null, _memberType.ToString())); break; } } private T GetParameterType<T>(object sourceValue) { return (T)LanguagePrimitives.ConvertTo(sourceValue, typeof(T), CultureInfo.InvariantCulture); } private void EnsureMemberNameHasBeenSpecified() { if (string.IsNullOrEmpty(_memberName)) { ThrowTerminatingError(NewError("MemberNameShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "MemberName", _memberType)); } } private void EnsureValue1HasBeenSpecified() { if (!HasBeenSpecified(_value1)) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "Value", _memberType)); } } private void EnsureValue1NotNullOrEmpty() { if (_value1 is string) { if (string.IsNullOrEmpty((string)_value1)) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } return; } if (_value1 == null) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } } private void EnsureValue2HasNotBeenSpecified() { if (_value2 != null) { ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", _memberType)); } } private void EnsureValue1AndValue2AreNotBothNull() { if (_value1 == null && _value2 == null) { ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, _memberType)); } } /// <summary> /// Check if the TypeData instance contains no members. /// </summary> /// <param name="typeData"></param> /// <returns>False if empty, true if not.</returns> private bool EnsureTypeDataIsNotEmpty(TypeData typeData) { if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 && typeData.TypeConverter == null && typeData.TypeAdapter == null && typeData.DefaultDisplayPropertySet == null && typeData.DefaultKeyPropertySet == null && typeData.PropertySerializationSet == null) { this.WriteError(NewError("TypeDataEmpty", UpdateDataStrings.TypeDataEmpty, null, typeData.TypeName)); return false; } return true; } private NotePropertyData GetNoteProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); return new NotePropertyData(_memberName, _value1); } private AliasPropertyData GetAliasProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1NotNullOrEmpty(); AliasPropertyData alias; string referencedName = GetParameterType<string>(_value1); if (_value2 != null) { Type type = GetParameterType<Type>(_value2); alias = new AliasPropertyData(_memberName, referencedName, type); return alias; } alias = new AliasPropertyData(_memberName, referencedName); return alias; } private ScriptPropertyData GetScriptProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1AndValue2AreNotBothNull(); ScriptBlock value1ScriptBlock = null; if (_value1 != null) { value1ScriptBlock = GetParameterType<ScriptBlock>(_value1); } ScriptBlock value2ScriptBlock = null; if (_value2 != null) { value2ScriptBlock = GetParameterType<ScriptBlock>(_value2); } ScriptPropertyData scriptProperty = new ScriptPropertyData(_memberName, value1ScriptBlock, value2ScriptBlock); return scriptProperty; } private CodePropertyData GetCodeProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1AndValue2AreNotBothNull(); MethodInfo value1CodeReference = null; if (_value1 != null) { value1CodeReference = GetParameterType<MethodInfo>(_value1); } MethodInfo value2CodeReference = null; if (_value2 != null) { value2CodeReference = GetParameterType<MethodInfo>(_value2); } CodePropertyData codeProperty = new CodePropertyData(_memberName, value1CodeReference, value2CodeReference); return codeProperty; } private ScriptMethodData GetScriptMethod() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); ScriptBlock method = GetParameterType<ScriptBlock>(_value1); ScriptMethodData scriptMethod = new ScriptMethodData(_memberName, method); return scriptMethod; } private CodeMethodData GetCodeMethod() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); MethodInfo codeReference = GetParameterType<MethodInfo>(_value1); CodeMethodData codeMethod = new CodeMethodData(_memberName, codeReference); return codeMethod; } /// <summary> /// Generate error record. /// </summary> /// <param name="errorId"></param> /// <param name="template"></param> /// <param name="targetObject"></param> /// <param name="args"></param> /// <returns></returns> private ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; } #endregion dynamic type processing #region type files processing private void ProcessTypeFiles() { Collection<string> prependPathTotal = Glob(this.PrependPath, "TypesPrependPathException", this); Collection<string> appendPathTotal = Glob(this.AppendPath, "TypesAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob if ((PrependPath.Length > 0 || AppendPath.Length > 0) && prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } string action = UpdateDataStrings.UpdateTypeDataAction; // Load the resource once and format it whenever a new target // filename is available string target = UpdateDataStrings.UpdateTarget; if (Context.InitialSessionState != null) { // This hashSet is to detect if there are duplicate type files var fullFileNameHash = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); var newTypes = new Collection<SessionStateTypeEntry>(); for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, prependPathTotal[i]); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(prependPathTotal[i], Context) ?? prependPathTotal[i]; if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); } } } // Copy everything from context's TypeTable to newTypes foreach (var entry in Context.InitialSessionState.Types) { if (entry.FileName != null) { string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(entry); } } else { newTypes.Add(entry); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, appendPathTotalItem); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(appendPathTotalItem, Context) ?? appendPathTotalItem; if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); } } } Context.InitialSessionState.Types.Clear(); Context.TypeTable.Clear(); var errors = new ConcurrentBag<string>(); foreach (SessionStateTypeEntry sste in newTypes) { try { if (sste.TypeTable != null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateTypeWithTypeTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateTypeWithTypeTable", ErrorCategory.InvalidOperation, null)); continue; } else if (sste.FileName != null) { bool unused; Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out unused); } else { Context.TypeTable.Update(sste.TypeData, errors, sste.IsRemove); } } catch (RuntimeException ex) { this.WriteError(new ErrorRecord(ex, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } Context.InitialSessionState.Types.Add(sste); // Write out any errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } errors = new ConcurrentBag<string>(); } } } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); } } #endregion type files processing } /// <summary> /// This class implements update-typeData command. /// </summary> [Cmdlet(VerbsData.Update, "FormatData", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, DefaultParameterSetName = FileParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113420")] public class UpdateFormatDataCommand : UpdateData { /// <summary> /// This method verify if the Format database manager is shared and cannot be updated. /// </summary> protected override void BeginProcessing() { if (Context.FormatDBManager.isShared) { var ex = new InvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated); this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedFormatTable", ErrorCategory.InvalidOperation, null)); } } /// <summary> /// This method implements the ProcessRecord method for update-FormatData command. /// </summary> protected override void ProcessRecord() { Collection<string> prependPathTotal = Glob(this.PrependPath, "FormatPrependPathException", this); Collection<string> appendPathTotal = Glob(this.AppendPath, "FormatAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob if ((PrependPath.Length > 0 || AppendPath.Length > 0) && prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } string action = UpdateDataStrings.UpdateFormatDataAction; // Load the resource once and format it whenever a new target // filename is available string target = UpdateDataStrings.UpdateTarget; if (Context.InitialSessionState != null) { if (Context.InitialSessionState.DisableFormatUpdates) { throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); } // This hashSet is to detect if there are duplicate format files var fullFileNameHash = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); var newFormats = new Collection<SessionStateFormatEntry>(); for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, prependPathTotal[i]); if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(prependPathTotal[i])) { fullFileNameHash.Add(prependPathTotal[i]); newFormats.Add(new SessionStateFormatEntry(prependPathTotal[i])); } } } // Always add InitialSessionState.Formats to the new list foreach (SessionStateFormatEntry entry in Context.InitialSessionState.Formats) { if (entry.FileName != null) { if (!fullFileNameHash.Contains(entry.FileName)) { fullFileNameHash.Add(entry.FileName); newFormats.Add(entry); } } else { newFormats.Add(entry); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, appendPathTotalItem); if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(appendPathTotalItem)) { fullFileNameHash.Add(appendPathTotalItem); newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); } } } var originalFormats = Context.InitialSessionState.Formats; try { // Always rebuild the format information Context.InitialSessionState.Formats.Clear(); var entries = new Collection<PSSnapInTypeAndFormatErrors>(); // Now update the formats... foreach (SessionStateFormatEntry ssfe in newFormats) { string name = ssfe.FileName; PSSnapInInfo snapin = ssfe.PSSnapIn; if (snapin != null && !string.IsNullOrEmpty(snapin.Name)) { name = snapin.Name; } if (ssfe.Formattable != null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); continue; } else if (ssfe.FormatData != null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } else { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FileName)); } Context.InitialSessionState.Formats.Add(ssfe); } if (entries.Count > 0) { Context.FormatDBManager.UpdateDataBase(entries, this.Context.AuthorizationManager, this.Context.EngineHostInterface, false); FormatAndTypeDataHelper.ThrowExceptionOnError("ErrorsUpdatingFormats", null, entries, FormatAndTypeDataHelper.Category.Formats); } } catch (RuntimeException e) { // revert Formats if there is a failure Context.InitialSessionState.Formats.Clear(); Context.InitialSessionState.Formats.Add(originalFormats); this.WriteError(new ErrorRecord(e, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); } } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-FormatData to work"); } } } /// <summary> /// Remove-TypeData cmdlet. /// </summary> [Cmdlet(VerbsCommon.Remove, "TypeData", SupportsShouldProcess = true, DefaultParameterSetName = RemoveTypeDataSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217038")] public class RemoveTypeDataCommand : PSCmdlet { private const string RemoveTypeSet = "RemoveTypeSet"; private const string RemoveFileSet = "RemoveFileSet"; private const string RemoveTypeDataSet = "RemoveTypeDataSet"; private string _typeName; /// <summary> /// The target type to remove. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveTypeSet)] [ArgumentToTypeNameTransformationAttribute()] [ValidateNotNullOrEmpty] public string TypeName { get { return _typeName; } set { _typeName = value; } } private string[] _typeFiles; /// <summary> /// The type xml file to remove from the cache. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(Mandatory = true, ParameterSetName = RemoveFileSet)] [ValidateNotNullOrEmpty] public string[] Path { get { return _typeFiles; } set { _typeFiles = value; } } private TypeData _typeData; /// <summary> /// The TypeData to remove. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = RemoveTypeDataSet)] public TypeData TypeData { get { return _typeData; } set { _typeData = value; } } private static void ConstructFileToIndexMap(string fileName, int index, Dictionary<string, List<int>> fileNameToIndexMap) { List<int> indexList; if (fileNameToIndexMap.TryGetValue(fileName, out indexList)) { indexList.Add(index); } else { fileNameToIndexMap[fileName] = new List<int> { index }; } } /// <summary> /// This method implements the ProcessRecord method for Remove-TypeData command. /// </summary> protected override void ProcessRecord() { if (ParameterSetName == RemoveFileSet) { // Load the resource strings string removeFileAction = UpdateDataStrings.RemoveTypeFileAction; string removeFileTarget = UpdateDataStrings.UpdateTarget; Collection<string> typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); if (typeFileTotal.Count == 0) { return; } // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might // exist in the cache because the user can add arbitrary files to the cache by $host.Runspace.InitialSessionState.Types.Add() Dictionary<string, List<int>> fileToIndexMap = new Dictionary<string, List<int>>(StringComparer.OrdinalIgnoreCase); List<int> indicesToRemove = new List<int>(); if (Context.InitialSessionState != null) { for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { string fileName = Context.InitialSessionState.Types[index].FileName; if (fileName == null) { continue; } // Resolving the file path because the path to the types file in module manifest is now specified as // ..\..\types.ps1xml which expands to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Core\..\..\types.ps1xml fileName = ModuleCmdletBase.ResolveRootedFilePath(fileName, Context) ?? fileName; ConstructFileToIndexMap(fileName, index, fileToIndexMap); } } foreach (string typeFile in typeFileTotal) { string removeFileFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeFileTarget, typeFile); if (ShouldProcess(removeFileFormattedTarget, removeFileAction)) { List<int> indexList; if (fileToIndexMap.TryGetValue(typeFile, out indexList)) { indicesToRemove.AddRange(indexList); } else { this.WriteError(NewError("TypeFileNotExistsInCurrentSession", UpdateDataStrings.TypeFileNotExistsInCurrentSession, null, typeFile)); } } } if (indicesToRemove.Count > 0) { indicesToRemove.Sort(); for (int i = indicesToRemove.Count - 1; i >= 0; i--) { if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.RemoveItem(indicesToRemove[i]); } } try { if (Context.InitialSessionState != null) { bool oldRefreshTypeFormatSetting = Context.InitialSessionState.RefreshTypeAndFormatSetting; try { Context.InitialSessionState.RefreshTypeAndFormatSetting = true; Context.InitialSessionState.UpdateTypes(Context, false); } finally { Context.InitialSessionState.RefreshTypeAndFormatSetting = oldRefreshTypeFormatSetting; } } } catch (RuntimeException ex) { this.WriteError(new ErrorRecord(ex, "TypesFileRemoveException", ErrorCategory.InvalidOperation, null)); } } return; } // Load the resource strings string removeTypeAction = UpdateDataStrings.RemoveTypeDataAction; string removeTypeTarget = UpdateDataStrings.RemoveTypeDataTarget; string typeNameToRemove = null; if (ParameterSetName == RemoveTypeDataSet) { typeNameToRemove = _typeData.TypeName; } else { if (string.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } typeNameToRemove = _typeName; } Dbg.Assert(!string.IsNullOrEmpty(typeNameToRemove), "TypeNameToRemove should be not null and not empty at this point"); TypeData type = new TypeData(typeNameToRemove); string removeTypeFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeTypeTarget, typeNameToRemove); if (ShouldProcess(removeTypeFormattedTarget, removeTypeAction)) { try { var errors = new ConcurrentBag<string>(); Context.TypeTable.Update(type, errors, true); // Write out errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } else { // Type is removed successfully, add it into the cache if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, true)); } else { Dbg.Assert(false, "InitialSessionState must be non-null for Remove-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } } /// <summary> /// This method implements the EndProcessing method for Remove-TypeData command. /// </summary> protected override void EndProcessing() { this.Context.TypeTable.ClearConsolidatedMembers(); } private ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; } } /// <summary> /// Get-TypeData cmdlet. /// </summary> [Cmdlet(VerbsCommon.Get, "TypeData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217033")] [OutputType(typeof(System.Management.Automation.PSObject))] public class GetTypeDataCommand : PSCmdlet { private WildcardPattern[] _filter; /// <summary> /// Get Formatting information only for the specified typename. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [ValidateNotNullOrEmpty] [Parameter(Position = 0, ValueFromPipeline = true)] public string[] TypeName { get; set; } private void ValidateTypeName() { if (TypeName == null) { _filter = new WildcardPattern[] { WildcardPattern.Get("*", WildcardOptions.None) }; return; } var typeNames = new List<string>(); var exception = new InvalidOperationException(UpdateDataStrings.TargetTypeNameEmpty); foreach (string typeName in TypeName) { if (string.IsNullOrWhiteSpace(typeName)) { WriteError( new ErrorRecord( exception, "TargetTypeNameEmpty", ErrorCategory.InvalidOperation, typeName)); continue; } Type type; string typeNameInUse = typeName; // Respect the type shortcut if (LanguagePrimitives.TryConvertTo(typeNameInUse, out type)) { typeNameInUse = type.FullName; } typeNames.Add(typeNameInUse); } _filter = new WildcardPattern[typeNames.Count]; for (int i = 0; i < _filter.Length; i++) { _filter[i] = WildcardPattern.Get(typeNames[i], WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } /// <summary> /// Takes out the content from the database and writes it out. /// </summary> protected override void ProcessRecord() { ValidateTypeName(); Dictionary<string, TypeData> alltypes = Context.TypeTable.GetAllTypeData(); Collection<TypeData> typedefs = new Collection<TypeData>(); foreach (string type in alltypes.Keys) { foreach (WildcardPattern pattern in _filter) { if (pattern.IsMatch(type)) { typedefs.Add(alltypes[type]); break; } } } // write out all the available type definitions foreach (TypeData typedef in typedefs) { WriteObject(typedef); } } } /// <summary> /// To make it easier to specify a TypeName, we add an ArgumentTransformationAttribute here. /// * string: return the string /// * Type: return the Type.ToString() /// * instance: return instance.GetType().ToString() . /// </summary> internal sealed class ArgumentToTypeNameTransformationAttribute : ArgumentTransformationAttribute { public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { string typeName; object target = PSObject.Base(inputData); if (target is Type) { typeName = ((Type)target).FullName; } else if (target is string) { // Respect the type shortcut Type type; typeName = (string)target; if (LanguagePrimitives.TryConvertTo(typeName, out type)) { typeName = type.FullName; } } else if (target is TypeData) { typeName = ((TypeData)target).TypeName; } else { typeName = target.GetType().FullName; } return typeName; } } }
/* * Copyright (c) 2008, 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.Runtime.InteropServices; using System.Globalization; namespace OpenMetaverse { [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Quaternion : IEquatable<Quaternion> { /// <summary>X value</summary> public float X; /// <summary>Y value</summary> public float Y; /// <summary>Z value</summary> public float Z; /// <summary>W value</summary> public float W; #region Constructors public Quaternion(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Quaternion(Vector3 vectorPart, float scalarPart) { X = vectorPart.X; Y = vectorPart.Y; Z = vectorPart.Z; W = scalarPart; } /// <summary> /// Build a quaternion from normalized float values /// </summary> /// <param name="x">X value from -1.0 to 1.0</param> /// <param name="y">Y value from -1.0 to 1.0</param> /// <param name="z">Z value from -1.0 to 1.0</param> public Quaternion(float x, float y, float z) { X = x; Y = y; Z = z; float xyzsum = 1 - X * X - Y * Y - Z * Z; W = (xyzsum > 0) ? (float)Math.Sqrt(xyzsum) : 0; } /// <summary> /// Constructor, builds a quaternion object from a byte array /// </summary> /// <param name="byteArray">Byte array containing four four-byte floats</param> /// <param name="pos">Offset in the byte array to start reading at</param> /// <param name="normalized">Whether the source data is normalized or /// not. If this is true 12 bytes will be read, otherwise 16 bytes will /// be read.</param> public Quaternion(byte[] byteArray, int pos, bool normalized) { X = Y = Z = W = 0; FromBytes(byteArray, pos, normalized); } public Quaternion(Quaternion q) { X = q.X; Y = q.Y; Z = q.Z; W = q.W; } #endregion Constructors #region Public Methods public bool ApproxEquals(Quaternion quat, float tolerance) { Quaternion diff = this - quat; return (diff.LengthSquared() <= tolerance * tolerance); } public float Length() { return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W); } public float LengthSquared() { return (X * X + Y * Y + Z * Z + W * W); } /// <summary> /// Normalizes the quaternion /// </summary> public void Normalize() { this = Normalize(this); } /// <summary> /// Builds a quaternion object from a byte array /// </summary> /// <param name="byteArray">The source byte array</param> /// <param name="pos">Offset in the byte array to start reading at</param> /// <param name="normalized">Whether the source data is normalized or /// not. If this is true 12 bytes will be read, otherwise 16 bytes will /// be read.</param> public void FromBytes(byte[] byteArray, int pos, bool normalized) { if (!normalized) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[16]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); Array.Reverse(conversionBuffer, 12, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); W = BitConverter.ToSingle(conversionBuffer, 12); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); W = BitConverter.ToSingle(byteArray, pos + 12); } } else { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[16]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); } float xyzsum = 1f - X * X - Y * Y - Z * Z; W = (xyzsum > 0f) ? (float)Math.Sqrt(xyzsum) : 0f; } } /// <summary> /// Normalize this quaternion and serialize it to a byte array /// </summary> /// <returns>A 12 byte array containing normalized X, Y, and Z floating /// point values in order using little endian byte ordering</returns> public byte[] GetBytes() { byte[] bytes = new byte[12]; ToBytes(bytes, 0); return bytes; } /// <summary> /// Writes the raw bytes for this quaternion to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 12 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { float norm = (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W); if (norm != 0f) { norm = 1f / norm; float x, y, z; if (W >= 0f) { x = X; y = Y; z = Z; } else { x = -X; y = -Y; z = -Z; } Buffer.BlockCopy(BitConverter.GetBytes(norm * x), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(norm * y), 0, dest, pos + 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(norm * z), 0, dest, pos + 8, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(dest, pos + 0, 4); Array.Reverse(dest, pos + 4, 4); Array.Reverse(dest, pos + 8, 4); } } else { throw new InvalidOperationException(String.Format( "Quaternion {0} normalized to zero", ToString())); } } /// <summary> /// Convert this quaternion to euler angles /// </summary> /// <param name="roll">X euler angle</param> /// <param name="pitch">Y euler angle</param> /// <param name="yaw">Z euler angle</param> public void GetEulerAngles(out float roll, out float pitch, out float yaw) { roll = 0f; pitch = 0f; yaw = 0f; Quaternion t = new Quaternion(this.X * this.X, this.Y * this.Y, this.Z * this.Z, this.W * this.W); float m = (t.X + t.Y + t.Z + t.W); if (Math.Abs(m) < 0.001d) return; float n = 2 * (this.Y * this.W + this.X * this.Z); float p = m * m - n * n; if (p > 0f) { roll = (float)Math.Atan2(2.0f * (this.X * this.W - this.Y * this.Z), (-t.X - t.Y + t.Z + t.W)); pitch = (float)Math.Atan2(n, Math.Sqrt(p)); yaw = (float)Math.Atan2(2.0f * (this.Z * this.W - this.X * this.Y), t.X - t.Y - t.Z + t.W); } else if (n > 0f) { roll = 0f; pitch = (float)(Math.PI / 2d); yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Y); } else { roll = 0f; pitch = -(float)(Math.PI / 2d); yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Z); } //float sqx = X * X; //float sqy = Y * Y; //float sqz = Z * Z; //float sqw = W * W; //// Unit will be a correction factor if the quaternion is not normalized //float unit = sqx + sqy + sqz + sqw; //double test = X * Y + Z * W; //if (test > 0.499f * unit) //{ // // Singularity at north pole // yaw = 2f * (float)Math.Atan2(X, W); // pitch = (float)Math.PI / 2f; // roll = 0f; //} //else if (test < -0.499f * unit) //{ // // Singularity at south pole // yaw = -2f * (float)Math.Atan2(X, W); // pitch = -(float)Math.PI / 2f; // roll = 0f; //} //else //{ // yaw = (float)Math.Atan2(2f * Y * W - 2f * X * Z, sqx - sqy - sqz + sqw); // pitch = (float)Math.Asin(2f * test / unit); // roll = (float)Math.Atan2(2f * X * W - 2f * Y * Z, -sqx + sqy - sqz + sqw); //} } /// <summary> /// Convert this quaternion to an angle around an axis /// </summary> /// <param name="axis">Unit vector describing the axis</param> /// <param name="angle">Angle around the axis, in radians</param> public void GetAxisAngle(out Vector3 axis, out float angle) { axis = new Vector3(); float scale = (float)Math.Sqrt(X * X + Y * Y + Z * Z); if (scale < Single.Epsilon || W > 1.0f || W < -1.0f) { angle = 0.0f; axis.X = 0.0f; axis.Y = 1.0f; axis.Z = 0.0f; } else { angle = 2.0f * (float)Math.Acos(W); float ooscale = 1f / scale; axis.X = X * ooscale; axis.Y = Y * ooscale; axis.Z = Z * ooscale; } } #endregion Public Methods #region Static Methods public static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2) { quaternion1.X += quaternion2.X; quaternion1.Y += quaternion2.Y; quaternion1.Z += quaternion2.Z; quaternion1.W += quaternion2.W; return quaternion1; } /// <summary> /// Returns the conjugate (spatial inverse) of a quaternion /// </summary> public static Quaternion Conjugate(Quaternion quaternion) { quaternion.X = -quaternion.X; quaternion.Y = -quaternion.Y; quaternion.Z = -quaternion.Z; return quaternion; } /// <summary> /// Build a quaternion from an axis and an angle of rotation around /// that axis /// </summary> public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle) { Vector3 axis = new Vector3(axisX, axisY, axisZ); return CreateFromAxisAngle(axis, angle); } /// <summary> /// Build a quaternion from an axis and an angle of rotation around /// that axis /// </summary> /// <param name="axis">Axis of rotation</param> /// <param name="angle">Angle of rotation</param> public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) { Quaternion q; axis = Vector3.Normalize(axis); angle *= 0.5f; float c = (float)Math.Cos(angle); float s = (float)Math.Sin(angle); q.X = axis.X * s; q.Y = axis.Y * s; q.Z = axis.Z * s; q.W = c; return Quaternion.Normalize(q); } /// <summary> /// Creates a quaternion from a vector containing roll, pitch, and yaw /// in radians /// </summary> /// <param name="eulers">Vector representation of the euler angles in /// radians</param> /// <returns>Quaternion representation of the euler angles</returns> public static Quaternion CreateFromEulers(Vector3 eulers) { return CreateFromEulers(eulers.X, eulers.Y, eulers.Z); } /// <summary> /// Creates a quaternion from roll, pitch, and yaw euler angles in /// radians /// </summary> /// <param name="roll">X angle in radians</param> /// <param name="pitch">Y angle in radians</param> /// <param name="yaw">Z angle in radians</param> /// <returns>Quaternion representation of the euler angles</returns> public static Quaternion CreateFromEulers(float roll, float pitch, float yaw) { if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI) throw new ArgumentException("Euler angles must be in radians"); double atCos = Math.Cos(roll / 2f); double atSin = Math.Sin(roll / 2f); double leftCos = Math.Cos(pitch / 2f); double leftSin = Math.Sin(pitch / 2f); double upCos = Math.Cos(yaw / 2f); double upSin = Math.Sin(yaw / 2f); double atLeftCos = atCos * leftCos; double atLeftSin = atSin * leftSin; return new Quaternion( (float)(atSin * leftCos * upCos + atCos * leftSin * upSin), (float)(atCos * leftSin * upCos - atSin * leftCos * upSin), (float)(atLeftCos * upSin + atLeftSin * upCos), (float)(atLeftCos * upCos - atLeftSin * upSin) ); } public static Quaternion CreateFromRotationMatrix(Matrix4 m) { Quaternion quat; float trace = m.Trace(); if (trace > Single.Epsilon) { float s = (float)Math.Sqrt(trace + 1f); quat.W = s * 0.5f; s = 0.5f / s; quat.X = (m.M23 - m.M32) * s; quat.Y = (m.M31 - m.M13) * s; quat.Z = (m.M12 - m.M21) * s; } else { if (m.M11 > m.M22 && m.M11 > m.M33) { float s = (float)Math.Sqrt(1f + m.M11 - m.M22 - m.M33); quat.X = 0.5f * s; s = 0.5f / s; quat.Y = (m.M12 + m.M21) * s; quat.Z = (m.M13 + m.M31) * s; quat.W = (m.M23 - m.M32) * s; } else if (m.M22 > m.M33) { float s = (float)Math.Sqrt(1f + m.M22 - m.M11 - m.M33); quat.Y = 0.5f * s; s = 0.5f / s; quat.X = (m.M21 + m.M12) * s; quat.Z = (m.M32 + m.M23) * s; quat.W = (m.M31 - m.M13) * s; } else { float s = (float)Math.Sqrt(1f + m.M33 - m.M11 - m.M22); quat.Z = 0.5f * s; s = 0.5f / s; quat.X = (m.M31 + m.M13) * s; quat.Y = (m.M32 + m.M23) * s; quat.W = (m.M12 - m.M21) * s; } } return quat; } public static Quaternion Divide(Quaternion quaternion1, Quaternion quaternion2) { float x = quaternion1.X; float y = quaternion1.Y; float z = quaternion1.Z; float w = quaternion1.W; float q2lensq = quaternion2.LengthSquared(); float ooq2lensq = 1f / q2lensq; float x2 = -quaternion2.X * ooq2lensq; float y2 = -quaternion2.Y * ooq2lensq; float z2 = -quaternion2.Z * ooq2lensq; float w2 = quaternion2.W * ooq2lensq; return new Quaternion( ((x * w2) + (x2 * w)) + (y * z2) - (z * y2), ((y * w2) + (y2 * w)) + (z * x2) - (x * z2), ((z * w2) + (z2 * w)) + (x * y2) - (y * x2), (w * w2) - ((x * x2) + (y * y2)) + (z * z2)); } public static float Dot(Quaternion q1, Quaternion q2) { return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W); } /// <summary> /// Conjugates and renormalizes a vector /// </summary> public static Quaternion Inverse(Quaternion quaternion) { float norm = quaternion.LengthSquared(); if (norm == 0f) { quaternion.X = quaternion.Y = quaternion.Z = quaternion.W = 0f; } else { float oonorm = 1f / norm; quaternion = Conjugate(quaternion); quaternion.X *= oonorm; quaternion.Y *= oonorm; quaternion.Z *= oonorm; quaternion.W *= oonorm; } return quaternion; } /// <summary> /// Spherical linear interpolation between two quaternions /// </summary> public static Quaternion Slerp(Quaternion q1, Quaternion q2, float amount) { float angle = Dot(q1, q2); if (angle < 0f) { q1 *= -1f; angle *= -1f; } float scale; float invscale; if ((angle + 1f) > 0.05f) { if ((1f - angle) >= 0.05f) { // slerp float theta = (float)Math.Acos(angle); float invsintheta = 1f / (float)Math.Sin(theta); scale = (float)Math.Sin(theta * (1f - amount)) * invsintheta; invscale = (float)Math.Sin(theta * amount) * invsintheta; } else { // lerp scale = 1f - amount; invscale = amount; } } else { q2.X = -q1.Y; q2.Y = q1.X; q2.Z = -q1.W; q2.W = q1.Z; scale = (float)Math.Sin(Utils.PI * (0.5f - amount)); invscale = (float)Math.Sin(Utils.PI * amount); } return (q1 * scale) + (q2 * invscale); } public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2) { quaternion1.X -= quaternion2.X; quaternion1.Y -= quaternion2.Y; quaternion1.Z -= quaternion2.Z; quaternion1.W -= quaternion2.W; return quaternion1; } public static Quaternion Multiply(Quaternion a, Quaternion b) { return new Quaternion( a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z ); } public static Quaternion Multiply(Quaternion quaternion, float scaleFactor) { quaternion.X *= scaleFactor; quaternion.Y *= scaleFactor; quaternion.Z *= scaleFactor; quaternion.W *= scaleFactor; return quaternion; } public static Quaternion Negate(Quaternion quaternion) { quaternion.X = -quaternion.X; quaternion.Y = -quaternion.Y; quaternion.Z = -quaternion.Z; quaternion.W = -quaternion.W; return quaternion; } public static Quaternion Normalize(Quaternion q) { const float MAG_THRESHOLD = 0.0000001f; float mag = q.Length(); // Catch very small rounding errors when normalizing if (mag > MAG_THRESHOLD) { float oomag = 1f / mag; q.X *= oomag; q.Y *= oomag; q.Z *= oomag; q.W *= oomag; } else { q.X = 0f; q.Y = 0f; q.Z = 0f; q.W = 1f; } return q; } public static Quaternion Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); if (split.Length == 3) { return new Quaternion( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture)); } else { return new Quaternion( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture), float.Parse(split[3].Trim(), Utils.EnUsCulture)); } } public static bool TryParse(string val, out Quaternion result) { try { result = Parse(val); return true; } catch (Exception) { result = new Quaternion(); return false; } } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Quaternion) ? this == (Quaternion)obj : false; } public bool Equals(Quaternion other) { return W == other.W && X == other.X && Y == other.Y && Z == other.Z; } public override int GetHashCode() { return (X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode()); } public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); } /// <summary> /// Get a string representation of the quaternion elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the quaternion</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W); } #endregion Overrides #region Operators public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2) { return quaternion1.Equals(quaternion2); } public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2) { return !(quaternion1 == quaternion2); } public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2) { return Add(quaternion1, quaternion2); } public static Quaternion operator -(Quaternion quaternion) { return Negate(quaternion); } public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2) { return Subtract(quaternion1, quaternion2); } public static Quaternion operator *(Quaternion a, Quaternion b) { return Multiply(a, b); } public static Quaternion operator *(Quaternion quaternion, float scaleFactor) { return Multiply(quaternion, scaleFactor); } public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2) { return Divide(quaternion1, quaternion2); } #endregion Operators /// <summary>A quaternion with a value of 0,0,0,1</summary> public readonly static Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f); } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using Axiom.Graphics; using Axiom.Media; namespace Axiom.Core { /// <summary> /// Class for loading & managing textures. /// </summary> /// <remarks> /// Texture manager serves as an abstract singleton for all API specific texture managers. /// When a class inherits from this and is created, a instance of that class (i.e. GLTextureManager) /// is stored in the global singleton instance of the TextureManager. /// Note: This will not take place until the RenderSystem is initialized and at least one RenderWindow /// has been created. /// </remarks> public abstract class TextureManager : ResourceManager { #region Singleton implementation /// <summary> /// Singleton instance of this class. /// </summary> private static TextureManager instance; /// <summary> /// Internal constructor. This class cannot be instantiated externally. /// </summary> /// <remarks> /// Protected internal because this singleton will actually hold the instance of a subclass /// created by a render system plugin. /// </remarks> protected internal TextureManager() { if (instance == null) { instance = this; } } /// <summary> /// Gets the singleton instance of this class. /// </summary> public static TextureManager Instance { get { return instance; } } #endregion Singleton implementation #region Fields /// <summary> /// Flag that indicates whether 32-bit texture are being used. /// </summary> protected bool is32Bit; /// <summary> /// Default number of mipmaps to be used for loaded textures. /// </summary> protected int defaultNumMipMaps = 5; #endregion Fields #region Properties /// <summary> /// Gets/Sets the default number of mipmaps to be used for loaded textures. /// </summary> public int DefaultNumMipMaps { get { return defaultNumMipMaps; } set { defaultNumMipMaps = value; } } public bool Is32Bit { get { return is32Bit; } } #endregion Properties #region Methods /// <summary> /// Method for creating a new blank texture. /// </summary> /// <param name="name"></param> /// <param name="texType"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="numMipMaps"></param> /// <param name="format"></param> /// <param name="usage"></param> /// <returns></returns> public Texture CreateManual(string name, TextureType texType, int width, int height, int depth, int numMipmaps, PixelFormat format, TextureUsage usage) { Texture ret = (Texture)Create(name, true); ret.TextureType = texType; ret.Width = width; ret.Height = height; ret.Depth = depth; ret.NumMipMaps = (numMipmaps == -1) ? defaultNumMipMaps : numMipmaps; ret.Format = format; ret.Usage = usage; ret.Enable32Bit(is32Bit); ret.CreateInternalResources(); return ret; } public Texture CreateManual(string name, TextureType type, int width, int height, int numMipmaps, PixelFormat format, TextureUsage usage) { return CreateManual(name, type, width, height, 1, numMipmaps, format, usage); } /// <summary> /// Loads a texture with the specified name. /// </summary> /// <param name="name"></param> /// <returns></returns> public Texture Load(string name) { return Load(name, TextureType.TwoD); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> public Texture Load(string name, TextureType type) { // load the texture by default with -1 mipmaps (uses default), gamma of 1, isAlpha of false return Load(name, type, -1, 1.0f, false); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="numMipMaps"></param> /// <param name="gamma"></param> /// <param name="priority"></param> /// <returns></returns> public Texture Load(string name, TextureType type, int numMipMaps, float gamma, bool isAlpha) { // does this texture exist already? Texture texture = GetByName(name); if (texture == null) { // create a new texture texture = (Texture)Create(name); texture.TextureType = type; if (numMipMaps == -1) texture.NumMipMaps = defaultNumMipMaps; else texture.NumMipMaps = numMipMaps; // set bit depth and gamma texture.Gamma = gamma; if (isAlpha) texture.Format = PixelFormat.A8; texture.Enable32Bit(is32Bit); } // The old code called the base class load method, but now we just call texture.Load() // base.Load(texture, 1); texture.Load(); return texture; } /// <summary> /// Overloaded method. /// </summary> /// <param name="name"></param> /// <param name="image"></param> /// <returns></returns> //public Texture LoadImage(string name, Image image) //{ // return LoadImage(name, image, TextureType.TwoD, -1, 1.0f, 1); //} /// <summary> /// Overloaded method. /// </summary> /// <param name="name"></param> /// <param name="image"></param> /// <param name="texType"></param> /// <returns></returns> //public Texture LoadImage(string name, Image image, TextureType texType) //{ // return LoadImage(name, image, texType, -1, 1.0f, 1); //} public Texture LoadImage(string name, Image image) { return LoadImage(name, image, TextureType.TwoD); } public Texture LoadImage(string name, Image image, TextureType texType) { return LoadImage(name, image, texType, -1, 1.0f, false); } /// <summary> /// Loads a pre-existing image into the texture. /// </summary> /// <param name="name"></param> /// <param name="image">the image to load, or null to return an empty texture</param> /// <param name="numMipMaps"></param> /// <param name="gamma"></param> /// <param name="priority"></param> /// <returns></returns> public Texture LoadImage(string name, Image image, TextureType texType, int numMipMaps, float gamma, bool isAlpha) { // create a new texture Texture texture = (Texture)Create(name, true); texture.TextureType = texType; // set the number of mipmaps to use for this texture if (numMipMaps == -1) texture.NumMipMaps = defaultNumMipMaps; else texture.NumMipMaps = numMipMaps; // set bit depth and gamma texture.Gamma = gamma; if (isAlpha) texture.Format = PixelFormat.A8; texture.Enable32Bit(is32Bit); if (image != null) // load image data texture.LoadImage(image); return texture; } /// <summary> /// Returns an instance of Texture that has the supplied name. /// </summary> /// <param name="name"></param> /// <returns></returns> public new Texture GetByName(string name) { return (Texture)base.GetByName(name); } /// <summary> /// Called when the engine is shutting down. /// </summary> public override void Dispose() { base.Dispose(); if (this == instance) { instance = null; } } public virtual PixelFormat GetNativeFormat(TextureType ttype, PixelFormat format, TextureUsage usage) { // Just throw an error, for non-overriders throw new NotImplementedException(); } public bool IsFormatSupported(TextureType ttype, PixelFormat format, TextureUsage usage) { return GetNativeFormat(ttype, format, usage) == format; } public bool IsEquivalentFormatSupported(TextureType ttype, PixelFormat format, TextureUsage usage) { PixelFormat supportedFormat = GetNativeFormat(ttype, format, usage); // Assume that same or greater number of bits means quality not degraded return PixelUtil.GetNumElemBits(supportedFormat) >= PixelUtil.GetNumElemBits(format); } public virtual int AvailableTextureMemory { get { throw new NotImplementedException(); } } #endregion Methods } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a Spot instance request. /// </summary> public partial class SpotInstanceRequest { private string _actualBlockHourlyPrice; private string _availabilityZoneGroup; private int? _blockDurationMinutes; private DateTime? _createTime; private SpotInstanceStateFault _fault; private string _instanceId; private string _launchedAvailabilityZone; private string _launchGroup; private LaunchSpecification _launchSpecification; private RIProductDescription _productDescription; private string _spotInstanceRequestId; private string _spotPrice; private SpotInstanceState _state; private SpotInstanceStatus _status; private List<Tag> _tags = new List<Tag>(); private SpotInstanceType _type; private DateTime? _validFrom; private DateTime? _validUntil; /// <summary> /// Gets and sets the property ActualBlockHourlyPrice. /// <para> /// If you specified a duration and your Spot instance request was fulfilled, this is /// the fixed hourly price in effect for the Spot instance while it runs. /// </para> /// </summary> public string ActualBlockHourlyPrice { get { return this._actualBlockHourlyPrice; } set { this._actualBlockHourlyPrice = value; } } // Check to see if ActualBlockHourlyPrice property is set internal bool IsSetActualBlockHourlyPrice() { return this._actualBlockHourlyPrice != null; } /// <summary> /// Gets and sets the property AvailabilityZoneGroup. /// <para> /// The Availability Zone group. If you specify the same Availability Zone group for all /// Spot instance requests, all Spot instances are launched in the same Availability Zone. /// </para> /// </summary> public string AvailabilityZoneGroup { get { return this._availabilityZoneGroup; } set { this._availabilityZoneGroup = value; } } // Check to see if AvailabilityZoneGroup property is set internal bool IsSetAvailabilityZoneGroup() { return this._availabilityZoneGroup != null; } /// <summary> /// Gets and sets the property BlockDurationMinutes. /// <para> /// The duration for the Spot instance, in minutes. /// </para> /// </summary> public int BlockDurationMinutes { get { return this._blockDurationMinutes.GetValueOrDefault(); } set { this._blockDurationMinutes = value; } } // Check to see if BlockDurationMinutes property is set internal bool IsSetBlockDurationMinutes() { return this._blockDurationMinutes.HasValue; } /// <summary> /// Gets and sets the property CreateTime. /// <para> /// The date and time when the Spot instance request was created, in UTC format (for example, /// <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z). /// </para> /// </summary> public DateTime CreateTime { get { return this._createTime.GetValueOrDefault(); } set { this._createTime = value; } } // Check to see if CreateTime property is set internal bool IsSetCreateTime() { return this._createTime.HasValue; } /// <summary> /// Gets and sets the property Fault. /// <para> /// The fault codes for the Spot instance request, if any. /// </para> /// </summary> public SpotInstanceStateFault Fault { get { return this._fault; } set { this._fault = value; } } // Check to see if Fault property is set internal bool IsSetFault() { return this._fault != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The instance ID, if an instance has been launched to fulfill the Spot instance request. /// </para> /// </summary> public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } /// <summary> /// Gets and sets the property LaunchedAvailabilityZone. /// <para> /// The Availability Zone in which the bid is launched. /// </para> /// </summary> public string LaunchedAvailabilityZone { get { return this._launchedAvailabilityZone; } set { this._launchedAvailabilityZone = value; } } // Check to see if LaunchedAvailabilityZone property is set internal bool IsSetLaunchedAvailabilityZone() { return this._launchedAvailabilityZone != null; } /// <summary> /// Gets and sets the property LaunchGroup. /// <para> /// The instance launch group. Launch groups are Spot instances that launch together and /// terminate together. /// </para> /// </summary> public string LaunchGroup { get { return this._launchGroup; } set { this._launchGroup = value; } } // Check to see if LaunchGroup property is set internal bool IsSetLaunchGroup() { return this._launchGroup != null; } /// <summary> /// Gets and sets the property LaunchSpecification. /// <para> /// Additional information for launching instances. /// </para> /// </summary> public LaunchSpecification LaunchSpecification { get { return this._launchSpecification; } set { this._launchSpecification = value; } } // Check to see if LaunchSpecification property is set internal bool IsSetLaunchSpecification() { return this._launchSpecification != null; } /// <summary> /// Gets and sets the property ProductDescription. /// <para> /// The product description associated with the Spot instance. /// </para> /// </summary> public RIProductDescription ProductDescription { get { return this._productDescription; } set { this._productDescription = value; } } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this._productDescription != null; } /// <summary> /// Gets and sets the property SpotInstanceRequestId. /// <para> /// The ID of the Spot instance request. /// </para> /// </summary> public string SpotInstanceRequestId { get { return this._spotInstanceRequestId; } set { this._spotInstanceRequestId = value; } } // Check to see if SpotInstanceRequestId property is set internal bool IsSetSpotInstanceRequestId() { return this._spotInstanceRequestId != null; } /// <summary> /// Gets and sets the property SpotPrice. /// <para> /// The maximum hourly price (bid) for the Spot instance launched to fulfill the request. /// </para> /// </summary> public string SpotPrice { get { return this._spotPrice; } set { this._spotPrice = value; } } // Check to see if SpotPrice property is set internal bool IsSetSpotPrice() { return this._spotPrice != null; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the Spot instance request. Spot bid status information can help you track /// your Spot instance requests. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html">Spot /// Bid Status</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public SpotInstanceState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status code and status message describing the Spot instance request. /// </para> /// </summary> public SpotInstanceStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the resource. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property Type. /// <para> /// The Spot instance request type. /// </para> /// </summary> public SpotInstanceType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property ValidFrom. /// <para> /// The start date of the request, in UTC format (for example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z). /// The request becomes active at this date and time. /// </para> /// </summary> public DateTime ValidFrom { get { return this._validFrom.GetValueOrDefault(); } set { this._validFrom = value; } } // Check to see if ValidFrom property is set internal bool IsSetValidFrom() { return this._validFrom.HasValue; } /// <summary> /// Gets and sets the property ValidUntil. /// <para> /// The end date of the request, in UTC format (for example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z). /// If this is a one-time request, it remains active until all instances launch, the request /// is canceled, or this date is reached. If the request is persistent, it remains active /// until it is canceled or this date is reached. /// </para> /// </summary> public DateTime ValidUntil { get { return this._validUntil.GetValueOrDefault(); } set { this._validUntil = value; } } // Check to see if ValidUntil property is set internal bool IsSetValidUntil() { return this._validUntil.HasValue; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // FixedMaxHeap.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.Contracts; namespace System.Linq.Parallel { /// <summary> /// Very simple heap data structure, of fixed size. /// </summary> /// <typeparam name="TElement"></typeparam> internal class FixedMaxHeap<TElement> { private TElement[] _elements; // Element array. private int _count; // Current count. private IComparer<TElement> _comparer; // Element comparison routine. //----------------------------------------------------------------------------------- // Create a new heap with the specified maximum size. // internal FixedMaxHeap(int maximumSize) : this(maximumSize, Util.GetDefaultComparer<TElement>()) { } internal FixedMaxHeap(int maximumSize, IComparer<TElement> comparer) { Contract.Assert(comparer != null); _elements = new TElement[maximumSize]; _comparer = comparer; } //----------------------------------------------------------------------------------- // Retrieve the count (i.e. how many elements are in the heap). // internal int Count { get { return _count; } } //----------------------------------------------------------------------------------- // Retrieve the size (i.e. the maximum size of the heap). // internal int Size { get { return _elements.Length; } } //----------------------------------------------------------------------------------- // Get the current maximum value in the max-heap. // // Note: The heap stores the maximumSize smallest elements that were inserted. // So, if the heap is full, the value returned is the maximumSize-th smallest // element that was inserted into the heap. // internal TElement MaxValue { get { if (_count == 0) { throw new InvalidOperationException(SR.NoElements); } // The maximum element is in the 0th position. return _elements[0]; } } //----------------------------------------------------------------------------------- // Removes all elements from the heap. // internal void Clear() { _count = 0; } //----------------------------------------------------------------------------------- // Inserts the new element, maintaining the heap property. // // Return Value: // If the element is greater than the current max element, this function returns // false without modifying the heap. Otherwise, it returns true. // internal bool Insert(TElement e) { if (_count < _elements.Length) { // There is room. We can add it and then max-heapify. _elements[_count] = e; _count++; HeapifyLastLeaf(); return true; } else { // No more room. The element might not even fit in the heap. The check // is simple: if it's greater than the maximum element, then it can't be // inserted. Otherwise, we replace the head with it and reheapify. if (_comparer.Compare(e, _elements[0]) < 0) { _elements[0] = e; HeapifyRoot(); return true; } return false; } } //----------------------------------------------------------------------------------- // Replaces the maximum value in the heap with the user-provided value, and restores // the heap property. // internal void ReplaceMax(TElement newValue) { Contract.Assert(_count > 0); _elements[0] = newValue; HeapifyRoot(); } //----------------------------------------------------------------------------------- // Removes the maximum value from the heap, and restores the heap property. // internal void RemoveMax() { Contract.Assert(_count > 0); _count--; if (_count > 0) { _elements[0] = _elements[_count]; HeapifyRoot(); } } //----------------------------------------------------------------------------------- // Private helpers to swap elements, and to reheapify starting from the root or // from a leaf element, depending on what is needed. // private void Swap(int i, int j) { TElement tmpElement = _elements[i]; _elements[i] = _elements[j]; _elements[j] = tmpElement; } private void HeapifyRoot() { // We are heapifying from the head of the list. int i = 0; int n = _count; while (i < n) { // Calculate the current child node indexes. int n0 = ((i + 1) * 2) - 1; int n1 = n0 + 1; if (n0 < n && _comparer.Compare(_elements[i], _elements[n0]) < 0) { // We have to select the bigger of the two subtrees, and float // the current element down. This maintains the max-heap property. if (n1 < n && _comparer.Compare(_elements[n0], _elements[n1]) < 0) { Swap(i, n1); i = n1; } else { Swap(i, n0); i = n0; } } else if (n1 < n && _comparer.Compare(_elements[i], _elements[n1]) < 0) { // Float down the "right" subtree. We needn't compare this subtree // to the "left", because if the element was smaller than that, the // first if statement's predicate would have evaluated to true. Swap(i, n1); i = n1; } else { // Else, the current key is in its final position. Break out // of the current loop and return. break; } } } private void HeapifyLastLeaf() { int i = _count - 1; while (i > 0) { int j = ((i + 1) / 2) - 1; if (_comparer.Compare(_elements[i], _elements[j]) > 0) { Swap(i, j); i = j; } else { break; } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/admin/table/v1/bigtable_table_service.proto #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Bigtable.Admin.Table.V1 { public static class BigtableTableService { static readonly string __ServiceName = "google.bigtable.admin.table.v1.BigtableTableService"; static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.CreateTableRequest> __Marshaller_CreateTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.CreateTableRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.Table> __Marshaller_Table = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.Table.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.ListTablesRequest> __Marshaller_ListTablesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.ListTablesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> __Marshaller_ListTablesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.ListTablesResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.GetTableRequest> __Marshaller_GetTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.GetTableRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest> __Marshaller_DeleteTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.Empty.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.RenameTableRequest> __Marshaller_RenameTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.RenameTableRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest> __Marshaller_CreateColumnFamilyRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> __Marshaller_ColumnFamily = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.ColumnFamily.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest> __Marshaller_DeleteColumnFamilyRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest.Parser.ParseFrom); static readonly Method<global::Google.Bigtable.Admin.Table.V1.CreateTableRequest, global::Google.Bigtable.Admin.Table.V1.Table> __Method_CreateTable = new Method<global::Google.Bigtable.Admin.Table.V1.CreateTableRequest, global::Google.Bigtable.Admin.Table.V1.Table>( MethodType.Unary, __ServiceName, "CreateTable", __Marshaller_CreateTableRequest, __Marshaller_Table); static readonly Method<global::Google.Bigtable.Admin.Table.V1.ListTablesRequest, global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> __Method_ListTables = new Method<global::Google.Bigtable.Admin.Table.V1.ListTablesRequest, global::Google.Bigtable.Admin.Table.V1.ListTablesResponse>( MethodType.Unary, __ServiceName, "ListTables", __Marshaller_ListTablesRequest, __Marshaller_ListTablesResponse); static readonly Method<global::Google.Bigtable.Admin.Table.V1.GetTableRequest, global::Google.Bigtable.Admin.Table.V1.Table> __Method_GetTable = new Method<global::Google.Bigtable.Admin.Table.V1.GetTableRequest, global::Google.Bigtable.Admin.Table.V1.Table>( MethodType.Unary, __ServiceName, "GetTable", __Marshaller_GetTableRequest, __Marshaller_Table); static readonly Method<global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest, global::Google.Protobuf.Empty> __Method_DeleteTable = new Method<global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest, global::Google.Protobuf.Empty>( MethodType.Unary, __ServiceName, "DeleteTable", __Marshaller_DeleteTableRequest, __Marshaller_Empty); static readonly Method<global::Google.Bigtable.Admin.Table.V1.RenameTableRequest, global::Google.Protobuf.Empty> __Method_RenameTable = new Method<global::Google.Bigtable.Admin.Table.V1.RenameTableRequest, global::Google.Protobuf.Empty>( MethodType.Unary, __ServiceName, "RenameTable", __Marshaller_RenameTableRequest, __Marshaller_Empty); static readonly Method<global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest, global::Google.Bigtable.Admin.Table.V1.ColumnFamily> __Method_CreateColumnFamily = new Method<global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>( MethodType.Unary, __ServiceName, "CreateColumnFamily", __Marshaller_CreateColumnFamilyRequest, __Marshaller_ColumnFamily); static readonly Method<global::Google.Bigtable.Admin.Table.V1.ColumnFamily, global::Google.Bigtable.Admin.Table.V1.ColumnFamily> __Method_UpdateColumnFamily = new Method<global::Google.Bigtable.Admin.Table.V1.ColumnFamily, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>( MethodType.Unary, __ServiceName, "UpdateColumnFamily", __Marshaller_ColumnFamily, __Marshaller_ColumnFamily); static readonly Method<global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest, global::Google.Protobuf.Empty> __Method_DeleteColumnFamily = new Method<global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest, global::Google.Protobuf.Empty>( MethodType.Unary, __ServiceName, "DeleteColumnFamily", __Marshaller_DeleteColumnFamilyRequest, __Marshaller_Empty); // service descriptor public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.Proto.BigtableTableService.Descriptor.Services[0]; } } // client interface public interface IBigtableTableServiceClient { global::Google.Bigtable.Admin.Table.V1.Table CreateTable(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Bigtable.Admin.Table.V1.Table CreateTable(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, CallOptions options); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> CreateTableAsync(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> CreateTableAsync(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, CallOptions options); global::Google.Bigtable.Admin.Table.V1.ListTablesResponse ListTables(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Bigtable.Admin.Table.V1.ListTablesResponse ListTables(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, CallOptions options); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> ListTablesAsync(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> ListTablesAsync(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, CallOptions options); global::Google.Bigtable.Admin.Table.V1.Table GetTable(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Bigtable.Admin.Table.V1.Table GetTable(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, CallOptions options); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> GetTableAsync(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> GetTableAsync(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, CallOptions options); global::Google.Protobuf.Empty DeleteTable(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Protobuf.Empty DeleteTable(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, CallOptions options); AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteTableAsync(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteTableAsync(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, CallOptions options); global::Google.Protobuf.Empty RenameTable(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Protobuf.Empty RenameTable(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, CallOptions options); AsyncUnaryCall<global::Google.Protobuf.Empty> RenameTableAsync(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Protobuf.Empty> RenameTableAsync(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, CallOptions options); global::Google.Bigtable.Admin.Table.V1.ColumnFamily CreateColumnFamily(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Bigtable.Admin.Table.V1.ColumnFamily CreateColumnFamily(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, CallOptions options); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> CreateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> CreateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, CallOptions options); global::Google.Bigtable.Admin.Table.V1.ColumnFamily UpdateColumnFamily(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Bigtable.Admin.Table.V1.ColumnFamily UpdateColumnFamily(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, CallOptions options); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> UpdateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> UpdateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, CallOptions options); global::Google.Protobuf.Empty DeleteColumnFamily(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Google.Protobuf.Empty DeleteColumnFamily(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, CallOptions options); AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, CallOptions options); } // server-side interface public interface IBigtableTableService { Task<global::Google.Bigtable.Admin.Table.V1.Table> CreateTable(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, ServerCallContext context); Task<global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> ListTables(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, ServerCallContext context); Task<global::Google.Bigtable.Admin.Table.V1.Table> GetTable(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, ServerCallContext context); Task<global::Google.Protobuf.Empty> DeleteTable(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, ServerCallContext context); Task<global::Google.Protobuf.Empty> RenameTable(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, ServerCallContext context); Task<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> CreateColumnFamily(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, ServerCallContext context); Task<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> UpdateColumnFamily(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, ServerCallContext context); Task<global::Google.Protobuf.Empty> DeleteColumnFamily(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, ServerCallContext context); } // client stub public class BigtableTableServiceClient : ClientBase, IBigtableTableServiceClient { public BigtableTableServiceClient(Channel channel) : base(channel) { } public global::Google.Bigtable.Admin.Table.V1.Table CreateTable(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CreateTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.Table CreateTable(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, CallOptions options) { var call = CreateCall(__Method_CreateTable, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> CreateTableAsync(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CreateTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> CreateTableAsync(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest request, CallOptions options) { var call = CreateCall(__Method_CreateTable, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.ListTablesResponse ListTables(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_ListTables, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.ListTablesResponse ListTables(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, CallOptions options) { var call = CreateCall(__Method_ListTables, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> ListTablesAsync(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_ListTables, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ListTablesResponse> ListTablesAsync(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest request, CallOptions options) { var call = CreateCall(__Method_ListTables, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.Table GetTable(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_GetTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.Table GetTable(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, CallOptions options) { var call = CreateCall(__Method_GetTable, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> GetTableAsync(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_GetTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.Table> GetTableAsync(global::Google.Bigtable.Admin.Table.V1.GetTableRequest request, CallOptions options) { var call = CreateCall(__Method_GetTable, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Protobuf.Empty DeleteTable(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_DeleteTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Protobuf.Empty DeleteTable(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, CallOptions options) { var call = CreateCall(__Method_DeleteTable, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteTableAsync(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_DeleteTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteTableAsync(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest request, CallOptions options) { var call = CreateCall(__Method_DeleteTable, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Protobuf.Empty RenameTable(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RenameTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Protobuf.Empty RenameTable(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, CallOptions options) { var call = CreateCall(__Method_RenameTable, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Protobuf.Empty> RenameTableAsync(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RenameTable, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Protobuf.Empty> RenameTableAsync(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest request, CallOptions options) { var call = CreateCall(__Method_RenameTable, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.ColumnFamily CreateColumnFamily(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CreateColumnFamily, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.ColumnFamily CreateColumnFamily(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, CallOptions options) { var call = CreateCall(__Method_CreateColumnFamily, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> CreateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CreateColumnFamily, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> CreateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest request, CallOptions options) { var call = CreateCall(__Method_CreateColumnFamily, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.ColumnFamily UpdateColumnFamily(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UpdateColumnFamily, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Bigtable.Admin.Table.V1.ColumnFamily UpdateColumnFamily(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, CallOptions options) { var call = CreateCall(__Method_UpdateColumnFamily, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> UpdateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UpdateColumnFamily, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Bigtable.Admin.Table.V1.ColumnFamily> UpdateColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.ColumnFamily request, CallOptions options) { var call = CreateCall(__Method_UpdateColumnFamily, options); return Calls.AsyncUnaryCall(call, request); } public global::Google.Protobuf.Empty DeleteColumnFamily(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_DeleteColumnFamily, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Google.Protobuf.Empty DeleteColumnFamily(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, CallOptions options) { var call = CreateCall(__Method_DeleteColumnFamily, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_DeleteColumnFamily, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Google.Protobuf.Empty> DeleteColumnFamilyAsync(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest request, CallOptions options) { var call = CreateCall(__Method_DeleteColumnFamily, options); return Calls.AsyncUnaryCall(call, request); } } // creates service definition that can be registered with a server public static ServerServiceDefinition BindService(IBigtableTableService serviceImpl) { return ServerServiceDefinition.CreateBuilder(__ServiceName) .AddMethod(__Method_CreateTable, serviceImpl.CreateTable) .AddMethod(__Method_ListTables, serviceImpl.ListTables) .AddMethod(__Method_GetTable, serviceImpl.GetTable) .AddMethod(__Method_DeleteTable, serviceImpl.DeleteTable) .AddMethod(__Method_RenameTable, serviceImpl.RenameTable) .AddMethod(__Method_CreateColumnFamily, serviceImpl.CreateColumnFamily) .AddMethod(__Method_UpdateColumnFamily, serviceImpl.UpdateColumnFamily) .AddMethod(__Method_DeleteColumnFamily, serviceImpl.DeleteColumnFamily).Build(); } // creates a new client public static BigtableTableServiceClient NewClient(Channel channel) { return new BigtableTableServiceClient(channel); } } } #endregion
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Management.Automation; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Used to initiate a recovery protection operation. /// </summary> [Cmdlet( VerbsData.Update, "AzureRmRecoveryServicesAsrProtectionDirection", DefaultParameterSetName = ASRParameterSets.ByRPIObject, SupportsShouldProcess = true)] [Alias("Update-ASRProtectionDirection")] [OutputType(typeof(ASRJob))] public class UpdateAzureRmRecoveryServicesAsrProtection : SiteRecoveryCmdletBase { /// <summary> /// Gets or sets Name of the Fabric. /// </summary> public string fabricName; /// <summary> /// Gets or sets Name of the Protection Container. /// </summary> public string protectionContainerName; /// <summary> /// Gets or sets Name of the PE. /// </summary> public string protectionEntityName; /// <summary> /// Gets or sets Recovery Plan object. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRRecoveryPlan RecoveryPlan { get; set; } /// <summary> /// Gets or sets Replication Protected Item. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRReplicationProtectedItem ReplicationProtectedItem { get; set; } /// <summary> /// Gets or sets Failover direction for the recovery plan. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.ByPEObject, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = true)] [ValidateSet( Constants.PrimaryToRecovery, Constants.RecoveryToPrimary)] public string Direction { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( "Protected item or Recovery plan", "Update protection direction")) { switch (this.ParameterSetName) { case ASRParameterSets.ByRPIObject: this.protectionContainerName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers); this.fabricName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationFabrics); this.SetRPIReprotect(); break; case ASRParameterSets.ByRPObject: this.SetRPReprotect(); break; } } } /// <summary> /// RPI Reprotect. /// </summary> private void SetRPIReprotect() { var plannedFailoverInputProperties = new ReverseReplicationInputProperties { FailoverDirection = this.Direction, ProviderSpecificDetails = new ReverseReplicationProviderSpecificInput() }; var input = new ReverseReplicationInput { Properties = plannedFailoverInputProperties }; // fetch the latest Protectable item objects var replicationProtectedItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryReplicationProtectedItem( this.fabricName, this.protectionContainerName, this.ReplicationProtectedItem.Name); var protectableItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( this.fabricName, this.protectionContainerName, Utilities.GetValueFromArmId( replicationProtectedItemResponse.Properties.ProtectableItemId, ARMResourceTypeConstants.ProtectableItems)); var aSRProtectableItem = new ASRProtectableItem(protectableItemResponse); if (0 == string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { if (this.Direction == Constants.PrimaryToRecovery) { var reprotectInput = new HyperVReplicaAzureReprotectInput { HvHostVmId = aSRProtectableItem.FabricObjectId, VmName = aSRProtectableItem.FriendlyName, OsType = (string.Compare( aSRProtectableItem.OS, "Windows") == 0) || (string.Compare( aSRProtectableItem.OS, "Linux") == 0) ? aSRProtectableItem.OS : "Windows", VHDId = aSRProtectableItem.OSDiskId }; var providerSpecificDetails = (HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse .Properties.ProviderSpecificDetails; reprotectInput.StorageAccountId = providerSpecificDetails.RecoveryAzureStorageAccount; input.Properties.ProviderSpecificDetails = reprotectInput; } } var response = this.RecoveryServicesClient.StartAzureSiteRecoveryReprotection( this.fabricName, this.protectionContainerName, this.ReplicationProtectedItem.Name, input); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } /// <summary> /// Starts RP Reprotect. /// </summary> private void SetRPReprotect() { var response = this.RecoveryServicesClient.UpdateAzureSiteRecoveryProtection( this.RecoveryPlan.Name); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } } }
//----------------------------------------------------------------------- // <copyright file="AntiEntropyProtocol.cs" company="CompanyName"> // Copyright info. // </copyright> //----------------------------------------------------------------------- namespace Distribox.Network { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Distribox.CommonLib; using Distribox.FileSystem; /// <summary> /// The implementation of Anti-entropy protocol. /// <para /> /// Anti-entropy protocol is first purposed in 1980s, using for maintaining replicated databases all over the world. According to literature, it is "extremely robust" [1]. /// Generally, there are two kind of approaches to synchronize data: the reactive approach and epidemic approach. In the former one, when some change happen, the peer changed acknowledge other peers and these peers get changed too. These newly changed peer continue acknowledging peers, until the change is spread to the whole network. This protocol is not robust, since connection error may happen any time, much effort is needed to prevent potential factors that leads spreading stop before changes are spread. For example, all the peers with change are isolated with other peers at some moment. /// Instead of passively receive changes, epidemic approach try to synchronize with other nodes consistently. Implementing such protocols involves much less consideration than radioactive approaches. /// <para /> /// Reference /// [1] Demers, Alan, et al. "Epidemic algorithms for replicated database maintenance." Proceedings of the sixth annual ACM Symposium on Principles of distributed computing. ACM, 1987. /// </summary> public class AntiEntropyProtocol { /// <summary> /// The peers. /// </summary> private PeerList peers; /// <summary> /// The listener. /// </summary> private AtomicMessageListener listener; /// <summary> /// The listening port. /// </summary> private int listeningPort; /// <summary> /// The version control. /// </summary> private VersionControl versionControl; /// <summary> /// Use File Event as its member /// </summary> private RequestManager requestManager; /// <summary> /// Factory class for ProtocolMessage /// </summary> private ProtocolMessageFactory messageFactory; /// <summary> /// Initializes a new instance of the <see cref="Distribox.Network.AntiEntropyProtocol"/> class. /// </summary> /// <param name="listeningPort">Listening port.</param> /// <param name="peerFileName">Peer file name.</param> /// <param name="versionControl">Version control.</param> public AntiEntropyProtocol(int listeningPort, string peerFileName, VersionControl versionControl) { // Initialize version control this.versionControl = versionControl; // Initialize peer list this.peers = PeerList.GetPeerList(peerFileName); this.listeningPort = listeningPort; // Initialize listener this.listener = new AtomicMessageListener(listeningPort); this.listener.OnReceive += this.OnReceiveMessage; // Initialize timer to connect other peers periodically System.Timers.Timer timer = new System.Timers.Timer(Config.ConnectPeriodMs); timer.Elapsed += this.OnTimerEvent; timer.AutoReset = true; timer.Enabled = true; // Initialize request manager this.requestManager = new RequestManager(); // Initialize Protocol message factory this.messageFactory = new ProtocolMessageFactory(); } /// <summary> /// Invites a peer into P2P network. /// </summary> /// <param name="peer">The peer to be invited.</param> public void InvitePeer(Peer peer) { SendMessage(peer, new InvitationRequest(this.listeningPort)); } /// <summary> /// Process the invitation message. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(InvitationRequest message, Peer peer) { // Send AcceptInvivation back SendMessage(peer, new InvitationAck(this.listeningPort)); } /// <summary> /// Process the accept message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(InvitationAck message, Peer peer) { // Try to sync with the newly accepted peer SendMessage(peer, new SyncRequest(this.listeningPort)); } /// <summary> /// Process the sync message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(SyncRequest message, Peer peer) { // Accept the sync request SendMessage(peer, new SyncAck(this.listeningPort)); // Send MetaData this.SendMetaData(peer); } /// <summary> /// Process the specified message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(SyncAck message, Peer peer) { this.SendMetaData(peer); } /// <summary> /// Process the peer list message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(PeerListMessage message, Peer peer) { lock (this.peers) { this.peers.AddPeer(peer); this.peers.MergeWith(message.List); } } /// <summary> /// Process the version list message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(VersionListMessage message, Peer peer) { List<FileEvent> versionRequest; lock (this.versionControl.VersionList) { versionRequest = this.versionControl.VersionList.GetLessThan(message.List); Logger.Info("Received version list from {1}\n{0}", message.List.Serialize(), peer.Serialize()); } // Don't request them now, add them to a request queue first this.requestManager.AddRequests(versionRequest, peer); this.TryToRequest(); } /// <summary> /// Process the file request message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(PatchRequest message, Peer peer) { Logger.Info("Receive file request\n{0}", message.Request.Serialize()); byte[] data = VersionControl.CreateFileBundle(message.Request); SendMessage(peer, new FileDataResponse(data, this.listeningPort)); } /// <summary> /// Process the specified message and peer. /// </summary> /// <param name="message">The message.</param> /// <param name="peer">The peer.</param> internal void Process(FileDataResponse message, Peer peer) { List<FileEvent> patches; lock (this.versionControl.VersionList) { patches = this.versionControl.AcceptFileBundle(message.Data); } this.requestManager.FinishRequests(patches); this.TryToRequest(); } /// <summary> /// Sends a message to peer. /// </summary> /// <param name="peer">The peer.</param> /// <param name="message">The message.</param> /// <param name="onCompleteHandler">On complete handler.</param> private static void SendMessage(Peer peer, ProtocolMessage message, AtomicMessageSender.OnCompleteHandler onCompleteHandler = null) { if (peer == null) { return; } AtomicMessageSender sender = new Network.AtomicMessageSender(peer); if (onCompleteHandler != null) { sender.OnComplete += onCompleteHandler; } byte[] bytesMessage = new ProtocolMessageContainer(message).SerializeAsBytes(); sender.SendBytes(bytesMessage); // TODO on error } /// <summary> /// Handle receive message event. /// </summary> /// <param name="data">The data.</param> /// <param name="peerFrom">peer from.</param> private void OnReceiveMessage(byte[] data, Peer peerFrom) { this.ParseAndDispatchMessage(data, peerFrom); } /// <summary> /// Parses and dispatch message from peer. /// </summary> /// <param name="data">The ata.</param> /// <param name="peerFrom">The address.</param> private void ParseAndDispatchMessage(byte[] data, Peer peerFrom) { // Parse it, and convert to the right derived class var container = CommonHelper.Deserialize<ProtocolMessageContainer>(data); ProtocolMessage message = this.messageFactory.CreateMessage(container); // ipAndPort[1] is the port of the sender socket, but we need the number of the listener port...... int port = message.ListeningPort; Peer peer = new Peer(peerFrom.IP, port); // Process message (visitor design pattern) message.Accept(this, peer); } /// <summary> /// Repeatedly get and send new requests, until `RequestManager` don't give us any more requests. (May because /// there are no more requests or request manager thinks there are too many patches requesting now). /// </summary> private void TryToRequest() { while (true) { // Get a request from RequestManager var requestTuple = this.requestManager.GetRequests(); // Maybe there are not any requests... if (requestTuple == null) { return; } List<FileEvent> patches = requestTuple.Item1; Peer peer = requestTuple.Item2; // Send out the request SendMessage(peer, new PatchRequest(patches, this.listeningPort)); } } /// <summary> /// Sends the meta data. /// </summary> /// <param name="peer">The peer.</param> private void SendMetaData(Peer peer) { // Send PeerList SendMessage(peer, new PeerListMessage(this.peers, this.listeningPort)); // Send VersionList SendMessage(peer, new VersionListMessage(this.versionControl.VersionList, this.listeningPort)); } /// <summary> /// Connects a random peer to send a connection request. /// </summary> private void ConnectRandomPeer() { if (this.peers.Peers.Count() == 0) { return; } Peer peer; // Lock peers to support thread-safety lock (this.peers) { // This might select itself, whatever, we'll accept it. peer = this.peers.SelectRandomPeer(); } if (peer != null) { SendMessage(peer, new SyncRequest(this.listeningPort)); } } /// <summary> /// Handle timer event. /// </summary> /// <param name="source">Source of event.</param> /// <param name="e">The event.</param> private void OnTimerEvent(object source, System.Timers.ElapsedEventArgs e) { this.ConnectRandomPeer(); } } }
using System; using System.Collections; using System.Collections.Generic; using StructureMap.Configuration.DSL; using StructureMap.Construction; using StructureMap.Diagnostics; using StructureMap.Exceptions; using StructureMap.Graph; using StructureMap.Interceptors; using StructureMap.Pipeline; using StructureMap.Query; using StructureMap.TypeRules; namespace StructureMap { public class Container : IContainer { private InterceptorLibrary _interceptorLibrary; private PipelineGraph _pipelineGraph; private PluginGraph _pluginGraph; public Container(Action<ConfigurationExpression> action) { var expression = new ConfigurationExpression(); action(expression); // As explained later in the article, // PluginGraph is part of the Semantic Model // of StructureMap PluginGraph graph = expression.BuildGraph(); // Take the PluginGraph object graph and // dynamically emit classes to build the // configured objects construct(graph); } public Container(Registry registry) : this(registry.Build()) { } public Container() : this(new PluginGraph()) { } /// <summary> /// Constructor to create an Container /// </summary> /// <param name="pluginGraph">PluginGraph containing the instance and type definitions /// for the Container</param> public Container(PluginGraph pluginGraph) { construct(pluginGraph); } protected MissingFactoryFunction onMissingFactory { set { _pipelineGraph.OnMissingFactory = value; } } public PluginGraph PluginGraph { get { return _pluginGraph; } } #region IContainer Members /// <summary> /// Provides queryable access to the configured PluginType's and Instances of this Container /// </summary> public IModel Model { get { return new Model(_pipelineGraph, this); } } /// <summary> /// Creates or finds the named instance of T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instanceKey"></param> /// <returns></returns> public T GetInstance<T>(string instanceKey) { return (T) GetInstance(typeof (T), instanceKey); } /// <summary> /// Creates a new instance of the requested type T using the supplied Instance. Mostly used internally /// </summary> /// <param name="instance"></param> /// <returns></returns> public T GetInstance<T>(Instance instance) { return (T) GetInstance(typeof (T), instance); } /// <summary> /// Gets the default instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <param name="args"></param> /// <returns></returns> public PLUGINTYPE GetInstance<PLUGINTYPE>(ExplicitArguments args) { return (PLUGINTYPE) GetInstance(typeof (PLUGINTYPE), args); } public T GetInstance<T>(ExplicitArguments args, string name) { Instance namedInstance = _pipelineGraph.ForType(typeof (T)).FindInstance(name); return (T) buildInstanceWithArgs(typeof (T), namedInstance, args, name); } /// <summary> /// Gets the default instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <param name="pluginType"></param> /// <param name="args"></param> /// <returns></returns> public object GetInstance(Type pluginType, ExplicitArguments args) { Instance defaultInstance = _pipelineGraph.GetDefault(pluginType); string requestedName = Plugin.DEFAULT; return buildInstanceWithArgs(pluginType, defaultInstance, args, requestedName); } /// <summary> /// Gets all configured instances of type T using explicitly configured arguments from the "args" /// </summary> /// <param name="type"></param> /// <param name="args"></param> /// <returns></returns> public IList GetAllInstances(Type type, ExplicitArguments args) { BuildSession session = withNewSession(Plugin.DEFAULT); args.RegisterDefaults(session); Array instances = session.CreateInstanceArray(type, null); return new ArrayList(instances); } public IList<T> GetAllInstances<T>(ExplicitArguments args) { BuildSession session = withNewSession(Plugin.DEFAULT); args.RegisterDefaults(session); return getListOfTypeWithSession<T>(session); } /// <summary> /// Creates or finds the default instance of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetInstance<T>() { return (T) GetInstance(typeof (T)); } [Obsolete("Please use GetInstance<T>() instead.")] public T FillDependencies<T>() { return (T) FillDependencies(typeof (T)); } /// <summary> /// Creates or resolves all registered instances of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public IList<T> GetAllInstances<T>() { BuildSession session = withNewSession(Plugin.DEFAULT); return getListOfTypeWithSession<T>(session); } /// <summary> /// Sets the default instance for all PluginType's to the designated Profile. /// </summary> /// <param name="profile"></param> public void SetDefaultsToProfile(string profile) { _pipelineGraph.CurrentProfile = profile; } /// <summary> /// Creates or finds the named instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> public object GetInstance(Type pluginType, string instanceKey) { return withNewSession(instanceKey).CreateInstance(pluginType, instanceKey); } /// <summary> /// Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> public object TryGetInstance(Type pluginType, string instanceKey) { return !_pipelineGraph.HasInstance(pluginType, instanceKey) ? null : GetInstance(pluginType, instanceKey); } /// <summary> /// Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public object TryGetInstance(Type pluginType) { return !_pipelineGraph.HasDefaultForPluginType(pluginType) ? null : GetInstance(pluginType); } /// <summary> /// Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T TryGetInstance<T>() { return (T) (TryGetInstance(typeof (T)) ?? default(T)); } /// <summary> /// The "BuildUp" method takes in an already constructed object /// and uses Setter Injection to push in configured dependencies /// of that object /// </summary> /// <param name="target"></param> public void BuildUp(object target) { Type pluggedType = target.GetType(); IConfiguredInstance instance = _pipelineGraph.GetDefault(pluggedType) as IConfiguredInstance ?? new ConfiguredInstance(pluggedType); IInstanceBuilder builder = PluginCache.FindBuilder(pluggedType); var arguments = new Arguments(instance, withNewSession(Plugin.DEFAULT)); builder.BuildUp(arguments, target); } /// <summary> /// Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T TryGetInstance<T>(string instanceKey) { return (T) (TryGetInstance(typeof (T), instanceKey) ?? default(T)); } /// <summary> /// Creates or finds the default instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public object GetInstance(Type pluginType) { return withNewSession(Plugin.DEFAULT).CreateInstance(pluginType); } /// <summary> /// Creates a new instance of the requested type using the supplied Instance. Mostly used internally /// </summary> /// <param name="pluginType"></param> /// <param name="instance"></param> /// <returns></returns> public object GetInstance(Type pluginType, Instance instance) { return withNewSession(instance.Name).CreateInstance(pluginType, instance); } public void SetDefault(Type pluginType, Instance instance) { _pipelineGraph.SetDefault(pluginType, instance); } [Obsolete("Please use GetInstance(Type) instead")] public object FillDependencies(Type type) { if (!type.IsConcrete()) { throw new StructureMapException(230, type.FullName); } var plugin = new Plugin(type); if (!plugin.CanBeAutoFilled) { throw new StructureMapException(230, type.FullName); } return GetInstance(type); } /// <summary> /// Creates or resolves all registered instances of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public IList GetAllInstances(Type pluginType) { Array instances = withNewSession(Plugin.DEFAULT).CreateInstanceArray(pluginType, null); return new ArrayList(instances); } /// <summary> /// Used to add additional configuration to a Container *after* the initialization. /// </summary> /// <param name="configure"></param> public void Configure(Action<ConfigurationExpression> configure) { lock (this) { var registry = new ConfigurationExpression(); configure(registry); PluginGraph graph = registry.BuildGraph(); graph.Log.AssertFailures(); _interceptorLibrary.ImportFrom(graph.InterceptorLibrary); _pipelineGraph.ImportFrom(graph); } } /// <summary> /// Returns a report detailing the complete configuration of all PluginTypes and Instances /// </summary> /// <returns></returns> public string WhatDoIHave() { var writer = new WhatDoIHaveWriter(_pipelineGraph); return writer.GetText(); } /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arg"></param> /// <returns></returns> public ExplicitArgsExpression With<T>(T arg) { return new ExplicitArgsExpression(this).With(arg); } /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <param name="pluginType"></param> /// <param name="arg"></param> /// <returns></returns> public ExplicitArgsExpression With(Type pluginType, object arg) { return new ExplicitArgsExpression(this).With(pluginType, arg); } /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument /// with the designated name should be the next value. /// </summary> /// <param name="argName"></param> /// <returns></returns> public IExplicitProperty With(string argName) { return new ExplicitArgsExpression(this).With(argName); } /// <summary> /// Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured /// instance and afterward calls any methods marked with the [ValidationMethod] attribute /// </summary> public void AssertConfigurationIsValid() { var session = new ValidationBuildSession(_pipelineGraph, _interceptorLibrary); session.PerformValidations(); if (!session.Success) { throw new StructureMapConfigurationException(session.BuildErrorMessages()); } } /// <summary> /// Removes all configured instances of type T from the Container. Use with caution! /// </summary> /// <typeparam name="T"></typeparam> public void EjectAllInstancesOf<T>() { _pipelineGraph.EjectAllInstancesOf<T>(); } /// <summary> /// Convenience method to request an object using an Open Generic /// Type and its parameter Types /// </summary> /// <param name="templateType"></param> /// <returns></returns> /// <example> /// IFlattener flattener1 = container.ForGenericType(typeof (IFlattener&lt;&gt;)) /// .WithParameters(typeof (Address)).GetInstanceAs&lt;IFlattener&gt;(); /// </example> public OpenGenericTypeExpression ForGenericType(Type templateType) { return new OpenGenericTypeExpression(templateType, this); } /// <summary> /// Shortcut syntax for using an object to find a service that handles /// that type of object by using an open generic type /// </summary> /// <example> /// IHandler handler = container.ForObject(shipment) /// .GetClosedTypeOf(typeof (IHandler<>)) /// .As<IHandler>(); /// </example> /// <param name="subject"></param> /// <returns></returns> public CloseGenericTypeExpression ForObject(object subject) { return new CloseGenericTypeExpression(subject, this); } /// <summary> /// Starts a "Nested" Container for atomic, isolated access /// </summary> /// <returns></returns> public IContainer GetNestedContainer() { var container = new Container { _interceptorLibrary = _interceptorLibrary, _pipelineGraph = _pipelineGraph.ToNestedGraph(), _onDispose = nestedDispose }; nameContainer(container); // Fixes a mild bug. The child container should inject itself container.Configure(x => x.For<IContainer>().Use(container)); return container; } /// <summary> /// Starts a new "Nested" Container for atomic, isolated service location. Opens /// </summary> /// <param name="profileName"></param> /// <returns></returns> public IContainer GetNestedContainer(string profileName) { IContainer container = GetNestedContainer(); container.SetDefaultsToProfile(profileName); return container; } private Action<Container> _onDispose = fullDispose; public void Dispose() { _onDispose(this); } private static void fullDispose(Container c) { c.Model.AllInstances.Each(i => { if (i != null) i.EjectObject(); }); nestedDispose(c); } private static void nestedDispose(Container c) { c._pipelineGraph.Dispose(); } /// <summary> /// The name of the container. By default this is set to /// a random Guid. This is a convience property to /// assist with debugging. Feel free to set to anything, /// as this is not used in any logic. /// </summary> public string Name { get; set; } #endregion /// <summary> /// Injects the given object into a Container as the default for the designated /// PLUGINTYPE. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="instance"></param> public void Inject<PLUGINTYPE>(PLUGINTYPE instance) { Configure(x => x.For<PLUGINTYPE>().Use(instance)); } public void Inject<PLUGINTYPE>(string name, PLUGINTYPE value) { Configure(x => x.For<PLUGINTYPE>().Use(value).Named(name)); } /// <summary> /// Injects the given object into a Container as the default for the designated /// pluginType. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <param name="pluginType"></param> /// <param name="object"></param> public void Inject(Type pluginType, object @object) { Configure(x => x.For(pluginType).Use(@object)); } private object buildInstanceWithArgs(Type pluginType, Instance defaultInstance, ExplicitArguments args, string requestedName) { if (defaultInstance == null && pluginType.IsConcrete()) { defaultInstance = new ConfiguredInstance(pluginType); } var basicInstance = defaultInstance as ConstructorInstance; Instance instance = basicInstance == null ? defaultInstance : basicInstance.Override(args); BuildSession session = withNewSession(requestedName); args.RegisterDefaults(session); return session.CreateInstance(pluginType, instance); } public ExplicitArgsExpression With(Action<ExplicitArgsExpression> action) { var expression = new ExplicitArgsExpression(this); action(expression); return expression; } private void construct(PluginGraph pluginGraph) { Name = Guid.NewGuid().ToString(); _interceptorLibrary = pluginGraph.InterceptorLibrary; if (!pluginGraph.IsSealed) { pluginGraph.Seal(); } _pluginGraph = pluginGraph; var thisInstance = new ObjectInstance(this); _pluginGraph.FindFamily(typeof (IContainer)).AddInstance(thisInstance); _pluginGraph.ProfileManager.SetDefault(typeof (IContainer), thisInstance); var funcInstance = new FactoryTemplate(typeof (LazyInstance<>)); _pluginGraph.FindFamily(typeof(Func<>)).AddInstance(funcInstance); _pluginGraph.ProfileManager.SetDefault(typeof(Func<>), funcInstance); pluginGraph.Log.AssertFailures(); _pipelineGraph = new PipelineGraph(pluginGraph); } [Obsolete("delegate to something cleaner in BuildSession")] private IList<T> getListOfTypeWithSession<T>(BuildSession session) { var list = new List<T>(); foreach (T instance in session.CreateInstanceArray(typeof (T), null)) { list.Add(instance); } return list; } private BuildSession withNewSession(string name) { return new BuildSession(_pipelineGraph, _interceptorLibrary) { RequestedName = name }; } /// <summary> /// Sets the default instance for the PluginType /// </summary> /// <param name="pluginType"></param> /// <param name="instance"></param> public void Inject(Type pluginType, Instance instance) { _pipelineGraph.SetDefault(pluginType, instance); } private void nameContainer(IContainer container) { container.Name = "Nested-" + container.Name; } #region Nested type: GetInstanceAsExpression public interface GetInstanceAsExpression { T GetInstanceAs<T>(); } #endregion #region Nested type: OpenGenericTypeExpression public class OpenGenericTypeExpression : GetInstanceAsExpression { private readonly Container _container; private readonly Type _templateType; private Type _pluginType; public OpenGenericTypeExpression(Type templateType, Container container) { if (!templateType.IsOpenGeneric()) { throw new StructureMapException(285); } _templateType = templateType; _container = container; } #region GetInstanceAsExpression Members public T GetInstanceAs<T>() { return (T) _container.GetInstance(_pluginType); } #endregion public GetInstanceAsExpression WithParameters(params Type[] parameterTypes) { _pluginType = _templateType.MakeGenericType(parameterTypes); return this; } } #endregion } }
using System; using System.Collections; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace SoapCore.Meta { public static class BodyWriterExtensions { //switches to easily revert to previous behaviour if there is a problem private static readonly bool UseXmlSchemaProvider = true; private static readonly bool UseXmlReflectionImporter = false; public static bool TryAddSchemaTypeFromXmlSchemaProviderAttribute(this XmlDictionaryWriter writer, Type type, string name, SoapSerializer serializer, XmlNamespaceManager xmlNamespaceManager = null, bool isUnqualified = false) { if (!UseXmlSchemaProvider && !UseXmlReflectionImporter) { return false; } if (UseXmlReflectionImporter) { var schemas = new XmlSchemas(); var xmlImporter = new XmlReflectionImporter(); var exporter = new XmlSchemaExporter(schemas); var xmlTypeMapping = xmlImporter.ImportTypeMapping(type, new XmlRootAttribute() { ElementName = name }); exporter.ExportTypeMapping(xmlTypeMapping); schemas.Compile(null, true); using var memoryStream = new MemoryStream(); foreach (XmlSchema schema in schemas) { schema.Write(memoryStream); } memoryStream.Position = 0; var streamReader = new StreamReader(memoryStream); var result = streamReader.ReadToEnd(); var doc = new XmlDocument(); doc.LoadXml(result); doc.DocumentElement.WriteContentTo(writer); return true; } var xmlSchemaSet = xmlNamespaceManager == null ? new XmlSchemaSet() : new XmlSchemaSet(xmlNamespaceManager.NameTable); var xmlSchemaProviderAttribute = type.GetCustomAttribute<XmlSchemaProviderAttribute>(true); if (xmlSchemaProviderAttribute != null && true) { XmlSchema schema = new XmlSchema(); if (xmlNamespaceManager != null) { schema.Namespaces = xmlNamespaceManager.Convert(); } if (xmlSchemaProviderAttribute.IsAny) { //MetaWCFBodyWriter usage.... //writer.WriteAttributeString("name", name); //writer.WriteAttributeString("nillable", "true"); //writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); //writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); //writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD); //writer.WriteAttributeString("minOccurs", "0"); //writer.WriteAttributeString("processContents", "lax"); //writer.WriteEndElement(); //writer.WriteEndElement(); //writer.WriteEndElement(); var sequence = new XmlSchemaSequence(); sequence.Items.Add(new XmlSchemaAny() { ProcessContents = XmlSchemaContentProcessing.Lax }); var complex = new XmlSchemaComplexType() { Particle = sequence }; var element = new XmlSchemaElement() { MinOccurs = 0, MaxOccurs = 1, Name = name, IsNillable = serializer == SoapSerializer.DataContractSerializer, SchemaType = complex }; if (isUnqualified) { element.Form = XmlSchemaForm.Unqualified; } schema.Items.Add(element); } else { var methodInfo = type.GetMethod(xmlSchemaProviderAttribute.MethodName, BindingFlags.Static | BindingFlags.Public); var xmlSchemaInfoObject = methodInfo.Invoke(null, new object[] { xmlSchemaSet }); var element = new XmlSchemaElement() { MinOccurs = 0, MaxOccurs = 1, Name = name, }; if (xmlSchemaInfoObject is XmlQualifiedName xmlQualifiedName) { element.SchemaTypeName = xmlQualifiedName; } else if (xmlSchemaInfoObject is XmlSchemaType xmlSchemaType) { element.SchemaType = xmlSchemaType; } else { throw new InvalidOperationException($"Invalid {nameof(xmlSchemaInfoObject)} type: {xmlSchemaInfoObject.GetType()}"); } if (isUnqualified) { element.Form = XmlSchemaForm.Unqualified; } schema.Items.Add(element); } using var memoryStream = new MemoryStream(); schema.Write(memoryStream); memoryStream.Position = 0; var streamReader = new StreamReader(memoryStream); var result = streamReader.ReadToEnd(); var doc = new XmlDocument(); doc.LoadXml(result); doc.DocumentElement.WriteContentTo(writer); return true; } return false; } public static bool IsChoice(this MemberInfo member) { var choiceItem = member.GetCustomAttribute<XmlChoiceIdentifierAttribute>(); return choiceItem != null || member.GetCustomAttributes<XmlElementAttribute>().Count() > 1; } public static bool IsAttribute(this MemberInfo member) { var attributeItem = member.GetCustomAttribute<XmlAttributeAttribute>(); return attributeItem != null; } public static bool IsIgnored(this MemberInfo member) { return member .CustomAttributes .Any(attr => attr.AttributeType == typeof(IgnoreDataMemberAttribute) || attr.AttributeType == typeof(XmlIgnoreAttribute)); } public static bool IsEnumerableType(this Type collectionType) { if (collectionType.IsArray) { return true; } return typeof(IEnumerable).IsAssignableFrom(collectionType); } public static Type GetGenericType(this Type collectionType) { // Recursively look through the base class to find the Generic Type of the Enumerable var baseType = collectionType; var baseTypeInfo = collectionType.GetTypeInfo(); while (!baseTypeInfo.IsGenericType && baseTypeInfo.BaseType != null) { baseType = baseTypeInfo.BaseType; baseTypeInfo = baseType.GetTypeInfo(); } return baseType.GetTypeInfo().GetGenericArguments().DefaultIfEmpty(typeof(object)).FirstOrDefault(); } public static string GetSerializedTypeName(this Type type) { var namedType = type; bool isNullableArray = false; if (type.IsArray) { namedType = type.GetElementType(); var underlyingType = Nullable.GetUnderlyingType(namedType); if (underlyingType != null) { namedType = underlyingType; isNullableArray = true; } } else if (typeof(IEnumerable).IsAssignableFrom(type) && type.IsGenericType) { namedType = GetGenericType(type); var underlyingType = Nullable.GetUnderlyingType(namedType); if (underlyingType != null) { namedType = underlyingType; isNullableArray = true; } } string typeName = namedType.Name; var xmlTypeAttribute = namedType.GetCustomAttribute<XmlTypeAttribute>(true); if (xmlTypeAttribute != null && !string.IsNullOrWhiteSpace(xmlTypeAttribute.TypeName)) { typeName = xmlTypeAttribute.TypeName; } if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type) && type.IsGenericType)) { if (namedType.IsArray || (typeof(IEnumerable).IsAssignableFrom(type) && type.IsGenericType)) { typeName = GetSerializedTypeName(namedType); } typeName = GetArrayTypeName(typeName.Replace("[]", string.Empty), isNullableArray); } return typeName; } private static string GetArrayTypeName(string typeName, bool isNullable) { return "ArrayOf" + (isNullable ? "Nullable" : null) + (ClrTypeResolver.ResolveOrDefault(typeName).FirstCharToUpperOrDefault() ?? typeName); } private static XmlSerializerNamespaces Convert(this XmlNamespaceManager xmlNamespaceManager) { XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces(); foreach (var ns in xmlNamespaceManager.GetNamespacesInScope(XmlNamespaceScope.Local)) { xmlSerializerNamespaces.Add(ns.Key, ns.Value); } return xmlSerializerNamespaces; } private static string FirstCharToUpperOrDefault(this string input) { if (string.IsNullOrEmpty(input)) { return input; } return input.First().ToString().ToUpper() + input.Substring(1); } } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; /// @file /// @addtogroup flatbuffers_csharp_api /// @{ namespace FlatBuffers { /// <summary> /// Responsible for building up and accessing a FlatBuffer formatted byte /// array (via ByteBuffer). /// </summary> public class FlatBufferBuilder { private int _space; private ByteBuffer _bb; private int _minAlign = 1; // The vtable for the current table (if _vtableSize >= 0) private int[] _vtable = new int[16]; // The size of the vtable. -1 indicates no vtable private int _vtableSize = -1; // Starting offset of the current struct/table. private int _objectStart; // List of offsets of all vtables. private int[] _vtables = new int[16]; // Number of entries in `vtables` in use. private int _numVtables = 0; // For the current vector being built. private int _vectorNumElems = 0; /// <summary> /// Create a FlatBufferBuilder with a given initial size. /// </summary> /// <param name="initialSize"> /// The initial size to use for the internal buffer. /// </param> public FlatBufferBuilder(int initialSize) { if (initialSize <= 0) throw new ArgumentOutOfRangeException("initialSize", initialSize, "Must be greater than zero"); _space = initialSize; _bb = new ByteBuffer(initialSize); } /// <summary> /// Reset the FlatBufferBuilder by purging all data that it holds. /// </summary> public void Clear() { _space = _bb.Length; _bb.Reset(); _minAlign = 1; while (_vtableSize > 0) _vtable[--_vtableSize] = 0; _vtableSize = -1; _objectStart = 0; _numVtables = 0; _vectorNumElems = 0; } /// <summary> /// Gets and sets a Boolean to disable the optimization when serializing /// default values to a Table. /// /// In order to save space, fields that are set to their default value /// don't get serialized into the buffer. /// </summary> public bool ForceDefaults { get; set; } /// @cond FLATBUFFERS_INTERNAL public int Offset { get { return _bb.Length - _space; } } public void Pad(int size) { _bb.PutByte(_space -= size, 0, size); } // Doubles the size of the ByteBuffer, and copies the old data towards // the end of the new buffer (since we build the buffer backwards). void GrowBuffer() { _bb.GrowFront(_bb.Length << 1); } // Prepare to write an element of `size` after `additional_bytes` // have been written, e.g. if you write a string, you need to align // such the int length field is aligned to SIZEOF_INT, and the string // data follows it directly. // If all you need to do is align, `additional_bytes` will be 0. public void Prep(int size, int additionalBytes) { // Track the biggest thing we've ever aligned to. if (size > _minAlign) _minAlign = size; // Find the amount of alignment needed such that `size` is properly // aligned after `additional_bytes` var alignSize = ((~((int)_bb.Length - _space + additionalBytes)) + 1) & (size - 1); // Reallocate the buffer if needed. while (_space < alignSize + size + additionalBytes) { var oldBufSize = (int)_bb.Length; GrowBuffer(); _space += (int)_bb.Length - oldBufSize; } if (alignSize > 0) Pad(alignSize); } public void PutBool(bool x) { _bb.PutByte(_space -= sizeof(byte), (byte)(x ? 1 : 0)); } public void PutSbyte(sbyte x) { _bb.PutSbyte(_space -= sizeof(sbyte), x); } public void PutByte(byte x) { _bb.PutByte(_space -= sizeof(byte), x); } public void PutShort(short x) { _bb.PutShort(_space -= sizeof(short), x); } public void PutUshort(ushort x) { _bb.PutUshort(_space -= sizeof(ushort), x); } public void PutInt(int x) { _bb.PutInt(_space -= sizeof(int), x); } public void PutUint(uint x) { _bb.PutUint(_space -= sizeof(uint), x); } public void PutLong(long x) { _bb.PutLong(_space -= sizeof(long), x); } public void PutUlong(ulong x) { _bb.PutUlong(_space -= sizeof(ulong), x); } public void PutFloat(float x) { _bb.PutFloat(_space -= sizeof(float), x); } public void PutDouble(double x) { _bb.PutDouble(_space -= sizeof(double), x); } /// @endcond /// <summary> /// Add a `bool` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `bool` to add to the buffer.</param> public void AddBool(bool x) { Prep(sizeof(byte), 0); PutBool(x); } /// <summary> /// Add a `sbyte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `sbyte` to add to the buffer.</param> public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); } /// <summary> /// Add a `byte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `byte` to add to the buffer.</param> public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); } /// <summary> /// Add a `short` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `short` to add to the buffer.</param> public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); } /// <summary> /// Add an `ushort` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ushort` to add to the buffer.</param> public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); } /// <summary> /// Add an `int` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `int` to add to the buffer.</param> public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); } /// <summary> /// Add an `uint` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `uint` to add to the buffer.</param> public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); } /// <summary> /// Add a `long` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `long` to add to the buffer.</param> public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); } /// <summary> /// Add an `ulong` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ulong` to add to the buffer.</param> public void AddUlong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); } /// <summary> /// Add a `float` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `float` to add to the buffer.</param> public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); } /// <summary> /// Add a `double` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `double` to add to the buffer.</param> public void AddDouble(double x) { Prep(sizeof(double), 0); PutDouble(x); } /// <summary> /// Adds an offset, relative to where it will be written. /// </summary> /// <param name="off">The offset to add to the buffer.</param> public void AddOffset(int off) { Prep(sizeof(int), 0); // Ensure alignment is already done. if (off > Offset) throw new ArgumentException(); off = Offset - off + sizeof(int); PutInt(off); } /// @cond FLATBUFFERS_INTERNAL public void StartVector(int elemSize, int count, int alignment) { NotNested(); _vectorNumElems = count; Prep(sizeof(int), elemSize * count); Prep(alignment, elemSize * count); // Just in case alignment > int. } /// @endcond /// <summary> /// Writes data necessary to finish a vector construction. /// </summary> public VectorOffset EndVector() { PutInt(_vectorNumElems); return new VectorOffset(Offset); } /// <summary> /// Creates a vector of tables. /// </summary> /// <param name="offsets">Offsets of the tables.</param> public VectorOffset CreateVectorOfTables<T>(Offset<T>[] offsets) where T : struct { NotNested(); StartVector(sizeof(int), offsets.Length, sizeof(int)); for (int i = offsets.Length - 1; i >= 0; i--) AddOffset(offsets[i].Value); return EndVector(); } /// @cond FLATBUFFERS_INTENRAL public void Nested(int obj) { // Structs are always stored inline, so need to be created right // where they are used. You'll get this assert if you created it // elsewhere. if (obj != Offset) throw new Exception( "FlatBuffers: struct must be serialized inline."); } public void NotNested() { // You should not be creating any other objects or strings/vectors // while an object is being constructed if (_vtableSize >= 0) throw new Exception( "FlatBuffers: object serialization must not be nested."); } public void StartObject(int numfields) { if (numfields < 0) throw new ArgumentOutOfRangeException("Flatbuffers: invalid numfields"); NotNested(); if (_vtable.Length < numfields) _vtable = new int[numfields]; _vtableSize = numfields; _objectStart = Offset; } // Set the current vtable at `voffset` to the current location in the // buffer. public void Slot(int voffset) { if (voffset >= _vtableSize) throw new IndexOutOfRangeException("Flatbuffers: invalid voffset"); _vtable[voffset] = Offset; } /// <summary> /// Adds a Boolean to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddBool(int o, bool x, bool d) { if (ForceDefaults || x != d) { AddBool(x); Slot(o); } } /// <summary> /// Adds a SByte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddSbyte(int o, sbyte x, sbyte d) { if (ForceDefaults || x != d) { AddSbyte(x); Slot(o); } } /// <summary> /// Adds a Byte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddByte(int o, byte x, byte d) { if (ForceDefaults || x != d) { AddByte(x); Slot(o); } } /// <summary> /// Adds a Int16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddShort(int o, short x, int d) { if (ForceDefaults || x != d) { AddShort(x); Slot(o); } } /// <summary> /// Adds a UInt16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUshort(int o, ushort x, ushort d) { if (ForceDefaults || x != d) { AddUshort(x); Slot(o); } } /// <summary> /// Adds an Int32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddInt(int o, int x, int d) { if (ForceDefaults || x != d) { AddInt(x); Slot(o); } } /// <summary> /// Adds a UInt32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUint(int o, uint x, uint d) { if (ForceDefaults || x != d) { AddUint(x); Slot(o); } } /// <summary> /// Adds an Int64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddLong(int o, long x, long d) { if (ForceDefaults || x != d) { AddLong(x); Slot(o); } } /// <summary> /// Adds a UInt64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUlong(int o, ulong x, ulong d) { if (ForceDefaults || x != d) { AddUlong(x); Slot(o); } } /// <summary> /// Adds a Single to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddFloat(int o, float x, double d) { if (ForceDefaults || x != d) { AddFloat(x); Slot(o); } } /// <summary> /// Adds a Double to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddDouble(int o, double x, double d) { if (ForceDefaults || x != d) { AddDouble(x); Slot(o); } } /// <summary> /// Adds a buffer offset to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddOffset(int o, int x, int d) { if (ForceDefaults || x != d) { AddOffset(x); Slot(o); } } /// @endcond /// <summary> /// Encode the string `s` in the buffer using UTF-8. /// </summary> /// <param name="s">The string to encode.</param> /// <returns> /// The offset in the buffer where the encoded string starts. /// </returns> public StringOffset CreateString(string s) { NotNested(); AddByte(0); var utf8StringLen = Encoding.UTF8.GetByteCount(s); StartVector(1, utf8StringLen, 1); _bb.PutStringUTF8(_space -= utf8StringLen, s); return new StringOffset(EndVector().Value); } /// @cond FLATBUFFERS_INTERNAL // Structs are stored inline, so nothing additional is being added. // `d` is always 0. public void AddStruct(int voffset, int x, int d) { if (x != d) { Nested(x); Slot(voffset); } } public int EndObject() { if (_vtableSize < 0) throw new InvalidOperationException( "Flatbuffers: calling endObject without a startObject"); AddInt((int)0); var vtableloc = Offset; // Write out the current vtable. int i = _vtableSize - 1; // Trim trailing zeroes. for (; i >= 0 && _vtable[i] == 0; i--) {} int trimmedSize = i + 1; for (; i >= 0 ; i--) { // Offset relative to the start of the table. short off = (short)(_vtable[i] != 0 ? vtableloc - _vtable[i] : 0); AddShort(off); // clear out written entry _vtable[i] = 0; } const int standardFields = 2; // The fields below: AddShort((short)(vtableloc - _objectStart)); AddShort((short)((trimmedSize + standardFields) * sizeof(short))); // Search for an existing vtable that matches the current one. int existingVtable = 0; for (i = 0; i < _numVtables; i++) { int vt1 = _bb.Length - _vtables[i]; int vt2 = _space; short len = _bb.GetShort(vt1); if (len == _bb.GetShort(vt2)) { for (int j = sizeof(short); j < len; j += sizeof(short)) { if (_bb.GetShort(vt1 + j) != _bb.GetShort(vt2 + j)) { goto endLoop; } } existingVtable = _vtables[i]; break; } endLoop: { } } if (existingVtable != 0) { // Found a match: // Remove the current vtable. _space = _bb.Length - vtableloc; // Point table to existing vtable. _bb.PutInt(_space, existingVtable - vtableloc); } else { // No match: // Add the location of the current vtable to the list of // vtables. if (_numVtables == _vtables.Length) { // Arrays.CopyOf(vtables num_vtables * 2); var newvtables = new int[ _numVtables * 2]; Array.Copy(_vtables, newvtables, _vtables.Length); _vtables = newvtables; }; _vtables[_numVtables++] = Offset; // Point table to current vtable. _bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc); } _vtableSize = -1; return vtableloc; } // This checks a required field has been set in a given table that has // just been constructed. public void Required(int table, int field) { int table_start = _bb.Length - table; int vtable_start = table_start - _bb.GetInt(table_start); bool ok = _bb.GetShort(vtable_start + field) != 0; // If this fails, the caller will show what field needs to be set. if (!ok) throw new InvalidOperationException("FlatBuffers: field " + field + " must be set"); } /// @endcond /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="sizePrefix"> /// Whether to prefix the size to the buffer. /// </param> protected void Finish(int rootTable, bool sizePrefix) { Prep(_minAlign, sizeof(int) + (sizePrefix ? sizeof(int) : 0)); AddOffset(rootTable); if (sizePrefix) { AddInt(_bb.Length - _space); } _bb.Position = _space; } /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void Finish(int rootTable) { Finish(rootTable, false); } /// <summary> /// Finalize a buffer, pointing to the given `root_table`, with the size prefixed. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void FinishSizePrefixed(int rootTable) { Finish(rootTable, true); } /// <summary> /// Get the ByteBuffer representing the FlatBuffer. /// </summary> /// <remarks> /// This is typically only called after you call `Finish()`. /// The actual data starts at the ByteBuffer's current position, /// not necessarily at `0`. /// </remarks> /// <returns> /// Returns the ByteBuffer for this FlatBuffer. /// </returns> public ByteBuffer DataBuffer { get { return _bb; } } /// <summary> /// A utility function to copy and return the ByteBuffer data as a /// `byte[]`. /// </summary> /// <returns> /// A full copy of the FlatBuffer data. /// </returns> public byte[] SizedByteArray() { return _bb.ToSizedArray(); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> /// <param name="sizePrefix"> /// Whether to prefix the size to the buffer. /// </param> protected void Finish(int rootTable, string fileIdentifier, bool sizePrefix) { Prep(_minAlign, sizeof(int) + (sizePrefix ? sizeof(int) : 0) + FlatBufferConstants.FileIdentifierLength); if (fileIdentifier.Length != FlatBufferConstants.FileIdentifierLength) throw new ArgumentException( "FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "fileIdentifier"); for (int i = FlatBufferConstants.FileIdentifierLength - 1; i >= 0; i--) { AddByte((byte)fileIdentifier[i]); } Finish(rootTable, sizePrefix); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void Finish(int rootTable, string fileIdentifier) { Finish(rootTable, fileIdentifier, false); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`, with the size prefixed. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void FinishSizePrefixed(int rootTable, string fileIdentifier) { Finish(rootTable, fileIdentifier, true); } } } /// @}
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; using System.Linq; static partial class MoreEnumerable { /// <summary> /// Combines <see cref="Enumerable.OrderBy{TSource,TKey}(IEnumerable{TSource},Func{TSource,TKey})"/>, /// where each element is its key, and <see cref="Enumerable.Take{TSource}"/> /// in a single operation. /// </summary> /// <typeparam name="T">Type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in their ascending order.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<T> PartialSort<T>(this IEnumerable<T> source, int count) { return source.PartialSort(count, null); } /// <summary> /// Combines <see cref="MoreEnumerable.OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, IComparer{TKey}, OrderByDirection)"/>, /// where each element is its key, and <see cref="Enumerable.Take{TSource}"/> /// in a single operation. /// An additional parameter specifies the direction of the sort /// </summary> /// <typeparam name="T">Type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<T> PartialSort<T>(this IEnumerable<T> source, int count, OrderByDirection direction) { return source.PartialSort(count, null, direction); } /// <summary> /// Combines <see cref="Enumerable.OrderBy{TSource,TKey}(IEnumerable{TSource},Func{TSource,TKey},IComparer{TKey})"/>, /// where each element is its key, and <see cref="Enumerable.Take{TSource}"/> /// in a single operation. An additional parameter specifies how the /// elements compare to each other. /// </summary> /// <typeparam name="T">Type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="comparer">A <see cref="IComparer{T}"/> to compare elements.</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in their ascending order.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<T> PartialSort<T>(this IEnumerable<T> source, int count, IComparer<T>? comparer) { if (source == null) throw new ArgumentNullException(nameof(source)); return PartialSortByImpl<T, T>(source, count, null, null, comparer); } /// <summary> /// Combines <see cref="MoreEnumerable.OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, IComparer{TKey}, OrderByDirection)"/>, /// where each element is its key, and <see cref="Enumerable.Take{TSource}"/> /// in a single operation. /// Additional parameters specify how the elements compare to each other and /// the direction of the sort. /// </summary> /// <typeparam name="T">Type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="comparer">A <see cref="IComparer{T}"/> to compare elements.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<T> PartialSort<T>(this IEnumerable<T> source, int count, IComparer<T>? comparer, OrderByDirection direction) { comparer ??= Comparer<T>.Default; if (direction == OrderByDirection.Descending) comparer = new ReverseComparer<T>(comparer); return source.PartialSort(count, comparer); } /// <summary> /// Combines <see cref="Enumerable.OrderBy{TSource,TKey}(IEnumerable{TSource},Func{TSource,TKey},IComparer{TKey})"/>, /// and <see cref="Enumerable.Take{TSource}"/> in a single operation. /// </summary> /// <typeparam name="TSource">Type of elements in the sequence.</typeparam> /// <typeparam name="TKey">Type of keys.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="keySelector">A function to extract a key from an element.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in ascending order of their keys.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<TSource> PartialSortBy<TSource, TKey>( this IEnumerable<TSource> source, int count, Func<TSource, TKey> keySelector) { return source.PartialSortBy(count, keySelector, null); } /// <summary> /// Combines <see cref="MoreEnumerable.OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, OrderByDirection)"/>, /// and <see cref="Enumerable.Take{TSource}"/> in a single operation. /// An additional parameter specifies the direction of the sort /// </summary> /// <typeparam name="TSource">Type of elements in the sequence.</typeparam> /// <typeparam name="TKey">Type of keys.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="keySelector">A function to extract a key from an element.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order of their keys.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<TSource> PartialSortBy<TSource, TKey>( this IEnumerable<TSource> source, int count, Func<TSource, TKey> keySelector, OrderByDirection direction) { return source.PartialSortBy(count, keySelector, null, direction); } /// <summary> /// Combines <see cref="Enumerable.OrderBy{TSource,TKey}(IEnumerable{TSource},Func{TSource,TKey},IComparer{TKey})"/>, /// and <see cref="Enumerable.Take{TSource}"/> in a single operation. /// An additional parameter specifies how the keys compare to each other. /// </summary> /// <typeparam name="TSource">Type of elements in the sequence.</typeparam> /// <typeparam name="TKey">Type of keys.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="keySelector">A function to extract a key from an element.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="comparer">A <see cref="IComparer{T}"/> to compare elements.</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in ascending order of their keys.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<TSource> PartialSortBy<TSource, TKey>( this IEnumerable<TSource> source, int count, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer) { if (source == null) throw new ArgumentNullException(nameof(source)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return PartialSortByImpl(source, count, keySelector, comparer, null); } /// <summary> /// Combines <see cref="MoreEnumerable.OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, OrderByDirection)"/>, /// and <see cref="Enumerable.Take{TSource}"/> in a single operation. /// Additional parameters specify how the elements compare to each other and /// the direction of the sort. /// </summary> /// <typeparam name="TSource">Type of elements in the sequence.</typeparam> /// <typeparam name="TKey">Type of keys.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="keySelector">A function to extract a key from an element.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="comparer">A <see cref="IComparer{T}"/> to compare elements.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order of their keys.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable<TSource> PartialSortBy<TSource, TKey>( this IEnumerable<TSource> source, int count, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, OrderByDirection direction) { comparer ??= Comparer<TKey>.Default; if (direction == OrderByDirection.Descending) comparer = new ReverseComparer<TKey>(comparer); return source.PartialSortBy(count, keySelector, comparer); } static IEnumerable<TSource> PartialSortByImpl<TSource, TKey>( IEnumerable<TSource> source, int count, Func<TSource, TKey>? keySelector, IComparer<TKey>? keyComparer, IComparer<TSource>? comparer) { var keys = keySelector != null ? new List<TKey>(count) : null; var top = new List<TSource>(count); int? Insert<T>(List<T> list, T item, IComparer<T>? comparer) { var i = list.BinarySearch(item, comparer); if (i < 0 && (i = ~i) >= count) return null; if (list.Count == count) list.RemoveAt(count - 1); list.Insert(i, item); return i; } foreach (var item in source) { if (keys != null) { var key = keySelector!(item); if (Insert(keys, key, keyComparer) is {} i) { if (top.Count == count) top.RemoveAt(count - 1); top.Insert(i, item); } } else { _ = Insert(top, item, comparer); } // TODO Stable sorting } // ReSharper disable once LoopCanBeConvertedToQuery foreach (var item in top) yield return item; } } }
// Copyright (C) 2014 dot42 // // Original filename: ArrayList.cs // // 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 Dot42; using Dot42.Collections; using Java.Util; namespace System.Collections { public class ArrayList : IList { private readonly IList<object> list; private readonly bool isFixedSize; private readonly bool isReadOnly; private readonly bool isSynchronized; /// <summary> /// Default ctor /// </summary> public ArrayList() : this(new ArrayList<object>(), false, false, false) { } /// <summary> /// Clone ctor /// </summary> public ArrayList(ICollection source) : this(new ArrayList<object>((source != null) ? source.Count : 0), false, false, false) { if (source == null) throw new ArgumentNullException(); foreach (var item in source) { list.Add(item); } } /// <summary> /// Default ctor with specified initial capacity. /// </summary> public ArrayList(int capacity) : this(new ArrayList<object>(capacity), false, false, false) { } /// <summary> /// Private ctor /// </summary> private ArrayList(IList<object> list, bool isFixedSize, bool isReadOnly, bool isSynchronized) { this.list = list; this.isFixedSize = isFixedSize; this.isReadOnly = isReadOnly; this.isSynchronized = isSynchronized; } /// <summary> /// Gets/sets the capacity of this list. /// </summary> public virtual int Capacity { get { return list.Size(); } set { /* ignore */ } } /// <summary> /// Gets the number of items in this list. /// </summary> public int Count { get { return list.Count; } } /// <summary> /// Does this list have a fixed size? /// </summary> public virtual bool IsFixedSize { get { return isFixedSize; } } /// <summary> /// Is this list readonly? /// </summary> public virtual bool IsReadOnly { get { return isReadOnly; } } /// <summary> /// Is this list synchronized? /// </summary> public virtual bool IsSynchronized { get { return isSynchronized; } } /// <summary> /// Is this list readonly? /// </summary> public virtual object this[int index] { get { if ((index < 0) || (index >= list.Size())) throw new ArgumentOutOfRangeException(); return list[index]; } set { if (isReadOnly) throw new NotSupportedException(); if ((index < 0) || (index >= list.Size())) throw new ArgumentOutOfRangeException(); list[index] = value; } } /// <summary> /// Gets an object that can be used to synchronized access to this list. /// </summary> public virtual object SyncRoot { get { return this; } } /// <summary> /// Copy all elements into the given array starting at the given index (into the array). /// </summary> public virtual void CopyTo(Array array) { CopyTo(0, array, 0, list.Count); } /// <summary> /// Copy all elements into the given array starting at the given index (into the array). /// </summary> public virtual void CopyTo(Array array, int index) { CopyTo(0, array, index, list.Count); } /// <summary> /// Copy all elements into the given array starting at the given index (into the array). /// </summary> public virtual void CopyTo(int index, Array array, int arrayIndex, int count) { if (array == null) throw new ArgumentNullException(); if ((index < 0) || (arrayIndex < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); var size = list.Size(); var available = array.Length- arrayIndex; if ((index > size) || (count > size) || (index + count > size) || (count > available)) throw new ArgumentException(); while (count > 0) { array.SetValue(list[index++], arrayIndex++); count--; } } /// <summary> /// Add an object to the end of this list /// </summary> /// <param name="value"></param> public virtual int Add(object value) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); list.Add(value); return list.Count - 1; } /// <summary> /// Add all elements in the given collection to the end of this list /// </summary> /// <param name="value"></param> public virtual void AddRange(ICollection c) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); if (c == null) throw new ArgumentNullException(); foreach (var i in c) { list.Add(i); } } [NotImplemented] public virtual int BinarySearch(object element) { return Java.Util.Collections.BinarySearch(list, element, Comparer.Default); } [NotImplemented] public virtual int BinarySearch(object element, IComparer comparer) { comparer = comparer ?? Comparer.Default; return Java.Util.Collections.BinarySearch(list, element, comparer); } [NotImplemented] public virtual int BinarySearch(int index, int count, object element, IComparer comparer) { if ((index < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); var size = list.Size(); if ((index >= size) || (count > size) || (index + count > size)) throw new ArgumentException(); comparer = comparer ?? Comparer.Default; return Java.Util.Collections.BinarySearch(list.SubList(index, index + count), element, comparer); } /// <summary> /// Remove all elements /// </summary> public virtual void Clear() { if (isFixedSize || isReadOnly) throw new NotSupportedException(); list.Clear(); } /// <summary> /// Create a shallow clone of this list. /// </summary> /// <returns></returns> public virtual object Clone() { return new ArrayList(this); } /// <summary> /// Returns an enumerator for the entire list. /// </summary> /// <returns></returns> public virtual IEnumerator GetEnumerator() { return new IteratorWrapper<object>(list); } /// <summary> /// Returns an enumerator for the given range of this list. /// </summary> public virtual IEnumerator GetEnumerator(int index, int count) { if ((index < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); var size = list.Size(); if ((index >= size) || (count > size) || (index + count > size)) throw new ArgumentException(); return new IteratorWrapper<object>(list.SubList(index, index + count)); } /// <summary> /// Is the given object part of this list? /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual bool Contains(object value) { return list.Contains(value); } /// <summary> /// Create a list that is a subset of this list. /// </summary> public virtual ArrayList GetRange(int index, int count) { if ((index < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); if (index + count >= list.Size()) throw new ArgumentException(); return new ArrayList(list.SubList(index, index + count), isFixedSize, isReadOnly, isSynchronized); } /// <summary> /// Gets the first index of the given element/ /// </summary> /// <returns>-1 if not found</returns> public virtual int IndexOf(object element) { return list.IndexOf(element); } /// <summary> /// Gets the first index of the given element/ /// </summary> /// <returns>-1 if not found</returns> public virtual int IndexOf(object element, int startIndex) { return IndexOf(element, startIndex, list.Count - startIndex); } /// <summary> /// Gets the first index of the given element/ /// </summary> /// <returns>-1 if not found</returns> public virtual int IndexOf(object element, int startIndex, int count) { if ((startIndex < 0) || (count < 0) || (startIndex >= list.Size())) throw new ArgumentOutOfRangeException(); var rc = list.SubList(startIndex, startIndex + count).IndexOf(element); return (rc >= 0) ? rc + startIndex : rc; } /// <summary> /// Insert the given item at the given index. /// </summary> public virtual void Insert(int index, object element) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); if ((index < 0) || (index > list.Size())) throw new ArgumentOutOfRangeException(); list.Add(index, element); } /// <summary> /// Insert the given items at the given index. /// </summary> public virtual void InsertRange(int index, ICollection c) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); if (c == null) throw new ArgumentNullException(); if ((index < 0) || (index > list.Size())) throw new ArgumentOutOfRangeException(); foreach (var item in c) { list.Add(index++, item); } } /// <summary> /// Gets the last index of the given element/ /// </summary> /// <returns>-1 if not found</returns> public virtual int LastIndexOf(object element) { return list.LastIndexOf(element); } /// <summary> /// Gets the last index of the given element/ /// </summary> /// <returns>-1 if not found</returns> public virtual int LastIndexOf(object element, int startIndex) { if ((startIndex < 0) || (startIndex >= list.Size())) throw new ArgumentOutOfRangeException(); return list.SubList(0, startIndex).LastIndexOf(element); } /// <summary> /// Gets the last index of the given element/ /// </summary> /// <returns>-1 if not found</returns> public virtual int LastIndexOf(object element, int startIndex, int count) { var size = list.Size(); if ((startIndex < 0) || (count < 0) || (startIndex >= size)) throw new ArgumentOutOfRangeException(); var start = (startIndex - count) + 1; if (start < 0) throw new ArgumentOutOfRangeException(); var end = startIndex + 1; var rc = list.SubList(start, end).LastIndexOf(element); return (rc >= 0) ? start + rc : rc; } /// <summary> /// Remove the given item /// </summary> public virtual void Remove(object element) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); list.Remove(element); } /// <summary> /// Remove the item at the given index. /// </summary> public virtual void RemoveAt(int index) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); if ((index < 0) || (index >= list.Size())) throw new ArgumentOutOfRangeException(); list.Remove(index); } /// <summary> /// Remove a range of items from list starting at the given the given index. /// </summary> public virtual void RemoveRange(int index, int count) { if (isFixedSize || isReadOnly) throw new NotSupportedException(); if ((index < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); var size = list.Size(); if ((index >= size) || (count > size) || (index + count > size)) throw new ArgumentException(); while (count > 0) { list.Remove(index); count--; } } /// <summary> /// Reverse the order of items in the entire list. /// </summary> public virtual void Reverse() { if (isReadOnly) throw new NotSupportedException(); var size = list.Size(); if (size > 1) { Java.Util.Collections.Reverse(list); } } /// <summary> /// Reverse the order of items in the given range. /// </summary> public virtual void Reverse(int index, int count) { if (isReadOnly) throw new NotSupportedException(); if ((index < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); var size = list.Size(); if ((index >= size) || (count > size) || (index + count > size)) throw new ArgumentException(); if (count > 1) { Java.Util.Collections.Reverse(list.SubList(index, index + count)); } } /// <summary> /// Copies the elements in the collection over the items in this list starting at the given list index. /// </summary> public virtual void SetRange(int index, ICollection c) { if (isReadOnly) throw new NotSupportedException(); if (c == null) throw new ArgumentNullException(); var count = c.Count; if ((index < 0) || (index + count > list.Size())) throw new ArgumentOutOfRangeException(); foreach (var item in c) { list[index++] = item; } } /// <summary> /// Sort the elements in the entire list. /// </summary> public virtual void Sort() { if (isReadOnly) throw new NotSupportedException(); Java.Util.Collections.Sort(list); } /// <summary> /// Sort the elements in the entire list. /// </summary> public virtual void Sort(IComparer comparer) { if (isReadOnly) throw new NotSupportedException(); comparer = comparer ?? Comparer.Default; Java.Util.Collections.Sort(list, comparer); } /// <summary> /// Sort the elements in the given range. /// </summary> public virtual void Sort(int index, int count, IComparer comparer) { if (isReadOnly) throw new NotSupportedException(); if ((index < 0) || (count < 0)) throw new ArgumentOutOfRangeException(); var size = list.Size(); if ((index > size) || (count > size) || (index + count > size)) throw new ArgumentException(); comparer = comparer ?? Comparer.Default; Java.Util.Collections.Sort(list.SubList(index, index + count), comparer); } /// <summary> /// Copy all items of the list into a new array. /// </summary> public virtual object[] ToArray() { return list.ToArray(); } /// <summary> /// Copy all items of the list into a new array. /// </summary> public virtual Array ToArray(Type elementType) { if (elementType == null) throw new ArgumentNullException(); var arr = (Array)Java.Lang.Reflect.Array.NewInstance(elementType, list.Count); CopyTo(arr); return arr; } /// <summary> /// Set the capacity of the list to the number of items in the list. /// </summary> public virtual void TrimToSize() { if (isFixedSize || isReadOnly) throw new NotSupportedException(); } /// <summary> /// Create an ArrayList wrapper around the given list. /// </summary> [NotImplemented] public static ArrayList Adapter(IList list) { if (list == null) throw new ArgumentNullException(); throw new NotImplementedException("System.Collections.ArrayList.Adapter"); } /// <summary> /// Create a list wrapper with a fixed size that is backed by the given list. /// </summary> public static ArrayList FixedSize(ArrayList list) { if (list == null) throw new ArgumentNullException(); return new ArrayList(list.list, true, list.isReadOnly, list.isSynchronized); } /// <summary> /// Create a list wrapper with a fixed size that is backed by the given list. /// </summary> [NotImplemented] public static ArrayList FixedSize(IList list) { if (list == null) throw new ArgumentNullException(); throw new NotImplementedException("System.Collections.ArrayList.FixedSize"); } /// <summary> /// Create a readonly list wrapper that is backed by the given list. /// </summary> public static ArrayList ReadOnly(ArrayList list) { if (list == null) throw new ArgumentNullException(); return new ArrayList(list.list, list.isFixedSize, true, list.isSynchronized); } /// <summary> /// Create a readonly list wrapper that is backed by the given list. /// </summary> [NotImplemented] public static ArrayList ReadOnly(IList list) { if (list == null) throw new ArgumentNullException(); throw new NotImplementedException("System.Collections.ArrayList.ReadOnly"); } /// <summary> /// Return an ArrayList filled count element of the given value. /// </summary> public static ArrayList Repeat(object value, int count) { if (count < 0) throw new ArgumentOutOfRangeException(); var result = new ArrayList(count); while (count > 0) { result.list.Add(value); count--; } return result; } /// <summary> /// Create a thread safe list wrapper that is backed by the given list. /// </summary> public static ArrayList Synchronized(ArrayList list) { if (list == null) throw new ArgumentNullException(); return new ArrayList(Java.Util.Collections.SynchronizedList(list.list), list.isFixedSize, list.isReadOnly, true); } /// <summary> /// Create a thread safe list wrapper that is backed by the given list. /// </summary> [NotImplemented] public static ArrayList Synchronized(IList list) { if (list == null) throw new ArgumentNullException(); throw new NotImplementedException("System.Collections.ArrayList.Synchronized"); } } }
// 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. // //permutations for (((class_s.a+class_s.b)+class_s.c)+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+(class_s.b+class_s.c)) //(class_s.b+(class_s.a+class_s.c)) //(class_s.b+class_s.c) //(class_s.a+class_s.c) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //((class_s.a+class_s.b)+(class_s.c+class_s.d)) //(class_s.c+((class_s.a+class_s.b)+class_s.d)) //(class_s.c+class_s.d) //((class_s.a+class_s.b)+class_s.d) //(class_s.a+(class_s.b+class_s.d)) //(class_s.b+(class_s.a+class_s.d)) //(class_s.b+class_s.d) //(class_s.a+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; class_s s = new class_s(); class_s.a = return_int(false, -51); class_s.b = return_int(false, 86); class_s.c = return_int(false, 89); class_s.d = return_int(false, 56); int v1 = 0; int v2 = 0; int v3 = 0; int v4 = 0; int v5 = 0; int v6 = 0; int v7 = 0; int v8 = 0; int v9 = 0; int v10 = 0; int v11 = 0; int v12 = 0; int v13 = 0; int v14 = 0; int v15 = 0; int v16 = 0; int v17 = 0; int v18 = 0; #if LOOP do { do { #endif #if TRY try{ #endif #if LOOP do { for (int i=0;i<10;i++){ #endif v1 = (((class_s.a + class_s.b) + class_s.c) + class_s.d); v2 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); v3 = ((class_s.a + class_s.b) + class_s.c); v4 = (class_s.c + (class_s.a + class_s.b)); v5 = (class_s.a + class_s.b); v6 = (class_s.b + class_s.a); v7 = (class_s.a + class_s.b); v8 = (class_s.b + class_s.a); v9 = (class_s.a + (class_s.b + class_s.c)); v10 = (class_s.b + (class_s.a + class_s.c)); v11 = (class_s.b + class_s.c); v12 = (class_s.a + class_s.c); v13 = ((class_s.a + class_s.b) + class_s.c); v14 = (class_s.c + (class_s.a + class_s.b)); v15 = ((class_s.a + class_s.b) + (class_s.c + class_s.d)); v16 = (class_s.c + ((class_s.a + class_s.b) + class_s.d)); v17 = (class_s.c + class_s.d); v18 = ((class_s.a + class_s.b) + class_s.d); #if LOOP } } while (v17 == 0); #endif #if TRY } finally { } #endif int v19 = (class_s.a + (class_s.b + class_s.d)); int v20 = (class_s.b + (class_s.a + class_s.d)); int v21 = (class_s.b + class_s.d); int v22 = (class_s.a + class_s.d); int v23 = (((class_s.a + class_s.b) + class_s.c) + class_s.d); int v24 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); if (v1 != 180) { Console.WriteLine("test0: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v1); ret = ret + 1; } if (v2 != 180) { Console.WriteLine("test1: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v2); ret = ret + 1; } if (v3 != 124) { Console.WriteLine("test2: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v3); ret = ret + 1; } if (v4 != 124) { Console.WriteLine("test3: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v4); ret = ret + 1; } if (v5 != 35) { Console.WriteLine("test4: for (class_s.a+class_s.b) failed actual value {0} ", v5); ret = ret + 1; } if (v6 != 35) { Console.WriteLine("test5: for (class_s.b+class_s.a) failed actual value {0} ", v6); ret = ret + 1; } if (v7 != 35) { Console.WriteLine("test6: for (class_s.a+class_s.b) failed actual value {0} ", v7); ret = ret + 1; } if (v8 != 35) { Console.WriteLine("test7: for (class_s.b+class_s.a) failed actual value {0} ", v8); ret = ret + 1; } if (v9 != 124) { Console.WriteLine("test8: for (class_s.a+(class_s.b+class_s.c)) failed actual value {0} ", v9); ret = ret + 1; } if (v10 != 124) { Console.WriteLine("test9: for (class_s.b+(class_s.a+class_s.c)) failed actual value {0} ", v10); ret = ret + 1; } if (v11 != 175) { Console.WriteLine("test10: for (class_s.b+class_s.c) failed actual value {0} ", v11); ret = ret + 1; } if (v12 != 38) { Console.WriteLine("test11: for (class_s.a+class_s.c) failed actual value {0} ", v12); ret = ret + 1; } if (v13 != 124) { Console.WriteLine("test12: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v13); ret = ret + 1; } if (v14 != 124) { Console.WriteLine("test13: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v14); ret = ret + 1; } if (v15 != 180) { Console.WriteLine("test14: for ((class_s.a+class_s.b)+(class_s.c+class_s.d)) failed actual value {0} ", v15); ret = ret + 1; } if (v16 != 180) { Console.WriteLine("test15: for (class_s.c+((class_s.a+class_s.b)+class_s.d)) failed actual value {0} ", v16); ret = ret + 1; } if (v17 != 145) { Console.WriteLine("test16: for (class_s.c+class_s.d) failed actual value {0} ", v17); ret = ret + 1; } if (v18 != 91) { Console.WriteLine("test17: for ((class_s.a+class_s.b)+class_s.d) failed actual value {0} ", v18); ret = ret + 1; } if (v19 != 91) { Console.WriteLine("test18: for (class_s.a+(class_s.b+class_s.d)) failed actual value {0} ", v19); ret = ret + 1; } if (v20 != 91) { Console.WriteLine("test19: for (class_s.b+(class_s.a+class_s.d)) failed actual value {0} ", v20); ret = ret + 1; } if (v21 != 142) { Console.WriteLine("test20: for (class_s.b+class_s.d) failed actual value {0} ", v21); ret = ret + 1; } if (v22 != 5) { Console.WriteLine("test21: for (class_s.a+class_s.d) failed actual value {0} ", v22); ret = ret + 1; } if (v23 != 180) { Console.WriteLine("test22: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v23); ret = ret + 1; } if (v24 != 180) { Console.WriteLine("test23: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v24); ret = ret + 1; } #if LOOP } while (v18 == 0); } while (v17 == 0); #endif Console.WriteLine(ret); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } public class class_s { public static int a; public static int b; public static int c; public static int d; } }
// 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.WebSites { 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 RecommendationsOperationsExtensions { /// <summary> /// Gets a list of recommendations associated with the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='filter'> /// Return only channels specified in the filter. Filter is specified by using /// OData syntax. Example: $filter=channels eq 'Api' or channel eq /// 'Notification' /// </param> public static IList<Recommendation> GetRecommendationBySubscription(this IRecommendationsOperations operations, bool? featured = default(bool?), string filter = default(string)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).GetRecommendationBySubscriptionAsync(featured, filter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of recommendations associated with the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='filter'> /// Return only channels specified in the filter. Filter is specified by using /// OData syntax. Example: $filter=channels eq 'Api' or channel eq /// 'Notification' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> GetRecommendationBySubscriptionAsync( this IRecommendationsOperations operations, bool? featured = default(bool?), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRecommendationBySubscriptionWithHttpMessagesAsync(featured, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the detailed properties of the recommendation object for the /// specified web site. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='name'> /// Recommendation rule name /// </param> public static RecommendationRule GetRuleDetailsBySiteName(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string name) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).GetRuleDetailsBySiteNameAsync(resourceGroupName, siteName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the detailed properties of the recommendation object for the /// specified web site. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='name'> /// Recommendation rule name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RecommendationRule> GetRuleDetailsBySiteNameAsync( this IRecommendationsOperations operations, string resourceGroupName, string siteName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRuleDetailsBySiteNameWithHttpMessagesAsync(resourceGroupName, siteName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of recommendations associated with the specified web site. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='siteSku'> /// The name of site SKU. /// </param> /// <param name='numSlots'> /// The number of site slots associated to the site /// </param> public static IList<Recommendation> GetRecommendedRulesForSite(this IRecommendationsOperations operations, string resourceGroupName, string siteName, bool? featured = default(bool?), string siteSku = default(string), int? numSlots = default(int?)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).GetRecommendedRulesForSiteAsync(resourceGroupName, siteName, featured, siteSku, numSlots), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of recommendations associated with the specified web site. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='siteSku'> /// The name of site SKU. /// </param> /// <param name='numSlots'> /// The number of site slots associated to the site /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> GetRecommendedRulesForSiteAsync( this IRecommendationsOperations operations, string resourceGroupName, string siteName, bool? featured = default(bool?), string siteSku = default(string), int? numSlots = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRecommendedRulesForSiteWithHttpMessagesAsync(resourceGroupName, siteName, featured, siteSku, numSlots, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of past recommendations optionally specified by the time /// range. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='startTime'> /// The start time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> /// <param name='endTime'> /// The end time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> public static IList<Recommendation> GetRecommendationHistoryForSite(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string startTime = default(string), string endTime = default(string)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).GetRecommendationHistoryForSiteAsync(resourceGroupName, siteName, startTime, endTime), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of past recommendations optionally specified by the time /// range. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='startTime'> /// The start time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> /// <param name='endTime'> /// The end time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> GetRecommendationHistoryForSiteAsync( this IRecommendationsOperations operations, string resourceGroupName, string siteName, string startTime = default(string), string endTime = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRecommendationHistoryForSiteWithHttpMessagesAsync(resourceGroupName, siteName, startTime, endTime, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using NLog.Common; /// <summary> /// Reflection helpers. /// </summary> internal static class ReflectionHelpers { /// <summary> /// Gets all usable exported types from the given assembly. /// </summary> /// <param name="assembly">Assembly to scan.</param> /// <returns>Usable types from the given assembly.</returns> /// <remarks>Types which cannot be loaded are skipped.</remarks> public static Type[] SafeGetTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException typeLoadException) { foreach (var ex in typeLoadException.LoaderExceptions) { InternalLogger.Warn(ex, "Type load exception."); } var loadedTypes = new List<Type>(); foreach (var t in typeLoadException.Types) { if (t != null) { loadedTypes.Add(t); } } return loadedTypes.ToArray(); } catch (Exception ex) { InternalLogger.Warn(ex, "Type load exception."); return ArrayHelper.Empty<Type>(); } } /// <summary> /// Is this a static class? /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks>This is a work around, as Type doesn't have this property. /// From: https://stackoverflow.com/questions/1175888/determine-if-a-type-is-static /// </remarks> public static bool IsStaticClass(this Type type) { return type.IsClass() && type.IsAbstract() && type.IsSealed(); } /// <summary> /// Optimized delegate for calling MethodInfo /// </summary> /// <param name="target">Object instance, use null for static methods.</param> /// <param name="arguments">Complete list of parameters that matches the method, including optional/default parameters.</param> public delegate object LateBoundMethod(object target, object[] arguments); /// <summary> /// Optimized delegate for calling a constructor /// </summary> /// <param name="arguments">Complete list of parameters that matches the constructor, including optional/default parameters. Could be null for no parameters.</param> public delegate object LateBoundConstructor([CanBeNull] object[] arguments); /// <summary> /// Creates an optimized delegate for calling the MethodInfo using Expression-Trees /// </summary> /// <param name="methodInfo">Method to optimize</param> /// <returns>Optimized delegate for invoking the MethodInfo</returns> public static LateBoundMethod CreateLateBoundMethod(MethodInfo methodInfo) { var instanceParameter = Expression.Parameter(typeof(object), "instance"); var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); var parameterExpressions = BuildParameterList(methodInfo, parametersParameter); var methodCall = BuildMethodCall(methodInfo, instanceParameter, parameterExpressions); // ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...) if (methodCall.Type == typeof(void)) { var lambda = Expression.Lambda<Action<object, object[]>>( methodCall, instanceParameter, parametersParameter); Action<object, object[]> execute = lambda.Compile(); return (instance, parameters) => { execute(instance, parameters); return null; // There is no return-type, so we return null-object }; } else { var castMethodCall = Expression.Convert(methodCall, typeof(object)); var lambda = Expression.Lambda<LateBoundMethod>( castMethodCall, instanceParameter, parametersParameter); return lambda.Compile(); } } /// <summary> /// Creates an optimized delegate for calling the constructors using Expression-Trees /// </summary> /// <param name="constructor">Constructor to optimize</param> /// <returns>Optimized delegate for invoking the constructor</returns> public static LateBoundConstructor CreateLateBoundConstructor(ConstructorInfo constructor) { var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); // build parameter list var parameterExpressions = BuildParameterList(constructor, parametersParameter); var ctorCall = Expression.New(constructor, parameterExpressions); var lambda = Expression.Lambda<LateBoundConstructor>(ctorCall, parametersParameter); return lambda.Compile(); } private static IEnumerable<Expression> BuildParameterList(MethodBase methodInfo, ParameterExpression parametersParameter) { var parameterExpressions = new List<Expression>(); var paramInfos = methodInfo.GetParameters(); for (int i = 0; i < paramInfos.Length; i++) { // (Ti)parameters[i] var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); var valueCast = CreateParameterExpression(paramInfos[i], valueObj); parameterExpressions.Add(valueCast); } return parameterExpressions; } private static MethodCallExpression BuildMethodCall(MethodInfo methodInfo, ParameterExpression instanceParameter, IEnumerable<Expression> parameterExpressions) { // non-instance for static method, or ((TInstance)instance) var instanceCast = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType); // static invoke or ((TInstance)instance).Method var methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions); return methodCall; } private static UnaryExpression CreateParameterExpression(ParameterInfo parameterInfo, Expression expression) { Type parameterType = parameterInfo.ParameterType; if (parameterType.IsByRef) parameterType = parameterType.GetElementType(); var valueCast = Expression.Convert(expression, parameterType); return valueCast; } public static bool IsEnum(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsEnum; #else return type.GetTypeInfo().IsEnum; #endif } public static bool IsPrimitive(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsPrimitive; #else return type.GetTypeInfo().IsPrimitive; #endif } public static bool IsValueType(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsValueType; #else return type.GetTypeInfo().IsValueType; #endif } public static bool IsSealed(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsSealed; #else return type.GetTypeInfo().IsSealed; #endif } public static bool IsAbstract(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsAbstract; #else return type.GetTypeInfo().IsAbstract; #endif } public static bool IsClass(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsClass; #else return type.GetTypeInfo().IsClass; #endif } public static bool IsGenericType(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsGenericType; #else return type.GetTypeInfo().IsGenericType; #endif } [CanBeNull] public static TAttr GetFirstCustomAttribute<TAttr>(this Type type) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return Attribute.GetCustomAttributes(type, typeof(TAttr)).FirstOrDefault() as TAttr; #else var typeInfo = type.GetTypeInfo(); return typeInfo.GetCustomAttributes<TAttr>().FirstOrDefault(); #endif } [CanBeNull] public static TAttr GetFirstCustomAttribute<TAttr>(this PropertyInfo info) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return Attribute.GetCustomAttributes(info, typeof(TAttr)).FirstOrDefault() as TAttr; #else return info.GetCustomAttributes(typeof(TAttr), false).FirstOrDefault() as TAttr; #endif } [CanBeNull] public static TAttr GetFirstCustomAttribute<TAttr>(this Assembly assembly) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return Attribute.GetCustomAttributes(assembly, typeof(TAttr)).FirstOrDefault() as TAttr; #else return assembly.GetCustomAttributes(typeof(TAttr)).FirstOrDefault() as TAttr; #endif } public static IEnumerable<TAttr> GetCustomAttributes<TAttr>(this Type type, bool inherit) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return (TAttr[])type.GetCustomAttributes(typeof(TAttr), inherit); #else return type.GetTypeInfo().GetCustomAttributes<TAttr>(inherit); #endif } public static Assembly GetAssembly(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.Assembly; #else var typeInfo = type.GetTypeInfo(); return typeInfo.Assembly; #endif } public static bool IsValidPublicProperty(this PropertyInfo p) { return p.CanRead && p.GetIndexParameters().Length == 0 && p.GetGetMethod() != null; } public static object GetPropertyValue(this PropertyInfo p, object instance) { #if !NET35 && !NET40 return p.GetValue(instance); #else return p.GetGetMethod().Invoke(instance, null); #endif } public static MethodInfo GetDelegateInfo(this Delegate method) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return method.Method; #else return System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(method); #endif } } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using System.Diagnostics; using Alexa.NET.Request; using Alexa.NET.Response; using MartinCostello.LondonTravel.Skill.Clients; namespace MartinCostello.LondonTravel.Skill.Intents; /// <summary> /// A class that handles the status intent. This class cannot be inherited. /// </summary> internal sealed class StatusIntent : IIntent { /// <summary> /// Initializes a new instance of the <see cref="StatusIntent"/> class. /// </summary> /// <param name="tflClient">The TfL API client to use.</param> /// <param name="config">The skill configuration to use.</param> public StatusIntent(ITflClient tflClient, SkillConfiguration config) { Config = config; TflClient = tflClient; } /// <summary> /// Gets the skill configuration. /// </summary> private SkillConfiguration Config { get; } /// <summary> /// Gets the TfL API client. /// </summary> private ITflClient TflClient { get; } /// <inheritdoc /> public async Task<SkillResponse> RespondAsync(Intent intent, Session session) { string rawLineName = null; if (intent.Slots.TryGetValue("LINE", out Slot slot)) { rawLineName = slot.Value; } string id = Lines.MapNameToId(rawLineName); SkillResponseBuilder builder; if (string.IsNullOrEmpty(id)) { builder = SkillResponseBuilder .Tell(Strings.StatusIntentUnknownLine) .WithReprompt(); } else if (string.Equals(id, "elizabeth", StringComparison.Ordinal)) { builder = SkillResponseBuilder .Tell(Strings.StatusIntentElizabethLineNotImplemented) .WithReprompt(); } else { IList<Line> statuses = await GetStatusesAsync(id); string cardTitle = Lines.ToCardTitle(statuses[0]?.Name ?? string.Empty); string text = GenerateResponse(statuses); builder = SkillResponseBuilder .Tell(text) .WithCard(cardTitle, text); } return builder.Build(); } /// <summary> /// Generates the text to respond to the specified lines' status responses. /// </summary> /// <param name="lines">A list of lines.</param> /// <returns> /// The response for the specified lines' statuses. /// </returns> internal static string GenerateResponse(IList<Line> lines) { Line line = lines[0]; if (line.LineStatuses.Count == 1) { LineStatus lineStatus = line.LineStatuses[0]; bool includeDetail = !ShouldStatusUseCustomResponse(lineStatus.StatusSeverity); return GenerateResponseForSingleStatus( line.Name, lineStatus, includeDetail); } else { return GenerateResponseForMultipleStatuses(line.Name, line.LineStatuses); } } /// <summary> /// Generates the text to respond for a multiple line statuses. /// </summary> /// <param name="name">The name of the line.</param> /// <param name="statuses">The statuses for the line.</param> /// <returns> /// The response for the specified line statuses. /// </returns> private static string GenerateResponseForMultipleStatuses(string name, ICollection<LineStatus> statuses) { // The descriptions appear to reference each other, so use the least severe's var sortedStatuses = statuses .OrderBy((p) => p.StatusSeverity) .ToList(); return GenerateResponseForSingleStatus( name, sortedStatuses[0], includeDetail: true); } /// <summary> /// Generates the text to respond for a single line status. /// </summary> /// <param name="name">The name of the line.</param> /// <param name="status">The status of the line.</param> /// <param name="includeDetail">Whether to include the detail in the response.</param> /// <returns> /// The response for the specified line status. /// </returns> private static string GenerateResponseForSingleStatus(string name, LineStatus status, bool includeDetail) { if (includeDetail) { return GenerateDetailedResponse(status); } else { return GenerateSummaryResponse(name, status); } } /// <summary> /// Generates the detailed text to respond for a single line status. /// </summary> /// <param name="status">The status for a line.</param> /// <returns> /// The response text for the specified line status. /// </returns> private static string GenerateDetailedResponse(LineStatus status) { string response = status.Reason; // Trim off the line name prefix, if present string delimiter = ": "; int index = response.IndexOf(delimiter, StringComparison.Ordinal); if (index > -1) { response = response.Substring(index + delimiter.Length); } return response; } /// <summary> /// Generates the summary text to respond for a single line status. /// </summary> /// <param name="name">The name of the line.</param> /// <param name="status">The status for a line.</param> /// <returns> /// The response text for the specified line status. /// </returns> private static string GenerateSummaryResponse(string name, LineStatus status) { string format; if (status.StatusSeverity == LineStatusSeverity.ServiceClosed) { format = Strings.StatusIntentClosedFormat; } else { Debug.Assert( status.StatusSeverity == LineStatusSeverity.GoodService || status.StatusSeverity == LineStatusSeverity.NoIssues, $"'{status.StatusSeverity}' is not supported for a summary response."); format = Strings.StatusIntentGoodServiceFormat; } var culture = CultureInfo.CurrentCulture; string spokenName = Verbalizer.LineName(name); string statusText = string.Format(culture, format, spokenName); return char.ToUpper(statusText[0], culture) + statusText.Substring(1); } /// <summary> /// Returns whether the specified status severity should use a custom response. /// </summary> /// <param name="statusSeverity">The status severity value.</param> /// <returns> /// <see langword="true"/> if the status should use a custom response; otherwise <see langword="false"/>. /// </returns> private static bool ShouldStatusUseCustomResponse(LineStatusSeverity statusSeverity) { switch (statusSeverity) { case LineStatusSeverity.GoodService: case LineStatusSeverity.NoIssues: case LineStatusSeverity.ServiceClosed: return true; default: return false; } } private async Task<IList<Line>> GetStatusesAsync(string id) { return await TflClient.GetLineStatusAsync( id, Config.TflApplicationId, Config.TflApplicationKey); } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.ApigeeConnect.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedConnectionServiceClientSnippets { /// <summary>Snippet for ListConnections</summary> public void ListConnectionsRequestObject() { // Snippet: ListConnections(ListConnectionsRequest, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create(); // Initialize request argument(s) ListConnectionsRequest request = new ListConnectionsRequest { ParentAsEndpointName = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"), }; // Make the request PagedEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnections(request); // Iterate over all response items, lazily performing RPCs as required foreach (Connection item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListConnectionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Connection item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Connection> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Connection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListConnectionsAsync</summary> public async Task ListConnectionsRequestObjectAsync() { // Snippet: ListConnectionsAsync(ListConnectionsRequest, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) ListConnectionsRequest request = new ListConnectionsRequest { ParentAsEndpointName = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"), }; // Make the request PagedAsyncEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Connection item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Connection item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Connection> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Connection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListConnections</summary> public void ListConnections() { // Snippet: ListConnections(string, string, int?, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/endpoints/[ENDPOINT]"; // Make the request PagedEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnections(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Connection item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListConnectionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Connection item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Connection> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Connection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListConnectionsAsync</summary> public async Task ListConnectionsAsync() { // Snippet: ListConnectionsAsync(string, string, int?, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/endpoints/[ENDPOINT]"; // Make the request PagedAsyncEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Connection item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Connection item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Connection> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Connection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListConnections</summary> public void ListConnectionsResourceNames() { // Snippet: ListConnections(EndpointName, string, int?, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create(); // Initialize request argument(s) EndpointName parent = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"); // Make the request PagedEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnections(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Connection item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListConnectionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Connection item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Connection> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Connection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListConnectionsAsync</summary> public async Task ListConnectionsResourceNamesAsync() { // Snippet: ListConnectionsAsync(EndpointName, string, int?, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) EndpointName parent = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"); // Make the request PagedAsyncEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Connection item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Connection item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Connection> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Connection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/ // // 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 JelloScrum.Web.Controllers { using System; using System.Configuration; using System.Drawing; using System.IO; using System.Web; using SD = System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Collections.Generic; using Castle.MonoRail.ActiveRecordSupport; using Castle.MonoRail.Framework; using JelloScrum.Model.Entities; using JelloScrum.Model.Enumerations; /// <summary> /// Controller voor alle Gebruiker beheer acties /// </summary> [Layout("jellobeheer")] public class GebruikerBeheerController : SecureController { /// <summary> /// Index /// </summary> public void Index() { PropertyBag.Add("systemRols", Enum.GetNames(typeof(SystemRole))); Titel = "Gebruikers"; } /// <summary> /// Gebruikers beheer vanuit een project /// </summary> /// <param name="sprint"></param> public void Index([ARFetch("id")] Sprint sprint) { PropertyBag.Add("sprint", sprint); PropertyBag.Add("gebruikers", GebruikerRepository.ZoekOpNietInSprint(sprint)); RenderView("sprintindex"); CancelLayout(); } /// <summary> /// Geeft een lijst terug met gebruikers aan de hand van de systeem rol /// </summary> /// <param name="rol"></param> public void ListGebruikers(SystemRole rol) { PropertyBag.Add("gebruikers", GebruikerRepository.ZoekOpSysteemRol(rol)); CancelLayout(); } /// <summary> /// Laad de gebruiker /// </summary> /// <param name="gebruiker"></param> public void LoadGebruiker([ARFetch("id")] User gebruiker) { PropertyBag.Add("item", gebruiker); RenderView("edit"); CancelLayout(); } /// <summary> /// Nieuwe gebruiker aan maken /// </summary> /// <param name="rol"></param> public void Nieuw(SystemRole rol) { PropertyBag.Add("item", new User(rol)); RenderView("edit"); CancelLayout(); } /// <summary> /// Upload plaatje om avatar van te maken /// </summary> /// <param name="postedFile"></param> public void Upload(HttpPostedFile postedFile) { string[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" }; string postedFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("\\") + 1); string avatarPath = HttpContext.Current.Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["avatarBigPath"]; try { if (string.IsNullOrEmpty(postedFileName) || (!((IList<string>)allowedExtensions).Contains(Path.GetExtension(postedFileName).ToLower()))) throw new Exception("Kan avatar niet uploaden"); postedFile.SaveAs(Path.Combine(avatarPath, postedFileName)); CurrentUser.BigAvatar = ConfigurationManager.AppSettings["avatarRelativePath"] + "big/" + postedFileName; GebruikerRepository.Save(CurrentUser); } catch (Exception ex) { AddInfoMessageToFlashBag("Kan avatar niet uploaden"); } RedirectToAction("GebruikersProfiel"); } /// <summary> /// Saved een nieuwe of bestaande gebruiker. /// </summary> /// <param name="gebruiker"></param> /// <param name="avatar"></param> public void Save([ARDataBind("item", AutoLoadBehavior.NewInstanceIfInvalidKey)] User gebruiker, [ARDataBind("avatar", AutoLoadBehavior.NewInstanceIfInvalidKey)] Avatar avatar) { try { //Als er geen selectie is gemaakt, hoeven we ook geen avatar te maken. if(avatar.Width != 0 && avatar.Height != 0) { gebruiker.SmallAvatar = gebruiker.BigAvatar.Replace("big", "small"); byte[] cropImage = avatar.CropResize(Path.GetFileName(gebruiker.BigAvatar)); using (MemoryStream ms = new MemoryStream(cropImage, 0, cropImage.Length)) { ms.Write(cropImage, 0, cropImage.Length); using (SD.Image croppedImage = SD.Image.FromStream(ms, true)) { string saveTo = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, ConfigurationManager.AppSettings["avatarSmallPath"] + Path.GetFileName(gebruiker.SmallAvatar)); croppedImage.Save(saveTo, croppedImage.RawFormat); } } } GebruikerRepository.Save(gebruiker); } catch (Exception e) { AddErrorMessageToFlashBag(e.Message); } RedirectToAction("GebruikersProfiel"); } /// <summary> /// Instellen gebruikersprofiel /// </summary> public void GebruikersProfiel() { Titel = "Bewerk gebruikersprofiel"; PropertyBag.Add("item", CurrentUser); RenderView("edit"); } /// <summary> /// Beheer de lijst met mijn projecten /// </summary> public void MijnProjecten() { Titel = "Kies mijn projecten"; IList<Project> projects = new List<Project>(ProjectRepository.FindAll()); PropertyBag.Add("projecten", projects); if (projects.Count == 0) { AddErrorMessageToPropertyBag("Er zijn nog geen projecten gedefini&euml;erd."); } else { foreach (ProjectShortList list in CurrentUser.ProjectShortList) { projects.Remove(list.Project); } } PropertyBag.Add("item", CurrentUser); } /// <summary> /// /// </summary> public void ProjectToevoegenAanShortList([ARFetch("id")] Project project) { try { CurrentUser.AddProjectToShortList(project); GebruikerRepository.Save(CurrentUser); } catch { AddErrorMessageToFlashBag("Het toevoegen van dit project aan de shortlist is niet gelukt, probeer het nogmaals."); } RedirectToAction("mijnprojecten"); } /// <summary> /// /// </summary> public void ProjectVerwijderenVanShortList([ARFetch("id")] ProjectShortList projectShortList) { try { ProjectShortListRepository.Delete(projectShortList); } catch { AddErrorMessageToFlashBag("Het verwijderen van dit project uit de shortlist is niet gelukt, probeer het nogmaals."); } RedirectToAction("mijnprojecten"); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using DotVVM.Framework.Parser; using DotVVM.Framework.Parser.Dothtml.Tokenizer; namespace DotVVM.Framework.Tests.Parser.Dothtml { [TestClass] public class DothtmlTokenizerBindingTests : DothtmlTokenizerTestsBase { [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_SelfClosing_BindingAttribute() { var input = @" tr <input value=""{binding: FirstName}"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Slash, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_BindingInPlainText() { var input = @"tr {{binding: FirstName}}"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding() { var input = @"<input value=""{"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_CloseBinding() { var input = @"<input value=""{}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Text_CloseBinding() { var input = @"<input value=""{value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Text_WhiteSpace_Text_CloseBinding() { var input = @"<input value=""{value value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Colon_Text_CloseBinding() { var input = @"<input value=""{:value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Colon_CloseBinding() { var input = @"<input value=""{:value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Text_Colon_CloseBinding() { var input = @"<input value=""{name:}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Invalid_BindingInPlainText_NotClosed() { var input = @"tr {{binding: FirstName"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Invalid_BindingInPlainText_ClosedWithOneBrace() { var input = @"tr {{binding: FirstName}test"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(1, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Invalid_BindingInPlainText_SingleBraces_TreatedAsText() { var input = @"tr {binding: FirstName}test"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(1, tokenizer.Tokens.Count); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } } }
// Copyright 2017, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using System; using System.Linq; namespace Google.Cloud.Spanner.Admin.Database.V1 { /// <summary> /// Resource name for the 'instance' resource. /// </summary> public sealed partial class InstanceName : IResourceName, IEquatable<InstanceName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/instances/{instance}"); /// <summary> /// Parses the given instance resource name in string form into a new /// <see cref="InstanceName"/> instance. /// </summary> /// <param name="instanceName">The instance resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) { GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); TemplatedResourceName resourceName = s_template.ParseName(instanceName); return new InstanceName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given instance resource name in string form into a new /// <see cref="InstanceName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="instanceName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="instanceName">The instance resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="InstanceName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, out InstanceName result) { GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); TemplatedResourceName resourceName; if (s_template.TryParseName(instanceName, out resourceName)) { result = new InstanceName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="InstanceName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param> public InstanceName(string projectId, string instanceId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceId = GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The instance ID. Never <c>null</c>. /// </summary> public string InstanceId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, InstanceId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as InstanceName); /// <inheritdoc /> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } /// <summary> /// Resource name for the 'database' resource. /// </summary> public sealed partial class DatabaseName : IResourceName, IEquatable<DatabaseName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/instances/{instance}/databases/{database}"); /// <summary> /// Parses the given database resource name in string form into a new /// <see cref="DatabaseName"/> instance. /// </summary> /// <param name="databaseName">The database resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DatabaseName"/> if successful.</returns> public static DatabaseName Parse(string databaseName) { GaxPreconditions.CheckNotNull(databaseName, nameof(databaseName)); TemplatedResourceName resourceName = s_template.ParseName(databaseName); return new DatabaseName(resourceName[0], resourceName[1], resourceName[2]); } /// <summary> /// Tries to parse the given database resource name in string form into a new /// <see cref="DatabaseName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="databaseName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="databaseName">The database resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="DatabaseName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string databaseName, out DatabaseName result) { GaxPreconditions.CheckNotNull(databaseName, nameof(databaseName)); TemplatedResourceName resourceName; if (s_template.TryParseName(databaseName, out resourceName)) { result = new DatabaseName(resourceName[0], resourceName[1], resourceName[2]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="DatabaseName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param> /// <param name="databaseId">The database ID. Must not be <c>null</c>.</param> public DatabaseName(string projectId, string instanceId, string databaseId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceId = GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId)); DatabaseId = GaxPreconditions.CheckNotNull(databaseId, nameof(databaseId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The instance ID. Never <c>null</c>. /// </summary> public string InstanceId { get; } /// <summary> /// The database ID. Never <c>null</c>. /// </summary> public string DatabaseId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, InstanceId, DatabaseId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as DatabaseName); /// <inheritdoc /> public bool Equals(DatabaseName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(DatabaseName a, DatabaseName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(DatabaseName a, DatabaseName b) => !(a == b); } public partial class CreateDatabaseMetadata { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Database"/> resource name property. /// </summary> public DatabaseName DatabaseAsDatabaseName { get { return string.IsNullOrEmpty(Database) ? null : Google.Cloud.Spanner.Admin.Database.V1.DatabaseName.Parse(Database); } set { Database = value != null ? value.ToString() : ""; } } } public partial class CreateDatabaseRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public InstanceName ParentAsInstanceName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Spanner.Admin.Database.V1.InstanceName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class DropDatabaseRequest { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Database"/> resource name property. /// </summary> public DatabaseName DatabaseAsDatabaseName { get { return string.IsNullOrEmpty(Database) ? null : Google.Cloud.Spanner.Admin.Database.V1.DatabaseName.Parse(Database); } set { Database = value != null ? value.ToString() : ""; } } } public partial class GetDatabaseDdlRequest { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Database"/> resource name property. /// </summary> public DatabaseName DatabaseAsDatabaseName { get { return string.IsNullOrEmpty(Database) ? null : Google.Cloud.Spanner.Admin.Database.V1.DatabaseName.Parse(Database); } set { Database = value != null ? value.ToString() : ""; } } } public partial class GetDatabaseRequest { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public DatabaseName DatabaseName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Database.V1.DatabaseName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ListDatabasesRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public InstanceName ParentAsInstanceName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Spanner.Admin.Database.V1.InstanceName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class UpdateDatabaseDdlMetadata { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Database"/> resource name property. /// </summary> public DatabaseName DatabaseAsDatabaseName { get { return string.IsNullOrEmpty(Database) ? null : Google.Cloud.Spanner.Admin.Database.V1.DatabaseName.Parse(Database); } set { Database = value != null ? value.ToString() : ""; } } } public partial class UpdateDatabaseDdlRequest { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Database"/> resource name property. /// </summary> public DatabaseName DatabaseAsDatabaseName { get { return string.IsNullOrEmpty(Database) ? null : Google.Cloud.Spanner.Admin.Database.V1.DatabaseName.Parse(Database); } set { Database = value != null ? value.ToString() : ""; } } } }
using UnityEngine; using System; using System.Collections; namespace Stratus.Gameplay { /// <summary> /// Provides common operations on a Transform /// </summary> public class StratusTransformEvent : StratusTriggerable, StratusTriggerBase.Restartable { public enum ValueType { [Tooltip("Use a static value")] Static, [Tooltip("Use the values of another transform")] Mirror } public enum EventType { Translate, Rotate, RotateAround, Scale, Parent, Reset } //--------------------------------------------------------------------------------------------/ // Fields //--------------------------------------------------------------------------------------------/ [Tooltip("The transform whos is being operated on")] public Transform target; [Tooltip("The type of the event")] public EventType eventType; [Tooltip("The duration of the event")] public float duration = 1.0f; [Tooltip("The interpolation algorithm to use")] public StratusEase ease; // Values [Tooltip("How the value to use is decided")] public ValueType valueType; [Tooltip("The value to set")] [DrawIf("valueType", ValueType.Static, ComparisonType.Equals)] public Vector3 value; [Tooltip("The transform whose values we are using for the operation")] [DrawIf("valueType", ValueType.Mirror, ComparisonType.Equals)] public Transform source; //[DrawIf("eventType", EventType.Scale, ComparisonType.Equals)] //public float scalar = 0f; // Options [DrawIf("eventType", EventType.RotateAround, ComparisonType.Equals)] public float angleAroundTarget = 0f; [DrawIf("eventType", EventType.RotateAround, ComparisonType.Equals)] public Vector3 axis = Vector3.up; [Tooltip("Whether to use local coordinates for the translation (respective to the parent)")] [DrawIf("eventType", EventType.Translate, ComparisonType.Equals)] public bool local = false; [Tooltip("Whether the value is an offset from the current value")] [DrawIf("valueType", ValueType.Mirror, ComparisonType.NotEqual)] public bool offset = false; //--------------------------------------------------------------------------------------------/ // Properties //--------------------------------------------------------------------------------------------/ public Vector3 currentValue => offset ? value + previousValue : value; public Vector3 previousValue { get; private set; } private StratusActionSet currentAction { get; set; } private IEnumerator currentCoroutine { get; set; } private bool isMirror => valueType == ValueType.Mirror; private TransformationType transformationType; public override string automaticDescription { get { if (target) return $"{eventType} {target.name} over {duration}s"; return string.Empty; } } //--------------------------------------------------------------------------------------------/ // Messages //--------------------------------------------------------------------------------------------/ protected override void OnAwake() { } protected override void OnReset() { } protected override void OnTrigger() { Apply(this.value); } public void OnRestart() { Cancel(); //Revert(); } //--------------------------------------------------------------------------------------------/ // Methods //--------------------------------------------------------------------------------------------/ /// <summary> /// Interpolates to the specified transformation. /// </summary> public void Apply(Vector3 value) { currentAction = StratusActions.Sequence(this); if (debug) StratusDebug.Log($"The {eventType} operation was applied on {target.name}", this); switch (eventType) { case EventType.Translate: transformationType = TransformationType.Translate; if (valueType == ValueType.Static) { if (local) { previousValue = target.localPosition; currentCoroutine = StratusRoutines.Interpolate(previousValue, currentValue, duration, (Vector3 val) => { target.localPosition = val; }, ease); //Actions.Property(currentAction, () => target.localPosition, currentValue, this.duration, this.ease); } else { previousValue = target.position; currentCoroutine = StratusRoutines.Interpolate(previousValue, currentValue, duration, (Vector3 val) => { target.position = val; }, ease); //Actions.Property(currentAction, () => target.position, currentValue, this.duration, this.ease); } } else if (valueType == ValueType.Mirror) { previousValue = target.position; currentCoroutine = StratusRoutines.Interpolate(previousValue, source.position, duration, (Vector3 val) => { target.position = val; }, ease); //Actions.Property(currentAction, () => target.position, source.position, this.duration, this.ease); } target.StartCoroutine(currentCoroutine, transformationType); break; case EventType.Rotate: transformationType = TransformationType.Rotate; previousValue = target.rotation.eulerAngles; currentCoroutine = StratusRoutines.Rotate(target, isMirror ? source.rotation.eulerAngles : currentValue, duration); target.StartCoroutine(currentCoroutine, transformationType); //Actions.Property(currentAction, () => target.rotation.eulerAngles, isMirror ? source.localRotation.eulerAngles : currentValue, this.duration, this.ease); break; case EventType.RotateAround: transformationType = TransformationType.Translate | TransformationType.Rotate; previousValue = target.rotation.eulerAngles; currentCoroutine = StratusRoutines.RotateAround(target, isMirror ? source.position : currentValue, axis, angleAroundTarget, duration); target.StartCoroutine(currentCoroutine, transformationType); break; case EventType.Scale: previousValue = target.localScale; transformationType = TransformationType.Scale; currentCoroutine = StratusRoutines.Interpolate(previousValue, isMirror ? source.localScale : currentValue, duration, (Vector3 val) => { target.localScale = val; }, ease); ; //Routines.Scale(target, isMirror ? source.localScale : currentValue, this.duration); target.StartCoroutine(currentCoroutine, transformationType); //Actions.Property(currentAction, () => target.localScale, isMirror ? source.localScale : currentValue, this.duration, this.ease); break; case EventType.Parent: StratusActions.Delay(currentAction, duration); StratusActions.Call(currentAction, () => { target.SetParent(source); }); break; case EventType.Reset: StratusActions.Delay(currentAction, duration); StratusActions.Call(currentAction, () => { target.Reset(); }); break; } } /// <summary> /// Cancels the current transformation event /// </summary> public void Cancel() { currentAction?.Cancel(); if (currentCoroutine != null) { target.StopCoroutine(transformationType); currentCoroutine = null; } } /// <summary> /// Reverts to the previous transformation. /// </summary> public void Revert() { this.Apply(this.previousValue); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Eto.Drawing; namespace Eto.Forms { /// <summary> /// Base class for controls that contain children controls /// </summary> public abstract class Container : Control { new IHandler Handler { get { return (IHandler)base.Handler; } } /// <summary> /// Gets or sets the size for the client area of the control /// </summary> /// <remarks> /// The client size differs from the <see cref="Control.Size"/> in that it excludes the decorations of /// the container, such as the title bar and border around a <see cref="Window"/>, or the title and line /// around a <see cref="GroupBox"/>. /// </remarks> /// <value>The size of the client area</value> public Size ClientSize { get { return Handler.ClientSize; } set { Handler.ClientSize = value; } } /// <summary> /// Gets an enumeration of controls that are directly contained by this container /// </summary> /// <value>The contained controls.</value> public abstract IEnumerable<Control> Controls { get; } /// <summary> /// Gets an enumeration of all contained child controls, including controls within child containers /// </summary> /// <value>The children.</value> public IEnumerable<Control> Children { get { foreach (var control in Controls) { yield return control; var container = control as Container; if (container != null) { foreach (var child in container.Children) yield return child; } } } } /// <summary> /// Raises the <see cref="BindableWidget.DataContextChanged"/> event /// </summary> /// <remarks> /// Implementors may override this to fire this event on child widgets in a heirarchy. /// This allows a control to be bound to its own <see cref="BindableWidget.DataContext"/>, which would be set /// on one of the parent control(s). /// </remarks> /// <param name="e">Event arguments</param> protected override void OnDataContextChanged(EventArgs e) { base.OnDataContextChanged(e); if (Handler.RecurseToChildren) { foreach (var control in Controls) { control.TriggerDataContextChanged(e); } } } /// <summary> /// Raises the <see cref="Control.PreLoad"/> event, and recurses to this container's children /// </summary> /// <param name="e">Event arguments</param> protected override void OnPreLoad(EventArgs e) { base.OnPreLoad(e); if (Handler.RecurseToChildren) { foreach (Control control in Controls) { control.TriggerPreLoad(e); } } } /// <summary> /// Raises the <see cref="Control.Load"/> event, and recurses to this container's children /// </summary> /// <param name="e">Event arguments</param> protected override void OnLoad(EventArgs e) { if (Handler.RecurseToChildren) { foreach (Control control in Controls) { control.TriggerLoad(e); } } base.OnLoad(e); } /// <summary> /// Raises the <see cref="Control.LoadComplete"/> event, and recurses to this container's children /// </summary> /// <param name="e">Event arguments</param> protected override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); if (Handler.RecurseToChildren) { foreach (Control control in Controls) { control.TriggerLoadComplete(e); } } } /// <summary> /// Raises the <see cref="Control.UnLoad"/> event, and recurses to this container's children /// </summary> /// <param name="e">Event arguments</param> protected override void OnUnLoad(EventArgs e) { if (Handler != null && Handler.RecurseToChildren) { foreach (Control control in Controls) { control.TriggerUnLoad(e); } } base.OnUnLoad(e); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.Container"/> class. /// </summary> protected Container() { } /// <summary> /// Initializes a new instance of the Container with the specified handler /// </summary> /// <param name="handler">Pre-created handler to attach to this instance</param> protected Container(IHandler handler) : base(handler) { } /// <summary> /// Unbinds any bindings in the <see cref="BindableWidget.Bindings"/> collection and removes the bindings, and recurses to this container's children /// </summary> public override void Unbind() { base.Unbind(); if (Handler.RecurseToChildren) { foreach (var control in Controls) { control.Unbind(); } } } /// <summary> /// Updates all bindings in this widget, and recurses to this container's children /// </summary> public override void UpdateBindings(BindingUpdateMode mode = BindingUpdateMode.Source) { base.UpdateBindings(mode); if (Handler.RecurseToChildren) { foreach (var control in Controls) { control.UpdateBindings(mode); } } } /// <summary> /// Remove the specified <paramref name="controls"/> from this container /// </summary> /// <param name="controls">Controls to remove</param> public virtual void Remove(IEnumerable<Control> controls) { foreach (var control in controls) Remove(control); } /// <summary> /// Removes all controls from this container /// </summary> public virtual void RemoveAll() { Remove(Controls.ToArray()); } /// <summary> /// Removes the specified <paramref name="child"/> control /// </summary> /// <param name="child">Child to remove</param> public abstract void Remove(Control child); /// <summary> /// Removes the specified control from the container. /// </summary> /// <remarks> /// This should only be called on controls that the container owns. Otherwise, call <see cref="Control.Detach"/> /// </remarks> /// <param name="child">Child to remove from this container</param> protected void RemoveParent(Control child) { if (child != null && !ReferenceEquals(child.Parent, null)) { #if DEBUG if (!ReferenceEquals(child.Parent, this)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The child control is not a child of this container. Ensure you only remove children that you own.")); #endif if (child.Loaded) { child.TriggerUnLoad(EventArgs.Empty); } child.Parent = null; child.TriggerDataContextChanged(EventArgs.Empty); } } /// <summary> /// Sets the parent of the specified <paramref name="child"/> to this container /// </summary> /// <remarks> /// This is used by container authors to set the parent of a child before it is added to the underlying platform control. /// /// The <paramref name="assign"/> parameter should call the handler method to add the child to the parent. /// </remarks> /// <returns><c>true</c>, if parent was set, <c>false</c> otherwise.</returns> /// <param name="child">Child to set the parent</param> /// <param name="assign">Method to assign the child to the handler</param> /// <param name="previousChild">Previous child that the new child is replacing.</param> protected void SetParent(Control child, Action assign, Control previousChild = null) { bool triggerPrevious = false; if (previousChild != null && !ReferenceEquals(previousChild.Parent, null) && (!ReferenceEquals(previousChild, child) || !ReferenceEquals(child.Parent, this))) { #if DEBUG if (!ReferenceEquals(previousChild.Parent, this)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The child control is not a child of this container. Ensure you only remove children that you own.")); #endif if (previousChild.Loaded) { previousChild.TriggerUnLoad(EventArgs.Empty); } previousChild.Parent = null; triggerPrevious = true; } if (child != null && !ReferenceEquals(child.Parent, this)) { // Detach so parent can remove from controls collection if necessary. // prevents UnLoad from being called more than once when containers think a control is still a child // no-op if there is no parent (handled in detach) child.Detach(); child.Parent = this; if (Loaded && !child.Loaded) { using (child.Platform.Context) { child.TriggerPreLoad(EventArgs.Empty); child.TriggerLoad(EventArgs.Empty); child.TriggerDataContextChanged(EventArgs.Empty); assign(); child.TriggerLoadComplete(EventArgs.Empty); } if (triggerPrevious) previousChild.TriggerDataContextChanged(EventArgs.Empty); return; } } assign(); if (triggerPrevious) previousChild.TriggerDataContextChanged(EventArgs.Empty); } /// <summary> /// Handler interface for the <see cref="Container"/> control /// </summary> public new interface IHandler : Control.IHandler { /// <summary> /// Gets or sets the size for the client area of the control /// </summary> /// <remarks> /// The client size differs from the <see cref="P:Eto.Forms.Control.IHandler.Size"/> in that it excludes the decorations of /// the container, such as the title bar and border around a <see cref="Window"/>, or the title and line /// around a <see cref="GroupBox"/>. /// </remarks> /// <value>The size of the client area</value> Size ClientSize { get; set; } /// <summary> /// Gets a value indicating whether PreLoad/Load/LoadComplete/Unload events are propegated to the children controls /// </summary> /// <remarks> /// This is mainly used when you want to use Eto controls in your handler, such as with the <see cref="ThemedContainerHandler{TContainer,TWidget,TCallback}"/> /// </remarks> /// <value><c>true</c> to recurse events to children; otherwise, <c>false</c>.</value> bool RecurseToChildren { get; } } } }
using System; using System.Net.Http; using System.Threading.Tasks; using System.Threading; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; #if !XAMARIN_MODERN using ModernHttpClient.CoreFoundation; using ModernHttpClient.Foundation; #endif #if UNIFIED using Foundation; using Security; #else using MonoTouch.Foundation; using MonoTouch.Security; using System.Globalization; #endif #if XAMARIN_MODERN #if SYSTEM_NET_HTTP using NativeMessageHandler = System.Net.Http.NSUrlSessionHandler; namespace System.Net.Http { #else using NativeMessageHandler = Foundation.NSUrlSessionHandler; namespace Foundation { #endif #else namespace ModernHttpClient { #endif class InflightOperation { public HttpRequestMessage Request { get; set; } public TaskCompletionSource<HttpResponseMessage> FutureResponse { get; set; } public ProgressDelegate Progress { get; set; } public ByteArrayListStream ResponseBody { get; set; } public CancellationToken CancellationToken { get; set; } public bool IsCompleted { get; set; } } #if XAMARIN_MODERN public partial class NSUrlSessionHandler : HttpMessageHandler #else public class NativeMessageHandler : HttpClientHandler #endif { readonly NSUrlSession session; readonly Dictionary<NSUrlSessionTask, InflightOperation> inflightRequests = new Dictionary<NSUrlSessionTask, InflightOperation>(); #if !XAMARIN_MODERN readonly Dictionary<HttpRequestMessage, ProgressDelegate> registeredProgressCallbacks = new Dictionary<HttpRequestMessage, ProgressDelegate>(); #endif readonly Dictionary<string, string> headerSeparators = new Dictionary<string, string>(){ {"User-Agent", " "} }; #if !XAMARIN_MODERN readonly bool throwOnCaptiveNetwork; readonly bool customSSLVerification; #endif public bool DisableCaching { get; set; } #if XAMARIN_MODERN public NSUrlSessionHandler() #else public NativeMessageHandler(): this(false, false) { } public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null, SslProtocol? minimumSSLProtocol = null) #endif { var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration; #if XAMARIN_MODERN // we cannot do a bitmask but we can set the minimum based on ServicePointManager.SecurityProtocol minimum var sp = ServicePointManager.SecurityProtocol; if ((sp & SecurityProtocolType.Ssl3) != 0) configuration.TLSMinimumSupportedProtocol = SslProtocol.Ssl_3_0; else if ((sp & SecurityProtocolType.Tls) != 0) configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_0; else if ((sp & SecurityProtocolType.Tls11) != 0) configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_1; else if ((sp & SecurityProtocolType.Tls12) != 0) configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_2; #else // System.Net.ServicePointManager.SecurityProtocol provides a mechanism for specifying supported protocol types // for System.Net. Since iOS only provides an API for a minimum and maximum protocol we are not able to port // this configuration directly and instead use the specified minimum value when one is specified. if (minimumSSLProtocol.HasValue) { configuration.TLSMinimumSupportedProtocol = minimumSSLProtocol.Value; } #endif session = NSUrlSession.FromConfiguration( NSUrlSessionConfiguration.DefaultSessionConfiguration, new DataTaskDelegate(this), null); #if !XAMARIN_MODERN this.throwOnCaptiveNetwork = throwOnCaptiveNetwork; this.customSSLVerification = customSSLVerification; #else this.AllowAutoRedirect = true; #endif this.DisableCaching = false; } string getHeaderSeparator(string name) { if (headerSeparators.ContainsKey(name)) { return headerSeparators[name]; } return ","; } #if !XAMARIN_MODERN public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback) { if (callback == null && registeredProgressCallbacks.ContainsKey(request)) { registeredProgressCallbacks.Remove(request); return; } registeredProgressCallbacks[request] = callback; } ProgressDelegate getAndRemoveCallbackFromRegister(HttpRequestMessage request) { ProgressDelegate emptyDelegate = delegate { }; lock (registeredProgressCallbacks) { if (!registeredProgressCallbacks.ContainsKey(request)) return emptyDelegate; var callback = registeredProgressCallbacks[request]; registeredProgressCallbacks.Remove(request); return callback; } } #endif #if SYSTEM_NET_HTTP || MONOMAC internal #endif protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { #if XAMARIN_MODERN Volatile.Write (ref sentRequest, true); #endif var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>; var ms = new MemoryStream(); if (request.Content != null) { await request.Content.CopyToAsync(ms).ConfigureAwait(false); headers = headers.Union(request.Content.Headers).ToArray(); } var rq = new NSMutableUrlRequest() { AllowsCellularAccess = true, Body = NSData.FromArray(ms.ToArray()), CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData), Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => { acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value))); return acc; }), HttpMethod = request.Method.ToString().ToUpperInvariant(), Url = NSUrl.FromString(request.RequestUri.AbsoluteUri), }; var op = session.CreateDataTask(rq); cancellationToken.ThrowIfCancellationRequested(); var ret = new TaskCompletionSource<HttpResponseMessage>(); cancellationToken.Register(() => ret.TrySetCanceled()); lock (inflightRequests) { inflightRequests[op] = new InflightOperation() { FutureResponse = ret, Request = request, #if !XAMARIN_MODERN Progress = getAndRemoveCallbackFromRegister(request), #endif ResponseBody = new ByteArrayListStream(), CancellationToken = cancellationToken, }; } op.Resume(); return await ret.Task.ConfigureAwait(false); } #if MONOMAC // Needed since we strip during linking since we're inside a product assembly. [Preserve (AllMembers = true)] #endif class DataTaskDelegate : NSUrlSessionDataDelegate { NativeMessageHandler This { get; set; } public DataTaskDelegate(NativeMessageHandler that) { this.This = that; } public override void DidReceiveResponse(NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler) { var data = getResponseForTask(dataTask); try { if (data.CancellationToken.IsCancellationRequested) { dataTask.Cancel(); } var resp = (NSHttpUrlResponse)response; var req = data.Request; #if !XAMARIN_MODERN if (This.throwOnCaptiveNetwork && req.RequestUri.Host != resp.Url.Host) { throw new CaptiveNetworkException(req.RequestUri, new Uri(resp.Url.ToString())); } #endif var content = new CancellableStreamContent(data.ResponseBody, () => { if (!data.IsCompleted) { dataTask.Cancel(); } data.IsCompleted = true; data.ResponseBody.SetException(new OperationCanceledException()); }); content.Progress = data.Progress; // NB: The double cast is because of a Xamarin compiler bug int status = (int)resp.StatusCode; var ret = new HttpResponseMessage((HttpStatusCode)status) { Content = content, RequestMessage = data.Request, }; ret.RequestMessage.RequestUri = new Uri(resp.Url.AbsoluteString); foreach(var v in resp.AllHeaderFields) { // NB: Cocoa trolling us so hard by giving us back dummy // dictionary entries if (v.Key == null || v.Value == null) continue; ret.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString()); ret.Content.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString()); } data.FutureResponse.TrySetResult(ret); } catch (Exception ex) { data.FutureResponse.TrySetException(ex); } completionHandler(NSUrlSessionResponseDisposition.Allow); } public override void WillCacheResponse (NSUrlSession session, NSUrlSessionDataTask dataTask, NSCachedUrlResponse proposedResponse, Action<NSCachedUrlResponse> completionHandler) { completionHandler (This.DisableCaching ? null : proposedResponse); } public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error) { var data = getResponseForTask(task); data.IsCompleted = true; if (error != null) { var ex = createExceptionForNSError(error); // Pass the exception to the response data.FutureResponse.TrySetException(ex); data.ResponseBody.SetException(ex); return; } data.ResponseBody.Complete(); lock (This.inflightRequests) { This.inflightRequests.Remove(task); } } public override void DidReceiveData (NSUrlSession session, NSUrlSessionDataTask dataTask, NSData byteData) { var data = getResponseForTask(dataTask); var bytes = byteData.ToArray(); // NB: If we're cancelled, we still might have one more chunk // of data that attempts to be delivered if (data.IsCompleted) return; data.ResponseBody.AddByteArray(bytes); } InflightOperation getResponseForTask(NSUrlSessionTask task) { lock (This.inflightRequests) { return This.inflightRequests[task]; } } #if !XAMARIN_MODERN static readonly Regex cnRegex = new Regex(@"CN\s*=\s*([^,]*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline); #endif public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) { NetworkCredential credentialsToUse; if (This.Credentials != null) { if (This.Credentials is NetworkCredential) { credentialsToUse = (NetworkCredential)This.Credentials; } else { var uri = this.getResponseForTask(task).Request.RequestUri; credentialsToUse = This.Credentials.GetCredential(uri, "NTLM"); } var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential); } return; } #if !XAMARIN_MODERN if (!This.customSSLVerification) { goto doDefault; } if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") { goto doDefault; } if (ServicePointManager.ServerCertificateValidationCallback == null) { goto doDefault; } // Convert Mono Certificates to .NET certificates and build cert // chain from root certificate var serverCertChain = challenge.ProtectionSpace.ServerSecTrust; var chain = new X509Chain(); X509Certificate2 root = null; var errors = SslPolicyErrors.None; if (serverCertChain == null || serverCertChain.Count == 0) { errors = SslPolicyErrors.RemoteCertificateNotAvailable; goto sslErrorVerify; } if (serverCertChain.Count == 1) { errors = SslPolicyErrors.RemoteCertificateChainErrors; goto sslErrorVerify; } var netCerts = Enumerable.Range(0, serverCertChain.Count) .Select(x => serverCertChain[x].ToX509Certificate2()) .ToArray(); for (int i = 1; i < netCerts.Length; i++) { chain.ChainPolicy.ExtraStore.Add(netCerts[i]); } root = netCerts[0]; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; if (!chain.Build(root)) { errors = SslPolicyErrors.RemoteCertificateChainErrors; goto sslErrorVerify; } var subject = root.Subject; var subjectCn = cnRegex.Match(subject).Groups[1].Value; if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) { errors = SslPolicyErrors.RemoteCertificateNameMismatch; goto sslErrorVerify; } sslErrorVerify: var hostname = task.CurrentRequest.Url.Host; bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors); if (result) { completionHandler( NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust)); } else { completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null); } return; doDefault: #endif completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential); return; } public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler) { NSUrlRequest nextRequest = (This.AllowAutoRedirect ? newRequest : null); completionHandler(nextRequest); } #if !XAMARIN_MODERN static Exception createExceptionForNSError(NSError error) { var ret = default(Exception); var webExceptionStatus = WebExceptionStatus.UnknownError; var innerException = new NSErrorException(error); if (error.Domain == NSError.NSUrlErrorDomain) { // Convert the error code into an enumeration (this is future // proof, rather than just casting integer) NSUrlErrorExtended urlError; if (!Enum.TryParse<NSUrlErrorExtended>(error.Code.ToString(), out urlError)) urlError = NSUrlErrorExtended.Unknown; // Parse the enum into a web exception status or exception. Some // of these values don't necessarily translate completely to // what WebExceptionStatus supports, so made some best guesses // here. For your reading pleasure, compare these: // // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx switch (urlError) { case NSUrlErrorExtended.Cancelled: case NSUrlErrorExtended.UserCancelledAuthentication: // No more processing is required so just return. return new OperationCanceledException(error.LocalizedDescription, innerException); case NSUrlErrorExtended.BadURL: case NSUrlErrorExtended.UnsupportedURL: case NSUrlErrorExtended.CannotConnectToHost: case NSUrlErrorExtended.ResourceUnavailable: case NSUrlErrorExtended.NotConnectedToInternet: case NSUrlErrorExtended.UserAuthenticationRequired: case NSUrlErrorExtended.InternationalRoamingOff: case NSUrlErrorExtended.CallIsActive: case NSUrlErrorExtended.DataNotAllowed: webExceptionStatus = WebExceptionStatus.ConnectFailure; break; case NSUrlErrorExtended.TimedOut: webExceptionStatus = WebExceptionStatus.Timeout; break; case NSUrlErrorExtended.CannotFindHost: case NSUrlErrorExtended.DNSLookupFailed: webExceptionStatus = WebExceptionStatus.NameResolutionFailure; break; case NSUrlErrorExtended.DataLengthExceedsMaximum: webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded; break; case NSUrlErrorExtended.NetworkConnectionLost: webExceptionStatus = WebExceptionStatus.ConnectionClosed; break; case NSUrlErrorExtended.HTTPTooManyRedirects: case NSUrlErrorExtended.RedirectToNonExistentLocation: webExceptionStatus = WebExceptionStatus.ProtocolError; break; case NSUrlErrorExtended.RequestBodyStreamExhausted: webExceptionStatus = WebExceptionStatus.SendFailure; break; case NSUrlErrorExtended.BadServerResponse: case NSUrlErrorExtended.ZeroByteResource: case NSUrlErrorExtended.CannotDecodeRawData: case NSUrlErrorExtended.CannotDecodeContentData: case NSUrlErrorExtended.CannotParseResponse: case NSUrlErrorExtended.FileDoesNotExist: case NSUrlErrorExtended.FileIsDirectory: case NSUrlErrorExtended.NoPermissionsToReadFile: case NSUrlErrorExtended.CannotLoadFromNetwork: case NSUrlErrorExtended.CannotCreateFile: case NSUrlErrorExtended.CannotOpenFile: case NSUrlErrorExtended.CannotCloseFile: case NSUrlErrorExtended.CannotWriteToFile: case NSUrlErrorExtended.CannotRemoveFile: case NSUrlErrorExtended.CannotMoveFile: case NSUrlErrorExtended.DownloadDecodingFailedMidStream: case NSUrlErrorExtended.DownloadDecodingFailedToComplete: webExceptionStatus = WebExceptionStatus.ReceiveFailure; break; case NSUrlErrorExtended.SecureConnectionFailed: webExceptionStatus = WebExceptionStatus.SecureChannelFailure; break; case NSUrlErrorExtended.ServerCertificateHasBadDate: case NSUrlErrorExtended.ServerCertificateHasUnknownRoot: case NSUrlErrorExtended.ServerCertificateNotYetValid: case NSUrlErrorExtended.ServerCertificateUntrusted: case NSUrlErrorExtended.ClientCertificateRejected: case NSUrlErrorExtended.ClientCertificateRequired: webExceptionStatus = WebExceptionStatus.TrustFailure; break; } goto done; } if (error.Domain == CFNetworkError.ErrorDomain) { // Convert the error code into an enumeration (this is future // proof, rather than just casting integer) CFNetworkErrors networkError; if (!Enum.TryParse<CFNetworkErrors>(error.Code.ToString(), out networkError)) { networkError = CFNetworkErrors.CFHostErrorUnknown; } // Parse the enum into a web exception status or exception. Some // of these values don't necessarily translate completely to // what WebExceptionStatus supports, so made some best guesses // here. For your reading pleasure, compare these: // // Apple docs: https://developer.apple.com/library/ios/documentation/Networking/Reference/CFNetworkErrors/#//apple_ref/c/tdef/CFNetworkErrors // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx switch (networkError) { case CFNetworkErrors.CFURLErrorCancelled: case CFNetworkErrors.CFURLErrorUserCancelledAuthentication: case CFNetworkErrors.CFNetServiceErrorCancel: // No more processing is required so just return. return new OperationCanceledException(error.LocalizedDescription, innerException); case CFNetworkErrors.CFSOCKS5ErrorBadCredentials: case CFNetworkErrors.CFSOCKS5ErrorUnsupportedNegotiationMethod: case CFNetworkErrors.CFSOCKS5ErrorNoAcceptableMethod: case CFNetworkErrors.CFErrorHttpAuthenticationTypeUnsupported: case CFNetworkErrors.CFErrorHttpBadCredentials: case CFNetworkErrors.CFErrorHttpBadURL: case CFNetworkErrors.CFURLErrorBadURL: case CFNetworkErrors.CFURLErrorUnsupportedURL: case CFNetworkErrors.CFURLErrorCannotConnectToHost: case CFNetworkErrors.CFURLErrorResourceUnavailable: case CFNetworkErrors.CFURLErrorNotConnectedToInternet: case CFNetworkErrors.CFURLErrorUserAuthenticationRequired: case CFNetworkErrors.CFURLErrorInternationalRoamingOff: case CFNetworkErrors.CFURLErrorCallIsActive: case CFNetworkErrors.CFURLErrorDataNotAllowed: webExceptionStatus = WebExceptionStatus.ConnectFailure; break; case CFNetworkErrors.CFURLErrorTimedOut: case CFNetworkErrors.CFNetServiceErrorTimeout: webExceptionStatus = WebExceptionStatus.Timeout; break; case CFNetworkErrors.CFHostErrorHostNotFound: case CFNetworkErrors.CFURLErrorCannotFindHost: case CFNetworkErrors.CFURLErrorDNSLookupFailed: case CFNetworkErrors.CFNetServiceErrorDNSServiceFailure: webExceptionStatus = WebExceptionStatus.NameResolutionFailure; break; case CFNetworkErrors.CFURLErrorDataLengthExceedsMaximum: webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded; break; case CFNetworkErrors.CFErrorHttpConnectionLost: case CFNetworkErrors.CFURLErrorNetworkConnectionLost: webExceptionStatus = WebExceptionStatus.ConnectionClosed; break; case CFNetworkErrors.CFErrorHttpRedirectionLoopDetected: case CFNetworkErrors.CFURLErrorHTTPTooManyRedirects: case CFNetworkErrors.CFURLErrorRedirectToNonExistentLocation: webExceptionStatus = WebExceptionStatus.ProtocolError; break; case CFNetworkErrors.CFSOCKSErrorUnknownClientVersion: case CFNetworkErrors.CFSOCKSErrorUnsupportedServerVersion: case CFNetworkErrors.CFErrorHttpParseFailure: case CFNetworkErrors.CFURLErrorRequestBodyStreamExhausted: webExceptionStatus = WebExceptionStatus.SendFailure; break; case CFNetworkErrors.CFSOCKS4ErrorRequestFailed: case CFNetworkErrors.CFSOCKS4ErrorIdentdFailed: case CFNetworkErrors.CFSOCKS4ErrorIdConflict: case CFNetworkErrors.CFSOCKS4ErrorUnknownStatusCode: case CFNetworkErrors.CFSOCKS5ErrorBadState: case CFNetworkErrors.CFSOCKS5ErrorBadResponseAddr: case CFNetworkErrors.CFURLErrorBadServerResponse: case CFNetworkErrors.CFURLErrorZeroByteResource: case CFNetworkErrors.CFURLErrorCannotDecodeRawData: case CFNetworkErrors.CFURLErrorCannotDecodeContentData: case CFNetworkErrors.CFURLErrorCannotParseResponse: case CFNetworkErrors.CFURLErrorFileDoesNotExist: case CFNetworkErrors.CFURLErrorFileIsDirectory: case CFNetworkErrors.CFURLErrorNoPermissionsToReadFile: case CFNetworkErrors.CFURLErrorCannotLoadFromNetwork: case CFNetworkErrors.CFURLErrorCannotCreateFile: case CFNetworkErrors.CFURLErrorCannotOpenFile: case CFNetworkErrors.CFURLErrorCannotCloseFile: case CFNetworkErrors.CFURLErrorCannotWriteToFile: case CFNetworkErrors.CFURLErrorCannotRemoveFile: case CFNetworkErrors.CFURLErrorCannotMoveFile: case CFNetworkErrors.CFURLErrorDownloadDecodingFailedMidStream: case CFNetworkErrors.CFURLErrorDownloadDecodingFailedToComplete: case CFNetworkErrors.CFHTTPCookieCannotParseCookieFile: case CFNetworkErrors.CFNetServiceErrorUnknown: case CFNetworkErrors.CFNetServiceErrorCollision: case CFNetworkErrors.CFNetServiceErrorNotFound: case CFNetworkErrors.CFNetServiceErrorInProgress: case CFNetworkErrors.CFNetServiceErrorBadArgument: case CFNetworkErrors.CFNetServiceErrorInvalid: webExceptionStatus = WebExceptionStatus.ReceiveFailure; break; case CFNetworkErrors.CFURLErrorServerCertificateHasBadDate: case CFNetworkErrors.CFURLErrorServerCertificateUntrusted: case CFNetworkErrors.CFURLErrorServerCertificateHasUnknownRoot: case CFNetworkErrors.CFURLErrorServerCertificateNotYetValid: case CFNetworkErrors.CFURLErrorClientCertificateRejected: case CFNetworkErrors.CFURLErrorClientCertificateRequired: webExceptionStatus = WebExceptionStatus.TrustFailure; break; case CFNetworkErrors.CFURLErrorSecureConnectionFailed: webExceptionStatus = WebExceptionStatus.SecureChannelFailure; break; case CFNetworkErrors.CFErrorHttpProxyConnectionFailure: case CFNetworkErrors.CFErrorHttpBadProxyCredentials: case CFNetworkErrors.CFErrorPACFileError: case CFNetworkErrors.CFErrorPACFileAuth: case CFNetworkErrors.CFErrorHttpsProxyConnectionFailure: case CFNetworkErrors.CFStreamErrorHttpsProxyFailureUnexpectedResponseToConnectMethod: webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy; break; } goto done; } done: // Always create a WebException so that it can be handled by the client. ret = new WebException(error.LocalizedDescription, innerException, webExceptionStatus, response: null); return ret; } #endif // !XAMARIN } } class ByteArrayListStream : Stream { Exception exception; IDisposable lockRelease; readonly AsyncLock readStreamLock; readonly List<byte[]> bytes = new List<byte[]>(); bool isCompleted; long maxLength = 0; long position = 0; int offsetInCurrentBuffer = 0; public ByteArrayListStream() { // Initially we have nothing to read so Reads should be parked readStreamLock = AsyncLock.CreateLocked(out lockRelease); } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void WriteByte(byte value) { throw new NotSupportedException(); } public override bool CanSeek { get { return false; } } public override bool CanTimeout { get { return false; } } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override long Position { get { return position; } set { throw new NotSupportedException(); } } public override long Length { get { return maxLength; } } public override int Read(byte[] buffer, int offset, int count) { return this.ReadAsync(buffer, offset, count).Result; } /* OMG THIS CODE IS COMPLICATED * * Here's the core idea. We want to create a ReadAsync function that * reads from our list of byte arrays **until it gets to the end of * our current list**. * * If we're not there yet, we keep returning data, serializing access * to the underlying position pointer (i.e. we definitely don't want * people concurrently moving position along). If we try to read past * the end, we return the section of data we could read and complete * it. * * Here's where the tricky part comes in. If we're not Completed (i.e. * the caller still wants to add more byte arrays in the future) and * we're at the end of the current stream, we want to *block* the read * (not blocking, but async blocking whatever you know what I mean), * until somebody adds another byte[] to chew through, or if someone * rewinds the position. * * If we *are* completed, we should return zero to simply complete the * read, signalling we're at the end of the stream */ public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { retry: int bytesRead = 0; int buffersToRemove = 0; if (isCompleted && position == maxLength) { return 0; } if (exception != null) throw exception; using (await readStreamLock.LockAsync().ConfigureAwait(false)) { lock (bytes) { foreach (var buf in bytes) { cancellationToken.ThrowIfCancellationRequested(); if (exception != null) throw exception; int toCopy = Math.Min(count, buf.Length - offsetInCurrentBuffer); Array.ConstrainedCopy(buf, offsetInCurrentBuffer, buffer, offset, toCopy); count -= toCopy; offset += toCopy; bytesRead += toCopy; offsetInCurrentBuffer += toCopy; if (offsetInCurrentBuffer >= buf.Length) { offsetInCurrentBuffer = 0; buffersToRemove++; } if (count <= 0) break; } // Remove buffers that we read in this operation bytes.RemoveRange(0, buffersToRemove); position += bytesRead; } } // If we're at the end of the stream and it's not done, prepare // the next read to park itself unless AddByteArray or Complete // posts if (position >= maxLength && !isCompleted) { lockRelease = await readStreamLock.LockAsync().ConfigureAwait(false); } if (bytesRead == 0 && !isCompleted) { // NB: There are certain race conditions where we somehow acquire // the lock yet are at the end of the stream, and we're not completed // yet. We should try again so that we can get stuck in the lock. goto retry; } if (cancellationToken.IsCancellationRequested) { Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); cancellationToken.ThrowIfCancellationRequested(); } if (exception != null) { Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); throw exception; } if (isCompleted && position < maxLength) { // NB: This solves a rare deadlock // // 1. ReadAsync called (waiting for lock release) // 2. AddByteArray called (release lock) // 3. AddByteArray called (release lock) // 4. Complete called (release lock the last time) // 5. ReadAsync called (lock released at this point, the method completed successfully) // 6. ReadAsync called (deadlock on LockAsync(), because the lock is block, and there is no way to release it) // // Current condition forces the lock to be released in the end of 5th point Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); } return bytesRead; } public void AddByteArray(byte[] arrayToAdd) { if (exception != null) throw exception; if (isCompleted) throw new InvalidOperationException("Can't add byte arrays once Complete() is called"); lock (bytes) { maxLength += arrayToAdd.Length; bytes.Add(arrayToAdd); //Console.WriteLine("Added a new byte array, {0}: max = {1}", arrayToAdd.Length, maxLength); } Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); } public void Complete() { isCompleted = true; Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose(); } public void SetException(Exception ex) { exception = ex; Complete(); } } sealed class CancellableStreamContent : ProgressStreamContent { Action onDispose; public CancellableStreamContent(Stream source, Action onDispose) : base(source, CancellationToken.None) { this.onDispose = onDispose; } protected override void Dispose(bool disposing) { var disp = Interlocked.Exchange(ref onDispose, null); if (disp != null) disp(); // EVIL HAX: We have to let at least one ReadAsync of the underlying // stream fail with OperationCancelledException before we can dispose // the base, or else the exception coming out of the ReadAsync will // be an ObjectDisposedException from an internal MemoryStream. This isn't // the Ideal way to fix this, but #yolo. Task.Run(() => base.Dispose(disposing)); } } sealed class EmptyDisposable : IDisposable { static readonly IDisposable instance = new EmptyDisposable(); public static IDisposable Instance { get { return instance; } } EmptyDisposable() { } public void Dispose() { } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : brian.nickel@gmail.com based on : id3v2header.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System; namespace TagLib.Id3v2 { public class Header { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private uint major_version; private uint revision_number; private bool unsynchronisation; private bool extended_header; private bool experimental_indicator; private bool footer_present; private uint tag_size; private static uint size = 10; ////////////////////////////////////////////////////////////////////////// // public static fields ////////////////////////////////////////////////////////////////////////// public static uint Size {get {return size;}} public static readonly ByteVector FileIdentifier = "ID3"; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public Header () { major_version = 4; revision_number = 0; unsynchronisation = false; extended_header = false; experimental_indicator = false; footer_present = false; tag_size = 0; } public Header (ByteVector data) : this () { Parse (data); } public void SetData (ByteVector data) { Parse (data); } public ByteVector Render () { ByteVector v = new ByteVector (); // add the file identifier -- "ID3" v.Add (FileIdentifier); // add the version number -- we always render a 2.4.0 tag regardless of what // the tag originally was. v.Add ((byte)4); v.Add ((byte)0); // render and add the flags byte flags = 0; if (Unsynchronisation) flags |= 128; if (ExtendedHeader) flags |= 64; if (ExperimentalIndicator) flags |= 32; if (FooterPresent) flags |= 16; v.Add (flags); // add the size v.Add (SynchData.FromUInt (TagSize)); return v; } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public uint MajorVersion { get {return major_version;} set {major_version = value;} } public uint RevisionNumber { get {return revision_number;} set {revision_number = value;} } public bool Unsynchronisation { get {return unsynchronisation;} set {unsynchronisation = value;} } public bool ExtendedHeader { get {return extended_header;} set {extended_header = value;} } public bool ExperimentalIndicator { get {return experimental_indicator;} set {experimental_indicator = value;} } public bool FooterPresent { get {return footer_present;} set {footer_present = value;} } public uint TagSize { get {return tag_size;} set {tag_size = value;} } public uint CompleteTagSize { get { if (footer_present) return TagSize + Size + Footer.Size; else return TagSize + Size; } } ////////////////////////////////////////////////////////////////////////// // protected methods ////////////////////////////////////////////////////////////////////////// protected void Parse (ByteVector data) { if(data.Count < Size) return; // do some sanity checking -- even in ID3v2.3.0 and less the tag size is a // synch-safe integer, so all bytes must be less than 128. If this is not // true then this is an invalid tag. // note that we're doing things a little out of order here -- the size is // later in the bytestream than the version ByteVector size_data = data.Mid (6, 4); if (size_data.Count != 4) { tag_size = 0; Debugger.Debug ("ID3v2.Header.Parse () - The tag size as read was 0 bytes!"); return; } foreach (byte b in size_data) if (b >= 128) { tag_size = 0; Debugger.Debug ("ID3v2.Header.Parse () - One of the size bytes in the id3v2 header was greater than the allowed 128."); return; } // The first three bytes, data[0..2], are the File Identifier, "ID3". (structure 3.1 "file identifier") // Read the version number from the fourth and fifth bytes. major_version = data [3]; // (structure 3.1 "major version") revision_number = data [4]; // (structure 3.1 "revision number") // Read the flags, the first four bits of the sixth byte. byte flags = data [5]; unsynchronisation = ((flags >> 7) & 1) == 1; // (structure 3.1.a) extended_header = ((flags >> 6) & 1) == 1; // (structure 3.1.b) experimental_indicator = ((flags >> 5) & 1) == 1; // (structure 3.1.c) footer_present = ((flags >> 4) & 1) == 1; // (structure 3.1.d) // Get the size from the remaining four bytes (read above) tag_size = SynchData.ToUInt (size_data); // (structure 3.1 "size") } } }
// <copyright file="RiakConstants.cs" company="Basho Technologies, Inc."> // Copyright 2011 - OJ Reeves & Jeremiah Peschka // Copyright 2014 - Basho Technologies, Inc. // // This file is provided 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> namespace RiakClient { using System; using System.Collections.Generic; using Messages; /// <summary> /// A collection of commonly used Riak string constants. /// </summary> public static class RiakConstants { /// <summary> /// Represents the value for the Default Bucket Type when using the .Net Client APIs. /// </summary> public const string DefaultBucketType = null; /// <summary> /// Represents Riak Enterprise Edition-only features. /// </summary> public static class RiakEnterprise { /// <summary> /// Represents the possible stats that Riak Replication could be configured for. /// </summary> public enum ReplicationMode { /// <summary> /// No replication is enabled. /// </summary> False = RpbBucketProps.RpbReplMode.FALSE, /// <summary> /// Realtime replication is enabled. /// </summary> Realtime = RpbBucketProps.RpbReplMode.REALTIME, /// <summary> /// Fullsync replication is enabled. /// </summary> FullSync = RpbBucketProps.RpbReplMode.FULLSYNC, /// <summary> /// Realtime and fullsync replication are both enabled. /// </summary> True = RpbBucketProps.RpbReplMode.TRUE } } /// <summary> /// A collection of known content-types. /// </summary> public static class ContentTypes { /// <summary> /// A wildcard content-type. /// </summary> public const string Any = @"*/*"; /// <summary> /// The binary, or octet-stream content-type. /// </summary> public const string ApplicationOctetStream = @"application/octet-stream"; /// <summary> /// The JSON content-type. /// </summary> public const string ApplicationJson = @"application/json"; /// <summary> /// The plain text content-type. /// </summary> public const string TextPlain = @"text/plain"; /// <summary> /// The HTML content-type. /// </summary> public const string TextHtml = @"text/html"; /// <summary> /// The multipart/mixed message content-type. /// </summary> public const string MultipartMixed = @"multipart/mixed"; /// <summary> /// The Jpeg image content-type. /// </summary> public const string ImageJpg = @"image/jpeg"; /// <summary> /// The Gif image content-type. /// </summary> public const string ImageGif = @"image/gif"; /// <summary> /// The Png image content-type. /// </summary> public const string ImagePng = @"image/png"; /// <summary> /// The Erlang Binary content-type. /// </summary> public const string ErlangBinary = @"application/x-erlang-binary"; /// <summary> /// The XML content-type. /// </summary> public const string Xml = @"application/xml"; /// <summary> /// The Protocol Buffers content-type. /// </summary> public const string ProtocolBuffers = ApplicationOctetStream; // @"application/x-protobuf"; } /// <summary> /// Represents the Secondary Index name suffixes used to determine the index's type. /// </summary> public static class IndexSuffix { /// <summary> /// The suffix for integer indexes. /// </summary> public const string Integer = @"_int"; /// <summary> /// The suffix for string(binary) indexes. /// </summary> public const string Binary = @"_bin"; } /// <summary> /// Represents the collection of possible MapReduce job languages. /// </summary> public static class MapReduceLanguage { /// <summary> /// The string for JavaScript MapReduce jobs. /// </summary> public const string JavaScript = "javascript"; /// <summary> /// The string for JSON(JavaScript) MapReduce jobs. /// </summary> public const string Json = JavaScript; /// <summary> /// The string for Erlang MapReduce jobs. /// </summary> public const string Erlang = "erlang"; } /// <summary> /// Represents the collection of possible MapReduce job phases. /// </summary> public static class MapReducePhaseType { /// <summary> /// The string for a Map phase. /// </summary> public const string Map = @"map"; /// <summary> /// The string for a Reduce phase. /// </summary> public const string Reduce = @"reduce"; /// <summary> /// The string for a Link phase. /// </summary> public const string Link = @"link"; } /// <summary> /// Represents some common Character sets. /// </summary> public static class CharSets { /// <summary> /// The charset string for the UTF-8 string data. /// </summary> public const string Utf8 = @"UTF-8"; /// <summary> /// The charset string used when dealing with Binary data. /// </summary> public const string Binary = null; } /// <summary> /// Represents some defaults for different Riak Client options. /// </summary> public static class Defaults { /// <summary> /// The default content-type. Defaults to <see cref="ContentTypes.ApplicationJson"/>. /// </summary> public const string ContentType = ContentTypes.ApplicationJson; /// <summary> /// The default character set. Defaults to <see cref="CharSets.Utf8"/>. /// </summary> public const string CharSet = CharSets.Utf8; /// <summary> /// Represents some Riak Search 2.0+ (Yokozuna) defaults. /// </summary> public static class YokozunaIndex { /// <summary> /// The default Schema Name to use for 2.0+ search. /// </summary> public const string DefaultSchemaName = "_yz_default"; /// <summary> /// The default NVal to use for 2.0+ search index operations. /// </summary> public const int NVal = 3; } } /// <summary> /// A collection of MapReduce key filter transformation string constants. /// See http://docs.basho.com/riak/latest/dev/using/keyfilters/ /// and http://docs.basho.com/riak/latest/dev/references/keyfilters/ for more information. /// </summary> public static class KeyFilterTransforms { /// <summary> /// Turns an integer (previously extracted with string_to_int), into a string. /// </summary> public const string IntToString = @"int_to_string"; /// <summary> /// Turns a string into an integer. /// </summary> public const string StringToInt = @"string_to_int"; /// <summary> /// Turns a floating point number (previously extracted with string_to_float), into a string. /// </summary> public const string FloatToString = @"float_to_string"; /// <summary> /// Turns a string into a floating point number. /// </summary> public const string StringToFloat = @"string_to_float"; /// <summary> /// Changes all letters to uppercase. /// </summary> public const string ToUpper = @"to_upper"; /// <summary> /// Changes all letters to lowercase. /// </summary> public const string ToLower = @"to_lower"; /// <summary> /// Splits the input on the string given as the first argument and returns the nth token specified by the second argument. /// </summary> public const string Tokenize = @"tokenize"; } /// <summary> /// A collection of special secondary index names. /// </summary> public static class SystemIndexKeys { /// <summary> /// The index name for the special system key index. /// This index holds all the different keys for a bucket. /// </summary> public const string RiakKeysIndex = "$key"; /// <summary> /// The index name for the special system bucket index. /// This index holds all the different bucket values. /// </summary> public const string RiakBucketIndex = "$bucket"; /// <summary> /// A collection of all the system binary index names. /// </summary> public static readonly HashSet<string> SystemBinKeys = new HashSet<string> { RiakKeysIndex, RiakBucketIndex }; /// <summary> /// A collection of all the system integer index names. /// </summary> public static readonly HashSet<string> SystemIntKeys = new HashSet<string>(); } /// <summary> /// A collection of string constants for riak search result documents. /// These constants represent keys for known fields within the document. /// </summary> public static class SearchFieldKeys { /// <summary> /// Key for the "Bucket Type" field. Riak 2.0+ /// </summary> public const string BucketType = "_yz_rt"; /// <summary> /// Key for the "Bucket" field. Riak 2.0+ /// </summary> public const string Bucket = "_yz_rb"; /// <summary> /// Key for the "Key" field. Riak 2.0+ /// </summary> public const string Key = "_yz_rk"; /// <summary> /// Key for the "Id" field. Riak 2.0+ /// </summary> public const string Id = "_yz_id"; /// <summary> /// Key for the "Score" field. Riak 2.0+ /// </summary> public const string Score = "score"; /// <summary> /// Key for the Riak 1.0 Search "Id" field. /// </summary> [Obsolete("Legacy Search is deprecated, this key will be removed in the future.")] public const string LegacySearchId = "id"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using DTD.Entity; using DTD.Entity.Enum; using DTD.Entity.Helpers; using DTD.Entity.vCodes; using GlobalLibrary; namespace Core.Converter { public class CodeToVCode { public Scope Scope { get; set; } private readonly RegexPatterns _regex; public CodeToVCode(string code) { _regex = new RegexPatterns(); //Call Function here. Scope = new Scope(); code = Regex.Replace(code, @"\t|\n", ""); CreateScopeObject(Scope, '{' + code.Trim() + '}'); } #region LexicalAnalyzer private void CreateConditionObject(Condition condition, string text) { Match op = _regex.BooleanOperator.Match(text); condition.BooleanOperator = op.Groups[0].ToString(); Match conditionString = _regex.Condition.Match(text); Match param = _regex.InstructionRegex.Match(conditionString.Groups[0].ToString()); byte count = 0; while (param.Success) { if (count == 0) { condition.LeftParameter = param.Groups[0].ToString(); } else { condition.RightParameter = param.Groups[0].ToString(); } count++; param = param.NextMatch(); } } private int CropScope(Scope scope, int start, string text) { Stack<char> stack = new Stack<char>(); int end = start; while (text[start] != '{') { start = ++end; } stack.Push('{'); while (stack.Count != 0) { end++; if (text[end] == '{') { stack.Push('{'); } else if (text[end] == '}') { stack.Pop(); } } CreateScopeObject(scope, text.Substring(start, end - start + 1)); return ++end; } private void CreateScopeObject(Scope scope, string currentScope) { int start = 1, end = 1; while (end < currentScope.Length - 1) { string selectedText = currentScope.Substring(start, end - start + 1); if (_regex.FunctionRegex.IsMatch(selectedText)) { Function funcObject = new Function(); funcObject.IsBody = true; scope.Items.Enqueue(funcObject); CreateFunctionObject(funcObject, selectedText); start = ++end; start = end = CropScope(funcObject.Scope, start, currentScope); } else if (_regex.FunctionCall.IsMatch(selectedText)) { Function funcObject = new Function(); scope.Items.Enqueue(funcObject); CreateFunctionCallObject(funcObject, selectedText); start = ++end; } else if (_regex.VarDeclaration.IsMatch(selectedText)) { CreateVariableObject(scope, selectedText, false); start = ++end; } else if (_regex.ArrayRegex.IsMatch(selectedText)) { CreateVariableObject(scope, selectedText, true); start = ++end; } else if (_regex.IfRegex.IsMatch(selectedText)) { If ifObject = new If(); scope.Items.Enqueue(ifObject); CreateConditionObject(ifObject.Condition, selectedText); start = ++end; start = end = CropScope(ifObject.Scope, start, currentScope); } else if (_regex.WhileRegex.IsMatch(selectedText)) { While whileObject = new While(); scope.Items.Enqueue(whileObject); CreateConditionObject(whileObject.Condition, selectedText); start = ++end; start = end = CropScope(whileObject.Scope, start, currentScope); } else if(_regex.VarAssignmentRegex.IsMatch(selectedText) || _regex.ArrayAssignment.IsMatch(selectedText)) { CreateAssignmentObject(scope,selectedText); start = ++end; } else if (currentScope[start] == ' ') { start = ++end; } else if (selectedText == "\n") { start = ++end; } else { end++; } } } private void CreateFunctionCallObject(Function funcObject, string text) { if (_regex.ArgumentRegex.IsMatch(text)) { Match parameters = _regex.ArgumentRegex.Match(text); Match m = _regex.SingleInstructionRegex.Match(parameters.Groups[0].ToString()); while (m.Success) { funcObject.Parameters.Add(new Parameter(m.Groups[0].ToString())); m = m.NextMatch(); } text = _regex.ParameterRegex.Replace(text, ""); } if (_regex.Variable.IsMatch(text)) { Match m = _regex.Variable.Match(text); funcObject.Name = m.Groups[0].ToString(); } } //will return function object globaly declared private void CreateFunctionObject(Function funcObject, string text) { if (_regex.ParameterRegex.IsMatch(text)) { Match parameters = _regex.ParameterRegex.Match(text); Regex param = new Regex("(" + _regex.DataType + ")[\\s]+(" + _regex.Variable + ")"); Match m = param.Match(parameters.Groups[0].ToString()); while (m.Success) { Parameter p = new Parameter(); string[] parameterContent = m.ToString().Split(' '); switch (parameterContent[0]) { case "int": p.Type = Enums.Type.Int; break; case "float": p.Type = Enums.Type.Float; break; case "double": p.Type = Enums.Type.Double; break; case "string": p.Type = Enums.Type.String; break; case "char": p.Type = Enums.Type.Char; break; case "bool": p.Type = Enums.Type.Bool; break; } p.Name = parameterContent[1]; funcObject.Parameters.Add(p); m = m.NextMatch(); } text = _regex.ParameterRegex.Replace(text, ""); } #region Function Return Type if (_regex.DataType.IsMatch(text)) { Match m = _regex.DataType.Match(text); switch (m.Groups[0].ToString()) { case "void": funcObject.Type = Enums.Type.Void; break; case "char": funcObject.Type = Enums.Type.Bool; break; case "bool": funcObject.Type = Enums.Type.Char; break; case "int": funcObject.Type = Enums.Type.Int; break; case "float": funcObject.Type = Enums.Type.Float; break; case "double": funcObject.Type = Enums.Type.Double; break; case "string": funcObject.Type = Enums.Type.String; break; } text = _regex.DataType.Replace(text, ""); } #endregion #region Variable AccessModifier if (_regex.AccessModifier.IsMatch(text)) { Match m = _regex.AccessModifier.Match(text); switch (m.Groups[0].ToString()) { case "public": funcObject.AccessModifier = Enums.AccessModifier.Public; break; case "private": funcObject.AccessModifier = Enums.AccessModifier.Private; break; case "protected": funcObject.AccessModifier = Enums.AccessModifier.Protected; break; } text = _regex.AccessModifier.Replace(text, ""); } #endregion if (_regex.IsStatic.IsMatch(text)) { funcObject.IsStatic = true; text = _regex.IsStatic.Replace(text, ""); } if (_regex.Variable.IsMatch(text)) { Match m = _regex.Variable.Match(text); funcObject.Name = m.Groups[0].ToString(); } } private void CreateVariableObject(Scope scope, string text, bool isArray) { Variable varObject = new Variable(); varObject.IsArray = isArray; #region Variable DataType if (_regex.DataType.IsMatch(text)) { Match m = _regex.DataType.Match(text); switch (m.Groups[0].ToString()) { case "void": varObject.Type = Enums.Type.Void; break; case "bool": varObject.Type = Enums.Type.Bool; break; case "int": varObject.Type = Enums.Type.Int; break; case "float": varObject.Type = Enums.Type.Float; break; case "double": varObject.Type = Enums.Type.Double; break; case "string": varObject.Type = Enums.Type.String; break; case "char": varObject.Type = Enums.Type.Char; break; } text = _regex.DataType.Replace(text, ""); } #endregion #region Variable AccessModifier if (_regex.AccessModifier.IsMatch(text)) { Match m = _regex.AccessModifier.Match(text); switch (m.Groups[0].ToString()) { case "public": varObject.AccessModifier = Enums.AccessModifier.Public; break; case "private": varObject.AccessModifier = Enums.AccessModifier.Private; break; case "protected": varObject.AccessModifier = Enums.AccessModifier.Protected; break; } text = _regex.AccessModifier.Replace(text, ""); } #endregion if (_regex.IsStatic.IsMatch(text)) { varObject.IsStatic = true; text = _regex.IsStatic.Replace(text, ""); } if (_regex.Variable.IsMatch(text)) { Match m = _regex.Variable.Match(text); varObject.Name = m.Groups[0].ToString(); text = _regex.Variable.Replace(text, ""); } if (isArray) { Match m = _regex.NumberRegex.Match(text); byte count = 0; while (m.Success) { if (count == 0) { varObject.Row = Convert.ToInt32(m.Groups[0].ToString()); varObject.ArrayType = "1D"; } else { varObject.Column = Convert.ToInt32(m.Groups[0].ToString()); varObject.ArrayType = "2D"; } m = m.NextMatch(); count++; } } scope.Items.Enqueue(varObject); } private void CreateAssignmentObject(Scope scope, string text) { Assignment assignment = new Assignment { AssignmentString = text.Replace(";", ""), Instruction=new SingleInstruction(), Variable="", LocalVariables=new List<Variable>(), VType=Enums.VType.Assignment, }; scope.Items.Enqueue(assignment); /*Match m = _regex.InstructionRegex.Match(text); Match ma = _regex.Array.Match(text); Match op = _regex.OperatorRegex.Match(text); if(ma.Groups.Count > 1) { assignment.Variable = ma.Groups[0].ToString(); text = text.Replace(ma.Groups[0].ToString(),""); m = _regex.InstructionRegex.Match(text); } else { assignment.Variable = m.Groups[0].ToString(); m = m.NextMatch(); } if (_regex.ThreeAddressInstructionRegex.IsMatch(text)) { ThreeAddressInstruction threeAddress = new ThreeAddressInstruction { InstructionType = Enums.InstructionType.ThreeAddress }; assignment.Instruction = threeAddress; byte count = 0; while (m.Success) { TypedvCodes ins = new TypedvCodes(); if (_regex.ConstantRegex.IsMatch(m.Groups[0].ToString())) { ins = CreateConstantObject(ins, m.Groups[0].ToString()); } else if (_regex.Variable.IsMatch(m.Groups[0].ToString())) { ins.Name = m.Groups[0].ToString(); ins.VType = Enums.VType.Variable; } else if (_regex.FunctionCall.IsMatch(m.Groups[0].ToString())) { ins.Name = m.Groups[0].ToString(); ins.VType = Enums.VType.Function; } if (count == 0) { threeAddress.LeftInstruction = ins; count++; } else { threeAddress.RightInstruction = ins; } m = m.NextMatch(); } threeAddress.Operator = op.Groups[0].ToString(); } else { SingleInstruction single = new SingleInstruction {InstructionType = Enums.InstructionType.SingleAddress}; TypedvCodes ins = new TypedvCodes(); if (_regex.ConstantRegex.IsMatch(m.Groups[0].ToString())) { ins = CreateConstantObject(ins, m.Groups[0].ToString()); } else if (_regex.Variable.IsMatch(m.Groups[0].ToString())) { ins.Name = m.Groups[0].ToString(); ins.VType = Enums.VType.Variable; } else if (_regex.FunctionCall.IsMatch(m.Groups[0].ToString())) { ins.Name = m.Groups[0].ToString(); ins.VType = Enums.VType.Function; } single.Instruction = ins; assignment.Instruction = single; MessageBox.Show(assignment.Instruction.InstructionType.ToString()); } */ } private Constant CreateConstantObject(TypedvCodes ins,string text) { Constant cns = new Constant { Value = text, VType = Enums.VType.Constant }; if (_regex.StringRegex.IsMatch(text)) { cns.Type = Enums.Type.String; } else if (_regex.DoubleRgex.IsMatch(text)) { cns.Type = Enums.Type.Double; } else if (_regex.IntRegex.IsMatch(text)) { cns.Type = Enums.Type.Int; } else if (_regex.BoolValue.IsMatch(text)) { cns.Type = Enums.Type.Bool; } else if (_regex.CharRegex.IsMatch(text)) { cns.Type = Enums.Type.Char; } return cns; } #endregion } }
using System; using System.Collections; using System.IO; using NAnt.Core.Attributes; using NAnt.Core; using NAnt.Core.Types; using System.Xml; using System.Reflection; using log4net; using QuickGraph.Representations; namespace MbUnit.Tasks { using MbUnit.Core; using MbUnit.Framework; using MbUnit.Core.Invokers; using MbUnit.Core.Remoting; using MbUnit.Core.Filters; using MbUnit.Core.Reports; using MbUnit.Core.Reports.Serialization; using MbUnit.Core.Graph; /// <summary> /// NAnt task for launching MbUnit /// </summary> [TaskName("mbunit")] public class MbUnitTask : Task { private FileSet[] assemblies; private string reportTypes = "Html"; private string reportFileNameFormat = "mbunit-result-{0}{1}"; private string reportOutputDirectory = null; private bool haltOnFailure = false; private DirSet assemblyPaths; private ReportResult result; [TaskAttribute("report-types")] public string ReportTypes { get { return reportTypes; } set { this.reportTypes = value; } } [BuildElementArray("assemblies", Required = true, ElementType = typeof(FileSet))] public FileSet[] Assemblies { get { return this.assemblies; } set { this.assemblies = value; } } [BuildElement("assemblie-paths",Required =false)] public DirSet AssemblyPaths { get { return this.assemblyPaths; } set { this.assemblyPaths = value; } } [TaskAttribute("report-filename-format", Required = false)] public string ReportFileNameFormat { get { return reportFileNameFormat; } set { reportFileNameFormat = value; } } [TaskAttribute("report-output-directory", Required = false)] public string ReportOutputDirectory { get { return reportOutputDirectory; } set { reportOutputDirectory = value; } } [BooleanValidator, TaskAttribute("halt-on-failure",Required =false)] public bool HaltOnFailure { get { return this.haltOnFailure; } set { this.haltOnFailure = value; } } /// <summary> /// This is where the work is done /// </summary> protected override void ExecuteTask() { this.Log(Level.Info, "MbUnit {0} test runner", typeof(MbUnit.Core.Fixture).Assembly.GetName().Version); this.DisplayTaskConfiguration(); if (this.Assemblies.Length == 0) { this.Log(Level.Warning, "No test assemblies, aborting task"); return; } int count = 0; foreach (FileSet files in this.Assemblies) count += files.FileNames.Count; if (count == 0) { this.Log(Level.Warning, "No test assemblies found in test"); return; } this.result = new ReportResult(); foreach (FileSet assemblySet in this.Assemblies) { bool failureCount = ExecuteTests(assemblySet); if (failureCount) break; } GenerateReports(); if (result.Counter.FailureCount > 0) throw new BuildException("There were failing tests. Please see build log."); } private void DisplayTaskConfiguration() { this.Log(Level.Verbose, "Test assemblies:"); foreach (FileSet assemblySet in this.Assemblies) { this.Log(Level.Verbose, "FileSet"); foreach (string fileName in assemblySet.FileNames) this.Log(Level.Verbose, "\t{0}", fileName); } this.Log(Level.Verbose, "ReportTypes: {0}", this.ReportTypes); this.Log(Level.Verbose, "ReportFileNameFormat: {0}", this.ReportFileNameFormat); this.Log(Level.Verbose, "ReportOutputDirectory: {0}", this.ReportOutputDirectory); this.Log(Level.Verbose, "HaltOnFailure: {0}", this.HaltOnFailure); } private void GenerateReports() { if (result == null) throw new InvalidOperationException("Report object is a null reference."); this.Log(Level.Info, "Generating reports"); foreach (string reportType in this.ReportTypes.Split(';')) { string reportName = null; this.Log(Level.Verbose, "Report type: {0}", reportType); switch (reportType.ToLower()) { case "text": reportName = TextReport.RenderToText(result, this.ReportOutputDirectory, this.ReportFileNameFormat); break; case "xml": reportName = XmlReport.RenderToXml(result, this.ReportOutputDirectory, this.ReportFileNameFormat); break; case "html": reportName = HtmlReport.RenderToHtml(result, this.ReportOutputDirectory, this.ReportFileNameFormat); break; case "dox": reportName = DoxReport.RenderToDox(result, this.ReportOutputDirectory, this.ReportFileNameFormat); break; default: this.Log(Level.Error, "Unknown report type {0}", reportType); break; } if (reportName != null) this.Log(Level.Info, "Created report at {0}", reportName); } } private bool ExecuteTests(FileSet assemblySet) { if (assemblySet.FileNames.Count == 0) { this.Log(Level.Warning, "No tests in assembly set"); return true; } // execute string[] assemblieNames = new string[assemblySet.FileNames.Count]; assemblySet.FileNames.CopyTo(assemblieNames, 0); // display information this.Log(Level.Info, "Loading {0} assemblies", assemblySet.FileNames.Count); foreach (string an in assemblieNames) this.Log(Level.Info, "\tAssemblyName: {0}", an); string[] dirNames = null; if (this.AssemblyPaths!=null) { dirNames = new string[this.AssemblyPaths.DirectoryNames.Count]; this.AssemblyPaths.DirectoryNames.CopyTo(dirNames, 0); } try { using ( TestDomainDependencyGraph graph = TestDomainDependencyGraph.BuildGraph(assemblieNames, dirNames, FixtureFilters.Any, false)) { graph.Log += new MbUnit.Core.Cons.CommandLine.ErrorReporter(graph_Log); try { ReportResult r = graph.RunTests(); this.Log(Level.Info, "Finished running tests"); this.Log(Level.Info, "Merging results"); result.Merge(r); return r.Counter.FailureCount == 0; } finally { graph.Log -= new MbUnit.Core.Cons.CommandLine.ErrorReporter(graph_Log); } } } catch (Exception ex) { throw new BuildException("Unexpected engine error while running Tests", ex); } } void graph_Log(string message) { this.Log(Level.Info, message); } } }
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; /// <summary> /// This class is a base class for all triggers. Triggers are scripts that /// target a controller, and can trigger events in the game, based on input /// from its target controller. /// </summary> public abstract class VisBaseTrigger : MonoBehaviour, IVisManagerTarget, IVisBaseControllerTarget { #region Defaults Static Class /// <summary> /// This internal class holds all of the defaults of the VisBaseTrigger class. /// </summary> public static class Defaults { public const TriggerType triggerType = TriggerType.GreaterThanChangeThreshold; public const float triggerThreshold = 0.1f; public const float triggerReactivateDelay = 0.25f; public const float triggerRandomReactivateDelay = 0.0f; } #endregion #region Enumerations /// <summary> /// This enumeration indicates how this trigger is activated. /// </summary> public enum TriggerType { /// <summary> /// This indicates no default triggering and it must be triggered by custom functionality. /// </summary> None, /// <summary> /// This indicates that this trigger is triggered when the associated controllers value goes under the specified threshold. /// </summary> LessThanValueThreshold, /// <summary> /// This indicates that this trigger is triggered when the associated controllers value goes over the specified threshold. /// </summary> GreaterThanValueThreshold, /// <summary> /// This indicates that this trigger is triggered when the associated controllers value difference/change goes under the specified threshold. /// </summary> LessThanChangeThreshold, /// <summary> /// This indicates that this trigger is triggered when the associated controllers value difference/change goes over the specified threshold. /// </summary> GreaterThanChangeThreshold } #endregion #region IVisManagerTarget Implementation /// <summary> /// This is the vis manager that this modifier is targeting. /// </summary> //[HideInInspector()] [SerializeField()] private VisManager m_oVisManager = null; /// <summary> /// This is the name of the last manager that was set to this base modifier /// </summary> [HideInInspector()] [SerializeField()] private string m_szLastVisManagerName = null; /// <summary> /// This property gets/sets the target manager for this modifier. /// </summary> public VisManager Manager { get { return m_oVisManager; } set { m_oVisManager = value; if (m_oVisManager != null) m_szLastVisManagerName = m_oVisManager.name; else m_szLastVisManagerName = null; } } /// <summary> /// This gets the name of the last manager that was set to this target. /// </summary> public string LastManagerName { get { return m_szLastVisManagerName; } } #endregion #region IVisBaseControllerTarget Implementation /// <summary> /// This is the controller that this modifier is targeting. /// </summary> //[HideInInspector()] [SerializeField()] private VisBaseController controller = null; /// <summary> /// This is the name of the last controller that was set to this base modifier /// </summary> [HideInInspector()] [SerializeField()] private string m_szLastControllerName = null; /// <summary> /// This property gets/sets the target controller for this modifier. /// </summary> public VisBaseController Controller { get { return controller; } set { controller = value; if (controller != null) m_szLastControllerName = controller.controllerName; else m_szLastControllerName = null; } } /// <summary> /// This gets the name of the last controller that was set to this target. /// </summary> public string LastControllerName { get { return m_szLastControllerName; } } #endregion #region Public Member Variables /// <summary> /// This describes the type of this trigger. (i.e. How it functions) /// </summary> //[HideInInspector()] public TriggerType triggerType = Defaults.triggerType; /// <summary> /// This is the threshold at which the trigger should activate, based on the current Trigger Type. /// </summary> //[HideInInspector()] public float triggerThreshold = Defaults.triggerThreshold; /// <summary> /// This is the amount of time to wait in between consecutive triggers of this trigger. /// </summary> //[HideInInspector()] public float triggerReactivateDelay = Defaults.triggerReactivateDelay; /// <summary> /// This is the amount of random delay to add to the reactivate time. /// Random range from "-value" to "value" /// </summary> //[HideInInspector()] public float triggerRandomReactivateDelay = Defaults.triggerRandomReactivateDelay; #endregion #region Protected Member Variables /// <summary> /// This is the timer used to control the trigger reactivate delay. /// </summary> protected float m_fTriggerDelayTimer = 0.0f; #endregion #region Init/Deinit Functions /// <summary> /// This function is called when this trigger is reset. /// Should be overriden by sub classes to reset variables /// to their default values. /// </summary> public virtual void Reset() { triggerType = Defaults.triggerType; triggerThreshold = Defaults.triggerThreshold; triggerReactivateDelay = Defaults.triggerReactivateDelay; } /// <summary> /// This function is called when this trigger is started. /// Should be override by sub classes to initialize. /// </summary> public virtual void Start () { //make sure to restore the targets if needed VisManager.RestoreVisManagerTarget(this); VisBaseController.RestoreVisBaseControllerTarget(this); //validate trigger variables. triggerThreshold = VisHelper.Validate(triggerThreshold, 0.0001f, 10000.0f, Defaults.triggerThreshold, this, "triggerThreshold", false); triggerReactivateDelay = VisHelper.Validate(triggerReactivateDelay, 0.0f, 10000.0f, Defaults.triggerReactivateDelay, this, "triggerReactivateDelay", false); } /// <summary> /// This function is called when this trigger is destroyed. /// Should be override by sub classes to handle destruction. /// </summary> public virtual void OnDestroy() { } #endregion #region Update Functions /// <summary> /// This updates this modifier using the default methods. This can be overriden to implement custom triggering criteria. /// </summary> public virtual void Update () { //make sure there is a target controller and it is enabled if (Controller != null && Controller.enabled) { //check if there is an active trigger delay timer if (m_fTriggerDelayTimer > 0.0f) { //update the trigger delay timer m_fTriggerDelayTimer -= Time.deltaTime; } //no delay timer is active, but make sure the trigger type is not none. else if (triggerType != TriggerType.None) { //create bool to track if we should be triggered bool trigger = false; //update the trigger based on the current trigger type switch (triggerType) { case TriggerType.LessThanValueThreshold: if (Controller.GetCurrentValue() < triggerThreshold) trigger = true; break; case TriggerType.GreaterThanValueThreshold: if (Controller.GetCurrentValue() > triggerThreshold) trigger = true; break; case TriggerType.LessThanChangeThreshold: if (Controller.GetAdjustedValueDifference() < triggerThreshold) trigger = true; break; case TriggerType.GreaterThanChangeThreshold: if (Controller.GetAdjustedValueDifference() > triggerThreshold) trigger = true; break; } //check if we should trigger if (trigger) { //set the delay timer and call OnTrigger m_fTriggerDelayTimer = triggerReactivateDelay + UnityEngine.Random.Range(-triggerRandomReactivateDelay, triggerRandomReactivateDelay); if (m_fTriggerDelayTimer < 0.0f) m_fTriggerDelayTimer = 0.0f; OnTriggered(Controller.GetCurrentValue(), Controller.GetPreviousValue(), Controller.GetValueDifference(), Controller.GetAdjustedValueDifference()); } } } } /// <summary> /// This function is called by the trigger whenever /// this trigger has been TRIGGERED. /// TO IMPLEMENT A CUSTOM TRIGGER REACTION, override this function /// to handle the trigger event. /// </summary> /// <param name="current"> /// The current value of the targeted controller. /// </param> /// <param name="previous"> /// The previous value of the targeted controller. /// </param> /// <param name="difference"> /// The value difference of the targeted controller. /// </param> /// <param name="adjustedDifference"> /// The adjusted value difference of the targeted controller. /// This value is the difference value as if it took place over a /// certain time period, controlled by VisBaseController.mc_fTargetAdjustedDifferenceTime. The /// default of this essientially indicates a frame rate of 60 fps to determine /// the adjusted difference. This should be used for almost all difference /// calculations, as it is NOT frame rate dependent. /// </param> public abstract void OnTriggered(float current, float previous, float difference, float adjustedDifference); #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.Reflection; using System.Composition.Runtime; using System.Collections.Generic; using System.Composition.Hosting.Core; using System.Composition.Hosting; namespace System.Composition { /// <summary> /// Provides retrieval of exports from the composition. /// </summary> public abstract class CompositionContext { private const string ImportManyImportMetadataConstraintName = "IsImportMany"; /// <summary> /// Retrieve the single <paramref name="contract"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="contract">The contract to retrieve.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public abstract bool TryGetExport(CompositionContract contract, out object export); /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public TExport GetExport<TExport>() { return GetExport<TExport>((string)null); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public TExport GetExport<TExport>(string contractName) { return (TExport)GetExport(typeof(TExport), contractName); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport(Type exportType, string contractName, out object export) { return TryGetExport(new CompositionContract(exportType, contractName), out export); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport(Type exportType, out object export) { return TryGetExport(exportType, null, out export); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport<TExport>(out TExport export) { return TryGetExport<TExport>(null, out export); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport<TExport>(string contractName, out TExport export) { object untypedExport; if (!TryGetExport(typeof(TExport), contractName, out untypedExport)) { export = default(TExport); return false; } export = (TExport)untypedExport; return true; } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public object GetExport(Type exportType) { return GetExport(exportType, (string)null); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public object GetExport(Type exportType, string contractName) { return GetExport(new CompositionContract(exportType, contractName)); } /// <summary> /// Retrieve the single <paramref name="contract"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="contract">The contract of the export to retrieve.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public object GetExport(CompositionContract contract) { object export; if (!TryGetExport(contract, out export)) throw new CompositionFailedException( string.Format(Properties.Resources.CompositionContext_NoExportFoundForContract, contract)); return export; } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <exception cref="CompositionFailedException" /> public IEnumerable<object> GetExports(Type exportType) { return GetExports(exportType, (string)null); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <param name="contractName">The discriminator to apply when selecting the export.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public IEnumerable<object> GetExports(Type exportType, string contractName) { var manyContract = new CompositionContract( exportType.MakeArrayType(), contractName, new Dictionary<string, object> { { ImportManyImportMetadataConstraintName, true } }); return (IEnumerable<object>)GetExport(manyContract); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The export type to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public IEnumerable<TExport> GetExports<TExport>() { return GetExports<TExport>((string)null); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The export type to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <param name="contractName">The discriminator to apply when selecting the export.</param> /// <exception cref="CompositionFailedException" /> public IEnumerable<TExport> GetExports<TExport>(string contractName) { return (IEnumerable<TExport>)GetExports(typeof(TExport), contractName); } } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using OpenLiveWriter.BlogClient.Detection; using OpenLiveWriter.BlogClient.Providers; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; /* * TODO * * Make sure all required fields are filled out. * Remove the HTML title from the friendly error message * Test ETags where HEAD not supported * Test experience when no media collection configured * Add command line option for preferring Atom over RSD * See if blogproviders.xml can override Atom vs. RSD preference */ namespace OpenLiveWriter.BlogClient.Clients { [BlogClient("Atom", "Atom")] public class GenericAtomClient : AtomClient, ISelfConfiguringClient, IBlogClientForCategorySchemeHack { static GenericAtomClient() { AuthenticationManager.Register(new GoogleLoginAuthenticationModule()); } private string _defaultCategoryScheme_HACK; public GenericAtomClient(Uri postApiUrl, IBlogCredentialsAccessor credentials) : base(AtomProtocolVersion.V10, postApiUrl, credentials) { } protected override void ConfigureClientOptions(OpenLiveWriter.BlogClient.Providers.BlogClientOptions clientOptions) { base.ConfigureClientOptions (clientOptions); clientOptions.SupportsCategories = true; clientOptions.SupportsMultipleCategories = true; clientOptions.SupportsNewCategories = true; clientOptions.SupportsCustomDate = true; clientOptions.SupportsExcerpt = true; clientOptions.SupportsSlug = true; clientOptions.SupportsFileUpload = true; } public virtual void DetectSettings(IBlogSettingsDetectionContext context, BlogSettingsDetector detector) { if (detector.IncludeOptionOverrides) { if (detector.IncludeCategoryScheme) { Debug.Assert(!detector.UseManifestCache, "This code will not run correctly under the manifest cache, due to option overrides not being set"); IDictionary optionOverrides = context.OptionOverrides; if (optionOverrides == null) optionOverrides = new Hashtable(); bool hasNewCategories = optionOverrides.Contains(BlogClientOptions.SUPPORTS_NEW_CATEGORIES); bool hasScheme = optionOverrides.Contains(BlogClientOptions.CATEGORY_SCHEME); if (!hasNewCategories || !hasScheme) { string scheme; bool supportsNewCategories; GetCategoryInfo(context.HostBlogId, optionOverrides[BlogClientOptions.CATEGORY_SCHEME] as string, // may be null out scheme, out supportsNewCategories); if (scheme == null) { // no supported scheme was found or provided optionOverrides[BlogClientOptions.SUPPORTS_CATEGORIES] = false.ToString(); } else { if (!optionOverrides.Contains(BlogClientOptions.SUPPORTS_NEW_CATEGORIES)) optionOverrides.Add(BlogClientOptions.SUPPORTS_NEW_CATEGORIES, supportsNewCategories.ToString()); if (!optionOverrides.Contains(BlogClientOptions.CATEGORY_SCHEME)) optionOverrides.Add(BlogClientOptions.CATEGORY_SCHEME, scheme); } context.OptionOverrides = optionOverrides; } } // GetFeaturesXml(context.HostBlogId); } } private void GetFeaturesXml(string blogId) { Uri uri = FeedServiceUrl; XmlDocument serviceDoc = xmlRestRequestHelper.Get(ref uri, RequestFilter); foreach (XmlElement entryEl in serviceDoc.SelectNodes("app:service/app:workspace/app:collection", _nsMgr)) { string href = XmlHelper.GetUrl(entryEl, "@href", uri); if (blogId == href) { XmlDocument results = new XmlDocument(); XmlElement rootElement = results.CreateElement("featuresInfo"); results.AppendChild(rootElement); foreach (XmlElement featuresNode in entryEl.SelectNodes("f:features", _nsMgr)) { AddFeaturesXml(featuresNode, rootElement, uri); } return; } } Trace.Fail("Couldn't find collection in service document:\r\n" + serviceDoc.OuterXml); } private void AddFeaturesXml(XmlElement featuresNode, XmlElement containerNode, Uri baseUri) { if (featuresNode.HasAttribute("href")) { string href = XmlHelper.GetUrl(featuresNode, "@href", baseUri); if (href != null && href.Length > 0) { Uri uri = new Uri(href); if (baseUri == null || !uri.Equals(baseUri)) // detect simple cycles { XmlDocument doc = xmlRestRequestHelper.Get(ref uri, RequestFilter); XmlElement features = (XmlElement)doc.SelectSingleNode(@"f:features", _nsMgr); if (features != null) AddFeaturesXml(features, containerNode, uri); } } } else { foreach (XmlElement featureEl in featuresNode.SelectNodes("f:feature")) containerNode.AppendChild(containerNode.OwnerDocument.ImportNode(featureEl, true)); } } string IBlogClientForCategorySchemeHack.DefaultCategoryScheme { set { _defaultCategoryScheme_HACK = value; } } /// <summary> /// /// </summary> /// <param name="blogId"></param> /// <param name="inScheme">The scheme that should definitely be used (i.e. from wlwmanifest), or null. /// If inScheme is non-null, then outScheme will equal inScheme.</param> /// <param name="outScheme">The scheme that should be used, or null if categories are not supported.</param> /// <param name="supportsNewCategories">Ignore this value if outScheme == null.</param> private void GetCategoryInfo(string blogId, string inScheme, out string outScheme, out bool supportsNewCategories) { XmlDocument xmlDoc = GetCategoryXml(ref blogId); foreach (XmlElement categoriesNode in xmlDoc.DocumentElement.SelectNodes("app:categories", _nsMgr)) { bool hasScheme = categoriesNode.HasAttribute("scheme"); string scheme = categoriesNode.GetAttribute("scheme"); bool isFixed = categoriesNode.GetAttribute("fixed") == "yes"; // <categories fixed="no" /> if (!hasScheme && inScheme == null && !isFixed) { outScheme = ""; supportsNewCategories = true; return; } // <categories scheme="inScheme" fixed="yes|no" /> if (hasScheme && scheme == inScheme) { outScheme = inScheme; supportsNewCategories = !isFixed; return; } // <categories scheme="" fixed="yes|no" /> if (hasScheme && inScheme == null && scheme == "") { outScheme = ""; supportsNewCategories = !isFixed; return; } } outScheme = inScheme; // will be null if no scheme was externally specified supportsNewCategories = false; } /* protected override OpenLiveWriter.CoreServices.HttpRequestFilter RequestFilter { get { return new HttpRequestFilter(WordPressCookieFilter); } } private void WordPressCookieFilter(HttpWebRequest request) { request.CookieContainer = new CookieContainer(); string COOKIE_STRING = "wordpressuser_6c27d03220bea936360daa76ec007cd7=admin; wordpresspass_6c27d03220bea936360daa76ec007cd7=696d29e0940a4957748fe3fc9efd22a3; __utma=260458847.291972184.1164155988.1176250147.1176308376.43; __utmz=260458847.1164155988.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); dbx-postmeta=grabit:0+|1+|2+|3+|4+|5+&advancedstuff:0-|1-|2-; dbx-pagemeta=grabit=0+,1+,2+,3+,4+,5+&advancedstuff=0+"; foreach (string cookie in StringHelper.Split(COOKIE_STRING, ";")) { string[] pair = cookie.Split('='); request.CookieContainer.Add(new Cookie(pair[0], pair[1], "/wp22test/", "www.unknown.com")); } } */ protected override string CategoryScheme { get { string scheme = Options.CategoryScheme; if (scheme == null) scheme = _defaultCategoryScheme_HACK; return scheme; } } protected override void VerifyCredentials(TransientCredentials tc) { // This sucks. We really want to authenticate against the actual feed, // not just the service document. Uri uri = FeedServiceUrl; xmlRestRequestHelper.Get(ref uri, RequestFilter); } protected void EnsureLoggedIn() { } #region image upload support public override void DoAfterPublishUploadWork(IFileUploadContext uploadContext) { } public override string DoBeforePublishUploadWork(IFileUploadContext uploadContext) { AtomMediaUploader uploader = new AtomMediaUploader(_nsMgr, RequestFilter, Options.ImagePostingUrl, Options); return uploader.DoBeforePublishUploadWork(uploadContext); } public override BlogInfo[] GetImageEndpoints() { EnsureLoggedIn(); Uri serviceDocUri = FeedServiceUrl; XmlDocument xmlDoc = xmlRestRequestHelper.Get(ref serviceDocUri, RequestFilter); ArrayList blogInfos = new ArrayList(); foreach (XmlElement coll in xmlDoc.SelectNodes("/app:service/app:workspace/app:collection", _nsMgr)) { // does this collection accept entries? XmlNodeList acceptNodes = coll.SelectNodes("app:accept", _nsMgr); string[] acceptTypes = new string[acceptNodes.Count]; for (int i = 0; i < acceptTypes.Length; i++) acceptTypes[i] = acceptNodes[i].InnerText; if (AcceptsImages(acceptTypes)) { string feedUrl = XmlHelper.GetUrl(coll, "@href", serviceDocUri); if (feedUrl == null || feedUrl.Length == 0) continue; // form title StringBuilder titleBuilder = new StringBuilder(); foreach (XmlElement titleContainerNode in new XmlElement[] { coll.ParentNode as XmlElement, coll }) { Debug.Assert(titleContainerNode != null); if (titleContainerNode != null) { XmlElement titleNode = titleContainerNode.SelectSingleNode("atom:title", _nsMgr) as XmlElement; if (titleNode != null) { string titlePart = _atomVer.TextNodeToPlaintext(titleNode); if (titlePart.Length != 0) { Res.LOCME("loc the separator between parts of the blog name"); if (titleBuilder.Length != 0) titleBuilder.Append(" - "); titleBuilder.Append(titlePart); } } } } blogInfos.Add(new BlogInfo(feedUrl, titleBuilder.ToString().Trim(), "")); } } return (BlogInfo[]) blogInfos.ToArray(typeof (BlogInfo)); } private static bool AcceptsImages(string[] contentTypes) { bool acceptsPng = false, acceptsJpeg = false, acceptsGif = false; foreach (string contentType in contentTypes) { IDictionary values = MimeHelper.ParseContentType(contentType, true); string mainType = values[""] as string; switch (mainType) { case "*/*": case "image/*": return true; case "image/png": acceptsPng = true; break; case "image/gif": acceptsGif = true; break; case "image/jpeg": acceptsJpeg = true; break; } } return acceptsPng && acceptsJpeg && acceptsGif; } #endregion } public class GoogleLoginAuthenticationModule : IAuthenticationModule { private static GDataCredentials _gdataCred = new GDataCredentials(); public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials) { if (!challenge.StartsWith("GoogleLogin ", StringComparison.OrdinalIgnoreCase)) return null; HttpWebRequest httpRequest = (HttpWebRequest) request; string service; string realm; ParseChallenge(challenge, out realm, out service); if (realm != "http://www.google.com/accounts/ClientLogin") return null; NetworkCredential cred = credentials.GetCredential(request.RequestUri, AuthenticationType); string auth = _gdataCred.GetCredentialsIfValid(cred.UserName, cred.Password, service); if (auth != null) { return new Authorization(auth, true); } else { try { _gdataCred.EnsureLoggedIn(cred.UserName, cred.Password, service, !BlogClientUIContext.SilentModeForCurrentThread); auth = _gdataCred.GetCredentialsIfValid(cred.UserName, cred.Password, service); if (auth != null) return new Authorization(auth, true); else return null; } catch (Exception e) { Trace.Fail(e.ToString()); return null; } } } private void ParseChallenge(string challenge, out string realm, out string service) { Match m = Regex.Match(challenge, @"\brealm=""([^""]*)"""); realm = m.Groups[1].Value; Match m2 = Regex.Match(challenge, @"\bservice=""([^""]*)"""); service = m2.Groups[1].Value; } public Authorization PreAuthenticate(WebRequest request, ICredentials credentials) { throw new NotImplementedException(); } public bool CanPreAuthenticate { get { return false; } } public string AuthenticationType { get { return "GoogleLogin"; } } } }
//--------------------------------------------------------------------- // <copyright file="ErrorHandler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Provides some utility functions for this project // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services { #region Namespaces. using System; using System.Data.Services.Serializers; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; #endregion Namespaces. /// <summary> /// Provides support for orchestrating error handling at different points in the processing cycle and for /// serializing structured errors. /// </summary> internal class ErrorHandler { #region Private fields. /// <summary>Arguments for the exception being handled.</summary> private HandleExceptionArgs exceptionArgs; /// <summary>Encoding to created over stream; null if a higher-level writer will be provided.</summary> private Encoding encoding; #endregion Private fields. #region Constructors. /// <summary>Initializes a new <see cref="ErrorHandler"/> instance.</summary> /// <param name="args">Arguments for the exception being handled.</param> /// <param name="encoding">Encoding to created over stream; null if a higher-level writer will be provided.</param> private ErrorHandler(HandleExceptionArgs args, Encoding encoding) { Debug.Assert(args != null, "args != null"); this.exceptionArgs = args; this.encoding = encoding; } #endregion Constructors. #region Internal methods. /// <summary>Handles an exception when processing a batch response.</summary> /// <param name='service'>Data service doing the processing.</param> /// <param name="host">host to which we need to write the exception message</param> /// <param name='exception'>Exception thrown.</param> /// <param name='writer'>Output writer for the batch.</param> internal static void HandleBatchProcessException(IDataService service, DataServiceHostWrapper host, Exception exception, StreamWriter writer) { Debug.Assert(service != null, "service != null"); Debug.Assert(host != null, "host != null"); Debug.Assert(exception != null, "exception != null"); Debug.Assert(writer != null, "writer != null"); Debug.Assert(service.Configuration != null, "service.Configuration != null"); Debug.Assert(WebUtil.IsCatchableExceptionType(exception), "WebUtil.IsCatchableExceptionType(exception)"); string contentType; Encoding encoding; TryGetResponseFormatForError(host, out contentType, out encoding); HandleExceptionArgs args = new HandleExceptionArgs(exception, false, contentType, service.Configuration.UseVerboseErrors); service.InternalHandleException(args); host.ResponseVersion = XmlConstants.DataServiceVersion1Dot0 + ";"; host.ProcessException(args); writer.Flush(); Action<Stream> errorWriter = ProcessBenignException(exception, service); if (errorWriter == null) { errorWriter = CreateErrorSerializer(args, encoding); } errorWriter(writer.BaseStream); writer.WriteLine(); } /// <summary>Handles an exception when processing a batch request.</summary> /// <param name='service'>Data service doing the processing.</param> /// <param name='exception'>Exception thrown.</param> /// <param name='writer'>Output writer for the batch.</param> internal static void HandleBatchRequestException(IDataService service, Exception exception, StreamWriter writer) { Debug.Assert(service != null, "service != null"); Debug.Assert(exception != null, "exception != null"); Debug.Assert(writer != null, "writer != null"); Debug.Assert(service.Configuration != null, "service.Configuration != null - it should have been initialized by now"); Debug.Assert(WebUtil.IsCatchableExceptionType(exception), "WebUtil.IsCatchableExceptionType(exception) - "); string contentType; Encoding encoding; DataServiceHostWrapper host = service.OperationContext == null ? null : service.OperationContext.Host; TryGetResponseFormatForError(host, out contentType, out encoding); encoding = writer.Encoding; HandleExceptionArgs args = new HandleExceptionArgs(exception, false, contentType, service.Configuration.UseVerboseErrors); service.InternalHandleException(args); writer.Flush(); Action<Stream> errorWriter = CreateErrorSerializer(args, encoding); errorWriter(writer.BaseStream); writer.WriteLine(); } /// <summary>Handles an exception before the response has been written out.</summary> /// <param name='exception'>Exception thrown.</param> /// <param name='service'>Data service doing the processing.</param> /// <param name='accept'>'Accept' header value; possibly null.</param> /// <param name='acceptCharset'>'Accept-Charset' header; possibly null.</param> /// <returns>An action that can serialize the exception into a stream.</returns> internal static Action<Stream> HandleBeforeWritingException(Exception exception, IDataService service, string accept, string acceptCharset) { Debug.Assert(WebUtil.IsCatchableExceptionType(exception), "WebUtil.IsCatchableExceptionType(exception)"); Debug.Assert(exception != null, "exception != null"); Debug.Assert(service != null, "service != null"); string contentType; Encoding encoding; TryGetResponseFormatForError(accept, acceptCharset, out contentType, out encoding); bool verbose = (service.Configuration != null) ? service.Configuration.UseVerboseErrors : false; HandleExceptionArgs args = new HandleExceptionArgs(exception, false, contentType, verbose); service.InternalHandleException(args); DataServiceHostWrapper host = service.OperationContext.Host; host.ResponseVersion = XmlConstants.DataServiceVersion1Dot0 + ";"; host.ProcessException(args); Action<Stream> action = ProcessBenignException(exception, service); if (action != null) { return action; } else { return CreateErrorSerializer(args, encoding); } } /// <summary>Handles an exception while the response is being written out.</summary> /// <param name='exception'>Exception thrown.</param> /// <param name='service'>Data service doing the processing.</param> /// <param name='contentType'>MIME type of output stream.</param> /// <param name='exceptionWriter'>Serializer-specific exception writer.</param> internal static void HandleDuringWritingException(Exception exception, IDataService service, string contentType, IExceptionWriter exceptionWriter) { Debug.Assert(service != null, "service != null"); Debug.Assert(exception != null, "exception != null"); Debug.Assert(exceptionWriter != null, "exceptionWriter != null"); Debug.Assert(service.Configuration != null, "service.Configuration != null"); Debug.Assert(WebUtil.IsCatchableExceptionType(exception), "WebUtil.IsCatchableExceptionType(exception)"); HandleExceptionArgs args = new HandleExceptionArgs(exception, true, contentType, service.Configuration.UseVerboseErrors); service.InternalHandleException(args); service.OperationContext.Host.ProcessException(args); exceptionWriter.WriteException(args); } /// <summary>Handles the specified <paramref name='exception'/>.</summary> /// <param name='exception'>Exception to handle</param> /// <remarks>The caller should re-throw the original exception if this method returns normally.</remarks> internal static void HandleTargetInvocationException(TargetInvocationException exception) { Debug.Assert(exception != null, "exception != null"); DataServiceException dataException = exception.InnerException as DataServiceException; if (dataException == null) { return; } throw new DataServiceException( dataException.StatusCode, dataException.ErrorCode, dataException.Message, dataException.MessageLanguage, exception); } /// <summary>Serializes an error in JSON format.</summary> /// <param name='args'>Arguments describing the error.</param> /// <param name='writer'>Writer to which error should be serialized.</param> internal static void SerializeJsonError(HandleExceptionArgs args, JsonWriter writer) { Debug.Assert(args != null, "args != null"); Debug.Assert(writer != null, "writer != null"); ErrorHandler serializer = new ErrorHandler(args, null); serializer.SerializeJsonError(writer); } /// <summary>Serializes an error in XML format.</summary> /// <param name='args'>Arguments describing the error.</param> /// <param name='writer'>Writer to which error should be serialized.</param> internal static void SerializeXmlError(HandleExceptionArgs args, XmlWriter writer) { Debug.Assert(args != null, "args != null"); Debug.Assert(writer != null, "writer != null"); ErrorHandler serializer = new ErrorHandler(args, null); serializer.SerializeXmlError(writer); } #endregion Internal methods. #region Private methods. /// <summary> /// Check to see if the given excpetion is a benign one such as statusCode = 304. If yes we return an action that can /// serialize the exception into a stream. Other wise we return null. /// </summary> /// <param name="exception">Exception to be processed</param> /// <param name="service">Data service instance</param> /// <returns>An action that can serialize the exception into a stream.</returns> private static Action<Stream> ProcessBenignException(Exception exception, IDataService service) { DataServiceException dataServiceException = exception as DataServiceException; if (dataServiceException != null) { if (dataServiceException.StatusCode == (int)System.Net.HttpStatusCode.NotModified) { DataServiceHostWrapper host = service.OperationContext.Host; Debug.Assert(host != null, "host != null"); host.ResponseStatusCode = (int)System.Net.HttpStatusCode.NotModified; // For 304, we MUST return an empty message-body. return WebUtil.GetEmptyStreamWriter(); } } return null; } /// <summary>Creates a delegate that can serialize an error for the specified arguments.</summary> /// <param name="args">Arguments for the exception being handled.</param> /// <param name="encoding">Encoding to created over stream.</param> /// <returns>A delegate that can serialize an error for the specified arguments.</returns> private static Action<Stream> CreateErrorSerializer(HandleExceptionArgs args, Encoding encoding) { Debug.Assert(args != null, "args != null"); Debug.Assert(encoding != null, "encoding != null"); ErrorHandler handler = new ErrorHandler(args, encoding); if (WebUtil.CompareMimeType(args.ResponseContentType, XmlConstants.MimeApplicationJson)) { return handler.SerializeJsonErrorToStream; } else { return handler.SerializeXmlErrorToStream; } } /// <summary> /// Gets values describing the <paramref name='exception' /> if it's a DataServiceException; /// defaults otherwise. /// </summary> /// <param name='exception'>Exception to extract value from.</param> /// <param name='errorCode'>Error code from the <paramref name='exception' />; blank if not available.</param> /// <param name='message'>Message from the <paramref name='exception' />; blank if not available.</param> /// <param name='messageLang'>Message language from the <paramref name='exception' />; current default if not available.</param> /// <returns>The cast DataServiceException; possibly null.</returns> private static DataServiceException ExtractErrorValues(Exception exception, out string errorCode, out string message, out string messageLang) { DataServiceException dataException = exception as DataServiceException; if (dataException != null) { errorCode = dataException.ErrorCode ?? ""; message = dataException.Message ?? ""; messageLang = dataException.MessageLanguage ?? CultureInfo.CurrentCulture.Name; return dataException; } else { errorCode = ""; message = Strings.DataServiceException_GeneralError; messageLang = CultureInfo.CurrentCulture.Name; return null; } } /// <summary>Serializes an exception in JSON format.</summary> /// <param name='writer'>Writer to which error should be serialized.</param> /// <param name='exception'>Exception to serialize.</param> private static void SerializeJsonException(JsonWriter writer, Exception exception) { string elementName = XmlConstants.JsonErrorInner; int nestingDepth = 0; while (exception != null) { writer.WriteName(elementName); writer.StartObjectScope(); nestingDepth++; string exceptionMessage = exception.Message ?? String.Empty; writer.WriteName(XmlConstants.JsonErrorMessage); writer.WriteValue(exceptionMessage); string exceptionType = exception.GetType().FullName; writer.WriteName(XmlConstants.JsonErrorType); writer.WriteValue(exceptionType); string exceptionStackTrace = exception.StackTrace ?? String.Empty; writer.WriteName(XmlConstants.JsonErrorStackTrace); writer.WriteValue(exceptionStackTrace); exception = exception.InnerException; elementName = XmlConstants.JsonErrorInternalException; } while (nestingDepth > 0) { writer.EndScope(); // </innererror> nestingDepth--; } } /// <summary>Serializes an exception in XML format.</summary> /// <param name='writer'>Writer to which error should be serialized.</param> /// <param name='exception'>Exception to serialize.</param> private static void SerializeXmlException(XmlWriter writer, Exception exception) { string elementName = XmlConstants.XmlErrorInnerElementName; int nestingDepth = 0; while (exception != null) { // Inner Error Tag namespace changed to DataWebMetadataNamespace // Maybe DataWebNamespace should be used on all error tags? Up to debate... // NOTE: this is a breaking change from V1 writer.WriteStartElement(elementName, XmlConstants.DataWebMetadataNamespace); nestingDepth++; string exceptionMessage = exception.Message ?? String.Empty; writer.WriteStartElement(XmlConstants.XmlErrorMessageElementName, XmlConstants.DataWebMetadataNamespace); writer.WriteString(exceptionMessage); writer.WriteEndElement(); // </message> string exceptionType = exception.GetType().FullName; writer.WriteStartElement(XmlConstants.XmlErrorTypeElementName, XmlConstants.DataWebMetadataNamespace); writer.WriteString(exceptionType); writer.WriteEndElement(); // </type> string exceptionStackTrace = exception.StackTrace ?? String.Empty; writer.WriteStartElement(XmlConstants.XmlErrorStackTraceElementName, XmlConstants.DataWebMetadataNamespace); writer.WriteString(exceptionStackTrace); writer.WriteEndElement(); // </stacktrace> exception = exception.InnerException; elementName = XmlConstants.XmlErrorInternalExceptionElementName; } while (nestingDepth > 0) { writer.WriteEndElement(); // </innererror> nestingDepth--; } } /// <summary>Gets content type and encoding information from the host if possible; defaults otherwise.</summary> /// <param name="host">Host to get headers from (possibly null).</param> /// <param name="contentType">After invocation, content type for the exception.</param> /// <param name="encoding">After invocation, encoding for the exception.</param> private static void TryGetResponseFormatForError(DataServiceHostWrapper host, out string contentType, out Encoding encoding) { TryGetResponseFormatForError( (host != null) ? host.RequestAccept : null, (host != null) ? host.RequestAcceptCharSet : null, out contentType, out encoding); } /// <summary>Gets content type and encoding information from the headers if possible; defaults otherwise.</summary> /// <param name="accept">A comma-separated list of client-supported MIME Accept types.</param> /// <param name="acceptCharset">The specification for the character set encoding that the client requested.</param> /// <param name="contentType">After invocation, content type for the exception.</param> /// <param name="encoding">After invocation, encoding for the exception.</param> private static void TryGetResponseFormatForError(string accept, string acceptCharset, out string contentType, out Encoding encoding) { contentType = null; encoding = null; if (accept != null) { try { string[] availableTypes = new string[] { XmlConstants.MimeApplicationXml, XmlConstants.MimeApplicationJson }; contentType = HttpProcessUtility.SelectMimeType(accept, availableTypes); } catch (DataServiceException) { // Ignore formatting erros in Accept and rely on text. } } if (acceptCharset != null) { try { encoding = HttpProcessUtility.EncodingFromAcceptCharset(acceptCharset); } catch (DataServiceException) { // Ignore formatting erros in Accept-Charset and rely on text. } } contentType = contentType ?? XmlConstants.MimeApplicationXml; encoding = encoding ?? HttpProcessUtility.FallbackEncoding; } /// <summary>Serializes an error in JSON format.</summary> /// <param name='writer'>Writer to which error should be serialized.</param> private void SerializeJsonError(JsonWriter writer) { Debug.Assert(writer != null, "writer != null"); writer.StartObjectScope(); // Wrapper for error. writer.WriteName(XmlConstants.JsonError); string errorCode, message, messageLang; DataServiceException dataException = ExtractErrorValues(this.exceptionArgs.Exception, out errorCode, out message, out messageLang); writer.StartObjectScope(); writer.WriteName(XmlConstants.JsonErrorCode); writer.WriteValue(errorCode); writer.WriteName(XmlConstants.JsonErrorMessage); writer.StartObjectScope(); writer.WriteName(XmlConstants.XmlLangAttributeName); writer.WriteValue(messageLang); writer.WriteName(XmlConstants.JsonErrorValue); writer.WriteValue(message); writer.EndScope(); // </message> if (this.exceptionArgs.UseVerboseErrors) { Exception exception = (dataException == null) ? this.exceptionArgs.Exception : dataException.InnerException; SerializeJsonException(writer, exception); } writer.EndScope(); // </error> writer.EndScope(); // </error wrapper> writer.Flush(); } /// <summary>Serializes an error in XML format.</summary> /// <param name='writer'>Writer to which error should be serialized.</param> private void SerializeXmlError(XmlWriter writer) { Debug.Assert(writer != null, "writer != null"); writer.WriteStartElement(XmlConstants.XmlErrorElementName, XmlConstants.DataWebMetadataNamespace); string errorCode, message, messageLang; DataServiceException dataException = ExtractErrorValues(this.exceptionArgs.Exception, out errorCode, out message, out messageLang); writer.WriteStartElement(XmlConstants.XmlErrorCodeElementName, XmlConstants.DataWebMetadataNamespace); writer.WriteString(errorCode); writer.WriteEndElement(); // </code> writer.WriteStartElement(XmlConstants.XmlErrorMessageElementName, XmlConstants.DataWebMetadataNamespace); writer.WriteAttributeString( XmlConstants.XmlNamespacePrefix, // prefix XmlConstants.XmlLangAttributeName, // localName null, // ns messageLang); // value writer.WriteString(message); writer.WriteEndElement(); // </message> if (this.exceptionArgs.UseVerboseErrors) { Exception exception = (dataException == null) ? this.exceptionArgs.Exception : dataException.InnerException; SerializeXmlException(writer, exception); } writer.WriteEndElement(); // </error> writer.Flush(); } /// <summary>Serializes the current exception description to the specified <paramref name="stream"/>.</summary> /// <param name="stream">Stream to write to.</param> private void SerializeJsonErrorToStream(Stream stream) { Debug.Assert(stream != null, "stream != null"); JsonWriter jsonWriter = new JsonWriter(new StreamWriter(stream, this.encoding)); try { SerializeJsonError(jsonWriter); } finally { // We should not close the writer, since the stream is owned by the underlying host. jsonWriter.Flush(); } } /// <summary>Serializes the current exception description to the specified <paramref name="stream"/>.</summary> /// <param name="stream">Stream to write to.</param> private void SerializeXmlErrorToStream(Stream stream) { Debug.Assert(stream != null, "stream != null"); using (XmlWriter writer = XmlUtil.CreateXmlWriterAndWriteProcessingInstruction(stream, this.encoding)) { SerializeXmlError(writer); } } #endregion Private 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 Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolAndTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolAnd(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolAndAlsoTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolAndAlso(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolOrTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolOr(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolOrElseTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolOrElse(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolAndWithMethodTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodAnd(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolAndAlsoWithMethodTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodAndAlso(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolWithMethodOrTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodOr(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedNullableBoolWithMethodOrElseTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodOrElse(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyNullableBoolAnd(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.And( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolAndAlso(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.AndAlso( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a == false ? false : a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolOr(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.Or( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a | b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolOrElse(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.OrElse( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a == true ? true : a | b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodAnd(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.And( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodAndAlso(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.AndAlso( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a == false ? false : a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodOr(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.Or( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a | b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodOrElse(bool? a, bool? b, bool useInterpreter) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.OrElse( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); bool? expected = a == true ? true : a | b; Assert.Equal(expected, f()); } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using NLog.Config; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Config { public class ConfigApiTests { [Fact] public void AddTarget_testname() { var config = new LoggingConfiguration(); config.AddTarget("name1", new FileTarget { Name = "File" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); //maybe confusing, but the name of the target is not changed, only the one of the key. Assert.Equal("File", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name1")); config.RemoveTarget("name1"); allTargets = config.AllTargets; Assert.Empty(allTargets); } [Fact] public void AddTarget_WithName_NullNameParam() { var config = new LoggingConfiguration(); Exception ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(name: null, target: new FileTarget { Name = "name1" })); } [Fact] public void AddTarget_WithName_EmptyPameParam() { var config = new LoggingConfiguration(); Exception ex = Assert.Throws<ArgumentException>(() => config.AddTarget(name: "", target: new FileTarget { Name = "name1" })); } [Fact] public void AddTarget_WithName_NullTargetParam() { var config = new LoggingConfiguration(); Exception ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(name: "Name1", target: null)); } [Fact] public void AddTarget_TargetOnly_NullParam() { var config = new LoggingConfiguration(); Exception ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(target: null)); } [Fact] public void AddTarget_testname_param() { var config = new LoggingConfiguration(); config.AddTarget("name1", new FileTarget { Name = "name2" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); //maybe confusing, but the name of the target is not changed, only the one of the key. Assert.Equal("name2", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name1")); } [Fact] public void AddTarget_testname_fromtarget() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "name2" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); Assert.Equal("name2", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name2")); } [Fact] public void AddRule_min_max() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); config.AddRule(LogLevel.Info, LogLevel.Error, "File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.False(rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_all() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); config.AddRuleForAllLevels("File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.False(rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_onelevel() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); config.AddRuleForOneLevel(LogLevel.Error, "File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.False(rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_with_target() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "File" }; config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); config.AddTarget(new FileTarget { Name = "File" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); Assert.Equal("File", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("File")); } [Fact] public void AddRule_missingtarget() { var config = new LoggingConfiguration(); Assert.Throws<NLogConfigurationException>(() => config.AddRuleForOneLevel(LogLevel.Error, "File", "*a")); } [Fact] public void CheckAllTargets() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "File", FileName = "file" }; config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a"); config.AddTarget(fileTarget); Assert.Single(config.AllTargets); Assert.Equal(fileTarget, config.AllTargets[0]); config.InitializeAll(); Assert.Single(config.AllTargets); Assert.Equal(fileTarget, config.AllTargets[0]); } [Fact] public void LogRuleToStringTest_min() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("*", LogLevel.Error, target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ Error Fatal ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_minAndMax() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("*", LogLevel.Debug, LogLevel.Error, target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ Debug Info Warn Error ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_none() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("*", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_empty() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:Equals) levels: [ ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_filter() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("namespace.comp1", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_multiple_targets() { var target = new FileTarget { Name = "file1" }; var target2 = new FileTarget { Name = "file2" }; var loggingRule = new LoggingRule("namespace.comp1", target); loggingRule.Targets.Add(target2); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] writeTo: [ file1 file2 ]", s); } [Fact] public void LogRuleSetLoggingLevels_enables() { var rule = new LoggingRule(); rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal); Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }); } [Fact] public void LogRuleSetLoggingLevels_disables() { var rule = new LoggingRule(); rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal); Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }); } [Fact] public void LogRuleSetLoggingLevels_off() { var rule = new LoggingRule(); rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); rule.SetLoggingLevels(LogLevel.Off, LogLevel.Off); Assert.Equal(rule.Levels, new LogLevel[0]); } [Fact] public void LogRuleDisableLoggingLevels() { var rule = new LoggingRule(); rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); rule.DisableLoggingForLevels(LogLevel.Warn, LogLevel.Fatal); Assert.Equal(rule.Levels, new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info }); } [Fact] public void ConfigLogRuleWithName() { var config = new LoggingConfiguration(); var rule = new LoggingRule("hello"); config.LoggingRules.Add(rule); var ruleLookup = config.FindRuleByName("hello"); Assert.Same(rule, ruleLookup); Assert.True(config.RemoveRuleByName("hello")); ruleLookup = config.FindRuleByName("hello"); Assert.Null(ruleLookup); Assert.False(config.RemoveRuleByName("hello")); } [Fact] public void FindRuleByName_AfterRename_FindNewOneAndDontFindOld() { // Arrange var config = new LoggingConfiguration(); var rule = new LoggingRule("hello"); config.LoggingRules.Add(rule); // Act var foundRule1 = config.FindRuleByName("hello"); foundRule1.RuleName = "world"; var foundRule2 = config.FindRuleByName("hello"); var foundRule3 = config.FindRuleByName("world"); // Assert Assert.Null(foundRule2); Assert.NotNull(foundRule1); Assert.Same(foundRule1, foundRule3); } [Fact] public void LoggerNameMatcher_None() { var matcher = LoggerNameMatcher.Create(null); Assert.Equal("logNamePattern: (:None)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_All() { var matcher = LoggerNameMatcher.Create("*"); Assert.Equal("logNamePattern: (:All)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_Empty() { var matcher = LoggerNameMatcher.Create(""); Assert.Equal("logNamePattern: (:Equals)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_Equals() { var matcher = LoggerNameMatcher.Create("abc"); Assert.Equal("logNamePattern: (abc:Equals)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_StartsWith() { var matcher = LoggerNameMatcher.Create("abc*"); Assert.Equal("logNamePattern: (abc:StartsWith)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_EndsWith() { var matcher = LoggerNameMatcher.Create("*abc"); Assert.Equal("logNamePattern: (abc:EndsWith)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_Contains() { var matcher = LoggerNameMatcher.Create("*abc*"); Assert.Equal("logNamePattern: (abc:Contains)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_MultiplePattern_StarInternal() { var matcher = LoggerNameMatcher.Create("a*bc"); Assert.Equal("logNamePattern: (^a.*bc$:MultiplePattern)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_MultiplePattern_QuestionMark() { var matcher = LoggerNameMatcher.Create("a?bc"); Assert.Equal("logNamePattern: (^a.bc$:MultiplePattern)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_MultiplePattern_EscapedChars() { var matcher = LoggerNameMatcher.Create("a?b.c.foo.bar"); Assert.Equal("logNamePattern: (^a.b\\.c\\.foo\\.bar$:MultiplePattern)", matcher.ToString()); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("foobar", false)] public void LoggerNameMatcher_Matches_None(string name, bool result) { LoggerNameMatcher_Matches("None", null, name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("foobar", false)] [InlineData("A", false)] [InlineData("a", true)] public void LoggerNameMatcher_Matches_Equals(string name, bool result) { LoggerNameMatcher_Matches("Equals", "a", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Foo", false)] [InlineData("Foobar", false)] [InlineData("foo", true)] [InlineData("foobar", true)] public void LoggerNameMatcher_Matches_StartsWith(string name, bool result) { LoggerNameMatcher_Matches("StartsWith", "foo*", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Bar", false)] [InlineData("fooBar", false)] [InlineData("bar", true)] [InlineData("foobar", true)] public void LoggerNameMatcher_Matches_EndsWith(string name, bool result) { LoggerNameMatcher_Matches("EndsWith", "*bar", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Bar", false)] [InlineData("fooBar", false)] [InlineData("Barbaz", false)] [InlineData("fooBarbaz", false)] [InlineData("bar", true)] [InlineData("foobar", true)] [InlineData("barbaz", true)] [InlineData("foobarbaz", true)] public void LoggerNameMatcher_Matches_Contains(string name, bool result) { LoggerNameMatcher_Matches("Contains", "*bar*", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Server[123].connection[2].reader", false)] [InlineData("server[123].connection[2].reader", true)] [InlineData("server[123].connection[2].", true)] [InlineData("server[123].connection[2]", false)] [InlineData("server[123].connection[25].reader", false)] [InlineData("server[].connection[2].reader", true)] public void LoggerNameMatcher_Matches_MultiplePattern(string name, bool result) { LoggerNameMatcher_Matches("MultiplePattern", "server[*].connection[?].*", name, result); } [Theory] [InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[2].reader", false)] [InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[25].reader", true)] [InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[254].reader", false)] public void LoggerNameMatcher_Matches(string matcherType, string pattern, string name, bool result) { var matcher = LoggerNameMatcher.Create(pattern); Assert.Contains(":" + matcherType, matcher.ToString()); Assert.Equal(result, matcher.NameMatches(name)); } } }
using UnityEngine; public enum MegaHoseType { Round, Rectangle, DSection, } // Option for mesh to deform along public enum MegaHoseSmooth { SMOOTHALL, SMOOTHNONE, SMOOTHSIDES, SMOOTHSEGS, } [ExecuteInEditMode] [AddComponentMenu("MegaShapes/Hose")] [RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))] public class MegaHose : MonoBehaviour { public bool freecreate = true; public bool updatemesh = true; Matrix4x4 S = Matrix4x4.identity; const float HalfIntMax = 16383.5f; const float PIover2 = 1.570796327f; const float EPSILON = 0.0001f; public MegaSpline hosespline = new MegaSpline(); Mesh mesh; public Vector3[] verts = new Vector3[1]; public Vector2[] uvs = new Vector2[1]; public int[] faces = new int[1]; public Vector3[] normals; public bool optimize = false; public bool calctangents = false; public bool recalcCollider = false; public bool calcnormals = false; public bool capends = true; public GameObject custnode2; public GameObject custnode; public Vector3 offset = Vector3.zero; public Vector3 offset1 = Vector3.zero; public Vector3 rotate = Vector3.zero; public Vector3 rotate1 = Vector3.zero; public Vector3 scale = Vector3.one; public Vector3 scale1 = Vector3.one; public int endsmethod = 0; public float noreflength = 1.0f; public int segments = 45; public MegaHoseSmooth smooth = MegaHoseSmooth.SMOOTHALL; public MegaHoseType wiretype = MegaHoseType.Round; public float rnddia = 0.2f; public int rndsides = 8; public float rndrot = 0.0f; public float rectwidth = 0.2f; public float rectdepth = 0.2f; public float rectfillet = 0.0f; public int rectfilletsides = 0; public float rectrotangle = 0.0f; public float dsecwidth = 0.2f; public float dsecdepth = 0.2f; public float dsecfillet = 0.0f; public int dsecfilletsides = 0; public int dsecrndsides = 4; public float dsecrotangle = 0.0f; public bool mapmemapme = true; public bool flexon = false; public float flexstart = 0.1f; public float flexstop = 0.9f; public int flexcycles = 5; public float flexdiameter = -0.2f; public float tension1 = 10.0f; public float tension2 = 10.0f; public bool usebulgecurve = false; public AnimationCurve bulge = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0)); public float bulgeamount = 1.0f; public float bulgeoffset = 0.0f; public Vector2 uvscale = Vector2.one; public bool animatebulge = false; public float bulgespeed = 0.0f; public float minbulge = -1.0f; public float maxbulge = 2.0f; public bool displayspline = true; //public bool realtime = true; bool visible = true; public bool InvisibleUpdate = false; public bool dolateupdate = false; [ContextMenu("Help")] public void Help() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=3436"); } void Awake() { updatemesh = true; rebuildcross = true; Rebuild(); } void Reset() { Rebuild(); } void OnBecameVisible() { visible = true; } void OnBecameInvisible() { visible = false; } public void SetEndTarget(int end, GameObject target) { if ( end == 0 ) { custnode = target; } else { custnode2 = target; } updatemesh = true; } public void Rebuild() { MeshFilter mf = GetComponent<MeshFilter>(); if ( mf != null ) { Mesh mesh = mf.sharedMesh; //Utils.GetMesh(gameObject); if ( mesh == null ) { mesh = new Mesh(); mf.sharedMesh = mesh; } if ( mesh != null ) { BuildMesh(); } //updatemesh = false; } } void MakeSaveVertex(int NvertsPerRing, int nfillets, int nsides, MegaHoseType wtype) { if ( wtype == MegaHoseType.Round ) { //Debug.Log("Verts " + NvertsPerRing); float ang = (Mathf.PI * 2.0f) / (float)(NvertsPerRing - 1); float diar = rnddia; diar *= 0.5f; for ( int i = 0; i < NvertsPerRing; i++ ) { float u = (float)(i + 1) * ang; SaveVertex[i] = new Vector3(diar * (float)Mathf.Cos(u), diar * (float)Mathf.Sin(u), 0.0f); } } else { if ( wtype == MegaHoseType.Rectangle ) { int savevertcnt = 0; int qtrverts = 1 + nfillets; int hlfverts = 2 * qtrverts; int thrverts = qtrverts + hlfverts; float Wr = rectwidth * 0.5f; float Dr = rectdepth * 0.5f; float Zfr = rectfillet; if ( Zfr < 0.0f ) Zfr = 0.0f; if ( nfillets > 0 ) { float WmZ = Wr - Zfr, DmZ = Dr - Zfr; float ZmW = -WmZ, ZmD = -DmZ; SaveVertex[0] = new Vector3(Wr , DmZ, 0.0f); SaveVertex[nfillets] = new Vector3(WmZ, Dr , 0.0f); SaveVertex[qtrverts] = new Vector3(ZmW, Dr , 0.0f); SaveVertex[qtrverts + nfillets] = new Vector3(-Wr, DmZ, 0.0f); SaveVertex[hlfverts] = new Vector3(-Wr, ZmD, 0.0f); SaveVertex[hlfverts + nfillets] = new Vector3(ZmW, -Dr, 0.0f); SaveVertex[thrverts] = new Vector3(WmZ, -Dr, 0.0f); SaveVertex[thrverts + nfillets] = new Vector3(Wr , ZmD, 0.0f); if ( nfillets > 1 ) { float ang = PIover2 / (float)nfillets; savevertcnt = 1; for ( int i = 0; i < nfillets - 1; i++ ) { float u = (float)(i + 1) * ang; float cu = Zfr * Mathf.Cos(u), su = Zfr * Mathf.Sin(u); SaveVertex[savevertcnt] = new Vector3(WmZ + cu, DmZ + su, 0.0f); SaveVertex[savevertcnt + qtrverts] = new Vector3(ZmW - su, DmZ + cu, 0.0f); SaveVertex[savevertcnt + hlfverts] = new Vector3(ZmW - cu, ZmD - su, 0.0f); SaveVertex[savevertcnt + thrverts] = new Vector3(WmZ + su, ZmD - cu, 0.0f); savevertcnt++; } } SaveVertex[SaveVertex.Length - 1] = SaveVertex[0]; } else { if ( smooth == MegaHoseSmooth.SMOOTHNONE ) { SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(-Wr, Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(-Wr, Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(-Wr, -Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(-Wr, -Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(Wr, -Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(Wr, -Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f); } else { SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(-Wr, Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(-Wr, -Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(Wr, -Dr, 0.0f); SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f); } } } else { int savevertcnt = 0; float sang = Mathf.PI / (float)nsides; float Wr = dsecwidth * 0.5f; float Dr = dsecdepth * 0.5f; float Zfr = dsecfillet; if ( Zfr < 0.0f ) Zfr = 0.0f; float LeftCenter = Dr-Wr; if ( nfillets > 0 ) { float DmZ = Dr-Zfr, ZmD = -DmZ, WmZ = Wr-Zfr; int oneqtrverts = 1 + nfillets; int threeqtrverts = oneqtrverts + 1 + nsides; SaveVertex[0] = new Vector3(Wr , DmZ, 0.0f); SaveVertex[nfillets] = new Vector3(WmZ, Dr , 0.0f); SaveVertex[oneqtrverts] = new Vector3(LeftCenter, Dr, 0.0f); SaveVertex[oneqtrverts + nsides] = new Vector3(LeftCenter, -Dr, 0.0f); SaveVertex[threeqtrverts] = new Vector3(WmZ, -Dr , 0.0f); SaveVertex[threeqtrverts + nfillets] = new Vector3(Wr, ZmD, 0.0f); if ( nfillets > 1 ) { float ang = PIover2 / (float)nfillets; savevertcnt = 1; for ( int i = 0; i < nfillets - 1; i++ ) { float u = (float)(i + 1) * ang; float cu = Zfr * Mathf.Cos(u); float su = Zfr * Mathf.Sin(u); SaveVertex[savevertcnt] = new Vector3(WmZ + cu, DmZ + su, 0.0f); SaveVertex[savevertcnt+threeqtrverts] = new Vector3(WmZ + su, ZmD - cu, 0.0f); savevertcnt++; } } savevertcnt = 1 + oneqtrverts; for ( int i = 0; i < nsides - 1; i++ ) { float u = (float)(i + 1) * sang; float cu = Dr * Mathf.Cos(u); float su = Dr * Mathf.Sin(u); SaveVertex[savevertcnt] = new Vector3(LeftCenter - su, cu, 0.0f); savevertcnt++; } } else { SaveVertex[savevertcnt] = new Vector3(Wr, Dr, 0.0f); savevertcnt++; SaveVertex[savevertcnt] = new Vector3(LeftCenter, Dr, 0.0f); savevertcnt++; for ( int i = 0; i < nsides - 1; i++ ) { float u = (float)(i + 1) * sang; float cu = Dr * Mathf.Cos(u); float su = Dr * Mathf.Sin(u); SaveVertex[savevertcnt] = new Vector3(LeftCenter - su, cu, 0.0f); savevertcnt++; } SaveVertex[savevertcnt] = new Vector3(LeftCenter, -Dr, 0.0f); savevertcnt++; SaveVertex[savevertcnt] = new Vector3(Wr, -Dr, 0.0f); savevertcnt++; } SaveVertex[SaveVertex.Length - 1] = SaveVertex[0]; } } // UVs float dist = 0.0f; Vector3 last = Vector3.zero; for ( int i = 0; i < NvertsPerRing; i++ ) { if ( i > 0 ) dist += (SaveVertex[i] - last).magnitude; SaveUV[i] = new Vector2(0.0f, dist * uvscale.y); last = SaveVertex[i]; } for ( int i = 0; i < NvertsPerRing; i++ ) SaveUV[i].y /= dist; float rotangle = 0.0f; switch ( wtype ) { case MegaHoseType.Round: rotangle = rndrot; break; case MegaHoseType.Rectangle: rotangle = rectrotangle; break; case MegaHoseType.DSection: rotangle = dsecrotangle; break; } if ( rotangle != 0.0f ) { rotangle *= Mathf.Deg2Rad; float cosu = Mathf.Cos(rotangle); float sinu = Mathf.Sin(rotangle); for ( int m = 0; m < NvertsPerRing; m++ ) { float tempx = SaveVertex[m].x * cosu - SaveVertex[m].y * sinu; float tempy = SaveVertex[m].x * sinu + SaveVertex[m].y * cosu; SaveVertex[m].x = tempx; SaveVertex[m].y = tempy; } } // Normals if ( calcnormals ) { for ( int i = 0; i < NvertsPerRing; i++ ) { int ii = (i + 1) % NvertsPerRing; Vector3 delta = (SaveVertex[ii] - SaveVertex[i]).normalized; //SaveNormals[i] = new Vector3(-delta.y, delta.x, 0.0f); //SaveNormals[i] = new Vector3(-delta.x, delta.y, 0.0f); //SaveNormals[i] = new Vector3(delta.y, delta.x, 0.0f); SaveNormals[i] = new Vector3(delta.y, -delta.x, 0.0f); } } } void FixHoseFillet() { float width = rectwidth; float height = rectdepth; float fillet = rectfillet; float hh = 0.5f * Mathf.Abs(height); float ww = 0.5f * Mathf.Abs(width); float maxf = (hh > ww ? ww : hh); if ( fillet > maxf ) rectfillet = maxf; } float RND11() { float num = Random.Range(0.0f, 32768.0f) - HalfIntMax; return (num / HalfIntMax); } void Mult1X3(Vector3 A, Matrix4x4 B, ref Vector3 C) { C[0] = A[0] * B[0, 0] + A[1] * B[0, 1] + A[2] * B[0, 2]; C[1] = A[0] * B[1, 0] + A[1] * B[1, 1] + A[2] * B[1, 2]; C[2] = A[0] * B[2, 0] + A[1] * B[2, 1] + A[2] * B[2, 2]; } void Mult1X4(Vector4 A, Matrix4x4 B, ref Vector4 C) { C[0] = A[0] * B[0, 0] + A[1] * B[0, 1] + A[2] * B[0, 2] + A[3] * B[0, 3]; C[1] = A[0] * B[1, 0] + A[1] * B[1, 1] + A[2] * B[1, 2] + A[3] * B[1, 3]; C[2] = A[0] * B[2, 0] + A[1] * B[2, 1] + A[2] * B[2, 2] + A[3] * B[2, 3]; C[3] = A[0] * B[3, 0] + A[1] * B[3, 1] + A[2] * B[3, 2] + A[3] * B[3, 3]; } void SetUpRotation(Vector3 Q, Vector3 W, float Theta, ref Matrix4x4 Rq) { float ww1,ww2,ww3,w12,w13,w23,CosTheta,SinTheta,MinCosTheta; Vector3 temp = Vector3.zero; Matrix4x4 R = Matrix4x4.identity; ww1 = W[0] * W[0]; ww2 = W[1] * W[1]; ww3 = W[2] * W[2]; w12 = W[0] * W[1]; w13 = W[0] * W[2]; w23 = W[1] * W[2]; CosTheta = Mathf.Cos(Theta); MinCosTheta = 1.0f - CosTheta; SinTheta = Mathf.Sin(Theta); R[0, 0] = ww1 + (1.0f - ww1) * CosTheta; R[1, 0] = w12 * MinCosTheta + W[2] * SinTheta; R[2, 0] = w13 * MinCosTheta - W[1] * SinTheta; R[0, 1] = w12 * MinCosTheta - W[2] * SinTheta; R[1, 1] = ww2 + (1.0f - ww2) * CosTheta; R[2, 1] = w23 * MinCosTheta + W[0] * SinTheta; R[0, 2] = w13 * MinCosTheta + W[1] * SinTheta; R[1, 2] = w23 * MinCosTheta - W[0] * SinTheta; R[2, 2] = ww3 + (1.0f - ww3) * CosTheta; Mult1X3(Q, R, ref temp); Rq.SetColumn(0, R.GetColumn(0)); Rq.SetColumn(1, R.GetColumn(1)); Rq.SetColumn(2, R.GetColumn(2)); Rq[0, 3] = Q[0] - temp.x; Rq[1, 3] = Q[1] - temp.y; Rq[2, 3] = Q[2] - temp.z; Rq[3, 0] = Rq[3, 1] = Rq[3, 2] = 0.0f; Rq[3, 3] = 1.0f; } void RotateOnePoint(ref Vector3 Pin, Vector3 Q, Vector3 W, float Theta) { Matrix4x4 Rq = Matrix4x4.identity; Vector4 Pout = Vector3.zero; Vector4 Pby4; SetUpRotation(Q, W, Theta, ref Rq); Pby4 = Pin; Pby4[3] = 1.0f; Mult1X4(Pby4, Rq, ref Pout); Pin = Pout; } Vector3 endp1 = Vector3.zero; Vector3 endp2 = Vector3.zero; Vector3 endr1 = Vector3.zero; Vector3 endr2 = Vector3.zero; public Vector3[] SaveVertex; public Vector2[] SaveUV; public Vector3[] SaveNormals; public bool rebuildcross = true; public int NvertsPerRing = 0; public int Nverts = 0; void Update() { if ( animatebulge ) { if ( Application.isPlaying ) bulgeoffset += bulgespeed * Time.deltaTime; if ( bulgeoffset > maxbulge ) bulgeoffset -= maxbulge - minbulge; if ( bulgeoffset < minbulge ) bulgeoffset += maxbulge - minbulge; updatemesh = true; } if ( custnode ) { if ( custnode.transform.position != endp1 ) { endp1 = custnode.transform.position; updatemesh = true; } if ( custnode.transform.eulerAngles != endr1 ) { endr1 = custnode.transform.eulerAngles; updatemesh = true; } } if ( custnode2 ) { if ( custnode2.transform.position != endp2 ) { endp1 = custnode2.transform.position; updatemesh = true; } if ( custnode2.transform.eulerAngles != endr2 ) { endr2 = custnode2.transform.eulerAngles; updatemesh = true; } } if ( !dolateupdate ) { if ( visible || InvisibleUpdate ) { // Check transforms so we dont update unless we have to if ( updatemesh ) //|| Application.isEditor ) { updatemesh = false; BuildMesh(); } } } } void LateUpdate() { if ( dolateupdate ) { if ( visible || InvisibleUpdate ) { // Check transforms so we dont update unless we have to if ( updatemesh ) //|| Application.isEditor ) { updatemesh = false; BuildMesh(); } } } } public Vector3 up = Vector3.up; Vector3 starty = Vector3.zero; Vector3 roty = Vector3.zero; float yangle = 0.0f; public Matrix4x4 Tlocal = Matrix4x4.identity; // we only need to build the savevertex and uvs if mesh def changes, else we can keep the uvs void BuildMesh() { if ( !mesh ) { mesh = GetComponent<MeshFilter>().sharedMesh; if ( mesh == null ) { updatemesh = true; return; } } if ( hosespline.knots.Count == 0 ) { hosespline.AddKnot(Vector3.zero, Vector3.zero, Vector3.zero); hosespline.AddKnot(Vector3.zero, Vector3.zero, Vector3.zero); } FixHoseFillet(); bool createfree = freecreate; if ( (!createfree) && ((!custnode) || (!custnode2)) ) createfree = true; if ( custnode && custnode2 ) createfree = false; Matrix4x4 mat1,mat2; float Lf = 0.0f; Tlocal = Matrix4x4.identity; Vector3 startvec, endvec, startpoint, endpoint, endy; starty = Vector3.zero; roty = Vector3.zero; yangle = 0.0f; Vector3 RV = Vector3.zero; if ( createfree ) Lf = noreflength; else { RV = up; //new Vector3(xtmp, ytmp, ztmp); mat1 = custnode.transform.localToWorldMatrix; mat2 = custnode2.transform.localToWorldMatrix; Matrix4x4 mato1 = Matrix4x4.identity; Matrix4x4 mato2 = Matrix4x4.identity; mato1 = Matrix4x4.TRS(offset, Quaternion.Euler(rotate), scale); mato1 = mato1.inverse; mato2 = Matrix4x4.TRS(offset1, Quaternion.Euler(rotate1), scale1); mato2 = mato2.inverse; S = transform.localToWorldMatrix; Matrix4x4 mat1NT, mat2NT; mat1NT = mat1; mat2NT = mat2; MegaMatrix.NoTrans(ref mat1NT); MegaMatrix.NoTrans(ref mat2NT); Vector3 P1 = mat1.MultiplyPoint(mato1.GetColumn(3)); Vector3 P2 = mat2.MultiplyPoint(mato2.GetColumn(3)); startvec = mat1NT.MultiplyPoint(mato1.GetColumn(2)); endvec = mat2NT.MultiplyPoint(mato2.GetColumn(2)); starty = mat1NT.MultiplyPoint(mato1.GetColumn(1)); endy = mat2NT.MultiplyPoint(mato2.GetColumn(1)); Matrix4x4 SI = S.inverse; Vector3 P0 = SI.MultiplyPoint(P1); Matrix4x4 T1 = mat1; MegaMatrix.NoTrans(ref T1); Vector3 RVw = T1.MultiplyPoint(RV); Lf = (P2 - P1).magnitude; Vector3 Zw; if ( Lf < 0.01f ) Zw = P1.normalized; else Zw = (P2 - P1).normalized; Vector3 Xw = Vector3.Cross(RVw, Zw).normalized; Vector3 Yw = Vector3.Cross(Zw, Xw).normalized; MegaMatrix.NoTrans(ref SI); Vector3 Xs = SI.MultiplyPoint(Xw); Vector3 Ys = SI.MultiplyPoint(Yw); Vector3 Zs = SI.MultiplyPoint(Zw); Tlocal.SetColumn(0, Xs); Tlocal.SetColumn(1, Ys); Tlocal.SetColumn(2, Zs); MegaMatrix.SetTrans(ref Tlocal, P0); // move z-axes of end transforms into local frame Matrix4x4 TlocalInvNT = Tlocal; MegaMatrix.NoTrans(ref TlocalInvNT); TlocalInvNT = TlocalInvNT.inverse; float tenstop = tension1; // * 0.01f; float tensbot = tension2; // * 0.01f; startvec = tensbot * (TlocalInvNT.MultiplyPoint(startvec)); endvec = tenstop * (TlocalInvNT.MultiplyPoint(endvec)); starty = TlocalInvNT.MultiplyPoint(starty); endy = TlocalInvNT.MultiplyPoint(endy); yangle = Mathf.Acos(Vector3.Dot(starty, endy)); if ( yangle > EPSILON ) roty = Vector3.Cross(starty, endy).normalized; else roty = Vector3.zero; startpoint = Vector3.zero; endpoint = new Vector3(0.0f, 0.0f, Lf); hosespline.knots[0].p = startpoint; hosespline.knots[0].invec = startpoint - startvec; hosespline.knots[0].outvec = startpoint + startvec; hosespline.knots[1].p = endpoint; hosespline.knots[1].invec = endpoint + endvec; hosespline.knots[1].outvec = endpoint - endvec; hosespline.CalcLength(); //10); } MegaHoseType wtype = wiretype; int Segs = segments; if ( Segs < 3 ) Segs = 3; if ( rebuildcross ) { rebuildcross = false; int nfillets = 0; int nsides = 0; if ( wtype == MegaHoseType.Round ) { NvertsPerRing = rndsides; if ( NvertsPerRing < 3 ) NvertsPerRing = 3; } else { if ( wtype == MegaHoseType.Rectangle ) { nfillets = rectfilletsides; if ( nfillets < 0 ) nfillets = 0; if ( smooth == MegaHoseSmooth.SMOOTHNONE ) NvertsPerRing = (nfillets > 0 ? 8 + 4 * (nfillets - 1) : 8); else NvertsPerRing = (nfillets > 0 ? 8 + 4 * (nfillets - 1) : 4); //4); } else { nfillets = dsecfilletsides; if ( nfillets < 0 ) nfillets = 0; nsides = dsecrndsides; if ( nsides < 2 ) nsides = 2; int nsm1 = nsides - 1; NvertsPerRing = (nfillets > 0 ? 6 + nsm1 + 2 * (nfillets - 1): 4 + nsm1); } } NvertsPerRing++; int NfacesPerEnd,NfacesPerRing,Nfaces = 0; //MegaHoseSmooth SMOOTH = smooth; Nverts = (Segs + 1) * (NvertsPerRing + 1); // + 2; if ( capends ) Nverts += 2; NfacesPerEnd = NvertsPerRing; NfacesPerRing = 6 * NvertsPerRing; Nfaces = Segs * NfacesPerRing; // + 2 * NfacesPerEnd; if ( capends ) { Nfaces += 2 * NfacesPerEnd; } if ( SaveVertex == null || SaveVertex.Length != NvertsPerRing ) { SaveVertex = new Vector3[NvertsPerRing]; SaveUV = new Vector2[NvertsPerRing]; } if ( calcnormals ) { if ( SaveNormals == null || SaveNormals.Length != NvertsPerRing ) SaveNormals = new Vector3[NvertsPerRing]; } MakeSaveVertex(NvertsPerRing, nfillets, nsides, wtype); if ( verts == null || verts.Length != Nverts ) { verts = new Vector3[Nverts]; uvs = new Vector2[Nverts]; faces = new int[Nfaces * 3]; } if ( calcnormals && (normals == null || normals.Length != Nverts) ) normals = new Vector3[Nverts]; } if ( Nverts == 0 ) return; bool mapmenow = mapmemapme; int thisvert = 0; int last = Nverts - 1; int last2 = last - 1; int lastvpr = NvertsPerRing; // - 1; int maxseg = Segs + 1; float flexhere; float dadjust; float flexlen; float flex1 = flexstart; float flex2 = flexstop; int flexn = flexcycles; float flexd = flexdiameter; Vector3 ThisPosition; Vector3 ThisXAxis, ThisYAxis, ThisZAxis; Vector2 uv = Vector2.zero; Matrix4x4 RingTM = Matrix4x4.identity; Matrix4x4 invRingTM = Matrix4x4.identity; for ( int i = 0; i < maxseg; i++ ) { float incr = (float)i / (float)Segs; if ( createfree ) { ThisPosition = new Vector3(0.0f, 0.0f, Lf * incr); ThisXAxis = new Vector3(1.0f, 0.0f, 0.0f); ThisYAxis = new Vector3(0.0f, 1.0f, 0.0f); ThisZAxis = new Vector3(0.0f, 0.0f, 1.0f); } else { int k = 0; ThisPosition = hosespline.InterpCurve3D(incr, true, ref k); ThisZAxis = (hosespline.InterpCurve3D(incr + 0.001f, true, ref k) - ThisPosition).normalized; ThisYAxis = starty; if ( yangle > EPSILON ) RotateOnePoint(ref ThisYAxis, Vector3.zero, roty, incr * yangle); ThisXAxis = Vector3.Cross(ThisYAxis, ThisZAxis).normalized; ThisYAxis = Vector3.Cross(ThisZAxis, ThisXAxis); } RingTM.SetColumn(0, ThisXAxis); RingTM.SetColumn(1, ThisYAxis); RingTM.SetColumn(2, ThisZAxis); MegaMatrix.SetTrans(ref RingTM, ThisPosition); if ( !createfree ) { RingTM = Tlocal * RingTM; } if ( calcnormals ) { invRingTM = RingTM; MegaMatrix.NoTrans(ref invRingTM); //invRingTM = invRingTM.inverse.transpose; } if ( (incr > flex1) && (incr < flex2) && flexon ) { flexlen = flex2 - flex1; if ( flexlen < 0.01f ) flexlen = 0.01f; flexhere = (incr - flex1) / flexlen; float ang = (float)flexn * flexhere * (Mathf.PI * 2.0f) + PIover2; dadjust = 1.0f + flexd * (1.0f - Mathf.Sin(ang)); //(float)flexn * flexhere * (Mathf.PI * 2.0f) + PIover2)); } else dadjust = 0.0f; if ( usebulgecurve ) { if ( dadjust == 0.0f ) dadjust = 1.0f + (bulge.Evaluate(incr + bulgeoffset) * bulgeamount); else dadjust += bulge.Evaluate(incr + bulgeoffset) * bulgeamount; } uv.x = 0.999999f * incr * uvscale.x; for ( int j = 0; j < NvertsPerRing; j++ ) { int jj = j; // % NvertsPerRing; if ( mapmenow ) { uv.y = SaveUV[jj].y; uvs[thisvert] = uv; //new Vector2(0.999999f * incr * uvscale.x, SaveUV[jj].y); } if ( dadjust != 0.0f ) { verts[thisvert] = RingTM.MultiplyPoint(dadjust * SaveVertex[jj]); } else { verts[thisvert] = RingTM.MultiplyPoint(SaveVertex[jj]); } if ( calcnormals ) normals[thisvert] = invRingTM.MultiplyPoint(SaveNormals[jj]).normalized; //.MultiplyPoint(-SaveNormals[jj]); //if ( j == 0 ) //{ // Debug.Log("norm " + normals[thisvert].ToString("0.000") + " save " + SaveNormals[jj].ToString("0.000")); //} thisvert++; } if ( mapmenow ) { //uvs[Nverts + i] = new Vector2(0.999999f * incr, 0.999f); } if ( capends ) { if ( i == 0 ) { verts[last2] = (createfree ? ThisPosition : Tlocal.MultiplyPoint(ThisPosition)); if ( mapmenow ) uvs[last2] = Vector3.zero; } else { if ( i == Segs ) { verts[last] = createfree ? ThisPosition : Tlocal.MultiplyPoint(ThisPosition); if ( mapmenow ) { uvs[last] = Vector3.zero; } } } } } // Now, set up the faces int thisface = 0, v1, v2, v3, v4; v3 = last2; if ( capends ) { for ( int i = 0; i < NvertsPerRing - 1; i++ ) { v1 = i; v2 = (i < lastvpr ? v1 + 1 : v1 - lastvpr); //v5 = (i < lastvpr ? v2 : Nverts); faces[thisface++] = v2; faces[thisface++] = v1; faces[thisface++] = v3; } } int ringnum = NvertsPerRing; // + 1; for ( int i = 0; i < Segs; i++ ) { for ( int j = 0; j < NvertsPerRing - 1; j++ ) { v1 = i * ringnum + j; v2 = v1 + 1; //(j < lastvpr? v1 + 1 : v1 - lastvpr); v4 = v1 + ringnum; v3 = v2 + ringnum; faces[thisface++] = v1; faces[thisface++] = v2; faces[thisface++] = v3; faces[thisface++] = v1; faces[thisface++] = v3; faces[thisface++] = v4; } } int basevert = Segs * ringnum; //NvertsPerRing; v3 = Nverts - 1; if ( capends ) { for ( int i = 0; i < NvertsPerRing - 1; i++ ) { v1 = i + basevert; v2 = (i < lastvpr? v1 + 1 : v1 - lastvpr); //v5 = (i < lastvpr? v2 : Nverts + Segs); faces[thisface++] = v1; faces[thisface++] = v2; faces[thisface++] = v3; } } mesh.Clear(); mesh.subMeshCount = 1; mesh.vertices = verts; mesh.uv = uvs; mesh.triangles = faces; if ( calcnormals ) mesh.normals = normals; else mesh.RecalculateNormals(); mesh.RecalculateBounds(); #if UNITY_5_5 || UNITY_5_6 || UNITY_2017 #else if ( optimize ) mesh.Optimize(); #endif if ( calctangents ) { MegaUtils.BuildTangents(mesh); } if ( recalcCollider ) { if ( meshCol == null ) meshCol = GetComponent<MeshCollider>(); if ( meshCol != null ) { meshCol.sharedMesh = null; meshCol.sharedMesh = mesh; //bool con = meshCol.convex; //meshCol.convex = con; } } } public void CalcMatrix(ref Matrix4x4 mat, float incr) { #if false Matrix4x4 RingTM = Matrix4x4.identity; Matrix4x4 invRingTM = Matrix4x4.identity; int k = 0; Vector3 ThisPosition = hosespline.InterpCurve3D(incr, true, ref k); Vector3 ThisZAxis = (hosespline.InterpCurve3D(incr + 0.001f, true, ref k) - ThisPosition).normalized; Vector3 ThisYAxis = starty; if ( yangle > EPSILON ) RotateOnePoint(ref ThisYAxis, Vector3.zero, roty, incr * yangle); Vector3 ThisXAxis = Vector3.Cross(ThisYAxis, ThisZAxis).normalized; ThisYAxis = Vector3.Cross(ThisZAxis, ThisXAxis); RingTM.SetColumn(0, ThisXAxis); RingTM.SetColumn(1, ThisYAxis); RingTM.SetColumn(2, ThisZAxis); MegaMatrix.SetTrans(ref RingTM, ThisPosition); #endif mat = Tlocal; // * RingTM; } MeshCollider meshCol; static float findmappos(float curpos) { float mappos; return (mappos = ((mappos = curpos) < 0.0f ? 0.0f : (mappos > 1.0f ? 1.0f : mappos))); } void DisplayNormals() { } public Vector3 GetPosition(float alpha) { Matrix4x4 RingTM = transform.localToWorldMatrix * Tlocal; int k = 0; return RingTM.MultiplyPoint(hosespline.InterpCurve3D(alpha, true, ref k)); } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: api@oanda.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// A ClientConfigureTransaction represents the configuration of an Account by a client. /// </summary> [DataContract] public partial class ClientConfigureTransaction : IEquatable<ClientConfigureTransaction>, IValidatableObject { /// <summary> /// The Type of the Transaction. Always set to \"CLIENT_CONFIGURE\" in a ClientConfigureTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"CLIENT_CONFIGURE\" in a ClientConfigureTransaction.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } /// <summary> /// The Type of the Transaction. Always set to \"CLIENT_CONFIGURE\" in a ClientConfigureTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"CLIENT_CONFIGURE\" in a ClientConfigureTransaction.</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ClientConfigureTransaction" /> class. /// </summary> /// <param name="Id">The Transaction&#39;s Identifier..</param> /// <param name="Time">The date/time when the Transaction was created..</param> /// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param> /// <param name="AccountID">The ID of the Account the Transaction was created for..</param> /// <param name="BatchID">The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param> /// <param name="RequestID">The Request ID of the request which generated the transaction..</param> /// <param name="Type">The Type of the Transaction. Always set to \&quot;CLIENT_CONFIGURE\&quot; in a ClientConfigureTransaction..</param> /// <param name="Alias">The client-provided alias for the Account..</param> /// <param name="MarginRate">The margin rate override for the Account..</param> public ClientConfigureTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?), string Alias = default(string), string MarginRate = default(string)) { this.Id = Id; this.Time = Time; this.UserID = UserID; this.AccountID = AccountID; this.BatchID = BatchID; this.RequestID = RequestID; this.Type = Type; this.Alias = Alias; this.MarginRate = MarginRate; } /// <summary> /// The Transaction&#39;s Identifier. /// </summary> /// <value>The Transaction&#39;s Identifier.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The date/time when the Transaction was created. /// </summary> /// <value>The date/time when the Transaction was created.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// The ID of the user that initiated the creation of the Transaction. /// </summary> /// <value>The ID of the user that initiated the creation of the Transaction.</value> [DataMember(Name="userID", EmitDefaultValue=false)] public int? UserID { get; set; } /// <summary> /// The ID of the Account the Transaction was created for. /// </summary> /// <value>The ID of the Account the Transaction was created for.</value> [DataMember(Name="accountID", EmitDefaultValue=false)] public string AccountID { get; set; } /// <summary> /// The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously. /// </summary> /// <value>The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value> [DataMember(Name="batchID", EmitDefaultValue=false)] public string BatchID { get; set; } /// <summary> /// The Request ID of the request which generated the transaction. /// </summary> /// <value>The Request ID of the request which generated the transaction.</value> [DataMember(Name="requestID", EmitDefaultValue=false)] public string RequestID { get; set; } /// <summary> /// The client-provided alias for the Account. /// </summary> /// <value>The client-provided alias for the Account.</value> [DataMember(Name="alias", EmitDefaultValue=false)] public string Alias { get; set; } /// <summary> /// The margin rate override for the Account. /// </summary> /// <value>The margin rate override for the Account.</value> [DataMember(Name="marginRate", EmitDefaultValue=false)] public string MarginRate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ClientConfigureTransaction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" UserID: ").Append(UserID).Append("\n"); sb.Append(" AccountID: ").Append(AccountID).Append("\n"); sb.Append(" BatchID: ").Append(BatchID).Append("\n"); sb.Append(" RequestID: ").Append(RequestID).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Alias: ").Append(Alias).Append("\n"); sb.Append(" MarginRate: ").Append(MarginRate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ClientConfigureTransaction); } /// <summary> /// Returns true if ClientConfigureTransaction instances are equal /// </summary> /// <param name="other">Instance of ClientConfigureTransaction to be compared</param> /// <returns>Boolean</returns> public bool Equals(ClientConfigureTransaction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Time == other.Time || this.Time != null && this.Time.Equals(other.Time) ) && ( this.UserID == other.UserID || this.UserID != null && this.UserID.Equals(other.UserID) ) && ( this.AccountID == other.AccountID || this.AccountID != null && this.AccountID.Equals(other.AccountID) ) && ( this.BatchID == other.BatchID || this.BatchID != null && this.BatchID.Equals(other.BatchID) ) && ( this.RequestID == other.RequestID || this.RequestID != null && this.RequestID.Equals(other.RequestID) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.Alias == other.Alias || this.Alias != null && this.Alias.Equals(other.Alias) ) && ( this.MarginRate == other.MarginRate || this.MarginRate != null && this.MarginRate.Equals(other.MarginRate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Time != null) hash = hash * 59 + this.Time.GetHashCode(); if (this.UserID != null) hash = hash * 59 + this.UserID.GetHashCode(); if (this.AccountID != null) hash = hash * 59 + this.AccountID.GetHashCode(); if (this.BatchID != null) hash = hash * 59 + this.BatchID.GetHashCode(); if (this.RequestID != null) hash = hash * 59 + this.RequestID.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.Alias != null) hash = hash * 59 + this.Alias.GetHashCode(); if (this.MarginRate != null) hash = hash * 59 + this.MarginRate.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { /// <summary> /// Most methods of this class are synchronized since they might be called both /// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory. /// </summary> internal class GrainDirectoryHandoffManager { private static readonly TimeSpan RetryDelay = TimeSpan.FromMilliseconds(250); private const int MAX_OPERATION_DEQUEUE = 2; private readonly LocalGrainDirectory localDirectory; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap; private readonly List<SiloAddress> silosHoldingMyPartition; private readonly Dictionary<SiloAddress, Task> lastPromise; private readonly ILogger logger; private readonly Factory<GrainDirectoryPartition> createPartion; private readonly Queue<(string name, Func<Task> action)> pendingOperations = new Queue<(string name, Func<Task> action)>(); private readonly AsyncLock executorLock = new AsyncLock(); internal GrainDirectoryHandoffManager( LocalGrainDirectory localDirectory, ISiloStatusOracle siloStatusOracle, IInternalGrainFactory grainFactory, Factory<GrainDirectoryPartition> createPartion, ILoggerFactory loggerFactory) { logger = loggerFactory.CreateLogger<GrainDirectoryHandoffManager>(); this.localDirectory = localDirectory; this.siloStatusOracle = siloStatusOracle; this.grainFactory = grainFactory; this.createPartion = createPartion; directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>(); silosHoldingMyPartition = new List<SiloAddress>(); lastPromise = new Dictionary<SiloAddress, Task>(); } internal void ProcessSiloRemoveEvent(SiloAddress removedSilo) { lock (this) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo remove event for " + removedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I hold this silo's copy) // (if yes, adjust local and/or handoffed directory partitions) if (!directoryPartitionsMap.TryGetValue(removedSilo, out var partition)) return; // at least one predcessor should exist, which is me SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0]; Dictionary<SiloAddress, List<ActivationAddress>> duplicates; if (localDirectory.MyAddress.Equals(predecessor)) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging my partition with the copy of silo " + removedSilo); // now I am responsible for this directory part duplicates = localDirectory.DirectoryPartition.Merge(partition); // no need to send our new partition to all others, as they // will realize the change and combine their copies without any additional communication (see below) } else { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging partition of " + predecessor + " with the copy of silo " + removedSilo); // adjust copy for the predecessor of the failed silo duplicates = directoryPartitionsMap[predecessor].Merge(partition); } if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removed copied partition of silo " + removedSilo); directoryPartitionsMap.Remove(removedSilo); DestroyDuplicateActivations(duplicates); } } internal void ProcessSiloAddEvent(SiloAddress addedSilo) { lock (this) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo add event for " + addedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I should hold this silo's copy) // (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one) // NOTE: We need to move part of our local directory to the new silo if it is an immediate successor. List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1); if (!successors.Contains(addedSilo)) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"{addedSilo} is not one of my successors."); return; } // check if this is an immediate successor if (successors[0].Equals(addedSilo)) { // split my local directory and send to my new immediate successor his share if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting my partition between me and " + addedSilo); GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split( grain => { var s = localDirectory.CalculateGrainDirectoryPartition(grain); return (s != null) && !localDirectory.MyAddress.Equals(s); }, false); List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(); EnqueueOperation( $"{nameof(ProcessSiloAddEvent)}({addedSilo})", () => ProcessAddedSiloAsync(addedSilo, splitPartListSingle)); } else { // adjust partitions by splitting them accordingly between new and old silos SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0]; if (!directoryPartitionsMap.TryGetValue(predecessorOfNewSilo, out var predecessorPartition)) { // we should have the partition of the predcessor of our new successor logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo); } else { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo); GrainDirectoryPartition splitPart = predecessorPartition.Split( grain => { // Need to review the 2nd line condition. var s = localDirectory.CalculateGrainDirectoryPartition(grain); return (s != null) && !predecessorOfNewSilo.Equals(s); }, true); directoryPartitionsMap[addedSilo] = splitPart; } } // remove partition of one of the old successors that we do not need to now SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key; if (oldSuccessor == null) return; if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)"); directoryPartitionsMap.Remove(oldSuccessor); } } private async Task ProcessAddedSiloAsync(SiloAddress addedSilo, List<ActivationAddress> splitPartListSingle) { if (!this.localDirectory.Running) return; if (this.siloStatusOracle.GetApproximateSiloStatus(addedSilo) == SiloStatus.Active) { if (splitPartListSingle.Count > 0) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo); } await localDirectory.GetDirectoryReference(addedSilo).AcceptSplitPartition(splitPartListSingle); } else { if (logger.IsEnabled(LogLevel.Warning)) logger.LogWarning("Silo " + addedSilo + " is no longer active and therefore cannot receive this partition split"); return; } if (splitPartListSingle.Count > 0) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing " + splitPartListSingle.Count + " single activation after partition split"); splitPartListSingle.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); } } internal void AcceptExistingRegistrations(List<ActivationAddress> singleActivations) { this.EnqueueOperation( nameof(AcceptExistingRegistrations), () => AcceptExistingRegistrationsAsync(singleActivations)); } private async Task AcceptExistingRegistrationsAsync(List<ActivationAddress> singleActivations) { if (!this.localDirectory.Running) return; if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.LogDebug( $"{nameof(AcceptExistingRegistrations)}: accepting {singleActivations?.Count ?? 0} single-activation registrations"); } if (singleActivations != null && singleActivations.Count > 0) { var tasks = singleActivations.Select(addr => this.localDirectory.RegisterAsync(addr, 1)).ToArray(); try { await Task.WhenAll(tasks); } catch (Exception exception) { if (this.logger.IsEnabled(LogLevel.Warning)) this.logger.LogWarning($"Exception registering activations in {nameof(AcceptExistingRegistrations)}: {LogFormatter.PrintException(exception)}"); throw; } finally { Dictionary<SiloAddress, List<ActivationAddress>> duplicates = new Dictionary<SiloAddress, List<ActivationAddress>>(); for (var i = tasks.Length - 1; i >= 0; i--) { // Retry failed tasks next time. if (tasks[i].Status != TaskStatus.RanToCompletion) continue; // Record the applications which lost the registration race (duplicate activations). var winner = await tasks[i]; if (!winner.Address.Equals(singleActivations[i])) { var duplicate = singleActivations[i]; if (!duplicates.TryGetValue(duplicate.Silo, out var activations)) { activations = duplicates[duplicate.Silo] = new List<ActivationAddress>(1); } activations.Add(duplicate); } // Remove tasks which completed. singleActivations.RemoveAt(i); } // Destroy any duplicate activations. DestroyDuplicateActivations(duplicates); } } } internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, GrainInfo> partition, bool isFullCopy) { lock (this) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source); if (!directoryPartitionsMap.TryGetValue(source, out var sourcePartition)) { if (!isFullCopy) { logger.Warn(ErrorCode.DirectoryUnexpectedDelta, String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}", source, this.siloStatusOracle.GetApproximateSiloStatus(source), this.siloStatusOracle.GetApproximateSiloStatuses(true).Count)); } directoryPartitionsMap[source] = sourcePartition = this.createPartion(); } if (isFullCopy) { sourcePartition.Set(partition); } else { sourcePartition.Update(partition); } } } internal void RemoveHandoffPartition(SiloAddress source) { lock (this) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to unregister directory partition copy from " + source); directoryPartitionsMap.Remove(source); } } private void ResetFollowers() { var copyList = silosHoldingMyPartition.ToList(); foreach (var follower in copyList) { RemoveOldFollower(follower); } } private void RemoveOldFollower(SiloAddress silo) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing my copy from silo " + silo); // release this old copy, as we have got a new one silosHoldingMyPartition.Remove(silo); localDirectory.RemoteGrainDirectory.QueueTask(() => localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress)) .Ignore(); } private void DestroyDuplicateActivations(Dictionary<SiloAddress, List<ActivationAddress>> duplicates) { if (duplicates == null || duplicates.Count == 0) return; this.EnqueueOperation( nameof(DestroyDuplicateActivations), () => DestroyDuplicateActivationsAsync(duplicates)); } private async Task DestroyDuplicateActivationsAsync(Dictionary<SiloAddress, List<ActivationAddress>> duplicates) { while (duplicates.Count > 0) { var pair = duplicates.FirstOrDefault(); if (this.siloStatusOracle.GetApproximateSiloStatus(pair.Key) == SiloStatus.Active) { if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.LogDebug( $"{nameof(DestroyDuplicateActivations)} will destroy {duplicates.Count} duplicate activations on silo {pair.Key}: {string.Join("\n * ", pair.Value.Select(_ => _))}"); } var remoteCatalog = this.grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogType, pair.Key); await remoteCatalog.DeleteActivations(pair.Value); } duplicates.Remove(pair.Key); } } private void EnqueueOperation(string name, Func<Task> action) { lock (this) { this.pendingOperations.Enqueue((name, action)); if (this.pendingOperations.Count <= 2) { this.localDirectory.RemoteGrainDirectory.QueueTask(this.ExecutePendingOperations); } } } private async Task ExecutePendingOperations() { using (await executorLock.LockAsync()) { var dequeueCount = 0; while (true) { // Get the next operation, or exit if there are none. (string Name, Func<Task> Action) op; lock (this) { if (this.pendingOperations.Count == 0) break; op = this.pendingOperations.Peek(); } dequeueCount++; try { await op.Action(); // Success, reset the dequeue count dequeueCount = 0; } catch (Exception exception) { if (dequeueCount < MAX_OPERATION_DEQUEUE) { if (this.logger.IsEnabled(LogLevel.Warning)) this.logger.LogWarning($"{op.Name} failed, will be retried: {LogFormatter.PrintException(exception)}."); await Task.Delay(RetryDelay); } else { if (this.logger.IsEnabled(LogLevel.Warning)) this.logger.LogWarning($"{op.Name} failed, will NOT be retried: {LogFormatter.PrintException(exception)}"); } } if (dequeueCount == 0 || dequeueCount >= MAX_OPERATION_DEQUEUE) { lock (this) { // Remove the operation from the queue if it was a success // or if we tried too many times this.pendingOperations.Dequeue(); } } } } } } }
// 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.Linq; using System.Globalization; using System.Collections.Generic; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; using System.Security.Cryptography.Pkcs.Tests; namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests { public static partial class EdgeCasesTests { [Fact] public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); try { ecms.Encrypt(cmsRecipient); } catch (CryptographicException e) { throw new Exception("ecms.Encrypt() threw " + e.Message + ".\nIf you're running on the desktop CLR, this is actually an expected result."); } } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); } [Fact] public static void ZeroLengthContent_FixedValue() { byte[] encodedMessage = ("3082010406092a864886f70d010703a081f63081f30201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818009" + "c16b674495c2c3d4763189c3274cf7a9142fbeec8902abdc9ce29910d541df910e029a31443dc9a9f3b05f02da1c38478c40" + "0261c734d6789c4197c20143c4312ceaa99ecb1849718326d4fc3b7fbb2d1d23281e31584a63e99f2c17132bcd8eddb63296" + "7125cd0a4baa1efa8ce4c855f7c093339211bdf990cef5cce6cd74302306092a864886f70d010701301406082a864886f70d" + "03070408779b3de045826b188000").HexToByteArray(); ValidateZeroLengthContent(encodedMessage); } [Fact] public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); } private static void ValidateZeroLengthContent(byte[] encodedMessage) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; byte[] content = contentInfo.Content; if (content.Length == 6) throw new Exception("ContentInfo expected to be 0 but was actually 6. If you're running on the desktop CLR, this is actually a known bug."); Assert.Equal(0, content.Length); } } [Fact] public static void ReuseEnvelopeCmsEncodeThenDecode() { // Test ability to encrypt, encode and decode all in one EnvelopedCms instance. ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void ReuseEnvelopeCmsDecodeThenEncode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void EnvelopedCmsNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null)); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null, new AlgorithmIdentifier(new Oid(Oids.TripleDesCbc)))); } [Fact] public static void EnvelopedCmsNullAlgorithm() { object ignore; ContentInfo contentInfo = new ContentInfo(new byte[3]); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(contentInfo, null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipient() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipient)null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipientCollection)null)); } [Fact] public static void EnvelopedCmsEncryptWithZeroRecipients() { // On the desktop, this throws up a UI for the user to select a recipient. We don't support that. EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<PlatformNotSupportedException>(() => ecms.Encrypt(new CmsRecipientCollection())); } [Fact] public static void EnvelopedCmsNullDecode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<ArgumentNullException>(() => ecms.Decode(null)); } [Fact] public static void EnvelopedCmsDecryptNullary() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt()); } [Fact] public static void EnvelopedCmsDecryptNullRecipient() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = null; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptNullExtraStore() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = null; Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptWithoutMatchingCert() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptWithoutMatchingCertSki() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void AlgorithmIdentifierNullaryCtor() { AlgorithmIdentifier a = new AlgorithmIdentifier(); Assert.Equal(Oids.TripleDesCbc, a.Oid.Value); Assert.Equal(0, a.KeyLength); } [Fact] public static void CmsRecipient1AryCtor() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassUnknown() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassNullCertificate() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(null)); Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void ContentInfoNullOid() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, new byte[3])); } [Fact] public static void ContentInfoNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null)); Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, null)); } [Fact] public static void ContentInfoGetContentTypeNull() { Assert.Throws<ArgumentNullException>(() => ContentInfo.GetContentType(null)); } [Fact] public static void CryptographicAttributeObjectOidCtor() { Oid oid = new Oid(Oids.DocumentDescription); CryptographicAttributeObject cao = new CryptographicAttributeObject(oid); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectPassNullValuesToCtor() { Oid oid = new Oid(Oids.DocumentDescription); // This is legal and equivalent to passing a zero-length AsnEncodedDataCollection. CryptographicAttributeObject cao = new CryptographicAttributeObject(oid, null); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectMismatch() { Oid oid = new Oid(Oids.DocumentDescription); Oid wrongOid = new Oid(Oids.DocumentName); AsnEncodedDataCollection col = new AsnEncodedDataCollection(); col.Add(new AsnEncodedData(oid, new byte[3])); object ignore; Assert.Throws<InvalidOperationException>(() => ignore = new CryptographicAttributeObject(wrongOid, col)); } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// gRPC server. A single server can serve an arbitrary number of services and can listen on more than one port. /// </summary> public class Server { const int DefaultRequestCallTokensPerCq = 2000; static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly ServiceDefinitionCollection serviceDefinitions; readonly ServerPortCollection ports; readonly GrpcEnvironment environment; readonly List<ChannelOption> options; readonly ServerSafeHandle handle; readonly object myLock = new object(); readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>(); readonly List<ServerPort> serverPortList = new List<ServerPort>(); readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); bool startRequested; volatile bool shutdownRequested; int requestCallTokensPerCq = DefaultRequestCallTokensPerCq; /// <summary> /// Creates a new server. /// </summary> public Server() : this(null) { } /// <summary> /// Creates a new server. /// </summary> /// <param name="options">Channel options.</param> public Server(IEnumerable<ChannelOption> options) { this.serviceDefinitions = new ServiceDefinitionCollection(this); this.ports = new ServerPortCollection(this); this.environment = GrpcEnvironment.AddRef(); this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>(); using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options)) { this.handle = ServerSafeHandle.NewServer(channelArgs); } foreach (var cq in environment.CompletionQueues) { this.handle.RegisterCompletionQueue(cq); } GrpcEnvironment.RegisterServer(this); } /// <summary> /// Services that will be exported by the server once started. Register a service with this /// server by adding its definition to this collection. /// </summary> public ServiceDefinitionCollection Services { get { return serviceDefinitions; } } /// <summary> /// Ports on which the server will listen once started. Register a port with this /// server by adding its definition to this collection. /// </summary> public ServerPortCollection Ports { get { return ports; } } /// <summary> /// To allow awaiting termination of the server. /// </summary> public Task ShutdownTask { get { return shutdownTcs.Task; } } /// <summary> /// Experimental API. Might anytime change without prior notice. /// Number or calls requested via grpc_server_request_call at any given time for each completion queue. /// </summary> public int RequestCallTokensPerCompletionQueue { get { return requestCallTokensPerCq; } set { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckArgument(value > 0); requestCallTokensPerCq = value; } } } /// <summary> /// Starts the server. /// Throws <c>IOException</c> if not successful. /// </summary> public void Start() { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckState(!shutdownRequested); startRequested = true; CheckPortsBoundSuccessfully(); handle.Start(); for (int i = 0; i < requestCallTokensPerCq; i++) { foreach (var cq in environment.CompletionQueues) { AllowOneRpc(cq); } } } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. The returned task finishes when shutdown procedure /// is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task ShutdownAsync() { return ShutdownInternalAsync(false); } /// <summary> /// Requests server shutdown while cancelling all the in-progress calls. /// The returned task finishes when shutdown procedure is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task KillAsync() { return ShutdownInternalAsync(true); } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); GrpcPreconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } /// <summary> /// Shuts down the server. /// </summary> private async Task ShutdownInternalAsync(bool kill) { lock (myLock) { GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } GrpcEnvironment.UnregisterServer(this); var cq = environment.CompletionQueues.First(); // any cq will do handle.ShutdownAndNotify(HandleServerShutdown, cq); if (kill) { handle.CancelAllCalls(); } await ShutdownCompleteOrEnvironmentDeadAsync().ConfigureAwait(false); DisposeHandle(); await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false); } /// <summary> /// In case the environment's threadpool becomes dead, the shutdown completion will /// never be delivered, but we need to release the environment's handle anyway. /// </summary> private async Task ShutdownCompleteOrEnvironmentDeadAsync() { while (true) { var task = await Task.WhenAny(shutdownTcs.Task, Task.Delay(20)).ConfigureAwait(false); if (shutdownTcs.Task == task) { return; } if (!environment.IsAlive) { return; } } } /// <summary> /// Adds a service definition. /// </summary> private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition) { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); foreach (var entry in serviceDefinition.GetCallHandlers()) { callHandlers.Add(entry.Key, entry.Value); } serviceDefinitionsList.Add(serviceDefinition); } } /// <summary> /// Adds a listening port. /// </summary> private int AddPortInternal(ServerPort serverPort) { lock (myLock) { GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort"); GrpcPreconditions.CheckState(!startRequested); var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port); int boundPort; using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials()) { if (nativeCredentials != null) { boundPort = handle.AddSecurePort(address, nativeCredentials); } else { boundPort = handle.AddInsecurePort(address); } } var newServerPort = new ServerPort(serverPort, boundPort); this.serverPortList.Add(newServerPort); return boundPort; } } /// <summary> /// Allows one new RPC call to be received by server. /// </summary> private void AllowOneRpc(CompletionQueueSafeHandle cq) { if (!shutdownRequested) { // TODO(jtattermusch): avoid unnecessary delegate allocation handle.RequestCall((success, ctx) => HandleNewServerRpc(success, ctx, cq), cq); } } /// <summary> /// Checks that all ports have been bound successfully. /// </summary> private void CheckPortsBoundSuccessfully() { lock (myLock) { var unboundPort = ports.FirstOrDefault(port => port.BoundPort == 0); if (unboundPort != null) { throw new IOException( string.Format("Failed to bind port \"{0}:{1}\"", unboundPort.Host, unboundPort.Port)); } } } private void DisposeHandle() { var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount); } handle.Dispose(); } /// <summary> /// Selects corresponding handler for given call and handles the call. /// </summary> private async Task HandleCallAsync(ServerRpcNew newRpc, CompletionQueueSafeHandle cq, Action<Server, CompletionQueueSafeHandle> continuation) { try { IServerCallHandler callHandler; if (!callHandlers.TryGetValue(newRpc.Method, out callHandler)) { callHandler = UnimplementedMethodCallHandler.Instance; } await callHandler.HandleCall(newRpc, cq).ConfigureAwait(false); } catch (Exception e) { Logger.Warning(e, "Exception while handling RPC."); } finally { continuation(this, cq); } } /// <summary> /// Handles the native callback. /// </summary> private void HandleNewServerRpc(bool success, RequestCallContextSafeHandle ctx, CompletionQueueSafeHandle cq) { bool nextRpcRequested = false; if (success) { var newRpc = ctx.GetServerRpcNew(this); // after server shutdown, the callback returns with null call if (!newRpc.Call.IsInvalid) { nextRpcRequested = true; // Start asynchronous handler for the call. // Don't await, the continuations will run on gRPC thread pool once triggered // by cq.Next(). #pragma warning disable 4014 HandleCallAsync(newRpc, cq, (server, state) => server.AllowOneRpc(state)); #pragma warning restore 4014 } } if (!nextRpcRequested) { AllowOneRpc(cq); } } /// <summary> /// Handles native callback. /// </summary> private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx, object state) { shutdownTcs.SetResult(null); } /// <summary> /// Collection of service definitions. /// </summary> public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition> { readonly Server server; internal ServiceDefinitionCollection(Server server) { this.server = server; } /// <summary> /// Adds a service definition to the server. This is how you register /// handlers for a service with the server. Only call this before Start(). /// </summary> public void Add(ServerServiceDefinition serviceDefinition) { server.AddServiceDefinitionInternal(serviceDefinition); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerServiceDefinition> GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } } /// <summary> /// Collection of server ports. /// </summary> public class ServerPortCollection : IEnumerable<ServerPort> { readonly Server server; internal ServerPortCollection(Server server) { this.server = server; } /// <summary> /// Adds a new port on which server should listen. /// Only call this before Start(). /// <returns>The port on which server will be listening.</returns> /// </summary> public int Add(ServerPort serverPort) { return server.AddPortInternal(serverPort); } /// <summary> /// Adds a new port on which server should listen. /// <returns>The port on which server will be listening.</returns> /// </summary> /// <param name="host">the host</param> /// <param name="port">the port. If zero, an unused port is chosen automatically.</param> /// <param name="credentials">credentials to use to secure this port.</param> public int Add(string host, int port, ServerCredentials credentials) { return Add(new ServerPort(host, port, credentials)); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerPort> GetEnumerator() { return server.serverPortList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serverPortList.GetEnumerator(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System.IO; using System; using System.Collections; using System.ComponentModel; /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e); /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlAttributeEventArgs : EventArgs { private object _o; private XmlAttribute _attr; private string _qnames; private int _lineNumber; private int _linePosition; internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) { _attr = attr; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.ObjectBeingDeserialized"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object ObjectBeingDeserialized { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.Attr"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttribute Attr { get { return _attr; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.LineNumber"]/*' /> /// <devdoc> /// <para> /// Gets the current line number. /// </para> /// </devdoc> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.LinePosition"]/*' /> /// <devdoc> /// <para> /// Gets the current line position. /// </para> /// </devdoc> public int LinePosition { get { return _linePosition; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.Attributes"]/*' /> /// <devdoc> /// <para> /// List the qnames of attributes expected in the current context. /// </para> /// </devdoc> public string ExpectedAttributes { get { return _qnames == null ? string.Empty : _qnames; } } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventHandler"]/*' /> public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e); /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs"]/*' /> public class XmlElementEventArgs : EventArgs { private object _o; private XmlElement _elem; private string _qnames; private int _lineNumber; private int _linePosition; internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames) { _elem = elem; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.ObjectBeingDeserialized"]/*' /> public object ObjectBeingDeserialized { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.Attr"]/*' /> public XmlElement Element { get { return _elem; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.LineNumber"]/*' /> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.LinePosition"]/*' /> public int LinePosition { get { return _linePosition; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.ExpectedElements"]/*' /> /// <devdoc> /// <para> /// List of qnames of elements expected in the current context. /// </para> /// </devdoc> public string ExpectedElements { get { return _qnames == null ? string.Empty : _qnames; } } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e); /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlNodeEventArgs : EventArgs { private object _o; private XmlNode _xmlNode; private int _lineNumber; private int _linePosition; internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o) { _o = o; _xmlNode = xmlNode; _lineNumber = lineNumber; _linePosition = linePosition; } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.ObjectBeingDeserialized"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object ObjectBeingDeserialized { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.NodeType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlNodeType NodeType { get { return _xmlNode.NodeType; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.Name"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Name { get { return _xmlNode.Name; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LocalName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string LocalName { get { return _xmlNode.LocalName; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.NamespaceURI"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string NamespaceURI { get { return _xmlNode.NamespaceURI; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.Text"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Text { get { return _xmlNode.Value; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LineNumber"]/*' /> /// <devdoc> /// <para> /// Gets the current line number. /// </para> /// </devdoc> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LinePosition"]/*' /> /// <devdoc> /// <para> /// Gets the current line position. /// </para> /// </devdoc> public int LinePosition { get { return _linePosition; } } } /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventHandler"]/*' /> public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e); /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs"]/*' /> public class UnreferencedObjectEventArgs : EventArgs { private object _o; private string _id; /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedObjectEventArgs"]/*' /> public UnreferencedObjectEventArgs(object o, string id) { _o = o; _id = id; } /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedObject"]/*' /> public object UnreferencedObject { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedId"]/*' /> public string UnreferencedId { get { return _id; } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using Avalonia.Controls.Primitives; using Avalonia.HtmlRenderer; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using TheArtOfDev.HtmlRenderer.Core; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Avalonia; using TheArtOfDev.HtmlRenderer.Avalonia.Adapters; namespace Avalonia.Controls.Html { /// <summary> /// Provides HTML rendering using the text property.<br/> /// Avalonia control that will render html content in it's client rectangle.<br/> /// The control will handle mouse and keyboard events on it to support html text selection, copy-paste and mouse clicks.<br/> /// <para> /// The major differential to use HtmlPanel or HtmlLabel is size and scrollbars.<br/> /// If the size of the control depends on the html content the HtmlLabel should be used.<br/> /// If the size is set by some kind of layout then HtmlPanel is more suitable, also shows scrollbars if the html contents is larger than the control client rectangle.<br/> /// </para> /// <para> /// <h4>LinkClicked event:</h4> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </para> /// <para> /// <h4>StylesheetLoad event:</h4> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </para> /// <para> /// <h4>ImageLoad event:</h4> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </para> /// <para> /// <h4>RenderError event:</h4> /// Raised when an error occurred during html rendering.<br/> /// </para> /// </summary> public class HtmlControl : Control { /// <summary> /// Underline html container instance. /// </summary> protected readonly HtmlContainer _htmlContainer; /// <summary> /// the base stylesheet data used in the control /// </summary> protected CssData _baseCssData; /// <summary> /// The last position of the scrollbars to know if it has changed to update mouse /// </summary> protected Point _lastScrollOffset; public static readonly AvaloniaProperty AvoidImagesLateLoadingProperty = PropertyHelper.Register<HtmlControl, bool>("AvoidImagesLateLoading", false, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty IsSelectionEnabledProperty = PropertyHelper.Register<HtmlControl, bool>("IsSelectionEnabled", true, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty IsContextMenuEnabledProperty = PropertyHelper.Register<HtmlControl, bool>("IsContextMenuEnabled", true, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty BaseStylesheetProperty = PropertyHelper.Register<HtmlControl, string>("BaseStylesheet", null, OnAvaloniaProperty_valueChanged); public static readonly AvaloniaProperty TextProperty = PropertyHelper.Register<HtmlControl, string>("Text", null, OnAvaloniaProperty_valueChanged); public static readonly StyledProperty<IBrush> BackgroundProperty = Border.BackgroundProperty.AddOwner<HtmlControl>(); public static readonly AvaloniaProperty BorderThicknessProperty = AvaloniaProperty.Register<HtmlControl, Thickness>("BorderThickness", new Thickness(0)); public static readonly AvaloniaProperty BorderBrushProperty = AvaloniaProperty.Register<HtmlControl, IBrush>("BorderBrush"); public static readonly AvaloniaProperty PaddingProperty = AvaloniaProperty.Register<HtmlControl, Thickness>("Padding", new Thickness(0)); public static readonly RoutedEvent LoadCompleteEvent = RoutedEvent.Register<RoutedEventArgs>("LoadComplete", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent LinkClickedEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlLinkClickedEventArgs>>("LinkClicked", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent RenderErrorEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlRenderErrorEventArgs>>("RenderError", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent RefreshEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlRefreshEventArgs>>("Refresh", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent StylesheetLoadEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlStylesheetLoadEventArgs>>("StylesheetLoad", RoutingStrategies.Bubble, typeof(HtmlControl)); public static readonly RoutedEvent ImageLoadEvent = RoutedEvent.Register<HtmlRendererRoutedEventArgs<HtmlImageLoadEventArgs>>("ImageLoad", RoutingStrategies.Bubble, typeof (HtmlControl)); static HtmlControl() { FocusableProperty.OverrideDefaultValue(typeof(HtmlControl), true); } /// <summary> /// Creates a new HtmlPanel and sets a basic css for it's styling. /// </summary> protected HtmlControl() { _htmlContainer = new HtmlContainer(); _htmlContainer.LoadComplete += (_, e) => OnLoadComplete(e); _htmlContainer.LinkClicked += (_, e) => OnLinkClicked(e); _htmlContainer.RenderError += (_, e) => OnRenderError(e); _htmlContainer.Refresh += (_, e) => OnRefresh(e); _htmlContainer.StylesheetLoad += (_, e) => OnStylesheetLoad(e); _htmlContainer.ImageLoad += (_, e) => OnImageLoad(e); } //Hack for adapter internal bool LeftMouseButton { get; private set; } /// <summary> /// Raised when the set html document has been fully loaded.<br/> /// Allows manipulation of the html dom, scroll position, etc. /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<EventArgs>> LoadComplete { add { AddHandler(LoadCompleteEvent, value); } remove { RemoveHandler(LoadCompleteEvent, value); } } /// <summary> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlLinkClickedEventArgs>> LinkClicked { add { AddHandler(LinkClickedEvent, value); } remove { RemoveHandler(LinkClickedEvent, value); } } /// <summary> /// Raised when an error occurred during html rendering.<br/> /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlRenderErrorEventArgs>> RenderError { add { AddHandler(RenderErrorEvent, value); } remove { RemoveHandler(RenderErrorEvent, value); } } /// <summary> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlStylesheetLoadEventArgs>> StylesheetLoad { add { AddHandler(StylesheetLoadEvent, value); } remove { RemoveHandler(StylesheetLoadEvent, value); } } /// <summary> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </summary> public event EventHandler<HtmlRendererRoutedEventArgs<HtmlImageLoadEventArgs>> ImageLoad { add { AddHandler(ImageLoadEvent, value); } remove { RemoveHandler(ImageLoadEvent, value); } } /// <summary> /// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/> /// True - images are loaded as soon as the html is parsed.<br/> /// False - images that are not visible because of scroll location are not loaded until they are scrolled to. /// </summary> /// <remarks> /// Images late loading improve performance if the page contains image outside the visible scroll area, especially if there is large /// amount of images, as all image loading is delayed (downloading and loading into memory).<br/> /// Late image loading may effect the layout and actual size as image without set size will not have actual size until they are loaded /// resulting in layout change during user scroll.<br/> /// Early image loading may also effect the layout if image without known size above the current scroll location are loaded as they /// will push the html elements down. /// </remarks> [Category("Behavior")] [Description("If image loading only when visible should be avoided")] public bool AvoidImagesLateLoading { get { return (bool)GetValue(AvoidImagesLateLoadingProperty); } set { SetValue(AvoidImagesLateLoadingProperty, value); } } /// <summary> /// Is content selection is enabled for the rendered html (default - true).<br/> /// If set to 'false' the rendered html will be static only with ability to click on links. /// </summary> [Category("Behavior")] [Description("Is content selection is enabled for the rendered html.")] public bool IsSelectionEnabled { get { return (bool)GetValue(IsSelectionEnabledProperty); } set { SetValue(IsSelectionEnabledProperty, value); } } /// <summary> /// Is the build-in context menu enabled and will be shown on mouse right click (default - true) /// </summary> [Category("Behavior")] [Description("Is the build-in context menu enabled and will be shown on mouse right click.")] public bool IsContextMenuEnabled { get { return (bool)GetValue(IsContextMenuEnabledProperty); } set { SetValue(IsContextMenuEnabledProperty, value); } } /// <summary> /// Set base stylesheet to be used by html rendered in the panel. /// </summary> [Category("Appearance")] [Description("Set base stylesheet to be used by html rendered in the control.")] public string BaseStylesheet { get { return (string)GetValue(BaseStylesheetProperty); } set { SetValue(BaseStylesheetProperty, value); } } /// <summary> /// Gets or sets the text of this panel /// </summary> [Description("Sets the html of this control.")] public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public Thickness BorderThickness { get { return (Thickness) GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } public IBrush BorderBrush { get { return (IBrush)GetValue(BorderBrushProperty); } set { SetValue(BorderThicknessProperty, value); } } public Thickness Padding { get { return (Thickness)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } public IBrush Background { get { return (IBrush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value);} } /// <summary> /// Get the currently selected text segment in the html. /// </summary> [Browsable(false)] public virtual string SelectedText { get { return _htmlContainer.SelectedText; } } /// <summary> /// Copy the currently selected html segment with style. /// </summary> [Browsable(false)] public virtual string SelectedHtml { get { return _htmlContainer.SelectedHtml; } } /// <summary> /// Get html from the current DOM tree with inline style. /// </summary> /// <returns>generated html</returns> public virtual string GetHtml() { return _htmlContainer != null ? _htmlContainer.GetHtml() : null; } /// <summary> /// Get the rectangle of html element as calculated by html layout.<br/> /// Element if found by id (id attribute on the html element).<br/> /// Note: to get the screen rectangle you need to adjust by the hosting control.<br/> /// </summary> /// <param name="elementId">the id of the element to get its rectangle</param> /// <returns>the rectangle of the element or null if not found</returns> public virtual Rect? GetElementRectangle(string elementId) { return _htmlContainer != null ? _htmlContainer.GetElementRectangle(elementId) : null; } /// <summary> /// Clear the current selection. /// </summary> public void ClearSelection() { if (_htmlContainer != null) _htmlContainer.ClearSelection(); } //HACK: We don't have support for RenderSize for now private Size RenderSize => new Size(Bounds.Width, Bounds.Height); public override void Render(DrawingContext context) { context.FillRectangle(Background, new Rect(RenderSize)); if (BorderThickness != new Thickness(0) && BorderBrush != null) { var brush = new SolidColorBrush(Colors.Black); if (BorderThickness.Top > 0) context.FillRectangle(brush, new Rect(0, 0, RenderSize.Width, BorderThickness.Top)); if (BorderThickness.Bottom > 0) context.FillRectangle(brush, new Rect(0, RenderSize.Height - BorderThickness.Bottom, RenderSize.Width, BorderThickness.Bottom)); if (BorderThickness.Left > 0) context.FillRectangle(brush, new Rect(0, 0, BorderThickness.Left, RenderSize.Height)); if (BorderThickness.Right > 0) context.FillRectangle(brush, new Rect(RenderSize.Width - BorderThickness.Right, 0, BorderThickness.Right, RenderSize.Height)); } var htmlWidth = HtmlWidth(RenderSize); var htmlHeight = HtmlHeight(RenderSize); if (_htmlContainer != null && htmlWidth > 0 && htmlHeight > 0) { /* //TODO: Revert antialiasing fixes var windows = Window.GetWindow(this); if (windows != null) { // adjust render location to round point so we won't get anti-alias smugness var wPoint = TranslatePoint(new Point(0, 0), windows); wPoint.Offset(-(int)wPoint.X, -(int)wPoint.Y); var xTrans = wPoint.X < .5 ? -wPoint.X : 1 - wPoint.X; var yTrans = wPoint.Y < .5 ? -wPoint.Y : 1 - wPoint.Y; context.PushTransform(new TranslateTransform(xTrans, yTrans)); }*/ using (context.PushClip(new Rect(Padding.Left + BorderThickness.Left, Padding.Top + BorderThickness.Top, htmlWidth, (int) htmlHeight))) { _htmlContainer.Location = new Point(Padding.Left + BorderThickness.Left, Padding.Top + BorderThickness.Top); _htmlContainer.PerformPaint(context, new Rect(Padding.Left + BorderThickness.Left, Padding.Top + BorderThickness.Top, htmlWidth, htmlHeight)); } if (!_lastScrollOffset.Equals(_htmlContainer.ScrollOffset)) { _lastScrollOffset = _htmlContainer.ScrollOffset; InvokeMouseMove(); } } } /// <summary> /// Handle mouse move to handle hover cursor and text selection. /// </summary> protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_htmlContainer != null) _htmlContainer.HandleMouseMove(this, e.GetPosition(this)); } /// <summary> /// Handle mouse leave to handle cursor change. /// </summary> protected override void OnPointerLeave(PointerEventArgs e) { base.OnPointerLeave(e); if (_htmlContainer != null) _htmlContainer.HandleMouseLeave(this); } /// <summary> /// Handle mouse down to handle selection. /// </summary> protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); LeftMouseButton = true; _htmlContainer?.HandleLeftMouseDown(this, e); } /// <summary> /// Handle mouse up to handle selection and link click. /// </summary> protected override void OnPointerReleased(PointerEventArgs e) { base.OnPointerReleased(e); LeftMouseButton = false; if (_htmlContainer != null) _htmlContainer.HandleLeftMouseUp(this, e); } //TODO: Implement double click /* /// <summary> /// Handle mouse double click to select word under the mouse. /// </summary> protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { base.OnMouseDoubleClick(e); if (_htmlContainer != null) _htmlContainer.HandleMouseDoubleClick(this, e); } */ /// <summary> /// Handle key down event for selection, copy and scrollbars handling. /// </summary> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (_htmlContainer != null) _htmlContainer.HandleKeyDown(this, e); } void RaiseRouted<T>(RoutedEvent ev, T arg) { var e =new HtmlRendererRoutedEventArgs<T> { Event = arg, Source = this, RoutedEvent = ev, Route = ev.RoutingStrategies }; RaiseEvent(e); } /// <summary> /// Propagate the LoadComplete event from root container. /// </summary> protected virtual void OnLoadComplete(EventArgs e) => RaiseRouted(LoadCompleteEvent, e); /// <summary> /// Propagate the LinkClicked event from root container. /// </summary> protected virtual void OnLinkClicked(HtmlLinkClickedEventArgs e) => RaiseRouted(LinkClickedEvent, e); /// <summary> /// Propagate the Render Error event from root container. /// </summary> protected virtual void OnRenderError(HtmlRenderErrorEventArgs e) => RaiseRouted(RenderErrorEvent, e); /// <summary> /// Propagate the stylesheet load event from root container. /// </summary> protected virtual void OnStylesheetLoad(HtmlStylesheetLoadEventArgs e) => RaiseRouted(StylesheetLoadEvent, e); /// <summary> /// Propagate the image load event from root container. /// </summary> protected virtual void OnImageLoad(HtmlImageLoadEventArgs e) => RaiseRouted(ImageLoadEvent, e); /// <summary> /// Handle html renderer invalidate and re-layout as requested. /// </summary> protected virtual void OnRefresh(HtmlRefreshEventArgs e) { if (e.Layout) InvalidateMeasure(); InvalidateVisual(); } /// <summary> /// Get the width the HTML has to render in (not including vertical scroll iff it is visible) /// </summary> protected virtual double HtmlWidth(Size size) { return size.Width - Padding.Left - Padding.Right - BorderThickness.Left - BorderThickness.Right; } /// <summary> /// Get the width the HTML has to render in (not including vertical scroll iff it is visible) /// </summary> protected virtual double HtmlHeight(Size size) { return size.Height - Padding.Top - Padding.Bottom - BorderThickness.Top - BorderThickness.Bottom; } /// <summary> /// call mouse move to handle paint after scroll or html change affecting mouse cursor. /// </summary> protected virtual void InvokeMouseMove() { _htmlContainer.HandleMouseMove(this, MouseDevice.Instance?.GetPosition(this) ?? default(Point)); } /// <summary> /// Handle when dependency property value changes to update the underline HtmlContainer with the new value. /// </summary> private static void OnAvaloniaProperty_valueChanged(AvaloniaObject AvaloniaObject, AvaloniaPropertyChangedEventArgs e) { var control = AvaloniaObject as HtmlControl; if (control != null) { var htmlContainer = control._htmlContainer; if (e.Property == AvoidImagesLateLoadingProperty) { htmlContainer.AvoidImagesLateLoading = (bool) e.NewValue; } else if (e.Property == IsSelectionEnabledProperty) { htmlContainer.IsSelectionEnabled = (bool) e.NewValue; } else if (e.Property == IsContextMenuEnabledProperty) { htmlContainer.IsContextMenuEnabled = (bool) e.NewValue; } else if (e.Property == BaseStylesheetProperty) { var baseCssData = CssData.Parse(AvaloniaAdapter.Instance, (string) e.NewValue); control._baseCssData = baseCssData; htmlContainer.SetHtml(control.Text, baseCssData); } else if (e.Property == TextProperty) { htmlContainer.ScrollOffset = new Point(0, 0); htmlContainer.SetHtml((string) e.NewValue, control._baseCssData); control.InvalidateMeasure(); control.InvalidateVisual(); if (control.VisualRoot != null) { control.InvokeMouseMove(); } } } } //TODO: Implement CheckAccess calls /* private void OnLoadComplete(object sender, EventArgs e) { if (CheckAccess()) OnLoadComplete(e); else Dispatcher.UIThread.Invoke(new Action<HtmlLinkClickedEventArgs>(OnLinkClicked), e); } private void OnLinkClicked(object sender, HtmlLinkClickedEventArgs e) { if (CheckAccess()) OnLinkClicked(e); else Dispatcher.UIThread.Invoke(new Action<HtmlLinkClickedEventArgs>(OnLinkClicked), e); } private void OnRenderError(object sender, HtmlRenderErrorEventArgs e) { if (CheckAccess()) OnRenderError(e); else Dispatcher.UIThread.Invoke(new Action<HtmlRenderErrorEventArgs>(OnRenderError), e); } private void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e) { if (CheckAccess()) OnStylesheetLoad(e); else Dispatcher.UIThread.Invoke(new Action<HtmlStylesheetLoadEventArgs>(OnStylesheetLoad), e); } private void OnImageLoad(object sender, HtmlImageLoadEventArgs e) { if (CheckAccess()) OnImageLoad(e); else Dispatcher.UIThread.Invoke(new Action<HtmlImageLoadEventArgs>(OnImageLoad), e); } private void OnRefresh(object sender, HtmlRefreshEventArgs e) { if (CheckAccess()) OnRefresh(e); else Dispatcher.UIThread.Invoke(new Action<HtmlRefreshEventArgs>(OnRefresh), e); } */ } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace BuildIt.CognitiveServices { /// <summary> /// The Autosuggest API lets partners send a partial search query to Bing /// and get back a list of suggested queries that other users have /// searched on. In addition to including searches that other users have /// made, the list may include suggestions based on user intent. For /// example, if the query string is weather in Lo, the list will include /// relevant weather suggestions. /// &lt;br&gt;&lt;br&gt; /// Typically, you use this API to support an auto-suggest search box /// feature. For example, as the user types a query into the search box, /// you would call this API to populate a drop-down list of suggested /// query strings. If the user selects a query from the list, you would /// either send the user to the Bing search results page for the selected /// query or call the Bing Search API to get the search results and /// display the results yourself. /// </summary> public partial class AutosuggestAPIV5 : Microsoft.Rest.ServiceClient<AutosuggestAPIV5>, IAutosuggestAPIV5 { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the AutosuggestAPIV5 class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutosuggestAPIV5(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutosuggestAPIV5 class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutosuggestAPIV5(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutosuggestAPIV5 class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutosuggestAPIV5(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutosuggestAPIV5 class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutosuggestAPIV5(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("https://api.cognitive.microsoft.com/bing/v5.0/suggestions"); SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// This operation provides suggestions for a given query or partial query. /// </summary> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SuggestionsWithHttpMessagesAsync(string query, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { string q = query; // 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("q", q); tracingParameters.Add("subscriptionKey", subscriptionKey); tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Suggestions", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (q != null) { _queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(q))); } if (subscriptionKey != null) { _queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey))); } if (_queryParameters.Count > 0) { _url += "?" + 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 (ocpApimSubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey); } 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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 429) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace android.graphics { [global::MonoJavaBridge.JavaClass()] public sealed partial class Rect : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Rect() { InitJNI(); } internal Rect(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _equals3668; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._equals3668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._equals3668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString3669; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Rect._toString3669)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._toString3669)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _offset3670; public void offset(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._offset3670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._offset3670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isEmpty3671; public bool isEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._isEmpty3671); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._isEmpty3671); } internal static global::MonoJavaBridge.MethodId _contains3672; public bool contains(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._contains3672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._contains3672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _contains3673; public bool contains(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._contains3673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._contains3673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _contains3674; public bool contains(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._contains3674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._contains3674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _set3675; public void set(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._set3675, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._set3675, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _set3676; public void set(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._set3676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._set3676, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _sort3677; public void sort() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._sort3677); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._sort3677); } internal static global::MonoJavaBridge.MethodId _intersects3678; public static bool intersects(android.graphics.Rect arg0, android.graphics.Rect arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(android.graphics.Rect.staticClass, global::android.graphics.Rect._intersects3678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _intersects3679; public bool intersects(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._intersects3679, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._intersects3679, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _union3680; public void union(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._union3680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._union3680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _union3681; public void union(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._union3681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._union3681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _union3682; public void union(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._union3682, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._union3682, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _centerX3683; public int centerX() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.Rect._centerX3683); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._centerX3683); } internal static global::MonoJavaBridge.MethodId _centerY3684; public int centerY() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.Rect._centerY3684); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._centerY3684); } internal static global::MonoJavaBridge.MethodId _height3685; public int height() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.Rect._height3685); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._height3685); } internal static global::MonoJavaBridge.MethodId _width3686; public int width() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.Rect._width3686); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._width3686); } internal static global::MonoJavaBridge.MethodId _writeToParcel3687; public void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._writeToParcel3687, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._writeToParcel3687, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents3688; public int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.Rect._describeContents3688); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._describeContents3688); } internal static global::MonoJavaBridge.MethodId _readFromParcel3689; public void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._readFromParcel3689, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._readFromParcel3689, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _flattenToString3690; public global::java.lang.String flattenToString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Rect._flattenToString3690)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._flattenToString3690)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _unflattenFromString3691; public static global::android.graphics.Rect unflattenFromString(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.Rect.staticClass, global::android.graphics.Rect._unflattenFromString3691, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Rect; } internal static global::MonoJavaBridge.MethodId _toShortString3692; public global::java.lang.String toShortString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Rect._toShortString3692)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._toShortString3692)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _setEmpty3693; public void setEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._setEmpty3693); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._setEmpty3693); } internal static global::MonoJavaBridge.MethodId _exactCenterX3694; public float exactCenterX() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.graphics.Rect._exactCenterX3694); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._exactCenterX3694); } internal static global::MonoJavaBridge.MethodId _exactCenterY3695; public float exactCenterY() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.graphics.Rect._exactCenterY3695); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._exactCenterY3695); } internal static global::MonoJavaBridge.MethodId _offsetTo3696; public void offsetTo(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._offsetTo3696, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._offsetTo3696, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _inset3697; public void inset(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Rect._inset3697, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._inset3697, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _intersect3698; public bool intersect(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._intersect3698, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._intersect3698, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _intersect3699; public bool intersect(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._intersect3699, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._intersect3699, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setIntersect3700; public bool setIntersect(android.graphics.Rect arg0, android.graphics.Rect arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Rect._setIntersect3700, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Rect.staticClass, global::android.graphics.Rect._setIntersect3700, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _Rect3701; public Rect() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Rect.staticClass, global::android.graphics.Rect._Rect3701); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Rect3702; public Rect(int arg0, int arg1, int arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Rect.staticClass, global::android.graphics.Rect._Rect3702, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Rect3703; public Rect(android.graphics.Rect arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Rect.staticClass, global::android.graphics.Rect._Rect3703, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _left3704; public int left { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _top3705; public int top { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _right3706; public int right { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _bottom3707; public int bottom { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR3708; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Rect.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Rect")); global::android.graphics.Rect._equals3668 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.graphics.Rect._toString3669 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "toString", "()Ljava/lang/String;"); global::android.graphics.Rect._offset3670 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "offset", "(II)V"); global::android.graphics.Rect._isEmpty3671 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "isEmpty", "()Z"); global::android.graphics.Rect._contains3672 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "contains", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Rect._contains3673 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "contains", "(IIII)Z"); global::android.graphics.Rect._contains3674 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "contains", "(II)Z"); global::android.graphics.Rect._set3675 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "set", "(IIII)V"); global::android.graphics.Rect._set3676 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "set", "(Landroid/graphics/Rect;)V"); global::android.graphics.Rect._sort3677 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "sort", "()V"); global::android.graphics.Rect._intersects3678 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Rect.staticClass, "intersects", "(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z"); global::android.graphics.Rect._intersects3679 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "intersects", "(IIII)Z"); global::android.graphics.Rect._union3680 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "union", "(II)V"); global::android.graphics.Rect._union3681 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "union", "(IIII)V"); global::android.graphics.Rect._union3682 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "union", "(Landroid/graphics/Rect;)V"); global::android.graphics.Rect._centerX3683 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "centerX", "()I"); global::android.graphics.Rect._centerY3684 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "centerY", "()I"); global::android.graphics.Rect._height3685 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "height", "()I"); global::android.graphics.Rect._width3686 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "width", "()I"); global::android.graphics.Rect._writeToParcel3687 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.graphics.Rect._describeContents3688 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "describeContents", "()I"); global::android.graphics.Rect._readFromParcel3689 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V"); global::android.graphics.Rect._flattenToString3690 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "flattenToString", "()Ljava/lang/String;"); global::android.graphics.Rect._unflattenFromString3691 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Rect.staticClass, "unflattenFromString", "(Ljava/lang/String;)Landroid/graphics/Rect;"); global::android.graphics.Rect._toShortString3692 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "toShortString", "()Ljava/lang/String;"); global::android.graphics.Rect._setEmpty3693 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "setEmpty", "()V"); global::android.graphics.Rect._exactCenterX3694 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "exactCenterX", "()F"); global::android.graphics.Rect._exactCenterY3695 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "exactCenterY", "()F"); global::android.graphics.Rect._offsetTo3696 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "offsetTo", "(II)V"); global::android.graphics.Rect._inset3697 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "inset", "(II)V"); global::android.graphics.Rect._intersect3698 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "intersect", "(IIII)Z"); global::android.graphics.Rect._intersect3699 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "intersect", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Rect._setIntersect3700 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "setIntersect", "(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z"); global::android.graphics.Rect._Rect3701 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "<init>", "()V"); global::android.graphics.Rect._Rect3702 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "<init>", "(IIII)V"); global::android.graphics.Rect._Rect3703 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "<init>", "(Landroid/graphics/Rect;)V"); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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.Globalization; using System.Text; using DiscUtils.Streams; namespace DiscUtils.Registry { /// <summary> /// A registry value. /// </summary> internal sealed class RegistryValue { private readonly ValueCell _cell; private readonly RegistryHive _hive; internal RegistryValue(RegistryHive hive, ValueCell cell) { _hive = hive; _cell = cell; } /// <summary> /// Gets the type of the value. /// </summary> public RegistryValueType DataType { get { return _cell.DataType; } } /// <summary> /// Gets the name of the value, or empty string if unnamed. /// </summary> public string Name { get { return _cell.Name ?? string.Empty; } } /// <summary> /// Gets the value data mapped to a .net object. /// </summary> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object Value { get { return ConvertToObject(GetData(), DataType); } } /// <summary> /// The raw value data as a byte array. /// </summary> /// <returns>The value as a raw byte array.</returns> public byte[] GetData() { if (_cell.DataLength < 0) { int len = _cell.DataLength & 0x7FFFFFFF; byte[] buffer = new byte[4]; EndianUtilities.WriteBytesLittleEndian(_cell.DataIndex, buffer, 0); byte[] result = new byte[len]; Array.Copy(buffer, result, len); return result; } return _hive.RawCellData(_cell.DataIndex, _cell.DataLength); } /// <summary> /// Sets the value as raw bytes, with no validation that enough data is specified for the given value type. /// </summary> /// <param name="data">The data to store.</param> /// <param name="offset">The offset within <c>data</c> of the first byte to store.</param> /// <param name="count">The number of bytes to store.</param> /// <param name="valueType">The type of the data.</param> public void SetData(byte[] data, int offset, int count, RegistryValueType valueType) { // If we can place the data in the DataIndex field, do that to save space / allocation if ((valueType == RegistryValueType.Dword || valueType == RegistryValueType.DwordBigEndian) && count <= 4) { if (_cell.DataLength >= 0) { _hive.FreeCell(_cell.DataIndex); } _cell.DataLength = (int)((uint)count | 0x80000000); _cell.DataIndex = EndianUtilities.ToInt32LittleEndian(data, offset); _cell.DataType = valueType; } else { if (_cell.DataIndex == -1 || _cell.DataLength < 0) { _cell.DataIndex = _hive.AllocateRawCell(count); } if (!_hive.WriteRawCellData(_cell.DataIndex, data, offset, count)) { int newDataIndex = _hive.AllocateRawCell(count); _hive.WriteRawCellData(newDataIndex, data, offset, count); _hive.FreeCell(_cell.DataIndex); _cell.DataIndex = newDataIndex; } _cell.DataLength = count; _cell.DataType = valueType; } _hive.UpdateCell(_cell, false); } /// <summary> /// Sets the value stored. /// </summary> /// <param name="value">The value to store.</param> /// <param name="valueType">The registry type of the data.</param> public void SetValue(object value, RegistryValueType valueType) { if (valueType == RegistryValueType.None) { if (value is int) { valueType = RegistryValueType.Dword; } else if (value is byte[]) { valueType = RegistryValueType.Binary; } else if (value is string[]) { valueType = RegistryValueType.MultiString; } else { valueType = RegistryValueType.String; } } byte[] data = ConvertToData(value, valueType); SetData(data, 0, data.Length, valueType); } /// <summary> /// Gets a string representation of the registry value. /// </summary> /// <returns>The registry value as a string.</returns> public override string ToString() { return Name + ":" + DataType + ":" + DataAsString(); } private static object ConvertToObject(byte[] data, RegistryValueType type) { switch (type) { case RegistryValueType.String: case RegistryValueType.ExpandString: case RegistryValueType.Link: return Encoding.Unicode.GetString(data).Trim('\0'); case RegistryValueType.Dword: return EndianUtilities.ToInt32LittleEndian(data, 0); case RegistryValueType.DwordBigEndian: return EndianUtilities.ToInt32BigEndian(data, 0); case RegistryValueType.MultiString: string multiString = Encoding.Unicode.GetString(data).Trim('\0'); return multiString.Split('\0'); case RegistryValueType.QWord: return string.Empty + EndianUtilities.ToUInt64LittleEndian(data, 0); default: return data; } } private static byte[] ConvertToData(object value, RegistryValueType valueType) { if (valueType == RegistryValueType.None) { throw new ArgumentException("Specific registry value type must be specified", nameof(valueType)); } byte[] data; switch (valueType) { case RegistryValueType.String: case RegistryValueType.ExpandString: string strValue = value.ToString(); data = new byte[strValue.Length * 2 + 2]; Encoding.Unicode.GetBytes(strValue, 0, strValue.Length, data, 0); break; case RegistryValueType.Dword: data = new byte[4]; EndianUtilities.WriteBytesLittleEndian((int)value, data, 0); break; case RegistryValueType.DwordBigEndian: data = new byte[4]; EndianUtilities.WriteBytesBigEndian((int)value, data, 0); break; case RegistryValueType.MultiString: string multiStrValue = string.Join("\0", (string[])value) + "\0"; data = new byte[multiStrValue.Length * 2 + 2]; Encoding.Unicode.GetBytes(multiStrValue, 0, multiStrValue.Length, data, 0); break; default: data = (byte[])value; break; } return data; } private string DataAsString() { switch (DataType) { case RegistryValueType.String: case RegistryValueType.ExpandString: case RegistryValueType.Link: case RegistryValueType.Dword: case RegistryValueType.DwordBigEndian: case RegistryValueType.QWord: return ConvertToObject(GetData(), DataType).ToString(); case RegistryValueType.MultiString: return string.Join(",", (string[])ConvertToObject(GetData(), DataType)); default: byte[] data = GetData(); string result = string.Empty; for (int i = 0; i < Math.Min(data.Length, 8); ++i) { result += string.Format(CultureInfo.InvariantCulture, "{0:X2} ", (int)data[i]); } return result + string.Format(CultureInfo.InvariantCulture, " ({0} bytes)", data.Length); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ID3Lite { public class ID3Lite { Dictionary<string, byte[]> frames; string filePath; /* internal variables for CoverArt */ static bool _isExist = false; static string _MIME = String.Empty; static PictureType _PictureType = 0; static string _Description = String.Empty; static byte[] _Image = null; struct CoverArt { bool IsExist { get { return _isExist; } } string MIME { get { return _MIME; } } PictureType PictureType { get { return _PictureType; } } string Description { get { return _Description; } } byte[] Image{ get { return _Image; } } } #region Enums private enum Flag { TagAlterPreservation = 0x8000, FileAlterPreservation = 0x4000, ReadOnly = 0x2000, Compression = 0x0080, Encryption = 0x0040, GroupingIdentity = 0x0020 } private enum PictureType { Other = 0x00, PNGFileIcon = 0x01, OtherFileIcon = 0x02, FrontCover = 0x03, BackCover = 0x04, LeafletPage = 0x05, Media = 0x06, LeadArtist = 0x07, Artist = 0x08, Conductor = 0x09, Orchestra = 0x0A, Composer = 0x0B, Lyricist = 0x0C, RecordingLocation = 0x0D, DuringRecording = 0x0E, DuringPerformance = 0x0F, VideoSnapshot = 0x10, BrightColouredFish = 0x11, Illustration = 0x12, ArtistLogotype = 0x13, PublisherLogotype = 0x14 } #endregion public ID3Lite(string _filePath) { filePath = _filePath; frames = new Dictionary<string, byte[]>(); using (FileStream fs = File.Open(filePath, FileMode.Open)) { int frameSizeInt; byte[] tag = new byte[3]; byte[] version = new byte[2]; byte[] flags = new byte[1]; byte[] size = new byte[4]; byte[] frameId = new byte[4]; byte[] frameSize = new byte[4]; byte[] dump = new byte[2]; Flag frameFlag; fs.Read(tag, 0, tag.Length); fs.Read(version, 0, version.Length); fs.Read(flags, 0, flags.Length); fs.Read(size, 0, size.Length); if (version[0] == 2) { throw new Exception("ID3v2.2 is not supported"); } ulong totalSize = (ulong)(size[0] * 0x200000 + size[1] * 0x4000 + size[2] * 0x80 + size[3]); byte buff; while (totalSize > 10) { buff = (byte)fs.ReadByte(); //Check Next Byte is Padding if (buff == 0) { totalSize--; continue; } fs.Seek(-1, SeekOrigin.Current); fs.Read(frameId, 0, frameId.Length); fs.Read(frameSize, 0, frameSize.Length); frameFlag = (Flag)fs.Read(dump, 0, 2); if (BitConverter.IsLittleEndian) Array.Reverse(frameSize); frameSizeInt = BitConverter.ToInt32(frameSize, 0); //Skip Text Encoding Type Flag buff = (byte)fs.ReadByte(); if (buff == 0) frameSizeInt--; else fs.Seek(-1, SeekOrigin.Current); byte[] data = new byte[frameSizeInt]; fs.Read(data, 0, data.Length); frames.Add(Encoding.UTF8.GetString(frameId), data); totalSize -= (ulong)frameSizeInt + 10; } fs.Close(); } //parse cover art data; if (frames.ContainsKey("APIC")) { _isExist = true; byte[] data = frames["APIC"]; int i; //get mime for (i = 0; data[i] != '\0'; i++) { _MIME += System.Text.Encoding.UTF8.GetString(new[] { data[i] }); ; } //get picture type _PictureType = (PictureType)Convert.ToInt32(data[++i].ToString(), 16); //get image description for (; data[i] != '\0'; i++) { _Description += System.Text.Encoding.UTF8.GetString(new[] { data[i] }); ; } //++i for skip encoding type flag _Image = new byte[data.Length - ++i]; Buffer.BlockCopy(data, i, _Image, 0, _Image.Length); } } public void SetFrameText(string FrameName, byte[] FrameData){ frames[FrameName] = FrameData; } public void Save() { byte[] id3Header; int fullLength = 10; int i; for (i = 0; i < frames.Count; i++) { KeyValuePair<string, byte[]> pair = frames.Skip(i).First(); fullLength += 10 + pair.Value.Length; } id3Header = new byte[4]{ 73, 68, 51, 4 }; Array.Resize(ref id3Header, fullLength); for (i = 9; i >= 6; i--) { id3Header[i] = Convert.ToByte(fullLength % 0x80); fullLength /= 0x80; } try { using (FileStream fs = File.Open(filePath, FileMode.Open)) { using (BinaryReader br = new BinaryReader(fs)) { } } } catch { //catch } } public string GetFrameData(string frameName) { return Encoding.UTF8.GetString(frames[frameName]); } public byte[] GetFrameByteData(string frameName) { return frames[frameName]; } #region Basic Infromation Getter public string Title { get { return GetFrameData("TIT2"); } } public string Album { get { return GetFrameData("TALB"); } } public string Artist { get { return GetFrameData("TPE1"); } } public string Comment { get { return GetFrameData("COMM"); } } public int Track { get { return Convert.ToInt32(GetFrameData("TRCK")); } } public int ReleaseYear { get { return Convert.ToInt32(GetFrameData("TYER")); } } #endregion } }
//#define DEBUG_UP using System; using System.IO; using System.Threading; using System.Collections.Generic; //using Alica.Reasoner; //using Al=Alica; using AutoDiff; namespace Alica.Reasoner.IntervalPropagation { public class UpwardPropagator : ITermVisitor<bool> { internal TermList Changed; //internal Queue<Term> Changed; /*private void AddAllChanged(List<Term> l) { foreach(Term t in l) { if(!Changed.Contains(t)) Changed.Enqueue(t); } }*/ private void AddChanged(Term t) { /*foreach(Term s in t.Parents) { Changed.Enqueue(s); } Changed.Enqueue(t);*/ foreach(Term s in t.Parents) { //Changed.Enqueue(s); if(!Changed.Contains(s)) Changed.Enqueue(s); //Changed.MoveToEnd(s); } if(!Changed.Contains(t)) Changed.Enqueue(t); //Changed.Enqueue(t); } public UpwardPropagator() { } internal DownwardPropagator DP {get; set;} public bool Visit(Constant constant) { return false; } public bool Visit(Zero zero) { return false; } public bool Visit(ConstPower intPower) { bool includesZero = intPower.Base.Min*intPower.Base.Max <= 0; if (intPower.Exponent > 0) { double a = Math.Pow(intPower.Base.Max,intPower.Exponent); double b = Math.Pow(intPower.Base.Min,intPower.Exponent); if (includesZero) { if(UpdateInterval(intPower,Math.Min(0,Math.Min(a,b)),Math.Max(0,Math.Max(a,b)))) { //if(UpdateInterval(intPower,Math.Min(0,Math.Pow(intPower.Base.Min,intPower.Exponent)),Math.Max(0,Math.Pow(intPower.Base.Max,intPower.Exponent)))) { AddChanged(intPower); return true; } } else { if(UpdateInterval(intPower,Math.Min(a,b),Math.Max(a,b))) { //if(UpdateInterval(intPower,Math.Pow(intPower.Base.Min,intPower.Exponent),Math.Pow(intPower.Base.Max,intPower.Exponent))) { AddChanged(intPower); return true; } } } else if (!includesZero) { double a = Math.Pow(intPower.Base.Max,intPower.Exponent); double b = Math.Pow(intPower.Base.Min,intPower.Exponent); //Console.WriteLine("Cur: {0} [{1} : {2}]",intPower,intPower.Min,intPower.Max); //Console.WriteLine("Base: [{0} : {1}]",intPower.Base.Min,intPower.Base.Max); if(UpdateInterval(intPower,Math.Min(a,b),Math.Max(a,b))) { //Console.WriteLine("From UW intpower {0}",intPower.Exponent); //if(UpdateInterval(intPower,Math.Pow(intPower.Base.Max,intPower.Exponent),Math.Pow(intPower.Base.Min,intPower.Exponent))) { AddChanged(intPower); return true; } } //else +- Infinity is possible return false; } public bool Visit(TermPower tp) { throw new NotImplementedException("Propagation for TemPower not implemented"); } public bool Visit(Gp gp) { throw new NotImplementedException("Propagation for TemPower not implemented"); } public bool Visit(Product product) { double aa = product.Left.Min*product.Right.Min; double bb = product.Left.Max*product.Right.Max; double max; double min; if (product.Left == product.Right) { min = Math.Min(aa,bb); max = Math.Max(aa,bb); if (product.Left.Min*product.Left.Max <= 0) min = 0; } else { double ab = product.Left.Min*product.Right.Max; double ba = product.Left.Max*product.Right.Min; max = Math.Max(aa,Math.Max(ab,Math.Max(ba,bb))); min = Math.Min(aa,Math.Min(ab,Math.Min(ba,bb))); } if(UpdateInterval(product,min,max)) { AddChanged(product); return true; } return false; } public bool Visit(Sigmoid sigmoid) { throw new NotImplementedException("Sigmoidal propagation not implemented"); } public bool Visit(LinSigmoid sigmoid) { throw new NotImplementedException("Sigmoidal propagation not implemented"); } public bool Visit(LTConstraint constraint) { if (constraint.Left.Max < constraint.Right.Min) { if(UpdateInterval(constraint,1,1)) { AddChanged(constraint); return true; } } else if (constraint.Left.Min >= constraint.Right.Max) { //Console.WriteLine("LT UP negated: {0} {1}",constraint.Left.Min ,constraint.Right.Max); if(UpdateInterval(constraint,Double.NegativeInfinity,0)) { AddChanged(constraint); return true; } } return false; } public bool Visit(LTEConstraint constraint) { if (constraint.Left.Max <= constraint.Right.Min) { if(UpdateInterval(constraint,1,1)) { AddChanged(constraint); return true; } } else if (constraint.Left.Min > constraint.Right.Max) { if(UpdateInterval(constraint,Double.NegativeInfinity,0)) { AddChanged(constraint); return true; } } return false; } public bool Visit(Min min) { if(UpdateInterval(min,Math.Min(min.Left.Min,min.Right.Min),Math.Max(min.Left.Max,min.Right.Max))) { AddChanged(min); return true; } return false; } public bool Visit(Max max) { if(UpdateInterval(max,Math.Min(max.Left.Min,max.Right.Min),Math.Max(max.Left.Max,max.Right.Max))) { AddChanged(max); return true; } return false; } public bool Visit(And and) { if(and.Left.Min > 0 && and.Right.Min > 0) { if(UpdateInterval(and,1,1)) { AddChanged(and); return true; } } else if(and.Left.Max <= 0 || and.Right.Max <= 0) { if(UpdateInterval(and,Double.NegativeInfinity,0)) { AddChanged(and); return true; } } return false; } public bool Visit(Or or) { if(or.Left.Min > 0 || or.Right.Min > 0) { if(UpdateInterval(or,1,1)) { AddChanged(or); return true; } } else if(or.Left.Max <= 0 && or.Right.Max <= 0) { if(UpdateInterval(or,Double.NegativeInfinity,0)) { AddChanged(or); return true; } } return false; } public bool Visit(ConstraintUtility cu) { if (cu.Constraint.Max < 1) { if (UpdateInterval(cu,Double.NegativeInfinity,cu.Constraint.Max)) { AddChanged(cu); return true; } } if (UpdateInterval(cu,Double.NegativeInfinity,cu.Utility.Max)) { AddChanged(cu); return true; } return false; } public bool Visit(Reification reif) { if (reif.Condition.Min > 0) { if(UpdateInterval(reif,reif.MaxVal,reif.MaxVal)) { AddChanged(reif); return true; } } else if (reif.Condition.Max < 0) { if(UpdateInterval(reif,reif.MinVal,reif.MinVal)) { AddChanged(reif); return true; } } return false; } public bool Visit(Sum sum) { double min = 0; double max = 0; for(int i=sum.Terms.Count-1; i>=0; --i) { min += sum.Terms[i].Min; max += sum.Terms[i].Max; } if(UpdateInterval(sum,min,max)) { AddChanged(sum); return true; } return false; } public bool Visit(AutoDiff.Variable variable) { return true; } public bool Visit(Log log) { if(UpdateInterval(log,Math.Log(log.Arg.Min),Math.Log(log.Arg.Max))) { AddChanged(log); return true; } return false; } public bool Visit(Sin sin) { double size = sin.Arg.Max - sin.Arg.Min; bool c = false; if (size <= 2*Math.PI) { double a = Math.Sin(sin.Arg.Max); double b = Math.Sin(sin.Arg.Min); double halfPI = Math.PI/2; double x = Math.Ceiling((sin.Arg.Min-halfPI) / Math.PI); double y = Math.Floor((sin.Arg.Max-halfPI)/ Math.PI); if (x==y) { //single extrema if(((int)x)%2 == 0) { //maxima c = UpdateInterval(sin,Math.Min(a,b),1); } else { //minima c = UpdateInterval(sin,-1,Math.Max(a,b)); } } else if (x > y) { //no extrema c = UpdateInterval(sin,Math.Min(a,b),Math.Max(a,b)); } //multiple extrema, don't update } if(c) AddChanged(sin); return c; } public bool Visit(Cos cos) { double size = cos.Arg.Max - cos.Arg.Min; bool c = false; if (size <= 2*Math.PI) { double a = Math.Cos(cos.Arg.Max); double b = Math.Cos(cos.Arg.Min); double x = Math.Ceiling(cos.Arg.Min / Math.PI); double y = Math.Floor(cos.Arg.Max / Math.PI); if (x==y) { //single extrema if(((int)x)%2 == 0) { //maxima c = UpdateInterval(cos,Math.Min(a,b),1); } else { //minima c = UpdateInterval(cos,-1,Math.Max(a,b)); } } else if (x > y) { //no extrema c = UpdateInterval(cos,Math.Min(a,b),Math.Max(a,b)); } //multiple extrema, don't update } if (c) AddChanged(cos); return c; } public bool Visit(Abs abs) { bool containsZero = abs.Arg.Min * abs.Arg.Max <= 0; bool c = false; if (containsZero) c = UpdateInterval(abs,0, Math.Max(Math.Abs(abs.Arg.Min),Math.Abs(abs.Arg.Max))); else c = UpdateInterval(abs,Math.Min(Math.Abs(abs.Arg.Min),Math.Abs(abs.Arg.Max)), Math.Max(Math.Abs(abs.Arg.Min),Math.Abs(abs.Arg.Max))); if (c) AddChanged(abs); return c; } public bool Visit(Exp exp) { if(UpdateInterval(exp,Math.Exp(exp.Arg.Min),Math.Exp(exp.Arg.Max))) { AddChanged(exp); return true; } return false; } public bool Visit(Atan2 atan2) { throw new NotImplementedException("Atan2 prop not implemented!"); } protected void OutputChange(Term t,double oldmin, double oldmax) { //Console.WriteLine("UW: Interval of {0} is now [{1}, {2}]",t,t.Min,t.Max); double oldwidth = oldmax - oldmin; double newwidth = t.Max - t.Min; if(t is AutoDiff.Variable) Console.WriteLine("UW shrinking [{0}..{1}] to [{2}..{3}] by {4} ({5}%)",oldmin,oldmax,t.Min,t.Max,oldwidth-newwidth,(oldwidth-newwidth)/oldwidth*100); } protected bool UpdateInterval(Term t, double min, double max) { bool ret = t.Min < min || t.Max > max; #if DEBUG_UP double oldmin = t.Min; double oldmax = t.Max; #endif if(!Double.IsNaN(min)) t.Min = Math.Max(t.Min,min); if(!Double.IsNaN(max)) t.Max = Math.Min(t.Max,max); if(ret) IntervalPropagator.updates++; IntervalPropagator.visits++; #if DEBUG_UP if (ret) OutputChange(t,oldmin,oldmax); #endif if (t.Min > t.Max) throw new UnsolveableException(); return ret; } } }
//----------------------------------------------------------------------- // <copyright file="<file>.cs" company="The Outercurve Foundation"> // Copyright (c) 2011, The Outercurve Foundation. // // Licensed under the MIT License (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.opensource.org/licenses/mit-license.php // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author> // <website>https://github.com/facebook-csharp-sdk/simple-json</website> //----------------------------------------------------------------------- namespace SimpleJsonTests { using System; using System.Collections.Generic; using System.Linq; #if NUNIT using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using ClassCleanup = NUnit.Framework.TestFixtureTearDownAttribute; using ClassInitialize = NUnit.Framework.TestFixtureSetUpAttribute; using NUnit.Framework; #else #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif #endif using SimpleJson; [TestClass] public class DeserializeObjectTypeTests { // Disable never used warnings for fields - they are actually used in deserialization #pragma warning disable 0169, 0649 private class Person { public string FirstName { get; set; } private string LastName { get; set; } public AddressInfo Address { get; set; } public string[] Langauges; public IEnumerable<string> Hobby; private string[] _nothing; public string[] Nothing { get { return _nothing; } } } private class AddressInfo { public string Country { get; set; } private string City; } #pragma warning restore 0169, 0649 [TestMethod] public void NullStringTests() { var result = SimpleJson.DeserializeObject(null, typeof(Person)); Assert.IsNull(result); } [TestMethod] public void NullStringGenericTests() { var result = SimpleJson.DeserializeObject<Person>(null); Assert.IsNull(result); } [TestMethod] public void BooleanTrueTests() { var json = "true"; var result = SimpleJson.DeserializeObject<bool>(json); Assert.IsTrue(result); } [TestMethod] public void BooleanFalseTests() { var json = "false"; var result = SimpleJson.DeserializeObject<bool>(json); Assert.IsFalse(result); } [TestMethod] public void NullTests() { var json = "null"; var result = SimpleJson.DeserializeObject<object>(json); Assert.IsNull(result); } [TestMethod] public void StringTests() { var json = "\"hello world\""; var result = SimpleJson.DeserializeObject<string>(json); Assert.AreEqual("hello world", result); } [TestMethod] public void DecimalToIntTest() { var json = "10.2"; var result = SimpleJson.DeserializeObject<int>(json); Assert.AreEqual(10, result); } [TestMethod] public void GivenNumberWithoutDecimalTypeIsLong() { var json = "10"; var result = SimpleJson.DeserializeObject(json); #if NETFX_CORE Assert.IsInstanceOfType(result, typeof(long)); #else Assert.IsInstanceOf<long>(result); #endif } [TestMethod] public void GivenNumberWithDecimalTypeIsDouble() { var json = "10.2"; var result = SimpleJson.DeserializeObject(json); #if NETFX_CORE Assert.IsInstanceOfType(result, typeof(double)); #else Assert.IsInstanceOf<double>(result); #endif } [TestMethod] public void GivenGuidAsNull() { var json = "null"; var guid = SimpleJson.DeserializeObject<Guid>(json); Assert.AreEqual(default(Guid), guid); } [TestMethod] public void GivenNullableGuidAsNull() { var json = "null"; var guid = SimpleJson.DeserializeObject<Guid?>(json); Assert.AreEqual(null, guid); } [TestMethod] public void GivenGuidAsEmptyString() { var json = @""""""; var guid = SimpleJson.DeserializeObject<Guid>(json); Assert.AreEqual(default(Guid), guid); } [TestMethod] public void GivenNullableGuidAsEmptyString() { var json = @""""""; var guid = SimpleJson.DeserializeObject<Guid?>(json); Assert.AreEqual(null, guid); } [TestMethod] public void GiveGuidAsStringWithHashAndSmallLetters() { var json = @"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d"""; var guid = SimpleJson.DeserializeObject<Guid>(json); Assert.AreEqual(new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"), guid); } [TestMethod] public void GiveNullableGuidAsStringWithHashAndSmallLetters() { var json = @"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d"""; var guid = SimpleJson.DeserializeObject<Guid?>(json); Assert.AreEqual(new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"), guid); } [TestMethod] public void GiveGuidAsStringWithHashAndCapitalLetters() { var json = @"""BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"""; var guid = SimpleJson.DeserializeObject<Guid>(json); Assert.AreEqual(new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"), guid); } [TestMethod] public void GivenNullableGuidAsStringWithHashAndCapitalLetters() { var json = @"""BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"""; var guid = SimpleJson.DeserializeObject<Guid?>(json); Assert.AreEqual(new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"), guid); } [TestMethod] public void ArrayAndListDeserializationTests() { var obj = new { FirstName = "Prabir", LastName = "Shrestha", Address = new { Country = "Nepal", City = "Kathmandu" }, Langauges = new[] { "English", "Nepali" }, Hobby = new[] { "Guitar", "Swimming", "Basketball" }, Nothing = new[] { "nothing" } }; var json = SimpleJson.SerializeObject(obj); var result = SimpleJson.DeserializeObject<Person>(json); Assert.AreEqual(obj.FirstName, result.FirstName); Assert.AreEqual(obj.Address.Country, result.Address.Country); Assert.AreEqual(obj.Langauges.Length, result.Langauges.Length); Assert.AreEqual(obj.Langauges[0], result.Langauges[0]); Assert.AreEqual(obj.Langauges[1], result.Langauges[1]); var hobies = result.Hobby.ToList(); Assert.AreEqual(obj.Hobby.Length, hobies.Count); Assert.AreEqual(obj.Hobby[0], hobies[0]); Assert.AreEqual(obj.Hobby[1], hobies[1]); Assert.AreEqual(obj.Hobby[2], hobies[2]); Assert.IsNull(result.Nothing); } [TestMethod] public void ClassArrayTests() { var json = "{\"Name\":\"person1\",\"HobbyArray\":[{\"name\":\"basketball\",\"value\":10},{\"name\":\"football\",\"value\":9}]}"; var result = SimpleJson.DeserializeObject<HobbyPersonArray>(json); Assert.IsNotNull(result); } [TestMethod] public void ClassListTests() { var json = "{\"Name\":\"person1\",\"HobbyArray\":[{\"name\":\"basketball\",\"value\":10},{\"name\":\"football\",\"value\":9}]}"; var result = SimpleJson.DeserializeObject<HobbyPersonList>(json); Assert.IsNotNull(result); } public class HobbyPersonArray { public string Name { get; set; } public Hobbies[] Hobbies { get; set; } } public class HobbyPersonList { public string Name { get; set; } public IList<Hobbies> Hobbies { get; set; } } public class Hobbies { public string Name; public int Value; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp.SoftBody { public enum DrawFlags { None = 0x00, Nodex = 0x01, Links = 0x02, Faces = 0x04, Tetras = 0x08, Normals = 0x10, Contacts = 0x20, Anchors = 0x40, Notes = 0x80, Clusters = 0x100, NodeTree = 0x200, FaceTree = 0x400, ClusterTree = 0x800, Joints = 0x1000, Std = Links | Faces | Tetras | Anchors | Notes | Joints, StdTetra = Std - Faces - Tetras } public sealed class SoftBodyHelpers { private SoftBodyHelpers() { } public static float CalculateUV(int resx, int resy, int ix, int iy, int id) { switch (id) { case 0: return 1.0f / ((resx - 1)) * ix; case 1: return 1.0f / ((resy - 1)) * (resy - 1 - iy); case 2: return 1.0f / ((resy - 1)) * (resy - 1 - iy - 1); case 3: return 1.0f / ((resx - 1)) * (ix + 1); default: return 0; } } public static SoftBody CreateEllipsoid(SoftBodyWorldInfo worldInfo, Vector3 center, Vector3 radius, int res) { int numVertices = res + 3; Vector3[] vtx = new Vector3[numVertices]; for (int i = 0; i < numVertices; i++) { float p = 0.5f, t = 0; for (int j = i; j > 0; j >>= 1) { if ((j & 1) != 0) t += p; p *= 0.5f; } float w = 2 * t - 1; float a = ((1 + 2 * i) * (float)System.Math.PI) / numVertices; float s = (float)System.Math.Sqrt(1 - w * w); vtx[i] = new Vector3(s * (float)System.Math.Cos(a), s * (float)System.Math.Sin(a), w) * radius + center; } return CreateFromConvexHull(worldInfo, vtx); } public static SoftBody CreateFromConvexHull(SoftBodyWorldInfo worldInfo, Vector3[] vertices, int nVertices, bool randomizeConstraints = true) { SoftBody body = new SoftBody(btSoftBodyHelpers_CreateFromConvexHull2(worldInfo._native, vertices, nVertices, randomizeConstraints)); body.WorldInfo = worldInfo; return body; } public static SoftBody CreateFromConvexHull(SoftBodyWorldInfo worldInfo, Vector3[] vertices, bool randomizeConstraints = true) { SoftBody body = new SoftBody(btSoftBodyHelpers_CreateFromConvexHull2(worldInfo._native, vertices, vertices.Length, randomizeConstraints)); body.WorldInfo = worldInfo; return body; } public static SoftBody CreateFromTetGenData(SoftBodyWorldInfo worldInfo, string ele, string face, string node, bool faceLinks, bool tetraLinks, bool facesFromTetras) { CultureInfo culture = CultureInfo.InvariantCulture; char[] separator = new[] { ' ' }; Vector3[] pos; using (StringReader nodeReader = new StringReader(node)) { string[] nodeHeader = nodeReader.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries); int numNodes = int.Parse(nodeHeader[0]); //int numDims = int.Parse(nodeHeader[1]); //int numAttrs = int.Parse(nodeHeader[2]); //bool hasBounds = !nodeHeader[3].Equals("0"); pos = new Vector3[numNodes]; for (int n = 0; n < numNodes; n++) { string[] nodeLine = nodeReader.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries); pos[int.Parse(nodeLine[0])] = new Vector3( float.Parse(nodeLine[1], culture), float.Parse(nodeLine[2], culture), float.Parse(nodeLine[3], culture)); } } SoftBody psb = new SoftBody(worldInfo, pos.Length, pos, null); /* if (!string.IsNullOrEmpty(face)) { throw new NotImplementedException(); } */ if (!string.IsNullOrEmpty(ele)) { using (StringReader eleReader = new StringReader(ele)) { string[] eleHeader = eleReader.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries); int numTetras = int.Parse(eleHeader[0]); //int numCorners = int.Parse(eleHeader[1]); //int numAttrs = int.Parse(eleHeader[2]); for (int n = 0; n < numTetras; n++) { string[] eleLine = eleReader.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries); //int index = int.Parse(eleLine[0], culture); int ni0 = int.Parse(eleLine[1], culture); int ni1 = int.Parse(eleLine[2], culture); int ni2 = int.Parse(eleLine[3], culture); int ni3 = int.Parse(eleLine[4], culture); psb.AppendTetra(ni0, ni1, ni2, ni3); if (tetraLinks) { psb.AppendLink(ni0, ni1, null, true); psb.AppendLink(ni1, ni2, null, true); psb.AppendLink(ni2, ni0, null, true); psb.AppendLink(ni0, ni3, null, true); psb.AppendLink(ni1, ni3, null, true); psb.AppendLink(ni2, ni3, null, true); } } } } //Console.WriteLine("Nodes: {0}", psb.Nodes.Count); //Console.WriteLine("Links: {0}", psb.Links.Count); //Console.WriteLine("Faces: {0}", psb.Faces.Count); //Console.WriteLine("Tetras: {0}", psb.Tetras.Count); return psb; } public static SoftBody CreateFromTetGenFile(SoftBodyWorldInfo worldInfo, string elementFilename, string faceFilename, string nodeFilename, bool faceLinks, bool tetraLinks, bool facesFromTetras) { string ele = (elementFilename != null) ? File.ReadAllText(elementFilename) : null; string face = (faceFilename != null) ? File.ReadAllText(faceFilename) : null; return CreateFromTetGenData(worldInfo, ele, face, File.ReadAllText(nodeFilename), faceLinks, tetraLinks, facesFromTetras); } public static SoftBody CreateFromTriMesh(SoftBodyWorldInfo worldInfo, float[] vertices, int[] triangles, bool randomizeConstraints = true) { int numVertices = vertices.Length / 3; Vector3[] vtx = new Vector3[numVertices]; for (int i = 0, j = 0; j < numVertices; j++, i += 3) { vtx[j] = new Vector3(vertices[i], vertices[i + 1], vertices[i + 2]); } return CreateFromTriMesh(worldInfo, vtx, triangles, randomizeConstraints); } public static SoftBody CreateFromTriMesh(SoftBodyWorldInfo worldInfo, Vector3[] vertices, int[] triangles, bool randomizeConstraints = true) { int numTriangleIndices = triangles.Length; int numTriangles = numTriangleIndices / 3; int maxIndex = 0; // triangles.Max() + 1; for (int i = 0; i < numTriangleIndices; i++) { if (triangles[i] > maxIndex) { maxIndex = triangles[i]; } } maxIndex++; SoftBody psb = new SoftBody(worldInfo, maxIndex, vertices, null); BitArray chks = new BitArray(maxIndex * maxIndex); for (int i = 0; i < numTriangleIndices; i += 3) { int[] idx = new int[] { triangles[i], triangles[i + 1], triangles[i + 2] }; for (int j = 2, k = 0; k < 3; j = k++) { int chkIndex = maxIndex * idx[k] + idx[j]; if (!chks[chkIndex]) { chks[chkIndex] = true; chks[maxIndex * idx[j] + idx[k]] = true; psb.AppendLink(idx[j], idx[k]); } } psb.AppendFace(idx[0], idx[1], idx[2]); } if (randomizeConstraints) { psb.RandomizeConstraints(); } return psb; } public static SoftBody CreatePatch(SoftBodyWorldInfo worldInfo, Vector3 corner00, Vector3 corner10, Vector3 corner01, Vector3 corner11, int resx, int resy, int fixeds, bool gendiags) { // Create nodes if ((resx < 2) || (resy < 2)) return null; int rx = resx; int ry = resy; int tot = rx * ry; Vector3[] x = new Vector3[tot]; float[] m = new float[tot]; for (int iy = 0; iy < ry; iy++) { float ty = iy / (float)(ry - 1); Vector3 py0, py1; Vector3.Lerp(ref corner00, ref corner01, ty, out py0); Vector3.Lerp(ref corner10, ref corner11, ty, out py1); for (int ix = 0; ix < rx; ix++) { float tx = ix / (float)(rx - 1); int index = rx * iy + ix; Vector3.Lerp(ref py0, ref py1, tx, out x[index]); m[index] = 1; } } SoftBody psb = new SoftBody(worldInfo, tot, x, m); if ((fixeds & 1) != 0) psb.SetMass(0, 0); if ((fixeds & 2) != 0) psb.SetMass(rx - 1, 0); if ((fixeds & 4) != 0) psb.SetMass(rx * (ry - 1), 0); if ((fixeds & 8) != 0) psb.SetMass(rx * (ry - 1) + rx - 1, 0); // Create links and faces for (int iy = 0; iy < ry; ++iy) { for (int ix = 0; ix < rx; ++ix) { int ixy = rx * iy + ix; int ix1y = ixy + 1; int ixy1 = rx * (iy + 1) + ix; bool mdx = (ix + 1) < rx; bool mdy = (iy + 1) < ry; if (mdx) psb.AppendLink(ixy, ix1y); if (mdy) psb.AppendLink(ixy, ixy1); if (mdx && mdy) { int ix1y1 = ixy1 + 1; if (((ix + iy) & 1) != 0) { psb.AppendFace(ixy, ix1y, ix1y1); psb.AppendFace(ixy, ix1y1, ixy1); if (gendiags) { psb.AppendLink(ixy, ix1y1); } } else { psb.AppendFace(ixy1, ixy, ix1y); psb.AppendFace(ixy1, ix1y, ix1y1); if (gendiags) { psb.AppendLink(ix1y, ixy1); } } } } } return psb; } public static SoftBody CreatePatchUV(SoftBodyWorldInfo worldInfo, Vector3 corner00, Vector3 corner10, Vector3 corner01, Vector3 corner11, int resx, int resy, int fixeds, bool gendiags) { SoftBody body = new SoftBody(btSoftBodyHelpers_CreatePatchUV(worldInfo._native, ref corner00, ref corner10, ref corner01, ref corner11, resx, resy, fixeds, gendiags)); body.WorldInfo = worldInfo; return body; } public static SoftBody CreatePatchUV(SoftBodyWorldInfo worldInfo, Vector3 corner00, Vector3 corner10, Vector3 corner01, Vector3 corner11, int resx, int resy, int fixeds, bool gendiags, float[] texCoords) { SoftBody body = new SoftBody(btSoftBodyHelpers_CreatePatchUV2(worldInfo._native, ref corner00, ref corner10, ref corner01, ref corner11, resx, resy, fixeds, gendiags, texCoords)); body.WorldInfo = worldInfo; return body; } public static SoftBody CreateRope(SoftBodyWorldInfo worldInfo, Vector3 from, Vector3 to, int res, int fixeds) { // Create nodes int r = res + 2; Vector3[] x = new Vector3[r]; float[] m = new float[r]; for (int i = 0; i < r; i++) { Vector3.Lerp(ref from, ref to, i / (float)(r - 1), out x[i]); m[i] = 1; } SoftBody psb = new SoftBody(worldInfo, r, x, m); if ((fixeds & 1) != 0) psb.SetMass(0, 0); if ((fixeds & 2) != 0) psb.SetMass(r - 1, 0); // Create links for (int i = 1; i < r; i++) { psb.AppendLink(i - 1, i); } return psb; } public static void Draw(SoftBody psb, IDebugDraw iDraw) { btSoftBodyHelpers_Draw(psb._native, DebugDraw.GetUnmanaged(iDraw)); } public static void Draw(SoftBody psb, IDebugDraw iDraw, int drawFlags) { btSoftBodyHelpers_Draw2(psb._native, DebugDraw.GetUnmanaged(iDraw), drawFlags); } public static void DrawClusterTree(SoftBody psb, IDebugDraw iDraw) { btSoftBodyHelpers_DrawClusterTree(psb._native, DebugDraw.GetUnmanaged(iDraw)); } public static void DrawClusterTree(SoftBody psb, IDebugDraw iDraw, int minDepth) { btSoftBodyHelpers_DrawClusterTree2(psb._native, DebugDraw.GetUnmanaged(iDraw), minDepth); } public static void DrawClusterTree(SoftBody psb, IDebugDraw iDraw, int minDepth, int maxDepth) { btSoftBodyHelpers_DrawClusterTree3(psb._native, DebugDraw.GetUnmanaged(iDraw), minDepth, maxDepth); } public static void DrawFaceTree(SoftBody psb, IDebugDraw iDraw) { btSoftBodyHelpers_DrawFaceTree(psb._native, DebugDraw.GetUnmanaged(iDraw)); } public static void DrawFaceTree(SoftBody psb, IDebugDraw iDraw, int minDepth) { btSoftBodyHelpers_DrawFaceTree2(psb._native, DebugDraw.GetUnmanaged(iDraw), minDepth); } public static void DrawFaceTree(SoftBody psb, IDebugDraw iDraw, int minDepth, int maxDepth) { btSoftBodyHelpers_DrawFaceTree3(psb._native, DebugDraw.GetUnmanaged(iDraw), minDepth, maxDepth); } public static void DrawFrame(SoftBody psb, IDebugDraw iDraw) { btSoftBodyHelpers_DrawFrame(psb._native, DebugDraw.GetUnmanaged(iDraw)); } public static void DrawInfos(SoftBody psb, IDebugDraw iDraw, bool masses, bool areas, bool stress) { btSoftBodyHelpers_DrawInfos(psb._native, DebugDraw.GetUnmanaged(iDraw), masses, areas, stress); } public static void DrawNodeTree(SoftBody psb, IDebugDraw iDraw) { btSoftBodyHelpers_DrawNodeTree(psb._native, DebugDraw.GetUnmanaged(iDraw)); } public static void DrawNodeTree(SoftBody psb, IDebugDraw iDraw, int minDepth) { btSoftBodyHelpers_DrawNodeTree2(psb._native, DebugDraw.GetUnmanaged(iDraw), minDepth); } public static void DrawNodeTree(SoftBody psb, IDebugDraw iDraw, int minDepth, int maxDepth) { btSoftBodyHelpers_DrawNodeTree3(psb._native, DebugDraw.GetUnmanaged(iDraw), minDepth, maxDepth); } private class LinkDep { public bool LinkB { get; set; } public LinkDep Next { get; set; } public Link Value { get; set; } } // ReoptimizeLinkOrder minimizes the cases where links L and L+1 share a common node. public static void ReoptimizeLinkOrder(SoftBody psb) { AlignedLinkArray links = psb.Links; AlignedNodeArray nodes = psb.Nodes; int nLinks = links.Count; int nNodes = nodes.Count; List<Link> readyList = new List<Link>(); Dictionary<Link, Link> linkBuffer = new Dictionary<Link, Link>(); Dictionary<Link, LinkDep> linkDeps = new Dictionary<Link, LinkDep>(); Dictionary<Node, Link> nodeWrittenAt = new Dictionary<Node, Link>(); Dictionary<Link, Link> linkDepA = new Dictionary<Link, Link>(); // Link calculation input is dependent upon prior calculation #N Dictionary<Link, Link> linkDepB = new Dictionary<Link, Link>(); foreach (Link link in links) { Node ar = link.Nodes[0]; Node br = link.Nodes[1]; linkBuffer.Add(link, new Link(btSoftBody_Link_new2(link._native))); LinkDep linkDep; if (nodeWrittenAt.ContainsKey(ar)) { linkDepA[link] = nodeWrittenAt[ar]; linkDeps.TryGetValue(nodeWrittenAt[ar], out linkDep); linkDeps[nodeWrittenAt[ar]] = new LinkDep() { Next = linkDep, Value = link}; } if (nodeWrittenAt.ContainsKey(br)) { linkDepB[link] = nodeWrittenAt[br]; linkDeps.TryGetValue(nodeWrittenAt[br], out linkDep); linkDeps[nodeWrittenAt[br]] = new LinkDep() { Next = linkDep, Value = link, LinkB = true }; } if (!linkDepA.ContainsKey(link) && !linkDepB.ContainsKey(link)) { readyList.Add(link); } // Update the nodes to mark which ones are calculated by this link nodeWrittenAt[ar] = link; nodeWrittenAt[br] = link; } int i = 0; while (readyList.Count != 0) { Link link = readyList[0]; links[i++] = linkBuffer[link]; readyList.RemoveAt(0); LinkDep linkDep; linkDeps.TryGetValue(link, out linkDep); while (linkDep != null) { link = linkDep.Value; if (linkDep.LinkB) { linkDepB.Remove(link); } else { linkDepA.Remove(link); } // Add this dependent link calculation to the ready list if *both* inputs are clear if (!linkDepA.ContainsKey(link) && !linkDepB.ContainsKey(link)) { readyList.Add(link); } linkDep = linkDep.Next; } } foreach (Link link in linkBuffer.Values) { btSoftBody_Element_delete(link._native); } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSoftBodyHelpers_CreateFromConvexHull(IntPtr worldInfo, [In] Vector3[] vertices, int nvertices); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSoftBodyHelpers_CreateFromConvexHull2(IntPtr worldInfo, [In] Vector3[] vertices, int nvertices, bool randomizeConstraints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSoftBodyHelpers_CreatePatchUV(IntPtr worldInfo, [In] ref Vector3 corner00, [In] ref Vector3 corner10, [In] ref Vector3 corner01, [In] ref Vector3 corner11, int resx, int resy, int fixeds, bool gendiags); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSoftBodyHelpers_CreatePatchUV2(IntPtr worldInfo, [In] ref Vector3 corner00, [In] ref Vector3 corner10, [In] ref Vector3 corner01, [In] ref Vector3 corner11, int resx, int resy, int fixeds, bool gendiags, float[] tex_coords); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_Draw(IntPtr psb, IntPtr idraw); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_Draw2(IntPtr psb, IntPtr idraw, int drawflags); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawClusterTree(IntPtr psb, IntPtr idraw); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawClusterTree2(IntPtr psb, IntPtr idraw, int minDepth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawClusterTree3(IntPtr psb, IntPtr idraw, int minDepth, int maxDepth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawFaceTree(IntPtr psb, IntPtr idraw); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawFaceTree2(IntPtr psb, IntPtr idraw, int minDepth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawFaceTree3(IntPtr psb, IntPtr idraw, int minDepth, int maxDepth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawFrame(IntPtr psb, IntPtr idraw); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawInfos(IntPtr psb, IntPtr idraw, bool masses, bool areas, bool stress); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawNodeTree(IntPtr psb, IntPtr idraw); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawNodeTree2(IntPtr psb, IntPtr idraw, int minDepth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBodyHelpers_DrawNodeTree3(IntPtr psb, IntPtr idraw, int minDepth, int maxDepth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSoftBody_Link_new2(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btSoftBody_Element_delete(IntPtr obj); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.Sys.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.Value; } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (IOException) when (!disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } private void FlushWriteBufferForWriteByte() { _asyncState?.Wait(); try { FlushWriteBuffer(); } finally { _asyncState?.Release(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> private int ReadSpan(Span<byte> destination) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (destination.Length >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(destination); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer()); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, destination.Length); new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < destination.Length) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(destination.Slice(bytesRead)); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary> /// <param name="buffer">The buffer into which data from the file is read.</param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(Span<byte> buffer) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference()) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length)); Debug.Assert(bytesRead <= buffer.Length); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_useAsyncIO) { if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= count) { try { PrepareForReading(); Buffer.BlockCopy(GetBuffer(), _readPos, buffer, offset, count); _readPos += count; return _asyncState._lastSuccessfulReadTask != null && _asyncState._lastSuccessfulReadTask.Result == count ? _asyncState._lastSuccessfulReadTask : (_asyncState._lastSuccessfulReadTask = Task.FromResult(count)); } catch (Exception exc) { return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.Update(buffer, offset, count); return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { byte[] b = thisRef._asyncState._buffer; thisRef._asyncState._buffer = null; // remove reference to user's buffer return thisRef.ReadSpan(new Span<byte>(b, thisRef._asyncState._offset, thisRef._asyncState._count)); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } else { return base.ReadAsync(buffer, offset, count, cancellationToken); } } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() { _asyncState?.Wait(); try { return ReadNative(_buffer); } finally { _asyncState?.Release(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private void WriteSpan(ReadOnlySpan<byte> source) { PrepareForWriting(); // If no data is being written, nothing more to do. if (source.Length == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { source.CopyTo(new Span<byte>(GetBuffer(), _writePos)); _writePos += source.Length; return; } else if (spaceRemaining > 0) { source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer(), _writePos)); _writePos += spaceRemaining; source = source.Slice(spaceRemaining); } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (source.Length >= _bufferLength) { WriteNative(source); } else { source.CopyTo(new Span<byte>(GetBuffer())); _writePos = source.Length; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private unsafe void WriteNative(ReadOnlySpan<byte> source) { VerifyOSHandlePosition(); fixed (byte* bufPtr = &source.DangerousGetPinnableReference()) { int offset = 0; int count = source.Length; while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); _filePosition += bytesWritten; offset += bytesWritten; count -= bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_useAsyncIO) { if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= count) { try { PrepareForWriting(); Buffer.BlockCopy(buffer, offset, GetBuffer(), _writePos, count); _writePos += count; return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.Update(buffer, offset, count); return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position/length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { byte[] b = thisRef._asyncState._buffer; thisRef._asyncState._buffer = null; // remove reference to user's buffer thisRef.WriteSpan(new ReadOnlySpan<byte>(b, thisRef._asyncState._offset, thisRef._asyncState._count)); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } else { return base.WriteAsync(buffer, offset, count, cancellationToken); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { /// <summary>The caller's buffer currently being used by the active async operation.</summary> internal byte[] _buffer; /// <summary>The caller's offset currently being used by the active async operation.</summary> internal int _offset; /// <summary>The caller's count currently being used by the active async operation.</summary> internal int _count; /// <summary>The last task successfully, synchronously returned task from ReadAsync.</summary> internal Task<int> _lastSuccessfulReadTask; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } /// <summary>Sets the active buffer, offset, and count.</summary> internal void Update(byte[] buffer, int offset, int count) { _buffer = buffer; _offset = offset; _count = count; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { internal class VerifyNameTests3 : CTestCase { public override void AddChildren() { AddChild(new CVariation(v16) { Attribute = new Variation("15.Test for VerifyNCName(\ud801\r\udc01)") { Params = new object[] { 15, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("6.Test for VerifyNCName(abcd\ralfafkjha)") { Params = new object[] { 6, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("8.Test for VerifyNCName(abcd\tdef)") { Params = new object[] { 8, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("9.Test for VerifyNCName( \b)") { Params = new object[] { 9, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("10.Test for VerifyNCName(\ud801\udc01)") { Params = new object[] { 10, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("11.Test for VerifyNCName( \ud801\udc01)") { Params = new object[] { 11, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("12.Test for VerifyNCName(\ud801\udc01 )") { Params = new object[] { 12, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("13.Test for VerifyNCName(\ud801 \udc01)") { Params = new object[] { 13, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("14.Test for VerifyNCName(\ud801 \udc01)") { Params = new object[] { 14, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("1.Test for VerifyNCName(abcd)") { Params = new object[] { 1, "valid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("16.Test for VerifyNCName(\ud801\n\udc01)") { Params = new object[] { 16, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("17.Test for VerifyNCName(\ud801\t\udc001)") { Params = new object[] { 17, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("18.Test for VerifyNCName(a\ud801\udc01b)") { Params = new object[] { 18, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("19.Test for VerifyNCName(a\udc01\ud801b)") { Params = new object[] { 19, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("20.Test for VerifyNCName(a\ud801b)") { Params = new object[] { 20, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("21.Test for VerifyNCName(a\udc01b)") { Params = new object[] { 21, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("22.Test for VerifyNCName(\ud801\udc01:)") { Params = new object[] { 22, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("23.Test for VerifyNCName(:a\ud801\udc01b)") { Params = new object[] { 23, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("24.Test for VerifyNCName(a\ud801\udc01:b)") { Params = new object[] { 24, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("25.Test for VerifyNCName(a\udbff\udc01\b)") { Params = new object[] { 25, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("7.Test for VerifyNCName(abcd def)") { Params = new object[] { 7, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("2.Test for VerifyNCName(abcd efgh)") { Params = new object[] { 2, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("3.Test for VerifyNCName( abcd)") { Params = new object[] { 3, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("4.Test for VerifyNCName(abcd\nalfafkjha)") { Params = new object[] { 4, "invalid" } } }); AddChild(new CVariation(v16) { Attribute = new Variation("5.Test for VerifyNCName(abcd\nalfafkjha)") { Params = new object[] { 5, "invalid" } } }); AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNCName(null)") { Param = 3 } }); AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyXmlChars(null)") { Param = 5 } }); AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyPublicId(null)") { Param = 6 } }); AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyWhitespace(null)") { Param = 7 } }); AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyName(null)") { Param = 2 } }); AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNMTOKEN(null)") { Param = 1 } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyPublicId(String.Empty)") { Params = new object[] { 6, null } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyWhitespace(String.Empty)") { Params = new object[] { 7, null } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyName(String.Empty)") { Params = new object[] { 2, typeof(ArgumentNullException) } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNCName(String.Empty)") { Params = new object[] { 3, typeof(ArgumentNullException) } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyXmlChars(String.Empty)") { Params = new object[] { 5, null } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNMTOKEN(String.Empty)") { Params = new object[] { 1, typeof(XmlException) } } }); } private int v16() { var param = (int)CurVariation.Params[0]; string input = String.Empty; switch (param) { case 1: input = "abcd"; break; case 2: input = "abcd efgh"; break; case 3: input = " abcd"; break; case 4: input = "abcd "; break; case 5: input = "abcd\nalfafkjha"; break; case 6: input = "abcd\ralfafkjha"; break; case 7: input = "abcd def"; break; case 8: input = "abcd\tdef"; break; case 9: input = " \b"; break; case 10: input = "\ud801\udc01"; break; case 11: input = " \ud801\udc01"; break; case 12: input = "\ud801\udc01 "; break; case 13: input = "\ud801 \udc01"; break; case 14: input = "\ud801 \udc01"; break; case 15: input = "\ud801\r\udc01"; break; case 16: input = "\ud801\n\udc01"; break; case 17: input = "\ud801\t\udc01"; break; case 18: input = "a\ud801\udc01b"; break; case 19: input = "a\udc01\ud801b"; break; case 20: input = "a\ud801b"; break; case 21: input = "a\udc01b"; break; case 22: input = "\ud801\udc01:"; break; case 23: input = ":a\ud801\udc01b"; break; case 24: input = "a\ud801\udc01b:"; break; case 25: input = "a\udbff\udc01\b"; break; } String expected = CurVariation.Params[1].ToString(); try { XmlConvert.VerifyNCName(input); } catch (XmlException e) { CError.WriteLine(e.LineNumber); CError.WriteLine(e.LinePosition); return (expected.Equals("invalid")) ? TEST_PASS : TEST_FAIL; } return (expected.Equals("valid")) ? TEST_PASS : TEST_FAIL; } private int v17() { var param = (int)CurVariation.Param; try { switch (param) { case 1: XmlConvert.VerifyNMTOKEN(null); break; case 2: XmlConvert.VerifyName(null); break; case 3: XmlConvert.VerifyNCName(null); break; case 5: XmlConvert.VerifyXmlChars(null); break; case 6: XmlConvert.VerifyPublicId(null); break; case 7: XmlConvert.VerifyWhitespace(null); break; } } catch (ArgumentNullException) { return param != 4 ? TEST_PASS : TEST_FAIL; //param4 -> VerifyToken should not throw here } return TEST_FAIL; } /// <summary> /// Params[] = { VariationNumber, Exception type (null if exception not expected) } /// </summary> /// <returns></returns> private int v18() { var param = (int)CurVariation.Params[0]; var exceptionType = (Type)CurVariation.Params[1]; try { switch (param) { case 1: XmlConvert.VerifyNMTOKEN(String.Empty); break; case 2: XmlConvert.VerifyName(String.Empty); break; case 3: XmlConvert.VerifyNCName(String.Empty); break; case 5: XmlConvert.VerifyXmlChars(String.Empty); break; case 6: XmlConvert.VerifyPublicId(String.Empty); break; case 7: XmlConvert.VerifyWhitespace(String.Empty); break; } } catch (ArgumentException e) { return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } catch (XmlException e) { CError.WriteLine(e.LineNumber); CError.WriteLine(e.LinePosition); return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } return exceptionType == null ? TEST_PASS : TEST_FAIL; } } }
namespace AngleSharp.Css.Parser { using AngleSharp.Css.Dom; using AngleSharp.Css.Values; using AngleSharp.Text; using System; using System.Collections.Generic; static class GridParser { public static ICssValue ParseGridTemplate(this StringSource source) { var pos = source.Index; if (source.IsIdentifier(CssKeywords.None)) { return new Identifier(CssKeywords.None); } var rows = source.ParseTrackList() ?? source.ParseAutoTrackList(); if (rows != null) { var c = source.SkipSpacesAndComments(); if (c == Symbols.Solidus) { source.SkipCurrentAndSpaces(); var cols = source.ParseTrackList() ?? source.ParseAutoTrackList(); if (cols != null) { source.SkipSpacesAndComments(); return new CssGridTemplateValue(rows, cols, null); } } } else { var rowValues = new List<ICssValue>(); var col = default(ICssValue); var areaValues = new List<ICssValue>(); var hasValue = false; while (!source.IsDone) { var value = source.ParseGridTemplateAlternative(); if (value == null) { break; } hasValue = true; source.SkipSpacesAndComments(); rowValues.Add(new CssTupleValue(new[] { value.Item1, value.Item3, value.Item4 })); areaValues.Add(new Label(value.Item2)); } if (hasValue) { if (source.Current == Symbols.Solidus) { source.SkipCurrentAndSpaces(); col = source.ParseExplicitTrackList(); if (col == null) { source.BackTo(pos); return null; } } var row = new CssTupleValue(rowValues.ToArray()); var area = new CssTupleValue(areaValues.ToArray()); return new CssGridTemplateValue(row, col, area); } } source.BackTo(pos); return null; } private static Tuple<LineNames?, String, ICssValue, LineNames?> ParseGridTemplateAlternative(this StringSource source) { var namesHead = source.ParseLineNames(); source.SkipSpacesAndComments(); var str = source.ParseString(); source.SkipSpacesAndComments(); if (str != null) { var trackSize = source.ParseTrackSize(); source.SkipSpacesAndComments(); var namesTail = source.ParseLineNames(); source.SkipSpacesAndComments(); return Tuple.Create(namesHead, str, trackSize, namesTail); } return null; } public static LineNames? ParseLineNames(this StringSource source) { var pos = source.Index; if (source.Current == Symbols.SquareBracketOpen) { source.SkipCurrentAndSpaces(); var names = new List<String>(); while (!source.IsDone) { var name = source.ParseIdent(); if (name == null) { break; } names.Add(name); var current = source.SkipSpacesAndComments(); if (current == Symbols.SquareBracketClose) { source.Next(); return new LineNames(names); } } } source.BackTo(pos); return null; } public static ICssValue ParseFixedSize(this StringSource source) { var length = source.ParseDistanceOrCalc(); if (length == null) { var pos = source.Index; var ident = source.ParseIdent(); if (ident.Isi(FunctionNames.Minmax) && source.Current == Symbols.RoundBracketOpen) { var c = source.SkipCurrentAndSpaces(); var min = source.ParseTrackBreadth(false); c = source.SkipSpaces(); if (min != null && c == Symbols.Comma) { source.SkipCurrentAndSpaces(); var max = source.ParseTrackBreadth(); c = source.SkipSpacesAndComments(); if (max != null && c == Symbols.RoundBracketClose && (min is Length? || max is Length?)) { source.Next(); return new CssMinMaxValue(min, max); } } } source.BackTo(pos); return null; } return length; } public static ICssValue ParseTrackSize(this StringSource source) { var length = source.ParseTrackBreadth(); if (length == null) { var pos = source.Index; var ident = source.ParseIdent(); if (ident.Isi(FunctionNames.FitContent) && source.Current == Symbols.RoundBracketOpen) { source.SkipCurrentAndSpaces(); var dim = source.ParseDistanceOrCalc(); var c = source.SkipSpacesAndComments(); if (dim != null && c == Symbols.RoundBracketClose) { source.Next(); return new CssFitContentValue(dim); } } else if (ident.Isi(FunctionNames.Minmax) && source.Current == Symbols.RoundBracketOpen) { var c = source.SkipCurrentAndSpaces(); var min = source.ParseTrackBreadth(false); c = source.SkipSpaces(); if (min != null && c == Symbols.Comma) { source.SkipCurrentAndSpaces(); var max = source.ParseTrackBreadth(); c = source.SkipSpacesAndComments(); if (max != null && c == Symbols.RoundBracketClose) { source.Next(); return new CssMinMaxValue(min, max); } } } source.BackTo(pos); return null; } return length; } public static ICssValue ParseFixedRepeat(this StringSource source) { return source.ParseRepeat(ParseIntegerCount, ParseFixedRepeatValue); } public static ICssValue ParseAutoRepeat(this StringSource source) { return source.ParseRepeat(ParseAutoCount, ParseFixedRepeatValue); } public static ICssValue ParseTrackRepeat(this StringSource source) { return source.ParseRepeat(ParseIntegerCount, ParseTrackRepeatValue); } private static ICssValue ParseAutoCount(this StringSource source) { var arg = source.ParseIdent(); if (arg != null) { if (arg.Isi(CssKeywords.AutoFill)) { return new Identifier(CssKeywords.AutoFill); } else if (arg.Isi(CssKeywords.AutoFit)) { return new Identifier(CssKeywords.AutoFit); } } return null; } private static ICssValue ParseIntegerCount(this StringSource source) { var arg = source.ParsePositiveInteger(); if (arg.HasValue) { return new Length(arg.Value, Length.Unit.None); } return null; } private static ICssValue ParseRepeat(this StringSource source, Func<StringSource, ICssValue> parseCount, Func<StringSource, ICssValue> parseValue) { var pos = source.Index; var ident = source.ParseIdent(); if (ident.Isi(FunctionNames.Repeat) && source.Current == Symbols.RoundBracketOpen) { var c = source.SkipCurrentAndSpaces(); var count = parseCount(source); c = source.SkipSpaces(); if (count != null && c == Symbols.Comma) { source.SkipCurrentAndSpaces(); var value = parseValue(source); c = source.SkipSpacesAndComments(); if (value != null && c == Symbols.RoundBracketClose) { source.Next(); return new CssRepeatValue(count, value); } } } source.BackTo(pos); return null; } private static ICssValue ParseFixedRepeatValue(this StringSource source) { return source.ParseRepeatValue(ParseFixedSize); } private static ICssValue ParseTrackRepeatValue(this StringSource source) { return source.ParseRepeatValue(ParseTrackSize); } public static ICssValue ParseTrackList(this StringSource source) { return source.ParseRepeatValue(s => s.ParseTrackSize() ?? s.ParseTrackRepeat()); } public static ICssValue ParseExplicitTrackList(this StringSource source) { return source.ParseRepeatValue(s => s.ParseTrackSize()); } public static ICssValue ParseAutoTrackList(this StringSource source) { var values = new List<ICssValue>(); var pos = source.Index; var head = source.ParseRepeatValue(s => s.ParseFixedSize() ?? s.ParseFixedRepeat(), true); if (head != null) { values.Add(head); } source.SkipSpacesAndComments(); var repeat = source.ParseAutoRepeat(); if (repeat == null) { source.BackTo(pos); return null; } values.Add(repeat); source.SkipSpacesAndComments(); var tail = source.ParseRepeatValue(s => s.ParseFixedSize() ?? s.ParseFixedRepeat(), true); source.SkipSpacesAndComments(); if (tail != null) { values.Add(tail); } return new CssTupleValue(values.ToArray()); } private static ICssValue ParseRepeatValue(this StringSource source, Func<StringSource, ICssValue> parseTrack, Boolean hasSize = false) { var values = new List<ICssValue>(); var pos = source.Index; while (!source.IsDone) { var names = source.ParseLineNames(); source.SkipSpacesAndComments(); if (names != null) { values.Add(names); } var size = parseTrack(source); source.SkipSpacesAndComments(); if (size == null) { break; } hasSize = true; values.Add(size); } if (hasSize) { return new CssTupleValue(values.ToArray()); } source.BackTo(pos); return null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using LibGit2Sharp.Core; using Xunit; namespace LibGit2Sharp.Tests.TestHelpers { public class BaseFixture : IPostTestDirectoryRemover, IDisposable { private readonly List<string> directories = new List<string>(); public BaseFixture() { BuildFakeConfigs(this); #if LEAKS_IDENTIFYING LeaksContainer.Clear(); #endif } static BaseFixture() { // Do the set up in the static ctor so it only happens once SetUpTestEnvironment(); } public static string BareTestRepoPath { get; private set; } public static string StandardTestRepoWorkingDirPath { get; private set; } public static string StandardTestRepoPath { get; private set; } public static string ShallowTestRepoPath { get; private set; } public static string MergedTestRepoWorkingDirPath { get; private set; } public static string MergeTestRepoWorkingDirPath { get; private set; } public static string MergeRenamesTestRepoWorkingDirPath { get; private set; } public static string RevertTestRepoWorkingDirPath { get; private set; } public static string SubmoduleTestRepoWorkingDirPath { get; private set; } private static string SubmoduleTargetTestRepoWorkingDirPath { get; set; } private static string AssumeUnchangedRepoWorkingDirPath { get; set; } public static string SubmoduleSmallTestRepoWorkingDirPath { get; set; } public static string PackBuilderTestRepoPath { get; private set; } public static DirectoryInfo ResourcesDirectory { get; private set; } public static bool IsFileSystemCaseSensitive { get; private set; } protected static DateTimeOffset TruncateSubSeconds(DateTimeOffset dto) { int seconds = dto.ToSecondsSinceEpoch(); return Epoch.ToDateTimeOffset(seconds, (int)dto.Offset.TotalMinutes); } private static void SetUpTestEnvironment() { IsFileSystemCaseSensitive = IsFileSystemCaseSensitiveInternal(); string initialAssemblyParentFolder = Directory.GetParent(new Uri(typeof(BaseFixture).GetTypeInfo().Assembly.CodeBase).LocalPath).FullName; const string sourceRelativePath = @"../../../../LibGit2Sharp.Tests/Resources"; ResourcesDirectory = new DirectoryInfo(Path.Combine(initialAssemblyParentFolder, sourceRelativePath)); // Setup standard paths to our test repositories BareTestRepoPath = Path.Combine(sourceRelativePath, "testrepo.git"); StandardTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "testrepo_wd"); StandardTestRepoPath = Path.Combine(StandardTestRepoWorkingDirPath, "dot_git"); ShallowTestRepoPath = Path.Combine(sourceRelativePath, "shallow.git"); MergedTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergedrepo_wd"); MergeRenamesTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergerenames_wd"); MergeTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "merge_testrepo_wd"); RevertTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "revert_testrepo_wd"); SubmoduleTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_wd"); SubmoduleTargetTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_target_wd"); AssumeUnchangedRepoWorkingDirPath = Path.Combine(sourceRelativePath, "assume_unchanged_wd"); SubmoduleSmallTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_small_wd"); PackBuilderTestRepoPath = Path.Combine(sourceRelativePath, "packbuilder_testrepo_wd"); CleanupTestReposOlderThan(TimeSpan.FromMinutes(15)); } public static void BuildFakeConfigs(IPostTestDirectoryRemover dirRemover) { var scd = new SelfCleaningDirectory(dirRemover); string global = null, xdg = null, system = null, programData = null; BuildFakeRepositoryOptions(scd, out global, out xdg, out system, out programData); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = global{0}", Environment.NewLine) .AppendFormat("[Wow]{0}", Environment.NewLine) .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); File.WriteAllText(Path.Combine(global, ".gitconfig"), sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = system{0}", Environment.NewLine); File.WriteAllText(Path.Combine(system, "gitconfig"), sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(Path.Combine(xdg, "config"), sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = programdata{0}", Environment.NewLine); File.WriteAllText(Path.Combine(programData, "config"), sb.ToString()); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Global, global); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Xdg, xdg); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.System, system); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.ProgramData, programData); } private static void CleanupTestReposOlderThan(TimeSpan olderThan) { var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath) .EnumerateDirectories() .Where(di => di.CreationTimeUtc < DateTimeOffset.Now.Subtract(olderThan)) .Select(di => di.FullName); foreach (var dir in oldTestRepos) { DirectoryHelper.DeleteDirectory(dir); } } private static bool IsFileSystemCaseSensitiveInternal() { var mixedPath = Path.Combine(Constants.TemporaryReposPath, "mIxEdCase-" + Path.GetRandomFileName()); if (Directory.Exists(mixedPath)) { Directory.Delete(mixedPath); } Directory.CreateDirectory(mixedPath); bool isInsensitive = Directory.Exists(mixedPath.ToLowerInvariant()); Directory.Delete(mixedPath); return !isInsensitive; } protected void CreateCorruptedDeadBeefHead(string repoPath) { const string deadbeef = "deadbeef"; string headPath = string.Format("refs/heads/{0}", deadbeef); Touch(repoPath, headPath, string.Format("{0}{0}{0}{0}{0}\n", deadbeef)); } protected SelfCleaningDirectory BuildSelfCleaningDirectory() { return new SelfCleaningDirectory(this); } protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path) { return new SelfCleaningDirectory(this, path); } protected string SandboxBareTestRepo() { return Sandbox(BareTestRepoPath); } protected string SandboxStandardTestRepo() { return Sandbox(StandardTestRepoWorkingDirPath); } protected string SandboxMergedTestRepo() { return Sandbox(MergedTestRepoWorkingDirPath); } protected string SandboxStandardTestRepoGitDir() { return Sandbox(Path.Combine(StandardTestRepoWorkingDirPath)); } protected string SandboxMergeTestRepo() { return Sandbox(MergeTestRepoWorkingDirPath); } protected string SandboxRevertTestRepo() { return Sandbox(RevertTestRepoWorkingDirPath); } public string SandboxSubmoduleTestRepo() { return Sandbox(SubmoduleTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); } public string SandboxAssumeUnchangedTestRepo() { return Sandbox(AssumeUnchangedRepoWorkingDirPath); } public string SandboxSubmoduleSmallTestRepo() { var path = Sandbox(SubmoduleSmallTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); Directory.CreateDirectory(Path.Combine(path, "submodule_target_wd")); return path; } protected string SandboxPackBuilderTestRepo() { return Sandbox(PackBuilderTestRepoPath); } protected string Sandbox(string sourceDirectoryPath, params string[] additionalSourcePaths) { var scd = BuildSelfCleaningDirectory(); var source = new DirectoryInfo(sourceDirectoryPath); var clonePath = Path.Combine(scd.DirectoryPath, source.Name); DirectoryHelper.CopyFilesRecursively(source, new DirectoryInfo(clonePath)); foreach (var additionalPath in additionalSourcePaths) { var additional = new DirectoryInfo(additionalPath); var targetForAdditional = Path.Combine(scd.DirectoryPath, additional.Name); DirectoryHelper.CopyFilesRecursively(additional, new DirectoryInfo(targetForAdditional)); } return clonePath; } protected string InitNewRepository(bool isBare = false) { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); return Repository.Init(scd.DirectoryPath, isBare); } public void Register(string directoryPath) { directories.Add(directoryPath); } public virtual void Dispose() { foreach (string directory in directories) { DirectoryHelper.DeleteDirectory(directory); } #if LEAKS_IDENTIFYING GC.Collect(); GC.WaitForPendingFinalizers(); if (LeaksContainer.TypeNames.Any()) { Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}" + "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in Libgit2Object.cs{1}" + "and run the tests locally.", string.Join(", ", LeaksContainer.TypeNames), Environment.NewLine)); } #endif } protected static void InconclusiveIf(Func<bool> predicate, string message) { if (!predicate()) { return; } throw new SkipException(message); } protected void RequiresDotNetOrMonoGreaterThanOrEqualTo(System.Version minimumVersion) { Type type = Type.GetType("Mono.Runtime"); if (type == null) { // We're running on top of .Net return; } MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName == null) { throw new InvalidOperationException("Cannot access Mono.RunTime.GetDisplayName() method."); } var version = (string)displayName.Invoke(null, null); System.Version current; try { current = new System.Version(version.Split(' ')[0]); } catch (Exception e) { throw new Exception(string.Format("Cannot parse Mono version '{0}'.", version), e); } InconclusiveIf(() => current < minimumVersion, string.Format( "Current Mono version is {0}. Minimum required version to run this test is {1}.", current, minimumVersion)); } protected static void AssertValueInConfigFile(string configFilePath, string regex) { var text = File.ReadAllText(configFilePath); var r = new Regex(regex, RegexOptions.Multiline).Match(text); Assert.True(r.Success, text); } private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system, out string programData) { string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); global = Path.Combine(confs, "my-global-config"); Directory.CreateDirectory(global); xdg = Path.Combine(confs, "my-xdg-config"); Directory.CreateDirectory(xdg); system = Path.Combine(confs, "my-system-config"); Directory.CreateDirectory(system); programData = Path.Combine(confs, "my-programdata-config"); Directory.CreateDirectory(programData); } /// <summary> /// Creates a configuration file with user.name and user.email set to signature /// </summary> /// <remarks>The configuration file will be removed automatically when the tests are finished</remarks> /// <param name="identity">The identity to use for user.name and user.email</param> /// <returns>The path to the configuration file</returns> protected void CreateConfigurationWithDummyUser(Repository repo, Identity identity) { CreateConfigurationWithDummyUser(repo, identity.Name, identity.Email); } protected void CreateConfigurationWithDummyUser(Repository repo, string name, string email) { Configuration config = repo.Config; { if (name != null) { config.Set("user.name", name); } if (email != null) { config.Set("user.email", email); } } } /// <summary> /// Asserts that the commit has been authored and committed by the specified signature /// </summary> /// <param name="commit">The commit</param> /// <param name="identity">The identity to compare author and commiter to</param> protected void AssertCommitIdentitiesAre(Commit commit, Identity identity) { Assert.Equal(identity.Name, commit.Author.Name); Assert.Equal(identity.Email, commit.Author.Email); Assert.Equal(identity.Name, commit.Committer.Name); Assert.Equal(identity.Email, commit.Committer.Email); } protected static string Touch(string parent, string file, string content = null, Encoding encoding = null) { string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); var newFile = !File.Exists(filePath); Directory.CreateDirectory(dir); File.WriteAllText(filePath, content ?? string.Empty, encoding ?? Encoding.ASCII); //Workaround for .NET Core 1.x behavior where all newly created files have execute permissions set. //https://github.com/dotnet/corefx/issues/13342 if (Constants.IsRunningOnUnix && newFile) { RemoveExecutePermissions(filePath, newFile); } return filePath; } protected static string Touch(string parent, string file, Stream stream) { Debug.Assert(stream != null); string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); var newFile = !File.Exists(filePath); Directory.CreateDirectory(dir); using (var fs = File.Open(filePath, FileMode.Create)) { CopyStream(stream, fs); fs.Flush(); } //Work around .NET Core 1.x behavior where all newly created files have execute permissions set. //https://github.com/dotnet/corefx/issues/13342 if (Constants.IsRunningOnUnix && newFile) { RemoveExecutePermissions(filePath, newFile); } return filePath; } private static void RemoveExecutePermissions(string filePath, bool newFile) { var process = Process.Start("chmod", $"644 {filePath}"); process.WaitForExit(); } protected string Expected(string filename) { return File.ReadAllText(Path.Combine(ResourcesDirectory.FullName, "expected/" + filename)); } protected string Expected(string filenameFormat, params object[] args) { return Expected(string.Format(CultureInfo.InvariantCulture, filenameFormat, args)); } protected static void AssertRefLogEntry(IRepository repo, string canonicalName, string message, ObjectId @from, ObjectId to, Identity committer, DateTimeOffset before) { var reflogEntry = repo.Refs.Log(canonicalName).First(); Assert.Equal(to, reflogEntry.To); Assert.Equal(message, reflogEntry.Message); Assert.Equal(@from ?? ObjectId.Zero, reflogEntry.From); Assert.Equal(committer.Email, reflogEntry.Committer.Email); Assert.InRange(reflogEntry.Committer.When, before, DateTimeOffset.Now); } protected static void EnableRefLog(IRepository repository, bool enable = true) { repository.Config.Set("core.logAllRefUpdates", enable); } public static void CopyStream(Stream input, Stream output) { // Reused from the following Stack Overflow post with permission // of Jon Skeet (obtained on 25 Feb 2013) // http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file/411605#411605 var buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } } public static bool StreamEquals(Stream one, Stream two) { int onebyte, twobyte; while ((onebyte = one.ReadByte()) >= 0 && (twobyte = two.ReadByte()) >= 0) { if (onebyte != twobyte) return false; } return true; } public void AssertBelongsToARepository<T>(IRepository repo, T instance) where T : IBelongToARepository { Assert.Same(repo, ((IBelongToARepository)instance).Repository); } protected void CreateAttributesFile(IRepository repo, string attributeEntry) { Touch(repo.Info.WorkingDirectory, ".gitattributes", attributeEntry); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using Encog.Util.Normalize; using Encog.Util.Normalize.Input; using Encog.Util.Normalize.Output; using Encog.Util.Normalize.Output.Nominal; using Encog.Util.Normalize.Segregate; using Encog.Util.Normalize.Segregate.Index; using Encog.Util.Normalize.Target; namespace Encog.Examples.Forest { public class GenerateData : IStatusReportable { private readonly ForestConfig _config; public GenerateData(ForestConfig config) { _config = config; } #region IStatusReportable Members public void Report(int total, int current, String message) { Console.WriteLine(current + @"/" + total + @" " + message); } #endregion public void BuildOutputOneOf(DataNormalization norm, IInputField coverType) { var outType = new OutputOneOf(); outType.AddItem(coverType, 1); outType.AddItem(coverType, 2); outType.AddItem(coverType, 3); outType.AddItem(coverType, 4); outType.AddItem(coverType, 5); outType.AddItem(coverType, 6); outType.AddItem(coverType, 7); norm.AddOutputField(outType, true); } public void BuildOutputEquilateral(DataNormalization norm, IInputField coverType) { var outType = new OutputEquilateral(); outType.AddItem(coverType, 1); outType.AddItem(coverType, 2); outType.AddItem(coverType, 3); outType.AddItem(coverType, 4); outType.AddItem(coverType, 5); outType.AddItem(coverType, 6); outType.AddItem(coverType, 7); norm.AddOutputField(outType, true); } public void Copy(FileInfo source, FileInfo target, int start, int stop, int size) { var inputField = new IInputField[55]; var norm = new DataNormalization {Report = this, Storage = new NormalizationStorageCSV(target.ToString())}; for (int i = 0; i < 55; i++) { inputField[i] = new InputFieldCSV(true, source.ToString(), i); norm.AddInputField(inputField[i]); IOutputField outputField = new OutputFieldDirect(inputField[i]); norm.AddOutputField(outputField); } // load only the part we actually want, i.e. training or eval var segregator2 = new IndexSampleSegregator(start, stop, size); norm.AddSegregator(segregator2); norm.Process(); } public void Narrow(FileInfo source, FileInfo target, int field, int count) { var inputField = new IInputField[55]; var norm = new DataNormalization {Report = this, Storage = new NormalizationStorageCSV(target.ToString())}; for (int i = 0; i < 55; i++) { inputField[i] = new InputFieldCSV(true, source.ToString(), i); norm.AddInputField(inputField[i]); IOutputField outputField = new OutputFieldDirect(inputField[i]); norm.AddOutputField(outputField); } var segregator = new IntegerBalanceSegregator(inputField[field], count); norm.AddSegregator(segregator); norm.Process(); Console.WriteLine(@"Samples per tree type:"); Console.WriteLine(segregator.DumpCounts()); } public void Step1() { Console.WriteLine(@"Step 1: Generate training and evaluation files"); Console.WriteLine(@"Generate training file"); Copy(_config.CoverTypeFile, _config.TrainingFile, 0, 2, 4); // take 3/4 Console.WriteLine(@"Generate evaluation file"); Copy(_config.CoverTypeFile, _config.EvaluateFile, 3, 3, 4); // take 1/4 } public void Step2() { Console.WriteLine(@"Step 2: Balance training to have the same number of each tree"); Narrow(_config.TrainingFile, _config.BalanceFile, 54, 3000); } public DataNormalization Step3(bool useOneOf) { Console.WriteLine(@"Step 3: Normalize training data"); IInputField inputElevation; IInputField inputAspect; IInputField inputSlope; IInputField hWater; IInputField vWater; IInputField roadway; IInputField shade9; IInputField shade12; IInputField shade3; IInputField firepoint; var wilderness = new IInputField[4]; var soilType = new IInputField[40]; IInputField coverType; var norm = new DataNormalization { Report = this, Storage = new NormalizationStorageCSV(_config.NormalizedDataFile.ToString()) }; norm.AddInputField(inputElevation = new InputFieldCSV(true, _config.BalanceFile.ToString(), 0)); norm.AddInputField(inputAspect = new InputFieldCSV(true, _config.BalanceFile.ToString(), 1)); norm.AddInputField(inputSlope = new InputFieldCSV(true, _config.BalanceFile.ToString(), 2)); norm.AddInputField(hWater = new InputFieldCSV(true, _config.BalanceFile.ToString(), 3)); norm.AddInputField(vWater = new InputFieldCSV(true, _config.BalanceFile.ToString(), 4)); norm.AddInputField(roadway = new InputFieldCSV(true, _config.BalanceFile.ToString(), 5)); norm.AddInputField(shade9 = new InputFieldCSV(true, _config.BalanceFile.ToString(), 6)); norm.AddInputField(shade12 = new InputFieldCSV(true, _config.BalanceFile.ToString(), 7)); norm.AddInputField(shade3 = new InputFieldCSV(true, _config.BalanceFile.ToString(), 8)); norm.AddInputField(firepoint = new InputFieldCSV(true, _config.BalanceFile.ToString(), 9)); for (int i = 0; i < 4; i++) { norm.AddInputField(wilderness[i] = new InputFieldCSV(true, _config.BalanceFile.ToString(), 10 + i)); } for (int i = 0; i < 40; i++) { norm.AddInputField(soilType[i] = new InputFieldCSV(true, _config.BalanceFile.ToString(), 14 + i)); } norm.AddInputField(coverType = new InputFieldCSV(false, _config.BalanceFile.ToString(), 54)); norm.AddOutputField(new OutputFieldRangeMapped(inputElevation)); norm.AddOutputField(new OutputFieldRangeMapped(inputAspect)); norm.AddOutputField(new OutputFieldRangeMapped(inputSlope)); norm.AddOutputField(new OutputFieldRangeMapped(hWater)); norm.AddOutputField(new OutputFieldRangeMapped(vWater)); norm.AddOutputField(new OutputFieldRangeMapped(roadway)); norm.AddOutputField(new OutputFieldRangeMapped(shade9)); norm.AddOutputField(new OutputFieldRangeMapped(shade12)); norm.AddOutputField(new OutputFieldRangeMapped(shade3)); norm.AddOutputField(new OutputFieldRangeMapped(firepoint)); for (int i = 0; i < 40; i++) { norm.AddOutputField(new OutputFieldDirect(soilType[i])); } if (useOneOf) BuildOutputOneOf(norm, coverType); else BuildOutputEquilateral(norm, coverType); norm.Process(); return norm; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// GenericResource /// </summary> [DataContract(Name = "GenericResource")] public partial class GenericResource : IEquatable<GenericResource>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="GenericResource" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="displayName">displayName.</param> /// <param name="durationInMillis">durationInMillis.</param> /// <param name="id">id.</param> /// <param name="result">result.</param> /// <param name="startTime">startTime.</param> public GenericResource(string _class = default(string), string displayName = default(string), int durationInMillis = default(int), string id = default(string), string result = default(string), string startTime = default(string)) { this.Class = _class; this.DisplayName = displayName; this.DurationInMillis = durationInMillis; this.Id = id; this.Result = result; this.StartTime = startTime; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name = "displayName", EmitDefaultValue = false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets DurationInMillis /// </summary> [DataMember(Name = "durationInMillis", EmitDefaultValue = false)] public int DurationInMillis { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets Result /// </summary> [DataMember(Name = "result", EmitDefaultValue = false)] public string Result { get; set; } /// <summary> /// Gets or Sets StartTime /// </summary> [DataMember(Name = "startTime", EmitDefaultValue = false)] public string StartTime { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class GenericResource {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Result: ").Append(Result).Append("\n"); sb.Append(" StartTime: ").Append(StartTime).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as GenericResource); } /// <summary> /// Returns true if GenericResource instances are equal /// </summary> /// <param name="input">Instance of GenericResource to be compared</param> /// <returns>Boolean</returns> public bool Equals(GenericResource input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.DurationInMillis == input.DurationInMillis || this.DurationInMillis.Equals(input.DurationInMillis) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Result == input.Result || (this.Result != null && this.Result.Equals(input.Result)) ) && ( this.StartTime == input.StartTime || (this.StartTime != null && this.StartTime.Equals(input.StartTime)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.DisplayName != null) { hashCode = (hashCode * 59) + this.DisplayName.GetHashCode(); } hashCode = (hashCode * 59) + this.DurationInMillis.GetHashCode(); if (this.Id != null) { hashCode = (hashCode * 59) + this.Id.GetHashCode(); } if (this.Result != null) { hashCode = (hashCode * 59) + this.Result.GetHashCode(); } if (this.StartTime != null) { hashCode = (hashCode * 59) + this.StartTime.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region License /* * Copyright (C) 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections.Generic; #endregion namespace Java.Util { /// <summary> /// A bounded <see cref="IQueue{T}"/> backed by an array. This queue orders /// elements FIFO (first-in-first-out). The <i>head</i> of the queue is /// that element that has been on the queue the longest time. The <i>tail</i> /// of the queue is that element that has been on the queue the shortest time. /// New elements are inserted at the tail of the queue, and the queue retrieval /// operations obtain elements at the head of the queue. /// </summary> /// <remarks> /// <para> /// This is a classic &quot;bounded buffer&quot;, in which a fixed-sized array /// holds elements inserted by producers and extracted by consumers. Once /// created, the capacity cannot be increased. /// </para> /// </remarks> /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu</author> [Serializable] public class ArrayQueue<T> : AbstractQueue<T> //BACKPORT_2_2 { /// <summary>The intial capacity of this queue.</summary> private readonly int _capacity; /// <summary>Number of items in the queue </summary> private int _count; /// <summary>The queued items </summary> private readonly T[] _items; /// <summary>items index for next take, poll or remove </summary> [NonSerialized] private int _takeIndex; /// <summary>items index for next put, offer, or add. </summary> [NonSerialized] private int _putIndex; #region Private Methods /// <summary> /// Utility for remove: Delete item at position <paramref name="index"/>. /// and return the next item position. Call only when holding lock. /// </summary> private int RemoveAt(int index) { T[] items = _items; if (index == _takeIndex) { items[_takeIndex] = default(T); _takeIndex = Increment(_takeIndex); index = _takeIndex; } else { int i = index; for (; ; ) { int nextIndex = Increment(i); if (nextIndex != _putIndex) { items[i] = items[nextIndex]; i = nextIndex; } else { items[i] = default(T); _putIndex = i; break; } } } --_count; return index; } /// <summary> Circularly increment i.</summary> private int Increment(int index) { return (++index == _items.Length) ? 0 : index; } /// <summary> /// Inserts element at current put position, advances, and signals. /// Call only when holding lock. /// </summary> private void Insert(T x) { _items[_putIndex] = x; _putIndex = Increment(_putIndex); ++_count; } /// <summary> /// Extracts element at current take position, advances, and signals. /// Call only when holding lock. /// </summary> private T Extract() { T[] items = _items; T x = items[_takeIndex]; items[_takeIndex] = default(T); _takeIndex = Increment(_takeIndex); --_count; return x; } #endregion #region Constructors /// <summary> /// Creates an <see cref="ArrayQueue{T}"/> with the given (fixed) /// <paramref name="capacity"/> and initially containing the elements /// of the given collection, added in traversal order of the /// collection's iterator. /// </summary> /// <param name="capacity"> /// The capacity of this queue. /// </param> /// <param name="collection"> /// The collection of elements to initially contain. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="capacity"/> is less than 1 or is less than the /// size of <pararef name="collection"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="collection"/> is <see langword="null"/>. /// </exception> public ArrayQueue(int capacity, IEnumerable<T> collection) : this(capacity) { if (collection == null) throw new ArgumentNullException("collection"); foreach (T currentObject in collection) { if(_count >= capacity) { throw new ArgumentOutOfRangeException( "collection", collection, "Collection size greater than queue capacity"); } Insert(currentObject); } } /// <summary> /// Creates an <see cref="ArrayQueue{T}"/> with the given (fixed) /// <paramref name="capacity"/> and default fairness access policy. /// </summary> /// <param name="capacity"> /// The capacity of this queue. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="capacity"/> is less than 1. /// </exception> public ArrayQueue(int capacity) { if (capacity <= 0) throw new ArgumentOutOfRangeException( "capacity", capacity, "Must not be negative"); _capacity = capacity; _items = new T[capacity]; } #endregion /// <summary> /// Clear the queue without locking, this is for subclass to provide /// the clear implementation without worrying about concurrency. /// </summary> public override void Clear() { T[] items = _items; int i = _takeIndex; int k = _count; while (k-- > 0) { items[i] = default(T); i = Increment(i); } _count = 0; _putIndex = 0; _takeIndex = 0; } /// <summary> /// /// </summary> public override int Capacity { get { return _capacity; } } /// <summary> /// Returns <see langword="true"/> if this queue contains the specified element. /// </summary> /// <remarks> /// More formally, returns <see langword="true"/> if and only if this queue contains /// at least one element <i>element</i> such that <i>elementToSearchFor.equals(element)</i>. /// </remarks> /// <param name="elementToSearchFor">object to be checked for containment in this queue</param> /// <returns> <see langword="true"/> if this queue contains the specified element</returns> public override bool Contains(T elementToSearchFor) { T[] items = _items; int i = _takeIndex; int k = 0; while (k++ < _count) { if (elementToSearchFor.Equals(items[i])) return true; i = Increment(i); } return false; } /// <summary> /// Removes a single instance of the specified element from this queue, /// if it is present. More formally, removes an <i>element</i> such /// that <i>elementToRemove.Equals(element)</i>, if this queue contains one or more such /// elements. /// </summary> /// <param name="elementToRemove">element to be removed from this queue, if present /// </param> /// <returns> <see langword="true"/> if this queue contained the specified element or /// if this queue changed as a result of the call, <see langword="false"/> otherwise /// </returns> public override bool Remove(T elementToRemove) { T[] items = _items; int currentIndex = _takeIndex; int currentStep = 0; for (;;) { if (currentStep++ >= _count) return false; if (elementToRemove.Equals(items[currentIndex])) { RemoveAt(currentIndex); return true; } currentIndex = Increment(currentIndex); } } /// <summary> /// Gets the capacity of the queue. /// </summary> public override int RemainingCapacity { get { return _capacity - _count; } } /// <summary> /// Returns the number of elements in this queue. /// </summary> /// <returns> the number of elements in this queue</returns> public override int Count { get { return _count; } } /// <summary> /// Inserts the specified element into this queue if it is possible to do /// so immediately without violating capacity restrictions. /// </summary> /// <remarks> /// <p/> /// When using a capacity-restricted queue, this method is generally /// preferable to <see cref="ArgumentException"/>, /// which can fail to insert an element only by throwing an exception. /// </remarks> /// <param name="element"> /// The element to add. /// </param> /// <returns> /// <see langword="true"/> if the element was added to this queue. /// </returns> /// <exception cref="object"> /// If the element cannot be added at this time due to capacity restrictions. /// </exception> /// <exception cref="ArgumentNullException"> /// If the supplied <paramref name="element"/> is <see langword="null"/> /// and this queue does not permit <see langword="null"/> elements. /// </exception> /// <exception cref="InvalidOperationException"> /// If some property of the supplied <paramref name="element"/> prevents /// it from being added to this queue. /// </exception> public override bool Offer(T element) { if (_count == _items.Length) return false; Insert(element); return true; } /// <summary> /// Retrieves and removes the head of this queue. /// </summary> /// <remarks> /// <p/> /// This method differs from <see cref="IQueue{T}.Poll"/> /// only in that it throws an exception if this queue is empty. /// </remarks> /// <returns> /// The head of this queue /// </returns> /// <exception cref="InvalidOperationException">if this queue is empty</exception> public override T Remove() { if (_count == 0) throw new InvalidOperationException("Queue is empty."); T x = Extract(); return x; } /// <summary> /// Retrieves and removes the head of this queue, /// or returns <see langword="null"/> if this queue is empty. /// </summary> /// <returns> /// The head of this queue, or <see langword="null"/> if this queue is empty. /// </returns> public override bool Poll(out T element) { bool notEmpty = _count > 0; element = notEmpty ? Extract() : default(T); return notEmpty; } /// <summary> /// Retrieves, but does not remove, the head of this queue, /// or returns <see langword="null"/> if this queue is empty. /// </summary> /// <returns> /// The head of this queue, or <see langword="null"/> if this queue is empty. /// </returns> public override bool Peek(out T element) { bool notEmpty = (_count > 0); element = notEmpty ? _items[_takeIndex] : default(T); return notEmpty; } /// <summary> /// Does the real work for all drain methods. Caller must /// guarantee the <paramref name="action"/> is not <c>null</c> and /// <paramref name="maxElements"/> is greater then zero (0). /// </summary> /// <seealso cref="IQueue{T}.Drain(System.Action{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int)"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, Predicate{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int, Predicate{T})"/> internal protected override int DoDrain(Action<T> action, int maxElements, Predicate<T> criteria) { T[] items = _items; int n = 0; int reject = 0; int currentIndex = _takeIndex; while(n < maxElements && _count > reject) { T element = items[currentIndex]; if (criteria == null || criteria(element)) { action(element); n++; currentIndex = RemoveAt(currentIndex); } else { reject++; currentIndex = Increment(currentIndex); } } return n; } /// <summary> /// Returns an array of <typeparamref name="T"/> containing all of the /// elements in this queue, in proper sequence. /// </summary> /// <remarks> /// The returned array will be "safe" in that no references to it are /// maintained by this queue. (In other words, this method must allocate /// a new array). The caller is thus free to modify the returned array. /// </remarks> /// <returns> an <c>T[]</c> containing all of the elements in this queue</returns> public override T[] ToArray() { T[] items = _items; T[] a = new T[_count]; int k = 0; int i = _takeIndex; while (k < _count) { a[k++] = items[i]; i = Increment(i); } return a; } /// <summary> /// Returns an array containing all of the elements in this queue, in /// proper sequence; the runtime type of the returned array is that of /// the specified array. /// </summary> /// <remarks> /// If the queue fits in the specified array, it /// is returned therein. Otherwise, a new array is allocated with the /// runtime type of the specified array and the size of this queue. /// /// <p/> /// If this queue fits in the specified array with room to spare /// (i.e., the array has more elements than this queue), the element in /// the array immediately following the end of the queue is set to /// <see langword="null"/>. /// /// <p/> /// Like the <see cref="ToArray()"/> method, /// this method acts as bridge between /// array-based and collection-based APIs. Further, this method allows /// precise control over the runtime type of the output array, and may, /// under certain circumstances, be used to save allocation costs. /// /// <p/> /// Suppose <i>x</i> is a queue known to contain only strings. /// The following code can be used to dump the queue into a newly /// allocated array of <see cref="System.String"/> objects: /// /// <code> /// string[] y = x.ToArray(new string[0]); /// </code> /// /// Note that <see cref="ToArray(T[])"/> with an empty /// arry is identical in function to /// <see cref="ToArray()"/>. /// </remarks> /// <param name="targetArray"> /// the array into which the elements of the queue are to /// be stored, if it is big enough; otherwise, a new array of the /// same runtime type is allocated for this purpose /// </param> /// <returns> an array containing all of the elements in this queue</returns> /// <exception cref="ArrayTypeMismatchException">if the runtime type of the <pararef name="targetArray"/> /// is not a super tyoe of the runtime tye of every element in this queue. /// </exception> /// <exception cref="System.ArgumentNullException">If the <paramref name="targetArray"/> is <see langword="null"/> /// </exception> public override T[] ToArray(T[] targetArray) { if (targetArray == null) throw new ArgumentNullException("targetArray"); T[] items = _items; if (targetArray.Length < _count) targetArray = (T[]) Array.CreateInstance(targetArray.GetType().GetElementType(), _count); int k = 0; int i = _takeIndex; while (k < _count) { targetArray[k++] = items[i]; i = Increment(i); } if (targetArray.Length > _count) targetArray[_count] = default(T); return targetArray; } /// <summary> /// Returns an <see cref="IEnumerator{T}"/> over the elements in this /// queue in proper sequence. /// </summary> /// <remarks> /// The returned <see cref="IEnumerator{T}"/> is a "weakly consistent" /// enumerator that will not throw <see cref="InvalidOperationException"/> /// when the queue is concurrently modified, and guarantees to traverse /// elements as they existed upon construction of the enumerator, and /// may (but is not guaranteed to) reflect any modifications subsequent /// to construction. /// </remarks> /// <returns> /// An enumerator over the elements in this queue in proper sequence. /// </returns> public override IEnumerator<T> GetEnumerator() { return new ArrayQueueEnumerator(this); } private class ArrayQueueEnumerator : AbstractEnumerator<T> { /// <summary> /// Index of element to be returned by next, /// or a negative number if no such element. /// </summary> private int _nextIndex; /// <summary> /// Parent <see cref="ArrayQueue{T}"/> /// for this <see cref="IEnumerator{T}"/> /// </summary> private readonly ArrayQueue<T> _queue; /// <summary> /// nextItem holds on to item fields because once we claim /// that an element exists in hasNext(), we must return it in /// the following next() call even if it was in the process of /// being removed when hasNext() was called. /// </summary> private T _nextItem; protected override T FetchCurrent() { return _nextItem; } internal ArrayQueueEnumerator(ArrayQueue<T> queue) { _queue = queue; SetInitialState(); } protected override bool GoNext() { var index = _nextIndex; if (index == -1) return false; _nextItem = _queue._items[index]; index = _queue.Increment(index); _nextIndex = index == _queue._putIndex ? -1 : index; return true; } protected override void DoReset() { SetInitialState(); } private void SetInitialState() { _nextIndex = _queue.Count == 0 ? - 1 : _queue._takeIndex; } } } }
using UnityEngine; using System.Collections; public abstract partial class UIBasicSprite : UIWidget { public enum Type { Simple, Sliced, Tiled, Filled, SlicedFilled, Advanced, } [HideInInspector][SerializeField]protected float mVertexOffset = 0.0f; /// <summary> /// Minimum allowed width for this widget. /// </summary> override public int minWidth { get { if (type == Type.Sliced || type == Type.Advanced || type == Type.SlicedFilled) { Vector4 b = border * pixelSize; int min = Mathf.RoundToInt(b.x + b.z); return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min); } return base.minWidth; } } /// <summary> /// Minimum allowed height for this widget. /// </summary> override public int minHeight { get { if (type == Type.Sliced || type == Type.Advanced || type == Type.SlicedFilled) { Vector4 b = border * pixelSize; int min = Mathf.RoundToInt(b.y + b.w); return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min); } return base.minHeight; } } protected void UpdateUV(Rect outer, Rect inner) { mOuterUV = outer; mInnerUV = inner; } /// <summary> /// Fill the draw buffers. /// </summary> protected void Fill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner) { mOuterUV = outer; mInnerUV = inner; switch (type) { case Type.Simple: SimpleFill(verts, uvs, cols); break; case Type.Sliced: SlicedFill(verts, uvs, cols); break; case Type.Filled: FilledFill(verts, uvs, cols); break; case Type.Tiled: TiledFill(verts, uvs, cols); break; case Type.SlicedFilled: SlicedFilledFill(verts, uvs, cols); break; case Type.Advanced: AdvancedFill(verts, uvs, cols); break; } } void SlicedFilledFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols) { Vector4 br = border * pixelSize; //if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f) //{ // SimpleFill(verts, uvs, cols); // return; //} Color32 c = drawingColor; Vector4 v = drawingDimensions; mTempPos[0].x = v.x; mTempPos[0].y = v.y; mTempPos[3].x = v.z; mTempPos[3].y = v.w; if (mFlip == Flip.Horizontally || mFlip == Flip.Both) { mTempPos[1].x = mTempPos[0].x + br.z; mTempPos[2].x = mTempPos[3].x - br.x; mTempUVs[3].x = mOuterUV.xMin; mTempUVs[2].x = mInnerUV.xMin; mTempUVs[1].x = mInnerUV.xMax; mTempUVs[0].x = mOuterUV.xMax; } else { mTempPos[1].x = mTempPos[0].x + br.x; mTempPos[2].x = mTempPos[3].x - br.z; mTempUVs[0].x = mOuterUV.xMin; mTempUVs[1].x = mInnerUV.xMin; mTempUVs[2].x = mInnerUV.xMax; mTempUVs[3].x = mOuterUV.xMax; } if (mFlip == Flip.Vertically || mFlip == Flip.Both) { mTempPos[1].y = mTempPos[0].y + br.w; mTempPos[2].y = mTempPos[3].y - br.y; mTempUVs[3].y = mOuterUV.yMin; mTempUVs[2].y = mInnerUV.yMin; mTempUVs[1].y = mInnerUV.yMax; mTempUVs[0].y = mOuterUV.yMax; } else { mTempPos[1].y = mTempPos[0].y + br.y; mTempPos[2].y = mTempPos[3].y - br.w; mTempUVs[0].y = mOuterUV.yMin; mTempUVs[1].y = mInnerUV.yMin; mTempUVs[2].y = mInnerUV.yMax; mTempUVs[3].y = mOuterUV.yMax; } bool[,] skip = new bool[3, 3] { {false, false, false}, {false, false, false}, {false, false, false} }; if (fillDirection == FillDirection.Horizontal) { if (invert) { float dv = (mTempPos[3].x - mTempPos[0].x) * (1 - fillAmount) + mTempPos[0].x; if (dv < mTempPos[1].x) { float fill = (dv - mTempPos[0].x) / (mTempPos[1].x - mTempPos[0].x); mTempPos[0].x = dv; mTempUVs[0].x = (mTempUVs[1].x - mTempUVs[0].x) * fill + mTempUVs[0].x; } else if (dv < mTempPos[2].x) { float fill = (dv - mTempPos[1].x) / (mTempPos[2].x - mTempPos[1].x); mTempPos[1].x = dv; mTempUVs[1].x = (mTempUVs[2].x - mTempUVs[1].x) * fill + mTempUVs[1].x; skip[0, 0] = skip[0, 1] = skip[0, 2] = true; } else { float fill = (dv - mTempPos[2].x) / (mTempPos[3].x - mTempPos[2].x); mTempPos[2].x = dv; mTempUVs[2].x = (mTempUVs[3].x - mTempUVs[2].x) * fill + mTempUVs[2].x; skip[0, 0] = skip[0, 1] = skip[0, 2] = skip[1, 0] = skip[1, 1] = skip[1, 2] = true; } } else { float dv = (mTempPos[3].x - mTempPos[0].x) * fillAmount + mTempPos[0].x; if (dv > mTempPos[2].x) { float fill = (dv - mTempPos[2].x) / (mTempPos[3].x - mTempPos[2].x); mTempPos[3].x = dv; mTempUVs[3].x = (mTempUVs[3].x - mTempUVs[2].x) * fill + mTempUVs[2].x; } else if (dv > mTempPos[1].x) { float fill = (dv - mTempPos[1].x) / (mTempPos[2].x - mTempPos[1].x); mTempPos[2].x = dv; mTempUVs[2].x = (mTempUVs[2].x - mTempUVs[1].x) * fill + mTempUVs[1].x; skip[2, 0] = skip[2, 1] = skip[2, 2] = true; } else { float fill = (dv - mTempPos[0].x) / (mTempPos[1].x - mTempPos[0].x); mTempPos[1].x = dv; mTempUVs[1].x = (mTempUVs[1].x - mTempUVs[0].x) * fill + mTempUVs[0].x; skip[1, 0] = skip[1, 1] = skip[1, 2] = skip[2, 0] = skip[2, 1] = skip[2, 2] = true; } } } else if (fillDirection == FillDirection.Vertical) { if (invert) { float dv = (mTempPos[3].y - mTempPos[0].y) * (1 - fillAmount) + mTempPos[0].y; if (dv < mTempPos[1].y) { float fill = (dv - mTempPos[0].y) / (mTempPos[1].y - mTempPos[0].y); mTempPos[0].y = dv; mTempUVs[0].y = (mTempUVs[1].y - mTempUVs[0].y) * fill + mTempUVs[0].y; } else if (dv < mTempPos[2].y) { float fill = (dv - mTempPos[1].y) / (mTempPos[2].y - mTempPos[1].y); mTempPos[1].y = dv; mTempUVs[1].y = (mTempUVs[2].y - mTempUVs[1].y) * fill + mTempUVs[1].y; skip[0, 0] = skip[1, 0] = skip[2, 0] = true; } else { float fill = (dv - mTempPos[2].y) / (mTempPos[3].y - mTempPos[2].y); mTempPos[2].y = dv; mTempUVs[2].y = (mTempUVs[3].y - mTempUVs[2].y) * fill + mTempUVs[2].y; skip[0, 0] = skip[1, 0] = skip[2, 0] = skip[0, 1] = skip[1, 1] = skip[2, 1] = true; } } else { float dv = (mTempPos[3].y - mTempPos[0].y) * fillAmount + mTempPos[0].y; if (dv > mTempPos[2].y) { float fill = (dv - mTempPos[2].y) / (mTempPos[3].y - mTempPos[2].y); mTempPos[3].y = dv; mTempUVs[3].y = (mTempUVs[3].y - mTempUVs[2].y) * fill + mTempUVs[2].y; } else if (dv > mTempPos[1].y) { float fill = (dv - mTempPos[1].y) / (mTempPos[2].y - mTempPos[1].y); mTempPos[2].y = dv; mTempUVs[2].y = (mTempUVs[2].y - mTempUVs[1].y) * fill + mTempUVs[1].y; skip[0, 2] = skip[1, 2] = skip[2, 2] = true; } else { float fill = (dv - mTempPos[0].y) / (mTempPos[1].y - mTempPos[0].y); mTempPos[1].y = dv; mTempUVs[1].y = (mTempUVs[1].y - mTempUVs[0].y) * fill + mTempUVs[0].y; skip[0, 1] = skip[1, 1] = skip[2, 1] = skip[0, 2] = skip[1, 2] = skip[2, 2] = true; } } } float diffY = mTempPos[3].y - mTempPos[0].y; float baseY = mTempPos[0].y; float[] offsetXs = new float[] { 0f, 0f, 0f, 0f }; if (diffY > 0) { for (int i = 0; i < 3; i++) { offsetXs[i] = mVertexOffset * (1f - (mTempPos[i].y - baseY) / diffY); } } for (int x = 0; x < 3; ++x) { int x2 = x + 1; for (int y = 0; y < 3; ++y) { int y2 = y + 1; if (skip[x, y]) continue; verts.Add(new Vector3(mTempPos[x].x + offsetXs[y], mTempPos[y].y)); verts.Add(new Vector3(mTempPos[x].x + offsetXs[y2], mTempPos[y2].y)); verts.Add(new Vector3(mTempPos[x2].x + offsetXs[y2], mTempPos[y2].y)); verts.Add(new Vector3(mTempPos[x2].x + offsetXs[y], mTempPos[y].y)); uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y)); uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y)); uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y)); uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y)); cols.Add(c); cols.Add(c); cols.Add(c); cols.Add(c); } } } protected void QuadrilateralFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Vector3[] vertexOffsets) { Vector4 v = drawingDimensions; Vector4 u = drawingUVs; Color32 c = drawingColor; bool vertsAdded = false; if (vertexOffsets != null && vertexOffsets.Length == 4) { Vector2[] va = new Vector2[] { new Vector2(v.x + vertexOffsets[0].x, v.y + vertexOffsets[0].y), new Vector2(v.x + vertexOffsets[1].x, v.w + vertexOffsets[1].y), new Vector2(v.z + vertexOffsets[2].x, v.w + vertexOffsets[2].y), new Vector2(v.z + vertexOffsets[3].x, v.y + vertexOffsets[3].y) }; Vector2 intersection = Vector2.zero; if (LineIntersectionPoint(va[0], va[2], va[1], va[3], ref intersection)) { float[] d = new float[] { Vector3.Magnitude(intersection - va[0]), Vector3.Magnitude(intersection - va[1]), Vector3.Magnitude(intersection - va[2]), Vector3.Magnitude(intersection - va[3]) }; float[] q = new float[] { (d[0] + d[2]) / d[2], (d[1] + d[3]) / d[3], (d[2] + d[0]) / d[0], (d[3] + d[1]) / d[1] }; verts.Add(new Vector3(v.x + vertexOffsets[0].x, v.y + vertexOffsets[0].y, q[0])); verts.Add(new Vector3(v.x + vertexOffsets[1].x, v.w + vertexOffsets[1].y, q[1])); verts.Add(new Vector3(v.z + vertexOffsets[2].x, v.w + vertexOffsets[2].y, q[2])); verts.Add(new Vector3(v.z + vertexOffsets[3].x, v.y + vertexOffsets[3].y, q[3])); vertsAdded = true; } } if (!vertsAdded) { verts.Add(new Vector3(v.x, v.y, 1)); verts.Add(new Vector3(v.x, v.w, 1)); verts.Add(new Vector3(v.z, v.w, 1)); verts.Add(new Vector3(v.z, v.y, 1)); } uvs.Add(new Vector2(u.x, u.y)); uvs.Add(new Vector2(u.x, u.w)); uvs.Add(new Vector2(u.z, u.w)); uvs.Add(new Vector2(u.z, u.y)); cols.Add(c); cols.Add(c); cols.Add(c); cols.Add(c); } bool LineIntersectionPoint(Vector2 ps1, Vector2 pe1, Vector2 ps2, Vector2 pe2, ref Vector2 intersection) { float a1 = pe1.y - ps1.y; float b1 = ps1.x - pe1.x; float c1 = a1 * ps1.x + b1 * ps1.y; float a2 = pe2.y - ps2.y; float b2 = ps2.x - pe2.x; float c2 = a2 * ps2.x + b2 * ps2.y; float delta = a1 * b2 - a2 * b1; if (delta == 0) return false; intersection = new Vector2( (b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta ); return true; } }
#region File Description //----------------------------------------------------------------------------- // SampleCamera.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Storage; #endregion namespace TexturesAndColorsSample { public enum SampleArcBallCameraMode { /// <summary> /// A totally free-look arcball that orbits relative /// to its orientation /// </summary> Free = 0, /// <summary> /// A camera constrained by roll so that orbits only /// occur on latitude and longitude /// </summary> RollConstrained = 1 } /// <summary> /// An example arc ball camera /// </summary> public class SampleArcBallCamera { #region Helper Functions /// <summary> /// Uses a pair of keys to simulate a positive or negative axis input. /// </summary> public static float ReadKeyboardAxis(KeyboardState keyState, Keys downKey, Keys upKey) { float value = 0; if (keyState.IsKeyDown(downKey)) value -= 1.0f; if (keyState.IsKeyDown(upKey)) value += 1.0f; return value; } #endregion #region Fields /// <summary> /// The location of the look-at target /// </summary> private Vector3 targetValue; /// <summary> /// The distance between the camera and the target /// </summary> private float distanceValue; /// <summary> /// The orientation of the camera relative to the target /// </summary> private Quaternion orientation; private float inputDistanceRateValue; private const float InputTurnRate = 3.0f; private SampleArcBallCameraMode mode; private float yaw, pitch; #endregion #region Constructors /// <summary> /// Create an arcball camera that allows free orbit around a target point. /// </summary> public SampleArcBallCamera(SampleArcBallCameraMode controlMode) { //orientation quaternion assumes a Pi rotation so you're facing the "front" //of the model (looking down the +Z axis) orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi); mode = controlMode; inputDistanceRateValue = 4.0f; yaw = MathHelper.Pi; pitch = 0; } #endregion #region Calculated Camera Properties /// <summary> /// Get the forward direction vector of the camera. /// </summary> public Vector3 Direction { get { //R v R' where v = (0,0,-1,0) //The equation can be reduced because we know the following things: // 1. We're using unit quaternions // 2. The initial aspect does not change //The reduced form of the same equation follows Vector3 dir = Vector3.Zero; dir.X = -2.0f * ((orientation.X * orientation.Z) + (orientation.W * orientation.Y)); dir.Y = 2.0f * ((orientation.W * orientation.X) - (orientation.Y * orientation.Z)); dir.Z = ((orientation.X * orientation.X) + (orientation.Y * orientation.Y)) - ((orientation.Z * orientation.Z) + (orientation.W * orientation.W)); Vector3.Normalize(ref dir, out dir); return dir; } } /// <summary> /// Get the right direction vector of the camera. /// </summary> public Vector3 Right { get { //R v R' where v = (1,0,0,0) //The equation can be reduced because we know the following things: // 1. We're using unit quaternions // 2. The initial aspect does not change //The reduced form of the same equation follows Vector3 right = Vector3.Zero; right.X = ((orientation.X * orientation.X) + (orientation.W * orientation.W)) - ((orientation.Z * orientation.Z) + (orientation.Y * orientation.Y)); right.Y = 2.0f * ((orientation.X * orientation.Y) + (orientation.Z * orientation.W)); right.Z = 2.0f * ((orientation.X * orientation.Z) - (orientation.Y * orientation.W)); return right; } } /// <summary> /// Get the up direction vector of the camera. /// </summary> public Vector3 Up { get { //R v R' where v = (0,1,0,0) //The equation can be reduced because we know the following things: // 1. We're using unit quaternions // 2. The initial aspect does not change //The reduced form of the same equation follows Vector3 up = Vector3.Zero; up.X = 2.0f * ((orientation.X * orientation.Y) - (orientation.Z * orientation.W)); up.Y = ((orientation.Y * orientation.Y) + (orientation.W * orientation.W)) - ((orientation.Z * orientation.Z) + (orientation.X * orientation.X)); up.Z = 2.0f * ((orientation.Y * orientation.Z) + (orientation.X * orientation.W)); return up; } } /// <summary> /// Get the View (look at) Matrix defined by the camera /// </summary> public Matrix ViewMatrix { get { return Matrix.CreateLookAt(targetValue - (Direction * distanceValue), targetValue, Up); } } public SampleArcBallCameraMode ControlMode { get { return mode; } set { if (value != mode) { mode = value; SetCamera(targetValue - (Direction* distanceValue), targetValue, Vector3.Up); } } } #endregion #region Position Controls /// <summary> /// Get or Set the current target of the camera /// </summary> public Vector3 Target { get { return targetValue; } set { targetValue = value; } } /// <summary> /// Get or Set the camera's distance to the target. /// </summary> public float Distance { get { return distanceValue; } set { distanceValue = value; } } /// <summary> /// Sets the rate of distance change /// when automatically handling input /// </summary> public float InputDistanceRate { get { return inputDistanceRateValue; } set { inputDistanceRateValue = value; } } /// <summary> /// Get/Set the camera's current postion. /// </summary> public Vector3 Position { get { return targetValue - (Direction * Distance); } set { SetCamera(value, targetValue, Vector3.Up); } } #endregion #region Orbit Controls /// <summary> /// Orbit directly upwards in Free camera or on /// the longitude line when roll constrained /// </summary> public void OrbitUp(float angle) { switch (mode) { case SampleArcBallCameraMode.Free: //rotate the aspect by the angle orientation = orientation * Quaternion.CreateFromAxisAngle(Vector3.Right, -angle); //normalize to reduce errors Quaternion.Normalize(ref orientation, out orientation); break; case SampleArcBallCameraMode.RollConstrained: //update the yaw pitch -= angle; //constrain pitch to vertical to avoid confusion pitch = MathHelper.Clamp(pitch, -(MathHelper.PiOver2) + .0001f, (MathHelper.PiOver2) - .0001f); //create a new aspect based on pitch and yaw orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) * Quaternion.CreateFromAxisAngle(Vector3.Right, pitch); break; } } /// <summary> /// Orbit towards the Right vector in Free camera /// or on the latitude line when roll constrained /// </summary> public void OrbitRight(float angle) { switch (mode) { case SampleArcBallCameraMode.Free: //rotate the aspect by the angle orientation = orientation * Quaternion.CreateFromAxisAngle(Vector3.Up, angle); //normalize to reduce errors Quaternion.Normalize(ref orientation, out orientation); break; case SampleArcBallCameraMode.RollConstrained: //update the yaw yaw -= angle; //float mod yaw to avoid eventual precision errors //as we move away from 0 yaw = yaw % MathHelper.TwoPi; //create a new aspect based on pitch and yaw orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) * Quaternion.CreateFromAxisAngle(Vector3.Right, pitch); //normalize to reduce errors Quaternion.Normalize(ref orientation, out orientation); break; } } /// <summary> /// Rotate around the Forward vector /// in free-look camera only /// </summary> public void RotateClockwise(float angle) { switch (mode) { case SampleArcBallCameraMode.Free: //rotate the orientation around the direction vector orientation = orientation * Quaternion.CreateFromAxisAngle(Vector3.Forward, angle); Quaternion.Normalize(ref orientation, out orientation); break; case SampleArcBallCameraMode.RollConstrained: //Do nothing, we don't want to roll at all to stay consistent break; } } /// <summary> /// Sets up a quaternion & position from vector camera components /// and oriented the camera up /// </summary> /// <param name="eye">The camera position</param> /// <param name="lookAt">The camera's look-at point</param> /// <param name="up"></param> public void SetCamera(Vector3 position, Vector3 target, Vector3 up) { //Create a look at matrix, to simplify matters a bit Matrix temp = Matrix.CreateLookAt(position, target, up); //invert the matrix, since we're determining the //orientation from the rotation matrix in RH coords temp = Matrix.Invert(temp); //set the postion targetValue = target; //create the new aspect from the look-at matrix orientation = Quaternion.CreateFromRotationMatrix(temp); //When setting a new eye-view direction //in one of the gimble-locked modes, the yaw and //pitch gimble must be calculated. if (mode != SampleArcBallCameraMode.Free) { //first, get the direction projected on the x/z plne Vector3 dir = Direction; dir.Y = 0; if (dir.Length() == 0f) { dir = Vector3.Forward; } dir.Normalize(); //find the yaw of the direction on the x/z plane //and use the sign of the x-component since we have 360 degrees //of freedom yaw = (float)(Math.Acos(-dir.Z) * Math.Sign(dir.X)); //Get the pitch from the angle formed by the Up vector and the //the forward direction, then subtracting Pi / 2, since //we pitch is zero at Forward, not Up. pitch = (float)-(Math.Acos(Vector3.Dot(Vector3.Up, Direction)) - MathHelper.PiOver2); } } #endregion #region Input Handlers /// <summary> /// Handle default keyboard input for a camera /// </summary> public void HandleDefaultKeyboardControls(KeyboardState kbState, GameTime gameTime) { if (gameTime == null) { throw new ArgumentNullException("gameTime", "GameTime parameter cannot be null."); } float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds; float dX = elapsedTime * ReadKeyboardAxis( kbState, Keys.A, Keys.D) * InputTurnRate; float dY = elapsedTime * ReadKeyboardAxis( kbState, Keys.S, Keys.W) * InputTurnRate; if (dY != 0) OrbitUp(dY); if (dX != 0) OrbitRight(dX); distanceValue += ReadKeyboardAxis(kbState, Keys.Z, Keys.X) * inputDistanceRateValue * elapsedTime; if (distanceValue < .001f) distanceValue = .001f; if (mode != SampleArcBallCameraMode.Free) { float dR = elapsedTime * ReadKeyboardAxis( kbState, Keys.Q, Keys.E) * InputTurnRate; if (dR != 0) RotateClockwise(dR); } } /// <summary> /// Handle default gamepad input for a camera /// </summary> public void HandleDefaultGamepadControls(GamePadState gpState, GameTime gameTime) { if (gameTime == null) { throw new ArgumentNullException("gameTime", "GameTime parameter cannot be null."); } if (gpState.IsConnected) { float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds; float dX = gpState.ThumbSticks.Right.X * elapsedTime * InputTurnRate; float dY = gpState.ThumbSticks.Right.Y * elapsedTime * InputTurnRate; float dR = gpState.Triggers.Right * elapsedTime * InputTurnRate; dR-= gpState.Triggers.Left * elapsedTime * InputTurnRate; //change orientation if necessary if(dY != 0) OrbitUp(dY); if(dX != 0) OrbitRight(dX); if (dR != 0) RotateClockwise(dR); //decrease distance to target (move forward) if (gpState.Buttons.A == ButtonState.Pressed) { distanceValue -= elapsedTime * inputDistanceRateValue; } //increase distance to target (move back) if (gpState.Buttons.B == ButtonState.Pressed) { distanceValue += elapsedTime * inputDistanceRateValue; } if (distanceValue < .001f) distanceValue = .001f; } } #endregion #region Misc Camera Controls /// <summary> /// Reset the camera to the defaults set in the constructor /// </summary> public void Reset() { //orientation quaternion assumes a Pi rotation so you're facing the "front" //of the model (looking down the +Z axis) orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi); distanceValue = 3f; targetValue = Vector3.Zero; yaw = MathHelper.Pi; pitch = 0; } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // //Assets/Editor/SearchForComponents.cs using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using UnityEditor.SceneManagement; public class SearchForComponents : EditorWindow { [MenuItem("Editor Tools/Search For Components")] static void Init() { SearchForComponents window = (SearchForComponents)EditorWindow.GetWindow(typeof(SearchForComponents)); window.Show(); window.position = new Rect(20, 80, 550, 500); } string[] modes = new string[] { "Search for component usage", "Search for missing components" }; string[] checkType = new string[] { "Check single component", "Check all components" }; List<string> listResult; List<ComponentNames> prefabComponents, notUsedComponents, addedComponents, existingComponents, sceneComponents; int editorMode, selectedCheckType; bool recursionVal; MonoScript targetComponent; string componentName = ""; bool showPrefabs, showAdded, showScene, showUnused = true; Vector2 scroll, scroll1, scroll2, scroll3, scroll4; class ComponentNames { public string componentName; public string namespaceName; public string assetPath; public List<string> usageSource; public ComponentNames(string comp, string space, string path) { this.componentName = comp; this.namespaceName = space; this.assetPath = path; this.usageSource = new List<string>(); } public override bool Equals(object obj) { return ((ComponentNames)obj).componentName == componentName && ((ComponentNames)obj).namespaceName == namespaceName; } public override int GetHashCode() { return componentName.GetHashCode() + namespaceName.GetHashCode(); } } void OnGUI() { GUILayout.Label(position + ""); GUILayout.Space(3); int oldValue = GUI.skin.window.padding.bottom; GUI.skin.window.padding.bottom = -20; Rect windowRect = GUILayoutUtility.GetRect(1, 17); windowRect.x += 4; windowRect.width -= 7; editorMode = GUI.SelectionGrid(windowRect, editorMode, modes, 2, "Window"); GUI.skin.window.padding.bottom = oldValue; switch (editorMode) { case 0: selectedCheckType = GUILayout.SelectionGrid(selectedCheckType, checkType, 2, "Toggle"); recursionVal = GUILayout.Toggle(recursionVal, "Search all dependencies"); GUI.enabled = selectedCheckType == 0; targetComponent = (MonoScript)EditorGUILayout.ObjectField(targetComponent, typeof(MonoScript), false); GUI.enabled = true; if (GUILayout.Button("Check component usage")) { AssetDatabase.SaveAssets(); switch (selectedCheckType) { case 0: componentName = targetComponent.name; string targetPath = AssetDatabase.GetAssetPath(targetComponent); string[] allPrefabs = GetAllPrefabs(); listResult = new List<string>(); foreach (string prefab in allPrefabs) { string[] single = new string[] { prefab }; string[] dependencies = AssetDatabase.GetDependencies(single, recursionVal); foreach (string dependedAsset in dependencies) { if (dependedAsset == targetPath) { listResult.Add(prefab); } } } break; case 1: List<string> scenesToLoad = new List<string>(); existingComponents = new List<ComponentNames>(); prefabComponents = new List<ComponentNames>(); notUsedComponents = new List<ComponentNames>(); addedComponents = new List<ComponentNames>(); sceneComponents = new List<ComponentNames>(); if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { string projectPath = Application.dataPath; projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets")); string[] allAssets = AssetDatabase.GetAllAssetPaths(); foreach (string asset in allAssets) { int indexCS = asset.IndexOf(".cs"); int indexJS = asset.IndexOf(".js"); if (indexCS != -1 || indexJS != -1) { ComponentNames newComponent = new ComponentNames(NameFromPath(asset), "", asset); try { System.IO.FileStream FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); System.IO.StreamReader SR = new System.IO.StreamReader(FS); string line; while (!SR.EndOfStream) { line = SR.ReadLine(); int index1 = line.IndexOf("namespace"); int index2 = line.IndexOf("{"); if (index1 != -1 && index2 != -1) { line = line.Substring(index1 + 9); index2 = line.IndexOf("{"); line = line.Substring(0, index2); line = line.Replace(" ", ""); newComponent.namespaceName = line; } } } catch { } existingComponents.Add(newComponent); try { System.IO.FileStream FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); System.IO.StreamReader SR = new System.IO.StreamReader(FS); string line; int lineNum = 0; while (!SR.EndOfStream) { lineNum++; line = SR.ReadLine(); int index = line.IndexOf("AddComponent"); if (index != -1) { line = line.Substring(index + 12); if (line[0] == '(') { line = line.Substring(1, line.IndexOf(')') - 1); } else if (line[0] == '<') { line = line.Substring(1, line.IndexOf('>') - 1); } else { continue; } line = line.Replace(" ", ""); line = line.Replace("\"", ""); index = line.LastIndexOf('.'); ComponentNames newComp; if (index == -1) { newComp = new ComponentNames(line, "", ""); } else { newComp = new ComponentNames(line.Substring(index + 1, line.Length - (index + 1)), line.Substring(0, index), ""); } string pName = asset + ", Line " + lineNum; newComp.usageSource.Add(pName); index = addedComponents.IndexOf(newComp); if (index == -1) { addedComponents.Add(newComp); } else { if (!addedComponents[index].usageSource.Contains(pName)) addedComponents[index].usageSource.Add(pName); } } } } catch { } } int indexPrefab = asset.IndexOf(".prefab"); if (indexPrefab != -1) { string[] single = new string[] { asset }; string[] dependencies = AssetDatabase.GetDependencies(single, recursionVal); foreach (string dependedAsset in dependencies) { if (dependedAsset.IndexOf(".cs") != -1 || dependedAsset.IndexOf(".js") != -1) { ComponentNames newComponent = new ComponentNames(NameFromPath(dependedAsset), GetNamespaceFromPath(dependedAsset), dependedAsset); int index = prefabComponents.IndexOf(newComponent); if (index == -1) { newComponent.usageSource.Add(asset); prefabComponents.Add(newComponent); } else { if (!prefabComponents[index].usageSource.Contains(asset)) prefabComponents[index].usageSource.Add(asset); } } } } int indexUnity = asset.IndexOf(".unity"); if (indexUnity != -1) { scenesToLoad.Add(asset); } } for (int i = addedComponents.Count - 1; i > -1; i--) { addedComponents[i].assetPath = GetPathFromNames(addedComponents[i].namespaceName, addedComponents[i].componentName); if (addedComponents[i].assetPath == "") addedComponents.RemoveAt(i); } foreach (string scene in scenesToLoad) { EditorSceneManager.OpenScene(scene); GameObject[] sceneGOs = GetAllObjectsInScene(); foreach (GameObject g in sceneGOs) { Component[] comps = g.GetComponentsInChildren<Component>(true); foreach (Component c in comps) { if (c != null && c.GetType() != null && c.GetType().BaseType != null && c.GetType().BaseType == typeof(MonoBehaviour)) { SerializedObject so = new SerializedObject(c); SerializedProperty p = so.FindProperty("m_Script"); string path = AssetDatabase.GetAssetPath(p.objectReferenceValue); ComponentNames newComp = new ComponentNames(NameFromPath(path), GetNamespaceFromPath(path), path); newComp.usageSource.Add(scene); int index = sceneComponents.IndexOf(newComp); if (index == -1) { sceneComponents.Add(newComp); } else { if (!sceneComponents[index].usageSource.Contains(scene)) sceneComponents[index].usageSource.Add(scene); } } } } } foreach (ComponentNames c in existingComponents) { if (addedComponents.Contains(c)) continue; if (prefabComponents.Contains(c)) continue; if (sceneComponents.Contains(c)) continue; notUsedComponents.Add(c); } addedComponents.Sort(SortAlphabetically); prefabComponents.Sort(SortAlphabetically); sceneComponents.Sort(SortAlphabetically); notUsedComponents.Sort(SortAlphabetically); } break; } } break; case 1: if (GUILayout.Button("Search!")) { string[] allPrefabs = GetAllPrefabs(); listResult = new List<string>(); foreach (string prefab in allPrefabs) { UnityEngine.Object o = AssetDatabase.LoadMainAssetAtPath(prefab); GameObject go; try { go = (GameObject)o; Component[] components = go.GetComponentsInChildren<Component>(true); foreach (Component c in components) { if (c == null) { listResult.Add(prefab); } } } catch { Debug.Log("For some reason, prefab " + prefab + " won't cast to GameObject"); } } } break; } if (editorMode == 1 || selectedCheckType == 0) { if (listResult != null) { if (listResult.Count == 0) { GUILayout.Label(editorMode == 0 ? (componentName == "" ? "Choose a component" : "No prefabs use component " + componentName) : ("No prefabs have missing components!\nClick Search to check again")); } else { GUILayout.Label(editorMode == 0 ? ("The following " + listResult.Count + " prefabs use component " + componentName + ":") : ("The following prefabs have missing components:")); scroll = GUILayout.BeginScrollView(scroll); foreach (string s in listResult) { GUILayout.BeginHorizontal(); GUILayout.Label(s, GUILayout.Width(position.width / 2)); if (GUILayout.Button("Select", GUILayout.Width(position.width / 2 - 10))) { Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(s); } GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); } } } else { showPrefabs = GUILayout.Toggle(showPrefabs, "Show prefab components"); if (showPrefabs) { GUILayout.Label("The following components are attatched to prefabs:"); DisplayResults(ref scroll1, ref prefabComponents); } showAdded = GUILayout.Toggle(showAdded, "Show AddComponent arguments"); if (showAdded) { GUILayout.Label("The following components are AddComponent arguments:"); DisplayResults(ref scroll2, ref addedComponents); } showScene = GUILayout.Toggle(showScene, "Show Scene-used components"); if (showScene) { GUILayout.Label("The following components are used by scene objects:"); DisplayResults(ref scroll3, ref sceneComponents); } showUnused = GUILayout.Toggle(showUnused, "Show Unused Components"); if (showUnused) { GUILayout.Label("The following components are not used by prefabs, by AddComponent, OR in any scene:"); DisplayResults(ref scroll4, ref notUsedComponents); } } } int SortAlphabetically(ComponentNames a, ComponentNames b) { return a.assetPath.CompareTo(b.assetPath); } GameObject[] GetAllObjectsInScene() { List<GameObject> objectsInScene = new List<GameObject>(); GameObject[] allGOs = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)); foreach (GameObject go in allGOs) { //if ( go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave ) // continue; string assetPath = AssetDatabase.GetAssetPath(go.transform.root.gameObject); if (!string.IsNullOrEmpty(assetPath)) continue; objectsInScene.Add(go); } return objectsInScene.ToArray(); } void DisplayResults(ref Vector2 scroller, ref List<ComponentNames> list) { if (list == null) return; scroller = GUILayout.BeginScrollView(scroller); foreach (ComponentNames c in list) { GUILayout.BeginHorizontal(); GUILayout.Label(c.assetPath, GUILayout.Width(position.width / 5 * 4)); if (GUILayout.Button("Select", GUILayout.Width(position.width / 5 - 30))) { Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(c.assetPath); } GUILayout.EndHorizontal(); if (c.usageSource.Count == 1) { GUILayout.Label(" In 1 Place: " + c.usageSource[0]); } if (c.usageSource.Count > 1) { GUILayout.Label(" In " + c.usageSource.Count + " Places: " + c.usageSource[0] + ", " + c.usageSource[1] + (c.usageSource.Count > 2 ? ", ..." : "")); } } GUILayout.EndScrollView(); } string NameFromPath(string s) { s = s.Substring(s.LastIndexOf('/') + 1); return s.Substring(0, s.Length - 3); } string GetNamespaceFromPath(string path) { foreach (ComponentNames c in existingComponents) { if (c.assetPath == path) { return c.namespaceName; } } return ""; } string GetPathFromNames(string space, string name) { ComponentNames test = new ComponentNames(name, space, ""); int index = existingComponents.IndexOf(test); if (index != -1) { return existingComponents[index].assetPath; } return ""; } public static string[] GetAllPrefabs() { string[] temp = AssetDatabase.GetAllAssetPaths(); List<string> result = new List<string>(); foreach (string s in temp) { if (s.Contains(".prefab")) result.Add(s); } return result.ToArray(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; namespace System.Reflection.Tests { public class ParamInfoPropertyTests { //Verify Member [Fact] public static void TestParamMember1() { ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 0); MemberInfo mi = pi.Member; Assert.NotNull(mi); } //Verify Member [Fact] public static void TestParamMember2() { ParameterInfo pi = getParamInfo(typeof(MyClass), "virtualMethod", 0); MemberInfo mi = pi.Member; Assert.NotNull(mi); } //Verify Member [Fact] public static void TestParamMember3() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithRefKW", 0); MemberInfo mi = pi.Member; Assert.NotNull(mi); } //Verify Member [Fact] public static void TestParamMember4() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 0); MemberInfo mi = pi.Member; Assert.NotNull(mi); } //Verify Member [Fact] public static void TestParamMember5() { ParameterInfo pi = getParamInfo(typeof(GenericClass<string>), "genericMethod", 0); MemberInfo mi = pi.Member; Assert.NotNull(mi); } //Verify HasDefaultValue for return param [Fact] public static void TestHasDefaultValue1() { ParameterInfo pi = getReturnParam(typeof(MyClass), "Method1"); Assert.True(pi.HasDefaultValue); } //Verify HasDefaultValue for param that has default [Fact] public static void TestHasDefaultValue2() { Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault1", 1).HasDefaultValue); } //Verify HasDefaultValue for different types of default values [Fact] public static void TestHasDefaultValue3() { Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault2", 0).HasDefaultValue); Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault3", 0).HasDefaultValue); Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault4", 0).HasDefaultValue); } //Verify HasDefaultValue for generic method [Fact] public static void TestHasDefaultValue4() { Assert.True(getParamInfo(typeof(GenericClass<int>), "genericMethodWithdefault", 1).HasDefaultValue); } //Verify HasDefaultValue for methods that do not have default [Fact] public static void TestHasDefaultValue5() { ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1); Assert.False(pi.HasDefaultValue); } //Verify HasDefaultValue for methods that do not have default [Fact] public static void TestHasDefaultValue6() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithRefKW", 0); Assert.False(pi.HasDefaultValue); } //Verify HasDefaultValue for methods that do not have default [Fact] public static void TestHasDefaultValue7() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1); Assert.False(pi.HasDefaultValue); } //Verify HasDefaultValue for methods that do not have default [Fact] public static void TestHasDefaultValue8() { ParameterInfo pi = getParamInfo(typeof(GenericClass<int>), "genericMethod", 0); Assert.False(pi.HasDefaultValue); } //Verify IsOut [Fact] public static void TestIsOut1() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithRefKW", 0); Assert.False(pi.IsOut); } //Verify IsOut [Fact] public static void TestIsOut2() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1); Assert.True(pi.IsOut); } //Verify IsOut [Fact] public static void TestIsOut3() { ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1); Assert.False(pi.IsOut); } //Verify IsIN [Fact] public static void TestIsIN1() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1); Assert.False(pi.IsIn); } //Verify DefaultValue for param that has default [Fact] public static void TestDefaultValue1() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault1", 1); int value = (int)pi.DefaultValue; Assert.Equal(0, value); } //Verify DefaultValue for param that has default [Fact] public static void TestDefaultValue2() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault2", 0); string value = (string)pi.DefaultValue; Assert.Equal("abc", value); } //Verify DefaultValue for param that has default [Fact] public static void TestDefaultValue3() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault3", 0); bool value = (bool)pi.DefaultValue; Assert.Equal(false, value); } //Verify DefaultValue for param that has default [Fact] public static void TestDefaultValue4() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault4", 0); char value = (char)pi.DefaultValue; Assert.Equal('\0', value); } [Fact] public static void TestDefaultValue5() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOptionalAndNoDefault", 0); Object defaultValue = pi.DefaultValue; Assert.Equal(Missing.Value, defaultValue); } //Verify IsOptional [Fact] public static void TestIsOptional1() { ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1); Assert.False(pi.IsOptional); } //Verify IsOptional [Fact] public static void TestIsOptional2() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1); Assert.False(pi.IsOptional); } //Verify IsRetval [Fact] public static void TestIsRetval1() { ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1); Assert.False(pi.IsRetval); } //Verify IsRetval [Fact] public static void TestIsRetval2() { ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault2", 0); Assert.False(pi.IsRetval); } //Helper Method to get ParameterInfo object based on index private static ParameterInfo getParamInfo(Type type, string methodName, int index) { MethodInfo mi = getMethod(type, methodName); Assert.NotNull(mi); ParameterInfo[] allparams = mi.GetParameters(); Assert.NotNull(allparams); if (index < allparams.Length) return allparams[index]; else return null; } private static ParameterInfo getReturnParam(Type type, string methodName) { MethodInfo mi = getMethod(type, methodName); Assert.NotNull(mi); return mi.ReturnParameter; } private static MethodInfo getMethod(Type t, string method) { TypeInfo ti = t.GetTypeInfo(); IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); MethodInfo mi = null; while (alldefinedMethods.MoveNext()) { if (alldefinedMethods.Current.Name.Equals(method)) { //found method mi = alldefinedMethods.Current; break; } } return mi; } // Class For Reflection Metadata public class MyClass { public int Method1(String str, int iValue, long lValue) { return 1; } public string Method2() { return "somestring"; } public int MethodWithArray(String[] strArray) { for (int ii = 0; ii < strArray.Length; ++ii) { } return strArray.Length; } public virtual void virtualMethod(long data) { } public bool MethodWithRefKW(ref String str) { str = "newstring"; return true; } public Object MethodWithOutKW(int i, out String str) { str = "newstring"; return (object)str; } public int MethodWithdefault1(long lValue, int iValue = 0) { return 1; } public int MethodWithdefault2(string str = "abc") { return 1; } public int MethodWithdefault3(bool result = false) { return 1; } public int MethodWithdefault4(char c = '\0') { return 1; } public int MethodWithOptionalAndNoDefault([Optional] Object o) { return 1; } } public class GenericClass<T> { public string genericMethod(T t) { return "somestring"; } public string genericMethodWithdefault(int i, T t = default(T)) { return "somestring"; } } } }
/* * * (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. * */ #if DEBUG using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Web; using System.Xml.Linq; namespace ASC.Api.Core.Tests { [TestClass] public class FormBinderTests { [TestInitialize] public void PreRun() { Bind1000GuidToCollection();//Warm up } [TestMethod] public void SimpleBind() { var nameValue = HttpUtility.ParseQueryString("files=11031&documents=111"); var result = (int)Utils.Binder.Bind(typeof(int), nameValue, "files"); var result2 = (int)Utils.Binder.Bind(typeof(int), nameValue, "documents"); Assert.AreEqual(result, 11031); Assert.AreEqual(result2, 111); } [TestMethod] public void TestBinderWithSimpleArray() { var nameValue = HttpUtility.ParseQueryString("files[]=11031&files[]=111"); var result = ((IEnumerable<int>)Utils.Binder.Bind(typeof(int[]), nameValue, "files")).ToArray(); Assert.IsNotNull(result); Assert.IsTrue(result.Length == 2); Assert.IsTrue(result[0] == 11031); Assert.IsTrue(result[1] == 111); } [TestMethod] public void TestBinderWithStringArray() { var nameValue = HttpUtility.ParseQueryString("strings[]=string1&strings[]=string2"); var result = Utils.Binder.Bind<string[]>(nameValue, "strings"); Assert.IsNotNull(result); Assert.IsTrue(result.Length == 2); Assert.IsTrue(result[0] == "string1"); Assert.IsTrue(result[1] == "string2"); } [TestMethod] public void TestJsonBinding() { var complex = new TestComplex(); complex.Name = "Aaabbb11"; complex.SharingOptions = new[] { new SharingParam(){ActionId = "asfd",IsGroup = false,ItemId = Guid.NewGuid()}, new SharingParam(){ActionId = "sdfsdg",IsGroup = true,ItemId = Guid.NewGuid()}, }; var collection = new NameValueCollection(); var str = JsonConvert.SerializeObject(complex); var xdoc = JsonConvert.DeserializeXNode(str, "request", false); FillCollectionFromXElement(xdoc.Root.Elements(), string.Empty, collection); var binded = Utils.Binder.Bind<TestComplex>(collection); } [TestMethod] public void TestJsonSimpleBinding() { var collection = new NameValueCollection(); var str = JsonConvert.SerializeObject(new { someData = new[] { 1,2,3,4} }); var xdoc = JsonConvert.DeserializeXNode(str, "request", false); FillCollectionFromXElement(xdoc.Root.Elements(), string.Empty, collection); var binded = Utils.Binder.Bind<int[]>(collection, "someData"); } private static void FillCollectionFromXElement(IEnumerable<XElement> elements, string prefix, NameValueCollection collection) { foreach (var grouping in elements.GroupBy(x => x.Name)) { if (grouping.Count()<2) { //Single element var element = grouping.SingleOrDefault(); if (element != null) { if (!element.HasElements) { //Last one in tree AddElement(prefix, collection, element); } else { FillCollectionFromXElement(element.Elements(), prefix + "." + element.Name.LocalName,collection); } } } else { //Grouping has more than one if (grouping.All(x=>!x.HasElements)) { //Simple collection foreach (XElement element in grouping) { AddElement(prefix,collection,element); } } else { var groupList = grouping.ToList(); for (int i = 0; i < groupList.Count; i++) { FillCollectionFromXElement(groupList[i].Elements(),prefix+"."+grouping.Key+"["+i+"]",collection); } } } } } private static void AddElement(string prefix, NameValueCollection collection, XElement element) { if (string.IsNullOrEmpty(prefix)) collection.Add(element.Name.LocalName, element.Value); else { var prefixes = prefix.TrimStart('.').Split('.'); string additional = string.Empty; if (prefixes.Length > 1) { additional = string.Join("", prefix.Skip(1).Select(x => "[" + x + "]").ToArray()); } collection.Add(prefixes[0]+additional + "[" + element.Name.LocalName + "]", element.Value); } } [TestMethod] public void TestBinderWithGuidArray() { var nameValue = HttpUtility.ParseQueryString("guids[]=2A0B1EB6-0B56-4641-A8D5-3AAE7E043E40&guids[]=DB01ED90-9E19-4c20-A454-20B9AEF4C579"); var result = Utils.Binder.Bind<Guid[]>(nameValue, "guids"); Assert.IsNotNull(result); Assert.IsTrue(result.Length == 2); Assert.IsTrue(result[0] == new Guid("2A0B1EB6-0B56-4641-A8D5-3AAE7E043E40")); Assert.IsTrue(result[1] == new Guid("DB01ED90-9E19-4c20-A454-20B9AEF4C579")); } [TestMethod] public void BindSimpleToCollection() { var nameValue = HttpUtility.ParseQueryString("file=11031"); var result = ((IEnumerable<int>)Utils.Binder.Bind(typeof(int[]), nameValue, "file")).ToArray(); Assert.IsNotNull(result); } [TestMethod] public void TestEmpty() { var nameValue = HttpUtility.ParseQueryString("subjects="); var result = ((IEnumerable<string>)Utils.Binder.Bind(typeof(IEnumerable<string>), nameValue, "subjects")).ToArray(); Assert.IsNotNull(result); } [TestMethod] public void BindGuidToCollection() { var nameValue = HttpUtility.ParseQueryString("Title=dsadsa&Description=xzxzxzxczcxz&Responsible=93580c54-1132-4d6b-bf2d-da0bfaaa1a28&Responsibles%5B%5D=93580c54-1132-4d6b-bf2d-da0bfaaa1a28&Responsibles%5B%5D=0017794f-aeb7-49a5-8817-9e870e02bd3f&Responsibles%5B%5D=535e344c-a478-42c6-a0ed-4d46331193de&priority=0"); var result = ((IEnumerable<Guid>)Utils.Binder.Bind(typeof(Guid[]), nameValue, "Responsibles")).ToArray(); Assert.IsNotNull(result); } [TestMethod] public void Bind1000GuidToCollection() { for (int i = 0; i < 1000; i++) { var nameValue = HttpUtility.ParseQueryString("Title=dsadsa&Description=xzxzxzxczcxz&Responsible=93580c54-1132-4d6b-bf2d-da0bfaaa1a28&Responsibles%5B%5D=93580c54-1132-4d6b-bf2d-da0bfaaa1a28&Responsibles%5B%5D=0017794f-aeb7-49a5-8817-9e870e02bd3f&Responsibles%5B%5D=535e344c-a478-42c6-a0ed-4d46331193de&priority=0"); var result = ((IEnumerable<Guid>)Utils.Binder.Bind(typeof(Guid[]), nameValue, "Responsibles")).ToArray(); Assert.IsNotNull(result); } } public class SubscriptionState { public string Id { get; set; } public bool IsAccepted { get; set; } } [TestMethod] public void TestComplexClassBinding() { var query = @"states%5B0%5D%5BId%5D=Project_588&states%5B0%5D%5BIsAccepted%5D=false"; var nameValue = HttpUtility.ParseQueryString(query); var result = (((List<SubscriptionState>)Utils.Binder.Bind(typeof(List<SubscriptionState>), nameValue, "states"))); } [TestMethod] public void TestNullArrayComplexClassBinding() { var query = @"name=New+calendar&description=&textColor=rgb(0%2C+0%2C+0)&backgroundColor=rgb(135%2C+206%2C+250)&timeZone=Arabian+Standard+Time&alertType=0&hideEvents=true&sharingOptions%5B0%5D%5BActionId%5D=read&sharingOptions%5B0%5D%5BitemId%5D=646a6cff-df57-4b83-8ffe-91a24910328c&sharingOptions%5B0%5D%5BisGroup%5D=false"; var nameValue = HttpUtility.ParseQueryString(query); var result = (((SharingParam[])Utils.Binder.Bind(typeof(SharingParam[]), nameValue, "sharingOptions"))); Assert.AreNotEqual(string.Empty, result); Assert.AreEqual(result.Length, 1); } [TestMethod] public void TestComplexLowerCamelCaseClassBinding() { var query = @"Name=New+calendar&description=&textColor=rgb(0%2C+0%2C+0)&backgroundColor=rgb(135%2C+206%2C+250)&timeZone=Arabian+Standard+Time&alertType=0&hideEvents=true&sharingOptions%5B0%5D%5BActionId%5D=read&sharingOptions%5B0%5D%5BitemId%5D=646a6cff-df57-4b83-8ffe-91a24910328c&sharingOptions%5B0%5D%5BisGroup%5D=false"; var nameValue = HttpUtility.ParseQueryString(query); var result = (((TestComplex)Utils.Binder.Bind(typeof(TestComplex), nameValue, ""))); Assert.IsNotNull(result); Assert.IsNotNull(result.Name); Assert.AreNotEqual(string.Empty, result.SharingOptions); Assert.AreEqual(result.SharingOptions.Length, 1); } public class TestComplex { public string Name { get; set; } public SharingParam[] SharingOptions { get; set; } } public class SharingParam { public string ActionId { get; set; } public Guid ItemId { get; set; } public bool IsGroup { get; set; } } } } #endif
using System; using System.IO; using System.Net; using System.Xml; using System.Diagnostics; using SharpVectors.Net; namespace SharpVectors.Renderers.Utils { public sealed class WpfCacheManager : ICacheManager { private XmlElement lastCacheElm; private Uri lastUri; private string cacheDir; private string cacheDocPath; private XmlDocument cacheDoc = new XmlDocument(); public WpfCacheManager() { cacheDoc = new XmlDocument(); cacheDir = Path.Combine(WpfApplicationContext.ExecutableDirectory.FullName, "cache/"); cacheDocPath = Path.Combine(cacheDir, "cache.xml"); LoadDoc(); } public WpfCacheManager(string cacheDir) { cacheDoc = new XmlDocument(); this.cacheDir = Path.Combine( WpfApplicationContext.ExecutableDirectory.FullName, cacheDir); cacheDocPath = Path.Combine(cacheDir, "cache.xml"); LoadDoc(); } private void LoadDoc() { if (cacheDoc == null) { cacheDoc = new XmlDocument(); } if(File.Exists(cacheDocPath)) { cacheDoc.Load(cacheDocPath); } else { Directory.CreateDirectory(Directory.GetParent(cacheDocPath).FullName); cacheDoc.LoadXml("<cache />"); } } private void SaveDoc() { if (cacheDoc == null) { return; } cacheDoc.Save(cacheDocPath); } private XmlElement GetCacheElm(Uri uri) { if(uri == lastUri && lastCacheElm != null) { return lastCacheElm; } else { //string xpath = "/cache/resource[@url='" + uri.ToString() + "']"; string xpath = "/cache/resource[@url='" + uri.ToString().Replace("'", "&apos;") + "']"; XmlNode node = cacheDoc.SelectSingleNode(xpath); if(node != null) { lastCacheElm = node as XmlElement; } else { lastCacheElm = cacheDoc.CreateElement("resource"); cacheDoc.DocumentElement.AppendChild(lastCacheElm); lastCacheElm.SetAttribute("url", uri.ToString()); } lastUri = uri; return lastCacheElm; } } private Uri GetLocalPathUri(XmlElement cacheElm) { if (cacheElm.HasAttribute("local-path")) { string path = Path.Combine(cacheDir, cacheElm.GetAttribute("local-path")); if(File.Exists(path)) { path = "file:///" + path.Replace('\\', '/'); return new Uri(path); } else { cacheElm.RemoveAttribute("local-path"); return null; } } else { return null; } } public long Size { get { DirectoryInfo di = new DirectoryInfo(cacheDir); FileInfo[] files = di.GetFiles(); long size = 0; foreach(FileInfo file in files) { size += file.Length; } return size; } } public void Clear() { DirectoryInfo di = new DirectoryInfo(cacheDir); FileInfo[] files = di.GetFiles(); foreach(FileInfo file in files) { try { file.Delete(); } catch{} } cacheDoc = new XmlDocument(); LoadDoc(); } public CacheInfo GetCacheInfo(Uri uri) { XmlElement cacheElm = GetCacheElm(uri); DateTime expires = DateTime.MinValue; if(cacheElm.HasAttribute("expires")) { expires = DateTime.Parse(cacheElm.GetAttribute("expires")); } DateTime lastModified = DateTime.MinValue; if(cacheElm.HasAttribute("last-modified")) { lastModified = DateTime.Parse(cacheElm.GetAttribute("last-modified")); } Uri cachedUri = GetLocalPathUri(cacheElm); return new CacheInfo(expires, cacheElm.GetAttribute("etag"), lastModified, cachedUri, cacheElm.GetAttribute("content-type")); } public void SetCacheInfo(Uri uri, CacheInfo cacheInfo, Stream stream) { XmlElement cacheElm = GetCacheElm(uri); if(cacheInfo != null) { if(cacheInfo.ETag != null) { cacheElm.SetAttribute("etag", cacheInfo.ETag); } else { cacheElm.RemoveAttribute("etag"); } if(cacheInfo.ContentType != null) { cacheElm.SetAttribute("content-type", cacheInfo.ContentType); } else { cacheElm.RemoveAttribute("content-type"); } if(cacheInfo.Expires != DateTime.MinValue) { cacheElm.SetAttribute("expires", cacheInfo.Expires.ToString("s")); } else { cacheElm.RemoveAttribute("expires"); } if(cacheInfo.LastModified != DateTime.MinValue) { cacheElm.SetAttribute("last-modified", cacheInfo.LastModified.ToString("s")); } else { cacheElm.RemoveAttribute("last-modified"); } } if (stream != null) { string localPath; if(cacheElm.HasAttribute("local-path")) { localPath = cacheElm.GetAttribute("local-path"); } else { localPath = Guid.NewGuid().ToString() + ".cache"; cacheElm.SetAttribute("local-path", localPath); } stream.Position = 0; int count; byte[] buffer = new byte[4096]; FileStream fs = File.OpenWrite(Path.Combine(cacheDir, localPath)); while((count = stream.Read(buffer, 0, 4096)) > 0) fs.Write(buffer, 0, count); fs.Flush(); fs.Close(); } SaveDoc(); } } }
#pragma warning disable 162,108 using UnityEngine; using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; public enum RuleResult { Done, Working } namespace Casanova.Prelude { public class Tuple<T,E> { public T Item1 { get; set;} public E Item2 { get; set;} public Tuple(T item1, E item2) { Item1 = item1; Item2 = item2; } } public static class MyExtensions { //public T this[List<T> list] //{ // get { return list.ElementAt(0); } //} public static T Head<T>(this List<T> list) { return list.ElementAt(0); } public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); } public static int Length<T>(this List<T> list) { return list.Count; } public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; } } public class Cons<T> : IEnumerable<T> { public class Enumerator : IEnumerator<T> { public Enumerator(Cons<T> parent) { firstEnumerated = 0; this.parent = parent; tailEnumerator = parent.tail.GetEnumerator(); } byte firstEnumerated; Cons<T> parent; IEnumerator<T> tailEnumerator; public T Current { get { if (firstEnumerated == 0) return default(T); if (firstEnumerated == 1) return parent.head; else return tailEnumerator.Current; } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { if (firstEnumerated == 0) { if (parent.head == null) return false; firstEnumerated++; return true; } if (firstEnumerated == 1) firstEnumerated++; return tailEnumerator.MoveNext(); } public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); } public void Dispose() { } } T head; IEnumerable<T> tail; public Cons(T head, IEnumerable<T> tail) { this.head = head; this.tail = tail; } public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } } public class Empty<T> : IEnumerable<T> { public Empty() { } public class Enumerator : IEnumerator<T> { public T Current { get { throw new Exception("Empty sequence has no elements"); } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { return false; } public void Reset() { } public void Dispose() { } } public IEnumerator<T> GetEnumerator() { return new Enumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(); } } public abstract class Option<T> : IComparable, IEquatable<Option<T>> { public bool IsSome; public bool IsNone { get { return !IsSome; } } protected abstract Just<T> Some { get; } public U Match<U>(Func<T,U> f, Func<U> g) { if (this.IsSome) return f(this.Some.Value); else return g(); } public bool Equals(Option<T> b) { return this.Match( x => b.Match( y => x.Equals(y), () => false), () => b.Match( y => false, () => true)); } public override bool Equals(System.Object other) { if (other == null) return false; if (other is Option<T>) { var other1 = other as Option<T>; return this.Equals(other1); } return false; } public override int GetHashCode() { return this.GetHashCode(); } public static bool operator ==(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return a.Equals(b); } public static bool operator !=(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return !(a.Equals(b)); } public int CompareTo(object obj) { if (obj == null) return 1; if (obj is Option<T>) { var obj1 = obj as Option<T>; if (this.Equals(obj1)) return 0; } return -1; } abstract public T Value { get; } public override string ToString() { return "Option<" + typeof(T).ToString() + ">"; } } public class Just<T> : Option<T> { T elem; public Just(T elem) { this.elem = elem; this.IsSome = true; } protected override Just<T> Some { get { return this; } } public override T Value { get { return elem; } } } public class Nothing<T> : Option<T> { public Nothing() { this.IsSome = false; } protected override Just<T> Some { get { return null; } } public override T Value { get { throw new Exception("Cant get a value from a None object"); } } } public class Utils { public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e) { if (c()) return t(); else return e(); } } } public class FastStack { public int[] Elements; public int Top; public FastStack(int elems) { Top = 0; Elements = new int[elems]; } public void Clear() { Top = 0; } public void Push(int x) { Elements[Top++] = x; } } public class RuleTable { public RuleTable(int elems) { ActiveIndices = new FastStack(elems); SupportStack = new FastStack(elems); ActiveSlots = new bool[elems]; } public FastStack ActiveIndices; public FastStack SupportStack; public bool[] ActiveSlots; public void Add(int i) { if (!ActiveSlots[i]) { ActiveSlots[i] = true; ActiveIndices.Push(i); } } } public class World : MonoBehaviour{ void Update () { Update(Time.deltaTime, this); } public void Start() { UnityBob = UnityBob.Find(); } public UnityBob UnityBob; public System.Collections.Generic.List<UnityEngine.Vector3> Checkpoints{ get { return UnityBob.Checkpoints; } } public UnityEngine.Vector3 Velocity{ get { return UnityBob.Velocity; } set{UnityBob.Velocity = value; } } public UnityEngine.Vector3 Position{ get { return UnityBob.Position; } } public BobAnimation CurrentAnimation{ set{UnityBob.CurrentAnimation = value; } } public System.Boolean useGUILayout{ get { return UnityBob.useGUILayout; } set{UnityBob.useGUILayout = value; } } public System.Boolean enabled{ get { return UnityBob.enabled; } set{UnityBob.enabled = value; } } public UnityEngine.Transform transform{ get { return UnityBob.transform; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityBob.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityBob.rigidbody2D; } } public UnityEngine.Camera camera{ get { return UnityBob.camera; } } public UnityEngine.Light light{ get { return UnityBob.light; } } public UnityEngine.Animation animation{ get { return UnityBob.animation; } } public UnityEngine.ConstantForce constantForce{ get { return UnityBob.constantForce; } } public UnityEngine.Renderer renderer{ get { return UnityBob.renderer; } } public UnityEngine.AudioSource audio{ get { return UnityBob.audio; } } public UnityEngine.GUIText guiText{ get { return UnityBob.guiText; } } public UnityEngine.NetworkView networkView{ get { return UnityBob.networkView; } } public UnityEngine.GUITexture guiTexture{ get { return UnityBob.guiTexture; } } public UnityEngine.Collider collider{ get { return UnityBob.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityBob.collider2D; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityBob.hingeJoint; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityBob.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityBob.particleSystem; } } public UnityEngine.GameObject gameObject{ get { return UnityBob.gameObject; } } public System.String tag{ get { return UnityBob.tag; } set{UnityBob.tag = value; } } public System.String name{ get { return UnityBob.name; } set{UnityBob.name = value; } } public UnityEngine.HideFlags hideFlags{ get { return UnityBob.hideFlags; } set{UnityBob.hideFlags = value; } } public UnityEngine.Vector3 ___c00; public System.Int32 counter1; public System.Collections.Generic.List<UnityEngine.Vector3> list0; public UnityEngine.Vector3 ___dir000; public System.Single count_down1; public void Update(float dt, World world) { this.Rule0(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: counter1 = -1; list0 = Checkpoints; if(((list0.Count) == (0))) { s0 = -1; return; }else { ___c00 = list0[0]; goto case 1; } case 1: counter1 = ((counter1) + (1)); if(((((list0.Count) == (counter1))) || (((counter1) > (list0.Count))))) { s0 = -1; return; }else { ___c00 = list0[counter1]; goto case 2; } case 2: ___dir000 = ((___c00) - (Position)); UnityBob.Velocity = ___dir000; UnityBob.CurrentAnimation = BobAnimation.Walk; s0 = 6; return; case 6: if(!(((0f) > (UnityEngine.Vector3.Dot(___dir000,(___c00) - (Position)))))) { s0 = 6; return; }else { goto case 5; } case 5: UnityBob.Velocity = Vector3.zero; UnityBob.CurrentAnimation = BobAnimation.Idle; s0 = 3; return; case 3: count_down1 = 1f; goto case 4; case 4: if(((count_down1) > (0f))) { count_down1 = ((count_down1) - (dt)); s0 = 4; return; }else { s0 = 1; return; } default: return;}} }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Helper class to validate objects, properties and other values using their associated /// <see cref="ValidationAttribute" /> /// custom attributes. /// </summary> public static class Validator { private static readonly ValidationAttributeStore _store = ValidationAttributeStore.Instance; /// <summary> /// Tests whether the given property value is valid. /// </summary> /// <remarks> /// This method will test each <see cref="ValidationAttribute" /> associated with the property /// identified by <paramref name="validationContext" />. If <paramref name="validationResults" /> is non-null, /// this method will add a <see cref="ValidationResult" /> to it for each validation failure. /// <para> /// If there is a <see cref="RequiredAttribute" /> found on the property, it will be evaluated before all other /// validation attributes. If the required validator fails then validation will abort, adding that single /// failure into the <paramref name="validationResults" /> when applicable, returning a value of <c>false</c>. /// </para> /// <para> /// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure, /// then all validators will be evaluated. /// </para> /// </remarks> /// <param name="value">The value to test.</param> /// <param name="validationContext"> /// Describes the property member to validate and provides services and context for the /// validators. /// </param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <returns><c>true</c> if the value is valid, <c>false</c> if any validation errors are encountered.</returns> /// <exception cref="ArgumentException"> /// When the <see cref="ValidationContext.MemberName" /> of <paramref name="validationContext" /> is not a valid /// property. /// </exception> public static bool TryValidateProperty(object value, ValidationContext validationContext, ICollection<ValidationResult> validationResults) { // Throw if value cannot be assigned to this property. That is not a validation exception. var propertyType = _store.GetPropertyType(validationContext); var propertyName = validationContext.MemberName; EnsureValidPropertyType(propertyName, propertyType, value); var result = true; var breakOnFirstError = (validationResults == null); var attributes = _store.GetPropertyValidationAttributes(validationContext); foreach (var err in GetValidationErrors(value, validationContext, attributes, breakOnFirstError)) { result = false; validationResults?.Add(err.ValidationResult); } return result; } /// <summary> /// Tests whether the given object instance is valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also /// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. It does not validate the /// property values of the object. /// <para> /// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation /// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be /// evaluated. /// </para> /// </remarks> /// <param name="instance">The object instance to test. It cannot be <c>null</c>.</param> /// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />. /// </exception> public static bool TryValidateObject( object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults) => TryValidateObject(instance, validationContext, validationResults, false /*validateAllProperties*/); /// <summary> /// Tests whether the given object instance is valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also /// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. If /// <paramref name="validateAllProperties" /> /// is <c>true</c>, this method will also evaluate the <see cref="ValidationAttribute" />s for all the immediate /// properties /// of this object. This process is not recursive. /// <para> /// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation /// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be /// evaluated. /// </para> /// <para> /// For any given property, if it has a <see cref="RequiredAttribute" /> that fails validation, no other validators /// will be evaluated for that property. /// </para> /// </remarks> /// <param name="instance">The object instance to test. It cannot be null.</param> /// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <param name="validateAllProperties"> /// If <c>true</c>, also evaluates all properties of the object (this process is not /// recursive over properties of the properties). /// </param> /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />. /// </exception> public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults, bool validateAllProperties) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (validationContext != null && instance != validationContext.ObjectInstance) { throw new ArgumentException( SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); } var result = true; var breakOnFirstError = (validationResults == null); foreach ( var err in GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError)) { result = false; validationResults?.Add(err.ValidationResult); } return result; } /// <summary> /// Tests whether the given value is valid against a specified list of <see cref="ValidationAttribute" />s. /// </summary> /// <remarks> /// This method will test each <see cref="ValidationAttribute" />s specified. If /// <paramref name="validationResults" /> is non-null, this method will add a <see cref="ValidationResult" /> /// to it for each validation failure. /// <para> /// If there is a <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" />, it will /// be evaluated before all other validation attributes. If the required validator fails then validation will /// abort, adding that single failure into the <paramref name="validationResults" /> when applicable, returning a /// value of <c>false</c>. /// </para> /// <para> /// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure, /// then all validators will be evaluated. /// </para> /// </remarks> /// <param name="value">The value to test. It cannot be null.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. /// </param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <param name="validationAttributes"> /// The list of <see cref="ValidationAttribute" />s to validate this /// <paramref name="value" /> against. /// </param> /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns> public static bool TryValidateValue(object value, ValidationContext validationContext, ICollection<ValidationResult> validationResults, IEnumerable<ValidationAttribute> validationAttributes) { var result = true; var breakOnFirstError = validationResults == null; foreach ( var err in GetValidationErrors(value, validationContext, validationAttributes, breakOnFirstError)) { result = false; validationResults?.Add(err.ValidationResult); } return result; } /// <summary> /// Throws a <see cref="ValidationException" /> if the given property <paramref name="value" /> is not valid. /// </summary> /// <param name="value">The value to test.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. It cannot be <c>null</c>. /// </param> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ValidationException">When <paramref name="value" /> is invalid for this property.</exception> public static void ValidateProperty(object value, ValidationContext validationContext) { // Throw if value cannot be assigned to this property. That is not a validation exception. var propertyType = _store.GetPropertyType(validationContext); EnsureValidPropertyType(validationContext.MemberName, propertyType, value); var attributes = _store.GetPropertyValidationAttributes(validationContext); GetValidationErrors(value, validationContext, attributes, false).FirstOrDefault() ?.ThrowValidationException(); } /// <summary> /// Throws a <see cref="ValidationException" /> if the given <paramref name="instance" /> is not valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type. /// </remarks> /// <param name="instance">The object instance to test. It cannot be null.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. It cannot be <c>null</c>. /// </param> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />. /// </exception> /// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception> public static void ValidateObject(object instance, ValidationContext validationContext) { ValidateObject(instance, validationContext, false /*validateAllProperties*/); } /// <summary> /// Throws a <see cref="ValidationException" /> if the given object instance is not valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type. /// If <paramref name="validateAllProperties" /> is <c>true</c> it also validates all the object's properties. /// </remarks> /// <param name="instance">The object instance to test. It cannot be null.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. It cannot be <c>null</c>. /// </param> /// <param name="validateAllProperties">If <c>true</c>, also validates all the <paramref name="instance" />'s properties.</param> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />. /// </exception> /// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception> public static void ValidateObject(object instance, ValidationContext validationContext, bool validateAllProperties) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } if (instance != validationContext.ObjectInstance) { throw new ArgumentException( SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); } GetObjectValidationErrors(instance, validationContext, validateAllProperties, false).FirstOrDefault()?.ThrowValidationException(); } /// <summary> /// Throw a <see cref="ValidationException" /> if the given value is not valid for the /// <see cref="ValidationAttribute" />s. /// </summary> /// <remarks> /// This method evaluates the <see cref="ValidationAttribute" />s supplied until a validation error occurs, /// at which time a <see cref="ValidationException" /> is thrown. /// <para> /// A <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" /> will always be evaluated /// first. /// </para> /// </remarks> /// <param name="value">The value to test. It cannot be null.</param> /// <param name="validationContext">Describes the object being tested.</param> /// <param name="validationAttributes">The list of <see cref="ValidationAttribute" />s to validate against this instance.</param> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ValidationException">When <paramref name="value" /> is found to be invalid.</exception> public static void ValidateValue(object value, ValidationContext validationContext, IEnumerable<ValidationAttribute> validationAttributes) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } GetValidationErrors(value, validationContext, validationAttributes, false).FirstOrDefault()?.ThrowValidationException(); } /// <summary> /// Creates a new <see cref="ValidationContext" /> to use to validate the type or a member of /// the given object instance. /// </summary> /// <param name="instance">The object instance to use for the context.</param> /// <param name="validationContext"> /// An parent validation context that supplies an <see cref="IServiceProvider" /> /// and <see cref="ValidationContext.Items" />. /// </param> /// <returns>A new <see cref="ValidationContext" /> for the <paramref name="instance" /> provided.</returns> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> private static ValidationContext CreateValidationContext(object instance, ValidationContext validationContext) { Debug.Assert(validationContext != null); // Create a new context using the existing ValidationContext that acts as an IServiceProvider and contains our existing items. var context = new ValidationContext(instance, validationContext, validationContext.Items); return context; } /// <summary> /// Determine whether the given value can legally be assigned into the specified type. /// </summary> /// <param name="destinationType">The destination <see cref="Type" /> for the value.</param> /// <param name="value"> /// The value to test to see if it can be assigned as the Type indicated by /// <paramref name="destinationType" />. /// </param> /// <returns><c>true</c> if the assignment is legal.</returns> /// <exception cref="ArgumentNullException">When <paramref name="destinationType" /> is null.</exception> private static bool CanBeAssigned(Type destinationType, object value) { if (value == null) { // Null can be assigned only to reference types or Nullable or Nullable<> return !destinationType.IsValueType || (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)); } // Not null -- be sure it can be cast to the right type return destinationType.IsInstanceOfType(value); } /// <summary> /// Determines whether the given value can legally be assigned to the given property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="propertyType">The type of the property.</param> /// <param name="value">The value. Null is permitted only if the property will accept it.</param> /// <exception cref="ArgumentException"> is thrown if <paramref name="value" /> is the wrong type for this property.</exception> private static void EnsureValidPropertyType(string propertyName, Type propertyType, object value) { if (!CanBeAssigned(propertyType, value)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.Validator_Property_Value_Wrong_Type, propertyName, propertyType), nameof(value)); } } /// <summary> /// Internal iterator to enumerate all validation errors for the given object instance. /// </summary> /// <param name="instance">Object instance to test.</param> /// <param name="validationContext">Describes the object type.</param> /// <param name="validateAllProperties">if <c>true</c> also validates all properties.</param> /// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param> /// <returns> /// A collection of validation errors that result from validating the <paramref name="instance" /> with /// the given <paramref name="validationContext" />. /// </returns> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />. /// </exception> private static IEnumerable<ValidationError> GetObjectValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError) { Debug.Assert(instance != null); if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } // Step 1: Validate the object properties' validation attributes var errors = new List<ValidationError>(); errors.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError)); // We only proceed to Step 2 if there are no errors if (errors.Any()) { return errors; } // Step 2: Validate the object's validation attributes var attributes = _store.GetTypeValidationAttributes(validationContext); errors.AddRange(GetValidationErrors(instance, validationContext, attributes, breakOnFirstError)); // We only proceed to Step 3 if there are no errors if (errors.Any()) { return errors; } // Step 3: Test for IValidatableObject implementation if (instance is IValidatableObject validatable) { var results = validatable.Validate(validationContext); foreach (var result in results.Where(r => r != ValidationResult.Success)) { errors.Add(new ValidationError(null, instance, result)); } } return errors; } /// <summary> /// Internal iterator to enumerate all the validation errors for all properties of the given object instance. /// </summary> /// <param name="instance">Object instance to test.</param> /// <param name="validationContext">Describes the object type.</param> /// <param name="validateAllProperties"> /// If <c>true</c>, evaluates all the properties, otherwise just checks that /// ones marked with <see cref="RequiredAttribute" /> are not null. /// </param> /// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param> /// <returns>A list of <see cref="ValidationError" /> instances.</returns> private static IEnumerable<ValidationError> GetObjectPropertyValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError) { var properties = GetPropertyValues(instance, validationContext); var errors = new List<ValidationError>(); foreach (var property in properties) { // get list of all validation attributes for this property var attributes = _store.GetPropertyValidationAttributes(property.Key); if (validateAllProperties) { // validate all validation attributes on this property errors.AddRange(GetValidationErrors(property.Value, property.Key, attributes, breakOnFirstError)); } else { // only validate the Required attributes var reqAttr = attributes.FirstOrDefault(a => a is RequiredAttribute) as RequiredAttribute; if (reqAttr != null) { // Note: we let the [Required] attribute do its own null testing, // since the user may have subclassed it and have a deeper meaning to what 'required' means var validationResult = reqAttr.GetValidationResult(property.Value, property.Key); if (validationResult != ValidationResult.Success) { errors.Add(new ValidationError(reqAttr, property.Value, validationResult)); } } } if (breakOnFirstError && errors.Any()) { break; } } return errors; } /// <summary> /// Retrieves the property values for the given instance. /// </summary> /// <param name="instance">Instance from which to fetch the properties.</param> /// <param name="validationContext">Describes the entity being validated.</param> /// <returns> /// A set of key value pairs, where the key is a validation context for the property and the value is its current /// value. /// </returns> /// <remarks>Ignores indexed properties.</remarks> private static ICollection<KeyValuePair<ValidationContext, object>> GetPropertyValues(object instance, ValidationContext validationContext) { var properties = instance.GetType().GetRuntimeProperties() .Where(p => ValidationAttributeStore.IsPublic(p) && !p.GetIndexParameters().Any()); var items = new List<KeyValuePair<ValidationContext, object>>(properties.Count()); foreach (var property in properties) { var context = CreateValidationContext(instance, validationContext); context.MemberName = property.Name; if (_store.GetPropertyValidationAttributes(context).Any()) { items.Add(new KeyValuePair<ValidationContext, object>(context, property.GetValue(instance, null))); } } return items; } /// <summary> /// Internal iterator to enumerate all validation errors for an value. /// </summary> /// <remarks> /// If a <see cref="RequiredAttribute" /> is found, it will be evaluated first, and if that fails, /// validation will abort, regardless of the <paramref name="breakOnFirstError" /> parameter value. /// </remarks> /// <param name="value">The value to pass to the validation attributes.</param> /// <param name="validationContext">Describes the type/member being evaluated.</param> /// <param name="attributes">The validation attributes to evaluate.</param> /// <param name="breakOnFirstError"> /// Whether or not to break on the first validation failure. A /// <see cref="RequiredAttribute" /> failure will always abort with that sole failure. /// </param> /// <returns>The collection of validation errors.</returns> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> private static IEnumerable<ValidationError> GetValidationErrors(object value, ValidationContext validationContext, IEnumerable<ValidationAttribute> attributes, bool breakOnFirstError) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } var errors = new List<ValidationError>(); ValidationError validationError; // Get the required validator if there is one and test it first, aborting on failure var required = attributes.FirstOrDefault(a => a is RequiredAttribute) as RequiredAttribute; if (required != null) { if (!TryValidate(value, validationContext, required, out validationError)) { errors.Add(validationError); return errors; } } // Iterate through the rest of the validators, skipping the required validator foreach (var attr in attributes) { if (attr != required) { if (!TryValidate(value, validationContext, attr, out validationError)) { errors.Add(validationError); if (breakOnFirstError) { break; } } } } return errors; } /// <summary> /// Tests whether a value is valid against a single <see cref="ValidationAttribute" /> using the /// <see cref="ValidationContext" />. /// </summary> /// <param name="value">The value to be tested for validity.</param> /// <param name="validationContext">Describes the property member to validate.</param> /// <param name="attribute">The validation attribute to test.</param> /// <param name="validationError"> /// The validation error that occurs during validation. Will be <c>null</c> when the return /// value is <c>true</c>. /// </param> /// <returns><c>true</c> if the value is valid.</returns> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute, out ValidationError validationError) { Debug.Assert(validationContext != null); var validationResult = attribute.GetValidationResult(value, validationContext); if (validationResult != ValidationResult.Success) { validationError = new ValidationError(attribute, value, validationResult); return false; } validationError = null; return true; } /// <summary> /// Private helper class to encapsulate a ValidationAttribute with the failed value and the user-visible /// target name against which it was validated. /// </summary> private class ValidationError { internal ValidationError(ValidationAttribute validationAttribute, object value, ValidationResult validationResult) { ValidationAttribute = validationAttribute; ValidationResult = validationResult; Value = value; } internal object Value { get; } internal ValidationAttribute ValidationAttribute { get; } internal ValidationResult ValidationResult { get; } internal Exception ThrowValidationException() => throw new ValidationException(ValidationResult, ValidationAttribute, Value); } } }
// Copyright 2012 Applied Geographics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Xml; namespace AppGeo.Clients.ArcIms.ArcXml { public class ArcXmlWriter : XmlWriter { private XmlWriter _innerWriter; public char[] CoordinateSeparator = new char[] { ' ' }; public char[] TupleSeparator = new char[] { ';' }; public ArcXmlWriter(XmlWriter innerWriter) { _innerWriter = innerWriter; } public XmlWriter InnerWriter { get { return _innerWriter; } } public override XmlWriterSettings Settings { get { return _innerWriter.Settings; } } public override WriteState WriteState { get { return _innerWriter.WriteState; } } public override string XmlLang { get { return _innerWriter.XmlLang; } } public override XmlSpace XmlSpace { get { return _innerWriter.XmlSpace; } } public override void Close() { _innerWriter.Close(); } public override void Flush() { _innerWriter.Flush(); } public override string LookupPrefix(string ns) { return _innerWriter.LookupPrefix(ns); } public override string ToString() { return _innerWriter.ToString(); } public override void WriteAttributes(XmlReader reader, bool defattr) { _innerWriter.WriteAttributes(reader, defattr); } public override void WriteBase64(byte[] buffer, int index, int count) { _innerWriter.WriteBase64(buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { _innerWriter.WriteBinHex(buffer, index, count); } public override void WriteCData(string text) { _innerWriter.WriteCData(text); } public override void WriteCharEntity(char ch) { _innerWriter.WriteCharEntity(ch); } public override void WriteChars(char[] buffer, int index, int count) { _innerWriter.WriteChars(buffer, index, count); } public override void WriteComment(string text) { _innerWriter.WriteComment(text); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { _innerWriter.WriteDocType(name, pubid, sysid, subset); } public void WriteEndArcXmlRequest() { WriteEndElement(); WriteEndElement(); } public override void WriteEndAttribute() { _innerWriter.WriteEndAttribute(); } public override void WriteEndDocument() { _innerWriter.WriteEndDocument(); } public override void WriteEndElement() { _innerWriter.WriteEndElement(); } public override void WriteEntityRef(string name) { _innerWriter.WriteEntityRef(name); } public override void WriteFullEndElement() { _innerWriter.WriteFullEndElement(); } public override void WriteName(string name) { _innerWriter.WriteName(name); } public override void WriteNmToken(string name) { _innerWriter.WriteNmToken(name); } public override void WriteNode(XmlReader reader, bool defattr) { _innerWriter.WriteNode(reader, defattr); } public override void WriteNode(System.Xml.XPath.XPathNavigator navigator, bool defattr) { _innerWriter.WriteNode(navigator, defattr); } public override void WriteProcessingInstruction(string name, string text) { _innerWriter.WriteProcessingInstruction(name, text); } public override void WriteQualifiedName(string localName, string ns) { _innerWriter.WriteQualifiedName(localName, ns); } public override void WriteRaw(char[] buffer, int index, int count) { _innerWriter.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { _innerWriter.WriteRaw(data); } public void WriteStartArcXmlRequest() { WriteStartDocument(); WriteStartElement("ARCXML"); WriteAttributeString("version", "1.1"); WriteStartElement("REQUEST"); } public override void WriteStartAttribute(string prefix, string localName, string ns) { _innerWriter.WriteStartAttribute(prefix, localName, ns); } public override void WriteStartDocument() { _innerWriter.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { _innerWriter.WriteStartDocument(standalone); } public override void WriteStartElement(string prefix, string localName, string ns) { _innerWriter.WriteStartElement(prefix, localName, ns); } public override void WriteString(string text) { _innerWriter.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { _innerWriter.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteValue(bool value) { _innerWriter.WriteValue(value); } public override void WriteValue(decimal value) { _innerWriter.WriteValue(value); } public override void WriteValue(double value) { _innerWriter.WriteValue(value); } public override void WriteValue(float value) { _innerWriter.WriteValue(value); } public override void WriteValue(int value) { _innerWriter.WriteValue(value); } public override void WriteValue(long value) { _innerWriter.WriteValue(value); } public override void WriteValue(object value) { _innerWriter.WriteValue(value); } public override void WriteValue(string value) { _innerWriter.WriteValue(value); } public override void WriteValue(DateTime value) { _innerWriter.WriteValue(value); } public override void WriteWhitespace(string ws) { _innerWriter.WriteWhitespace(ws); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PropertySetterBuilder.cs" company="Mark Rendle and Ian Battersby."> // Copyright (C) Mark Rendle and Ian Battersby 2014 - All Rights Reserved. // </copyright> // <summary> // Defines the PropertySetterBuilder type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Simple.Http.CodeGeneration { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; internal sealed class PropertySetterBuilder { private static readonly MethodInfo DictionaryContainsKeyMethod = typeof(IDictionary<string, string>).GetMethod("ContainsKey", new[] { typeof(string) }); private static readonly PropertyInfo DictionaryIndexerProperty = typeof(IDictionary<string, string>).GetProperty("Item"); private readonly ParameterExpression param; private readonly Expression obj; private readonly PropertyInfo property; private MemberExpression nameProperty; private Expression itemProperty; private MethodCallExpression containsKey; public PropertySetterBuilder(ParameterExpression param, Expression obj, PropertyInfo property) { this.param = param; this.obj = obj; this.property = property; } public ConditionalExpression CreatePropertySetter() { this.CreatePropertyExpressions(); if (PropertyIsPrimitive()) { return Expression.IfThen(this.containsKey, this.CreateTrySimpleAssign()); } return null; } private bool PropertyIsPrimitive() { return PropertyIsPrimitive(this.property); } public static bool PropertyIsPrimitive(PropertyInfo property) { return TypeIsPrimitive(property.PropertyType); } private static bool TypeIsPrimitive(Type type) { return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(Guid) || type == typeof(byte[]) || type.IsEnum || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) || IsPrimitiveEnumerable(type); } private static bool IsPrimitiveEnumerable(Type type) { return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) && TypeIsPrimitive(type.GetGenericArguments()[0]); } private void CreatePropertyExpressions() { var constName = Expression.Constant(this.property.Name, typeof(string)); this.containsKey = Expression.Call(this.param, DictionaryContainsKeyMethod, constName); this.nameProperty = Expression.Property(this.obj, this.property); this.itemProperty = Expression.Property(this.param, DictionaryIndexerProperty, constName); } private CatchBlock CreateCatchBlock() { return Expression.Catch( typeof(Exception), Expression.Assign(this.nameProperty, Expression.Default(this.property.PropertyType))); } [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed. Suppression is OK here.")] private TryExpression CreateTrySimpleAssign() { var changeTypeMethod = typeof(PropertySetterBuilder).GetMethod( "SafeConvert", BindingFlags.Static | BindingFlags.NonPublic); MethodCallExpression callConvert; if (this.property.PropertyType.IsEnum) { callConvert = Expression.Call( changeTypeMethod, this.itemProperty, Expression.Constant(this.property.PropertyType.GetEnumUnderlyingType())); } else if (this.property.PropertyType.IsNullable()) { callConvert = Expression.Call( changeTypeMethod, this.itemProperty, Expression.Constant(this.property.PropertyType.GetGenericArguments().Single())); } else if (IsEnumerable(this.property.PropertyType)) { changeTypeMethod = typeof(PropertySetterBuilder).GetMethod( "SafeConvertEnumerable", BindingFlags.Static | BindingFlags.NonPublic); callConvert = Expression.Call( changeTypeMethod, this.itemProperty, Expression.Constant(this.property.PropertyType)); } else { callConvert = Expression.Call( changeTypeMethod, this.itemProperty, Expression.Constant(this.property.PropertyType)); } var assign = Expression.Assign(this.nameProperty, Expression.Convert(callConvert, this.property.PropertyType)); if (this.property.PropertyType.IsEnum) { return Expression.TryCatch( Expression.IfThenElse( Expression.TypeIs(this.itemProperty, typeof(string)), Expression.Assign( this.nameProperty, Expression.Convert( Expression.Call( typeof(Enum).GetMethod("Parse", new[] { typeof(Type), typeof(string), typeof(bool) }), Expression.Constant(this.property.PropertyType), Expression.Call(this.itemProperty, typeof(object).GetMethod("ToString")), Expression.Constant(true)), this.property.PropertyType)), assign), Expression.Catch(typeof(Exception), Expression.Empty())); } if (IsAGuid(this.property.PropertyType)) { return Expression.TryCatch( Expression.IfThenElse( Expression.TypeIs(this.itemProperty, typeof(string)), Expression.Assign( this.nameProperty, Expression.Convert( Expression.Call( typeof(Guid).GetMethod("Parse", new[] { typeof(string) }), Expression.Call(this.itemProperty, typeof(object).GetMethod("ToString"))), this.property.PropertyType)), assign), Expression.Catch(typeof(Exception), Expression.Empty())); } return Expression.TryCatch( assign, this.CreateCatchBlock()); } private static object SafeConvert(object source, Type targetType) { return ReferenceEquals(source, null) ? null : Convert.ChangeType(source, targetType); } private static object SafeConvertEnumerable(object source, Type targetType) { if (source == null) { return null; } var tmpSource = (string)source; var destinationType = targetType.GetGenericArguments()[0]; var collection = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(destinationType)); if (!tmpSource.Contains("\t")) { // Single value IEnumerable element collection.Add(Cast(source, destinationType)); } else { // Multi value IEnumerable element var parts = tmpSource.Split('\t'); foreach (var part in parts) { collection.Add(Cast(part, destinationType)); } } return (IEnumerable)collection; } private static object Cast(object value, Type destinationType) { if (IsAGuid(destinationType)) { var tmp = (string)value; return Guid.Parse(tmp); } if (destinationType.IsEnum) { var tmp = (string)value; return Enum.Parse(destinationType, tmp, true); } return Convert.ChangeType(value, destinationType); } private static bool IsAGuid(Type type) { return type == typeof(Guid) || type == typeof(Guid?); } private static bool IsEnumerable(Type type) { return typeof(IEnumerable).IsAssignableFrom(type) && (typeof(string) != type); } public static BlockExpression MakePropertySetterBlock( Type type, ParameterExpression variables, ParameterExpression instance, BinaryExpression construct) { var lines = new List<Expression> { construct }; var setters = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite) .Where(PropertyIsPrimitive) .Select(p => new PropertySetterBuilder(variables, instance, p)) .Select(ps => ps.CreatePropertySetter()); lines.AddRange(setters); lines.Add(instance); var block = Expression.Block(type, new[] { instance }, lines); return block; } public static BlockExpression MakePropertySetterBlock( Type type, MethodCallExpression getVariables, ParameterExpression instance, BinaryExpression construct) { var variables = Expression.Variable(typeof(IDictionary<string, string[]>), "variables"); var lines = new List<Expression> { construct, Expression.Assign(variables, getVariables) }; var setters = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite) .Where(PropertyIsPrimitive) .Select(p => new PropertySetterBuilder(variables, instance, p)) .Select(ps => ps.CreatePropertySetter()); lines.AddRange(setters); lines.Add(instance); var block = Expression.Block(type, new[] { variables, instance }.AsEnumerable(), lines.AsEnumerable()); return block; } } }
using CocosSharp; namespace tests.FontTest { public class SystemFontTestScene : TestScene { private static int fontIdx; private static readonly string[] fontList = { #if IOS || IPHONE || MACOS "Chalkboard SE", "Chalkduster", "Noteworthy", "Marker Felt", "Papyrus", "American Typewriter", "Arial", "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", "fonts/Courier New.ttf", "fonts/Marker Felt.ttf", "fonts/Paint Boy.ttf", "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", "fonts/tahoma.ttf", "fonts/Thonburi.ttf", "fonts/ThonburiBold.ttf" #endif #if WINDOWS || WINDOWSGL || NETFX_CORE "A Damn Mess", // A Damn Mess.ttf "Abberancy", // Abberancy.ttf "Abduction", //Abduction.ttf "AmerType Md BT", // American Typewriter.ttf "Scissor Cuts", //Scissor Cuts.ttf "Felt", //Marker Felt.ttf "arial", "Courier New", "Marker Felt", "Comic Sans MS", "Felt", "MoolBoran", "Courier New", "Georgia", "Symbol", "Wingdings", "Arial", //"fonts/A Damn Mess.ttf", //"fonts/Abberancy.ttf", //"fonts/Abduction.ttf", //"fonts/American Typewriter.ttf", //"fonts/arial.ttf", //"fonts/Courier New.ttf", //"fonts/Marker Felt.ttf", //"fonts/Paint Boy.ttf", //"fonts/Schwarzwald Regular.ttf", //"fonts/Scissor Cuts.ttf", //"fonts/tahoma.ttf", //"fonts/Thonburi.ttf", //"fonts/ThonburiBold.ttf" #endif #if ANDROID "Arial", "Courier New", "Georgia", "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", "fonts/arial.ttf", "fonts/Courier New.ttf", "fonts/Marker Felt.ttf", "fonts/Paint Boy.ttf", "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", "fonts/tahoma.ttf", "fonts/Thonburi.ttf", "fonts/ThonburiBold.ttf" #endif }; public static int verticalAlignIdx = 0; public static CCVerticalTextAlignment[] verticalAlignment = { CCVerticalTextAlignment.Top, CCVerticalTextAlignment.Center, CCVerticalTextAlignment.Bottom }; public override void runThisTest() { CCLayer pLayer = new SystemFontTest(); AddChild(pLayer); Scene.Director.ReplaceScene(this); } protected override void NextTestCase() { nextAction(); } protected override void PreviousTestCase() { backAction(); } protected override void RestTestCase() { restartAction(); } public static string nextAction() { fontIdx++; if (fontIdx >= fontList.Length) { fontIdx = 0; verticalAlignIdx = (verticalAlignIdx + 1) % verticalAlignment.Length; } return fontList[fontIdx]; } public static string backAction() { fontIdx--; if (fontIdx < 0) { fontIdx = fontList.Length - 1; verticalAlignIdx--; if (verticalAlignIdx < 0) verticalAlignIdx = verticalAlignment.Length - 1; } return fontList[fontIdx]; } public static string restartAction() { return fontList[fontIdx]; } } public class SystemFontTest : TestNavigationLayer { private const int kTagLabel1 = 1; private const int kTagLabel2 = 2; private const int kTagLabel3 = 3; private const int kTagLabel4 = 4; private CCSize blockSize; private CCSize visibleRect; private float fontSize = 36; public SystemFontTest() { } public override void OnEnter() { base.OnEnter(); var leftColor = new Background(blockSize, new CCColor4B(100, 100, 100, 255)); var centerColor = new Background(blockSize, new CCColor4B(200, 100, 100, 255)); var rightColor = new Background(blockSize, new CCColor4B(100, 100, 200, 255)); leftColor.IgnoreAnchorPointForPosition = false; centerColor.IgnoreAnchorPointForPosition = false; rightColor.IgnoreAnchorPointForPosition = false; leftColor.AnchorPoint = new CCPoint(0, 0.5f); centerColor.AnchorPoint = new CCPoint(0, 0.5f); rightColor.AnchorPoint = new CCPoint(0, 0.5f); leftColor.Position = new CCPoint(0, visibleRect.Height / 2); centerColor.Position = new CCPoint(blockSize.Width, visibleRect.Height / 2); rightColor.Position = new CCPoint(blockSize.Width * 2, visibleRect.Height / 2); AddChild(leftColor, -1); AddChild(rightColor, -1); AddChild(centerColor, -1); showFont(SystemFontTestScene.restartAction()); } protected override void AddedToScene() { base.AddedToScene(); visibleRect = VisibleBoundsWorldspace.Size; blockSize = new CCSize(visibleRect.Width / 3, visibleRect.Height / 2); } public void showFont(string pFont) { RemoveChildByTag(kTagLabel1, true); RemoveChildByTag(kTagLabel2, true); RemoveChildByTag(kTagLabel3, true); RemoveChildByTag(kTagLabel4, true); var top = new CCLabel(pFont,"Helvetica", 32); var center = new CCLabel("alignment center", pFont, fontSize, blockSize, CCTextAlignment.Center, SystemFontTestScene.verticalAlignment[SystemFontTestScene.verticalAlignIdx]); var left = new CCLabel("alignment left", pFont, fontSize, blockSize, CCTextAlignment.Left, SystemFontTestScene.verticalAlignment[SystemFontTestScene.verticalAlignIdx]); var right = new CCLabel("alignment right", pFont, fontSize, blockSize, CCTextAlignment.Right, SystemFontTestScene.verticalAlignment[SystemFontTestScene.verticalAlignIdx]); top.AnchorPoint = CCPoint.AnchorMiddleTop; left.AnchorPoint = CCPoint.AnchorMiddleLeft; center.AnchorPoint = CCPoint.AnchorMiddleLeft; right.AnchorPoint = CCPoint.AnchorMiddleLeft; top.Position = TitleLabel.Position - new CCPoint(0, 20); left.Position = new CCPoint(0, visibleRect.Height / 2); center.Position = new CCPoint(blockSize.Width, visibleRect.Height / 2); right.Position = new CCPoint(blockSize.Width * 2, visibleRect.Height / 2); AddChild(left, 0, kTagLabel1); AddChild(right, 0, kTagLabel2); AddChild(center, 0, kTagLabel3); AddChild(top, 0, kTagLabel4); } public override void RestartCallback(object sender) { base.RestartCallback(sender); showFont(SystemFontTestScene.restartAction()); } public override void NextCallback(object sender) { base.NextCallback(sender); showFont(SystemFontTestScene.nextAction()); } public override void BackCallback(object sender) { base.BackCallback(sender); showFont(SystemFontTestScene.backAction()); } public override string Title { get { return "System Font test"; } } } }
/* * 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 Apache.Ignite.Core.Impl.Unmanaged { using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Unmanaged utility classes. /// </summary> internal static unsafe class UnmanagedUtils { /** Interop factory ID for .Net. */ private const int InteropFactoryId = 1; #region PROCEDURE NAMES private const string ProcReallocate = "IgniteReallocate"; private const string ProcIgnitionStart = "IgniteIgnitionStart"; private const string ProcIgnitionStop = "IgniteIgnitionStop"; private const string ProcIgnitionStopAll = "IgniteIgnitionStopAll"; private const string ProcProcessorReleaseStart = "IgniteProcessorReleaseStart"; private const string ProcProcessorProjection = "IgniteProcessorProjection"; private const string ProcProcessorCache = "IgniteProcessorCache"; private const string ProcProcessorGetOrCreateCache = "IgniteProcessorGetOrCreateCache"; private const string ProcProcessorCreateCache = "IgniteProcessorCreateCache"; private const string ProcProcessorAffinity = "IgniteProcessorAffinity"; private const string ProcProcessorDataStreamer = "IgniteProcessorDataStreamer"; private const string ProcProcessorTransactions = "IgniteProcessorTransactions"; private const string ProcProcessorCompute = "IgniteProcessorCompute"; private const string ProcProcessorMessage = "IgniteProcessorMessage"; private const string ProcProcessorEvents = "IgniteProcessorEvents"; private const string ProcProcessorServices = "IgniteProcessorServices"; private const string ProcProcessorExtensions = "IgniteProcessorExtensions"; private const string ProcTargetInStreamOutLong = "IgniteTargetInStreamOutLong"; private const string ProcTargetInStreamOutStream = "IgniteTargetInStreamOutStream"; private const string ProcTargetInStreamOutObject = "IgniteTargetInStreamOutObject"; private const string ProcTargetInObjectStreamOutStream = "IgniteTargetInObjectStreamOutStream"; private const string ProcTargetOutLong = "IgniteTargetOutLong"; private const string ProcTargetOutStream = "IgniteTargetOutStream"; private const string ProcTargetOutObject = "IgniteTargetOutObject"; private const string ProcTargetListenFut = "IgniteTargetListenFuture"; private const string ProcTargetListenFutForOp = "IgniteTargetListenFutureForOperation"; private const string ProcAffinityParts = "IgniteAffinityPartitions"; private const string ProcCacheWithSkipStore = "IgniteCacheWithSkipStore"; private const string ProcCacheWithNoRetries = "IgniteCacheWithNoRetries"; private const string ProcCacheWithExpiryPolicy = "IgniteCacheWithExpiryPolicy"; private const string ProcCacheWithAsync = "IgniteCacheWithAsync"; private const string ProcCacheWithKeepPortable = "IgniteCacheWithKeepPortable"; private const string ProcCacheClear = "IgniteCacheClear"; private const string ProcCacheRemoveAll = "IgniteCacheRemoveAll"; private const string ProcCacheOutOpQueryCursor = "IgniteCacheOutOpQueryCursor"; private const string ProcCacheOutOpContinuousQuery = "IgniteCacheOutOpContinuousQuery"; private const string ProcCacheIterator = "IgniteCacheIterator"; private const string ProcCacheLocalIterator = "IgniteCacheLocalIterator"; private const string ProcCacheEnterLock = "IgniteCacheEnterLock"; private const string ProcCacheExitLock = "IgniteCacheExitLock"; private const string ProcCacheTryEnterLock = "IgniteCacheTryEnterLock"; private const string ProcCacheCloseLock = "IgniteCacheCloseLock"; private const string ProcCacheRebalance = "IgniteCacheRebalance"; private const string ProcCacheSize = "IgniteCacheSize"; private const string ProcCacheStoreCallbackInvoke = "IgniteCacheStoreCallbackInvoke"; private const string ProcComputeWithNoFailover = "IgniteComputeWithNoFailover"; private const string ProcComputeWithTimeout = "IgniteComputeWithTimeout"; private const string ProcComputeExecuteNative = "IgniteComputeExecuteNative"; private const string ProcContinuousQryClose = "IgniteContinuousQueryClose"; private const string ProcContinuousQryGetInitialQueryCursor = "IgniteContinuousQueryGetInitialQueryCursor"; private const string ProcDataStreamerListenTop = "IgniteDataStreamerListenTopology"; private const string ProcDataStreamerAllowOverwriteGet = "IgniteDataStreamerAllowOverwriteGet"; private const string ProcDataStreamerAllowOverwriteSet = "IgniteDataStreamerAllowOverwriteSet"; private const string ProcDataStreamerSkipStoreGet = "IgniteDataStreamerSkipStoreGet"; private const string ProcDataStreamerSkipStoreSet = "IgniteDataStreamerSkipStoreSet"; private const string ProcDataStreamerPerNodeBufferSizeGet = "IgniteDataStreamerPerNodeBufferSizeGet"; private const string ProcDataStreamerPerNodeBufferSizeSet = "IgniteDataStreamerPerNodeBufferSizeSet"; private const string ProcDataStreamerPerNodeParallelOpsGet = "IgniteDataStreamerPerNodeParallelOperationsGet"; private const string ProcDataStreamerPerNodeParallelOpsSet = "IgniteDataStreamerPerNodeParallelOperationsSet"; private const string ProcMessagingWithAsync = "IgniteMessagingWithAsync"; private const string ProcQryCursorIterator = "IgniteQueryCursorIterator"; private const string ProcQryCursorClose = "IgniteQueryCursorClose"; private const string ProcProjectionForOthers = "IgniteProjectionForOthers"; private const string ProcProjectionForRemotes = "IgniteProjectionForRemotes"; private const string ProcProjectionForDaemons = "IgniteProjectionForDaemons"; private const string ProcProjectionForRandom = "IgniteProjectionForRandom"; private const string ProcProjectionForOldest = "IgniteProjectionForOldest"; private const string ProcProjectionForYoungest = "IgniteProjectionForYoungest"; private const string ProcProjectionResetMetrics = "IgniteProjectionResetMetrics"; private const string ProcProjectionOutOpRet = "IgniteProjectionOutOpRet"; private const string ProcAcquire = "IgniteAcquire"; private const string ProcRelease = "IgniteRelease"; private const string ProcTxStart = "IgniteTransactionsStart"; private const string ProcTxCommit = "IgniteTransactionsCommit"; private const string ProcTxCommitAsync = "IgniteTransactionsCommitAsync"; private const string ProcTxRollback = "IgniteTransactionsRollback"; private const string ProcTxRollbackAsync = "IgniteTransactionsRollbackAsync"; private const string ProcTxClose = "IgniteTransactionsClose"; private const string ProcTxState = "IgniteTransactionsState"; private const string ProcTxSetRollbackOnly = "IgniteTransactionsSetRollbackOnly"; private const string ProcTxResetMetrics = "IgniteTransactionsResetMetrics"; private const string ProcThrowToJava = "IgniteThrowToJava"; private const string ProcDestroyJvm = "IgniteDestroyJvm"; private const string ProcHandlersSize = "IgniteHandlersSize"; private const string ProcCreateContext = "IgniteCreateContext"; private const string ProcEventsWithAsync = "IgniteEventsWithAsync"; private const string ProcEventsStopLocalListen = "IgniteEventsStopLocalListen"; private const string ProcEventsLocalListen = "IgniteEventsLocalListen"; private const string ProcEventsIsEnabled = "IgniteEventsIsEnabled"; private const string ProcDeleteContext = "IgniteDeleteContext"; private const string ProcServicesWithAsync = "IgniteServicesWithAsync"; private const string ProcServicesWithServerKeepPortable = "IgniteServicesWithServerKeepPortable"; private const string ProcServicesCancel = "IgniteServicesCancel"; private const string ProcServicesCancelAll = "IgniteServicesCancelAll"; private const string ProcServicesGetServiceProxy = "IgniteServicesGetServiceProxy"; #endregion #region DELEGATE DEFINITIONS private delegate int ReallocateDelegate(long memPtr, int cap); private delegate void* IgnitionStartDelegate(void* ctx, sbyte* cfgPath, sbyte* gridName, int factoryId, long dataPtr); private delegate bool IgnitionStopDelegate(void* ctx, sbyte* gridName, bool cancel); private delegate void IgnitionStopAllDelegate(void* ctx, bool cancel); private delegate void ProcessorReleaseStartDelegate(void* ctx, void* obj); private delegate void* ProcessorProjectionDelegate(void* ctx, void* obj); private delegate void* ProcessorCacheDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorCreateCacheDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorGetOrCreateCacheDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorAffinityDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorDataStreamerDelegate(void* ctx, void* obj, sbyte* name, bool keepPortable); private delegate void* ProcessorTransactionsDelegate(void* ctx, void* obj); private delegate void* ProcessorComputeDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorMessageDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorEventsDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorServicesDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorExtensionsDelegate(void* ctx, void* obj); private delegate long TargetInStreamOutLongDelegate(void* ctx, void* target, int opType, long memPtr); private delegate void TargetInStreamOutStreamDelegate(void* ctx, void* target, int opType, long inMemPtr, long outMemPtr); private delegate void* TargetInStreamOutObjectDelegate(void* ctx, void* target, int opType, long memPtr); private delegate void TargetInObjectStreamOutStreamDelegate(void* ctx, void* target, int opType, void* arg, long inMemPtr, long outMemPtr); private delegate long TargetOutLongDelegate(void* ctx, void* target, int opType); private delegate void TargetOutStreamDelegate(void* ctx, void* target, int opType, long memPtr); private delegate void* TargetOutObjectDelegate(void* ctx, void* target, int opType); private delegate void TargetListenFutureDelegate(void* ctx, void* target, long futId, int typ); private delegate void TargetListenFutureForOpDelegate(void* ctx, void* target, long futId, int typ, int opId); private delegate int AffinityPartitionsDelegate(void* ctx, void* target); private delegate void* CacheWithSkipStoreDelegate(void* ctx, void* obj); private delegate void* CacheNoRetriesDelegate(void* ctx, void* obj); private delegate void* CacheWithExpiryPolicyDelegate(void* ctx, void* obj, long create, long update, long access); private delegate void* CacheWithAsyncDelegate(void* ctx, void* obj); private delegate void* CacheWithKeepPortableDelegate(void* ctx, void* obj); private delegate void CacheClearDelegate(void* ctx, void* obj); private delegate void CacheRemoveAllDelegate(void* ctx, void* obj); private delegate void* CacheOutOpQueryCursorDelegate(void* ctx, void* obj, int type, long memPtr); private delegate void* CacheOutOpContinuousQueryDelegate(void* ctx, void* obj, int type, long memPtr); private delegate void* CacheIteratorDelegate(void* ctx, void* obj); private delegate void* CacheLocalIteratorDelegate(void* ctx, void* obj, int peekModes); private delegate void CacheEnterLockDelegate(void* ctx, void* obj, long id); private delegate void CacheExitLockDelegate(void* ctx, void* obj, long id); private delegate bool CacheTryEnterLockDelegate(void* ctx, void* obj, long id, long timeout); private delegate void CacheCloseLockDelegate(void* ctx, void* obj, long id); private delegate void CacheRebalanceDelegate(void* ctx, void* obj, long futId); private delegate int CacheSizeDelegate(void* ctx, void* obj, int peekModes, bool loc); private delegate void CacheStoreCallbackInvokeDelegate(void* ctx, void* obj, long memPtr); private delegate void ComputeWithNoFailoverDelegate(void* ctx, void* target); private delegate void ComputeWithTimeoutDelegate(void* ctx, void* target, long timeout); private delegate void ComputeExecuteNativeDelegate(void* ctx, void* target, long taskPtr, long topVer); private delegate void ContinuousQueryCloseDelegate(void* ctx, void* target); private delegate void* ContinuousQueryGetInitialQueryCursorDelegate(void* ctx, void* target); private delegate void DataStreamerListenTopologyDelegate(void* ctx, void* obj, long ptr); private delegate bool DataStreamerAllowOverwriteGetDelegate(void* ctx, void* obj); private delegate void DataStreamerAllowOverwriteSetDelegate(void* ctx, void* obj, bool val); private delegate bool DataStreamerSkipStoreGetDelegate(void* ctx, void* obj); private delegate void DataStreamerSkipStoreSetDelegate(void* ctx, void* obj, bool val); private delegate int DataStreamerPerNodeBufferSizeGetDelegate(void* ctx, void* obj); private delegate void DataStreamerPerNodeBufferSizeSetDelegate(void* ctx, void* obj, int val); private delegate int DataStreamerPerNodeParallelOperationsGetDelegate(void* ctx, void* obj); private delegate void DataStreamerPerNodeParallelOperationsSetDelegate(void* ctx, void* obj, int val); private delegate void* MessagingWithAsyncDelegate(void* ctx, void* target); private delegate void* ProjectionForOthersDelegate(void* ctx, void* obj, void* prj); private delegate void* ProjectionForRemotesDelegate(void* ctx, void* obj); private delegate void* ProjectionForDaemonsDelegate(void* ctx, void* obj); private delegate void* ProjectionForRandomDelegate(void* ctx, void* obj); private delegate void* ProjectionForOldestDelegate(void* ctx, void* obj); private delegate void* ProjectionForYoungestDelegate(void* ctx, void* obj); private delegate void ProjectionResetMetricsDelegate(void* ctx, void* obj); private delegate void* ProjectionOutOpRetDelegate(void* ctx, void* obj, int type, long memPtr); private delegate void QueryCursorIteratorDelegate(void* ctx, void* target); private delegate void QueryCursorCloseDelegate(void* ctx, void* target); private delegate void* AcquireDelegate(void* ctx, void* target); private delegate void ReleaseDelegate(void* target); private delegate long TransactionsStartDelegate(void* ctx, void* target, int concurrency, int isolation, long timeout, int txSize); private delegate int TransactionsCommitDelegate(void* ctx, void* target, long id); private delegate void TransactionsCommitAsyncDelegate(void* ctx, void* target, long id, long futId); private delegate int TransactionsRollbackDelegate(void* ctx, void* target, long id); private delegate void TransactionsRollbackAsyncDelegate(void* ctx, void* target, long id, long futId); private delegate int TransactionsCloseDelegate(void* ctx, void* target, long id); private delegate int TransactionsStateDelegate(void* ctx, void* target, long id); private delegate bool TransactionsSetRollbackOnlyDelegate(void* ctx, void* target, long id); private delegate void TransactionsResetMetricsDelegate(void* ctx, void* target); private delegate void ThrowToJavaDelegate(void* ctx, char* msg); private delegate void DestroyJvmDelegate(void* ctx); private delegate int HandlersSizeDelegate(); private delegate void* CreateContextDelegate(void* opts, int optsLen, void* cbs); private delegate void* EventsWithAsyncDelegate(void* ctx, void* obj); private delegate bool EventsStopLocalListenDelegate(void* ctx, void* obj, long hnd); private delegate void EventsLocalListenDelegate(void* ctx, void* obj, long hnd, int type); private delegate bool EventsIsEnabledDelegate(void* ctx, void* obj, int type); private delegate void DeleteContextDelegate(void* ptr); private delegate void* ServicesWithAsyncDelegate(void* ctx, void* target); private delegate void* ServicesWithServerKeepPortableDelegate(void* ctx, void* target); private delegate long ServicesCancelDelegate(void* ctx, void* target, char* name); private delegate long ServicesCancelAllDelegate(void* ctx, void* target); private delegate void* ServicesGetServiceProxyDelegate(void* ctx, void* target, char* name, bool sticky); #endregion #region DELEGATE MEMBERS // ReSharper disable InconsistentNaming private static readonly ReallocateDelegate REALLOCATE; private static readonly IgnitionStartDelegate IGNITION_START; private static readonly IgnitionStopDelegate IGNITION_STOP; private static readonly IgnitionStopAllDelegate IGNITION_STOP_ALL; private static readonly ProcessorReleaseStartDelegate PROCESSOR_RELEASE_START; private static readonly ProcessorProjectionDelegate PROCESSOR_PROJECTION; private static readonly ProcessorCacheDelegate PROCESSOR_CACHE; private static readonly ProcessorCreateCacheDelegate PROCESSOR_CREATE_CACHE; private static readonly ProcessorGetOrCreateCacheDelegate PROCESSOR_GET_OR_CREATE_CACHE; private static readonly ProcessorAffinityDelegate PROCESSOR_AFFINITY; private static readonly ProcessorDataStreamerDelegate PROCESSOR_DATA_STREAMER; private static readonly ProcessorTransactionsDelegate PROCESSOR_TRANSACTIONS; private static readonly ProcessorComputeDelegate PROCESSOR_COMPUTE; private static readonly ProcessorMessageDelegate PROCESSOR_MESSAGE; private static readonly ProcessorEventsDelegate PROCESSOR_EVENTS; private static readonly ProcessorServicesDelegate PROCESSOR_SERVICES; private static readonly ProcessorExtensionsDelegate PROCESSOR_EXTENSIONS; private static readonly TargetInStreamOutLongDelegate TARGET_IN_STREAM_OUT_LONG; private static readonly TargetInStreamOutStreamDelegate TARGET_IN_STREAM_OUT_STREAM; private static readonly TargetInStreamOutObjectDelegate TARGET_IN_STREAM_OUT_OBJECT; private static readonly TargetInObjectStreamOutStreamDelegate TARGET_IN_OBJECT_STREAM_OUT_STREAM; private static readonly TargetOutLongDelegate TARGET_OUT_LONG; private static readonly TargetOutStreamDelegate TARGET_OUT_STREAM; private static readonly TargetOutObjectDelegate TARGET_OUT_OBJECT; private static readonly TargetListenFutureDelegate TargetListenFut; private static readonly TargetListenFutureForOpDelegate TargetListenFutForOp; private static readonly AffinityPartitionsDelegate AffinityParts; private static readonly CacheWithSkipStoreDelegate CACHE_WITH_SKIP_STORE; private static readonly CacheNoRetriesDelegate CACHE_WITH_NO_RETRIES; private static readonly CacheWithExpiryPolicyDelegate CACHE_WITH_EXPIRY_POLICY; private static readonly CacheWithAsyncDelegate CACHE_WITH_ASYNC; private static readonly CacheWithKeepPortableDelegate CACHE_WITH_KEEP_PORTABLE; private static readonly CacheClearDelegate CACHE_CLEAR; private static readonly CacheRemoveAllDelegate CACHE_REMOVE_ALL; private static readonly CacheOutOpQueryCursorDelegate CACHE_OUT_OP_QUERY_CURSOR; private static readonly CacheOutOpContinuousQueryDelegate CACHE_OUT_OP_CONTINUOUS_QUERY; private static readonly CacheIteratorDelegate CACHE_ITERATOR; private static readonly CacheLocalIteratorDelegate CACHE_LOCAL_ITERATOR; private static readonly CacheEnterLockDelegate CACHE_ENTER_LOCK; private static readonly CacheExitLockDelegate CACHE_EXIT_LOCK; private static readonly CacheTryEnterLockDelegate CACHE_TRY_ENTER_LOCK; private static readonly CacheCloseLockDelegate CACHE_CLOSE_LOCK; private static readonly CacheRebalanceDelegate CACHE_REBALANCE; private static readonly CacheSizeDelegate CACHE_SIZE; private static readonly CacheStoreCallbackInvokeDelegate CACHE_STORE_CALLBACK_INVOKE; private static readonly ComputeWithNoFailoverDelegate COMPUTE_WITH_NO_FAILOVER; private static readonly ComputeWithTimeoutDelegate COMPUTE_WITH_TIMEOUT; private static readonly ComputeExecuteNativeDelegate COMPUTE_EXECUTE_NATIVE; private static readonly ContinuousQueryCloseDelegate ContinuousQryClose; private static readonly ContinuousQueryGetInitialQueryCursorDelegate ContinuousQryGetInitialQueryCursor; private static readonly DataStreamerListenTopologyDelegate DataStreamerListenTop; private static readonly DataStreamerAllowOverwriteGetDelegate DATA_STREAMER_ALLOW_OVERWRITE_GET; private static readonly DataStreamerAllowOverwriteSetDelegate DATA_STREAMER_ALLOW_OVERWRITE_SET; private static readonly DataStreamerSkipStoreGetDelegate DATA_STREAMER_SKIP_STORE_GET; private static readonly DataStreamerSkipStoreSetDelegate DATA_STREAMER_SKIP_STORE_SET; private static readonly DataStreamerPerNodeBufferSizeGetDelegate DATA_STREAMER_PER_NODE_BUFFER_SIZE_GET; private static readonly DataStreamerPerNodeBufferSizeSetDelegate DATA_STREAMER_PER_NODE_BUFFER_SIZE_SET; private static readonly DataStreamerPerNodeParallelOperationsGetDelegate DataStreamerPerNodeParallelOpsGet; private static readonly DataStreamerPerNodeParallelOperationsSetDelegate DataStreamerPerNodeParallelOpsSet; private static readonly MessagingWithAsyncDelegate MessagingWithAsync; private static readonly ProjectionForOthersDelegate PROJECTION_FOR_OTHERS; private static readonly ProjectionForRemotesDelegate PROJECTION_FOR_REMOTES; private static readonly ProjectionForDaemonsDelegate PROJECTION_FOR_DAEMONS; private static readonly ProjectionForRandomDelegate PROJECTION_FOR_RANDOM; private static readonly ProjectionForOldestDelegate PROJECTION_FOR_OLDEST; private static readonly ProjectionForYoungestDelegate PROJECTION_FOR_YOUNGEST; private static readonly ProjectionResetMetricsDelegate PROJECTION_RESET_METRICS; private static readonly ProjectionOutOpRetDelegate PROJECTION_OUT_OP_RET; private static readonly QueryCursorIteratorDelegate QryCursorIterator; private static readonly QueryCursorCloseDelegate QryCursorClose; private static readonly AcquireDelegate ACQUIRE; private static readonly ReleaseDelegate RELEASE; private static readonly TransactionsStartDelegate TxStart; private static readonly TransactionsCommitDelegate TxCommit; private static readonly TransactionsCommitAsyncDelegate TxCommitAsync; private static readonly TransactionsRollbackDelegate TxRollback; private static readonly TransactionsRollbackAsyncDelegate TxRollbackAsync; private static readonly TransactionsCloseDelegate TxClose; private static readonly TransactionsStateDelegate TxState; private static readonly TransactionsSetRollbackOnlyDelegate TxSetRollbackOnly; private static readonly TransactionsResetMetricsDelegate TxResetMetrics; private static readonly ThrowToJavaDelegate THROW_TO_JAVA; private static readonly DestroyJvmDelegate DESTROY_JVM; private static readonly HandlersSizeDelegate HANDLERS_SIZE; private static readonly CreateContextDelegate CREATE_CONTEXT; private static readonly EventsWithAsyncDelegate EVENTS_WITH_ASYNC; private static readonly EventsStopLocalListenDelegate EVENTS_STOP_LOCAL_LISTEN; private static readonly EventsLocalListenDelegate EVENTS_LOCAL_LISTEN; private static readonly EventsIsEnabledDelegate EVENTS_IS_ENABLED; private static readonly DeleteContextDelegate DELETE_CONTEXT; private static readonly ServicesWithAsyncDelegate SERVICES_WITH_ASYNC; private static readonly ServicesWithServerKeepPortableDelegate SERVICES_WITH_SERVER_KEEP_PORTABLE; private static readonly ServicesCancelDelegate SERVICES_CANCEL; private static readonly ServicesCancelAllDelegate SERVICES_CANCEL_ALL; private static readonly ServicesGetServiceProxyDelegate SERVICES_GET_SERVICE_PROXY; // ReSharper restore InconsistentNaming #endregion /** Library pointer. */ private static readonly IntPtr Ptr; /// <summary> /// Initializer. /// </summary> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] static UnmanagedUtils() { var path = IgniteUtils.UnpackEmbeddedResource(IgniteUtils.FileIgniteJniDll); Ptr = NativeMethods.LoadLibrary(path); if (Ptr == IntPtr.Zero) throw new IgniteException("Failed to load " + IgniteUtils.FileIgniteJniDll + ": " + Marshal.GetLastWin32Error()); REALLOCATE = CreateDelegate<ReallocateDelegate>(ProcReallocate); IGNITION_START = CreateDelegate<IgnitionStartDelegate>(ProcIgnitionStart); IGNITION_STOP = CreateDelegate<IgnitionStopDelegate>(ProcIgnitionStop); IGNITION_STOP_ALL = CreateDelegate<IgnitionStopAllDelegate>(ProcIgnitionStopAll); PROCESSOR_RELEASE_START = CreateDelegate<ProcessorReleaseStartDelegate>(ProcProcessorReleaseStart); PROCESSOR_PROJECTION = CreateDelegate<ProcessorProjectionDelegate>(ProcProcessorProjection); PROCESSOR_CACHE = CreateDelegate<ProcessorCacheDelegate>(ProcProcessorCache); PROCESSOR_CREATE_CACHE = CreateDelegate<ProcessorCreateCacheDelegate>(ProcProcessorCreateCache); PROCESSOR_GET_OR_CREATE_CACHE = CreateDelegate<ProcessorGetOrCreateCacheDelegate>(ProcProcessorGetOrCreateCache); PROCESSOR_AFFINITY = CreateDelegate<ProcessorAffinityDelegate>(ProcProcessorAffinity); PROCESSOR_DATA_STREAMER = CreateDelegate<ProcessorDataStreamerDelegate>(ProcProcessorDataStreamer); PROCESSOR_TRANSACTIONS = CreateDelegate<ProcessorTransactionsDelegate>(ProcProcessorTransactions); PROCESSOR_COMPUTE = CreateDelegate<ProcessorComputeDelegate>(ProcProcessorCompute); PROCESSOR_MESSAGE = CreateDelegate<ProcessorMessageDelegate>(ProcProcessorMessage); PROCESSOR_EVENTS = CreateDelegate<ProcessorEventsDelegate>(ProcProcessorEvents); PROCESSOR_SERVICES = CreateDelegate<ProcessorServicesDelegate>(ProcProcessorServices); PROCESSOR_EXTENSIONS = CreateDelegate<ProcessorExtensionsDelegate>(ProcProcessorExtensions); TARGET_IN_STREAM_OUT_LONG = CreateDelegate<TargetInStreamOutLongDelegate>(ProcTargetInStreamOutLong); TARGET_IN_STREAM_OUT_STREAM = CreateDelegate<TargetInStreamOutStreamDelegate>(ProcTargetInStreamOutStream); TARGET_IN_STREAM_OUT_OBJECT = CreateDelegate<TargetInStreamOutObjectDelegate>(ProcTargetInStreamOutObject); TARGET_IN_OBJECT_STREAM_OUT_STREAM = CreateDelegate<TargetInObjectStreamOutStreamDelegate>(ProcTargetInObjectStreamOutStream); TARGET_OUT_LONG = CreateDelegate<TargetOutLongDelegate>(ProcTargetOutLong); TARGET_OUT_STREAM = CreateDelegate<TargetOutStreamDelegate>(ProcTargetOutStream); TARGET_OUT_OBJECT = CreateDelegate<TargetOutObjectDelegate>(ProcTargetOutObject); TargetListenFut = CreateDelegate<TargetListenFutureDelegate>(ProcTargetListenFut); TargetListenFutForOp = CreateDelegate<TargetListenFutureForOpDelegate>(ProcTargetListenFutForOp); AffinityParts = CreateDelegate<AffinityPartitionsDelegate>(ProcAffinityParts); CACHE_WITH_SKIP_STORE = CreateDelegate<CacheWithSkipStoreDelegate>(ProcCacheWithSkipStore); CACHE_WITH_NO_RETRIES = CreateDelegate<CacheNoRetriesDelegate>(ProcCacheWithNoRetries); CACHE_WITH_EXPIRY_POLICY = CreateDelegate<CacheWithExpiryPolicyDelegate>(ProcCacheWithExpiryPolicy); CACHE_WITH_ASYNC = CreateDelegate<CacheWithAsyncDelegate>(ProcCacheWithAsync); CACHE_WITH_KEEP_PORTABLE = CreateDelegate<CacheWithKeepPortableDelegate>(ProcCacheWithKeepPortable); CACHE_CLEAR = CreateDelegate<CacheClearDelegate>(ProcCacheClear); CACHE_REMOVE_ALL = CreateDelegate<CacheRemoveAllDelegate>(ProcCacheRemoveAll); CACHE_OUT_OP_QUERY_CURSOR = CreateDelegate<CacheOutOpQueryCursorDelegate>(ProcCacheOutOpQueryCursor); CACHE_OUT_OP_CONTINUOUS_QUERY = CreateDelegate<CacheOutOpContinuousQueryDelegate>(ProcCacheOutOpContinuousQuery); CACHE_ITERATOR = CreateDelegate<CacheIteratorDelegate>(ProcCacheIterator); CACHE_LOCAL_ITERATOR = CreateDelegate<CacheLocalIteratorDelegate>(ProcCacheLocalIterator); CACHE_ENTER_LOCK = CreateDelegate<CacheEnterLockDelegate>(ProcCacheEnterLock); CACHE_EXIT_LOCK = CreateDelegate<CacheExitLockDelegate>(ProcCacheExitLock); CACHE_TRY_ENTER_LOCK = CreateDelegate<CacheTryEnterLockDelegate>(ProcCacheTryEnterLock); CACHE_CLOSE_LOCK = CreateDelegate<CacheCloseLockDelegate>(ProcCacheCloseLock); CACHE_REBALANCE = CreateDelegate<CacheRebalanceDelegate>(ProcCacheRebalance); CACHE_SIZE = CreateDelegate<CacheSizeDelegate>(ProcCacheSize); CACHE_STORE_CALLBACK_INVOKE = CreateDelegate<CacheStoreCallbackInvokeDelegate>(ProcCacheStoreCallbackInvoke); COMPUTE_WITH_NO_FAILOVER = CreateDelegate<ComputeWithNoFailoverDelegate>(ProcComputeWithNoFailover); COMPUTE_WITH_TIMEOUT = CreateDelegate<ComputeWithTimeoutDelegate>(ProcComputeWithTimeout); COMPUTE_EXECUTE_NATIVE = CreateDelegate<ComputeExecuteNativeDelegate>(ProcComputeExecuteNative); ContinuousQryClose = CreateDelegate<ContinuousQueryCloseDelegate>(ProcContinuousQryClose); ContinuousQryGetInitialQueryCursor = CreateDelegate<ContinuousQueryGetInitialQueryCursorDelegate>(ProcContinuousQryGetInitialQueryCursor); DataStreamerListenTop = CreateDelegate<DataStreamerListenTopologyDelegate>(ProcDataStreamerListenTop); DATA_STREAMER_ALLOW_OVERWRITE_GET = CreateDelegate<DataStreamerAllowOverwriteGetDelegate>(ProcDataStreamerAllowOverwriteGet); DATA_STREAMER_ALLOW_OVERWRITE_SET = CreateDelegate<DataStreamerAllowOverwriteSetDelegate>(ProcDataStreamerAllowOverwriteSet); DATA_STREAMER_SKIP_STORE_GET = CreateDelegate<DataStreamerSkipStoreGetDelegate>(ProcDataStreamerSkipStoreGet); DATA_STREAMER_SKIP_STORE_SET = CreateDelegate<DataStreamerSkipStoreSetDelegate>(ProcDataStreamerSkipStoreSet); DATA_STREAMER_PER_NODE_BUFFER_SIZE_GET = CreateDelegate<DataStreamerPerNodeBufferSizeGetDelegate>(ProcDataStreamerPerNodeBufferSizeGet); DATA_STREAMER_PER_NODE_BUFFER_SIZE_SET = CreateDelegate<DataStreamerPerNodeBufferSizeSetDelegate>(ProcDataStreamerPerNodeBufferSizeSet); DataStreamerPerNodeParallelOpsGet = CreateDelegate<DataStreamerPerNodeParallelOperationsGetDelegate>(ProcDataStreamerPerNodeParallelOpsGet); DataStreamerPerNodeParallelOpsSet = CreateDelegate<DataStreamerPerNodeParallelOperationsSetDelegate>(ProcDataStreamerPerNodeParallelOpsSet); MessagingWithAsync = CreateDelegate<MessagingWithAsyncDelegate>(ProcMessagingWithAsync); PROJECTION_FOR_OTHERS = CreateDelegate<ProjectionForOthersDelegate>(ProcProjectionForOthers); PROJECTION_FOR_REMOTES = CreateDelegate<ProjectionForRemotesDelegate>(ProcProjectionForRemotes); PROJECTION_FOR_DAEMONS = CreateDelegate<ProjectionForDaemonsDelegate>(ProcProjectionForDaemons); PROJECTION_FOR_RANDOM = CreateDelegate<ProjectionForRandomDelegate>(ProcProjectionForRandom); PROJECTION_FOR_OLDEST = CreateDelegate<ProjectionForOldestDelegate>(ProcProjectionForOldest); PROJECTION_FOR_YOUNGEST = CreateDelegate<ProjectionForYoungestDelegate>(ProcProjectionForYoungest); PROJECTION_RESET_METRICS = CreateDelegate<ProjectionResetMetricsDelegate>(ProcProjectionResetMetrics); PROJECTION_OUT_OP_RET = CreateDelegate<ProjectionOutOpRetDelegate>(ProcProjectionOutOpRet); QryCursorIterator = CreateDelegate<QueryCursorIteratorDelegate>(ProcQryCursorIterator); QryCursorClose = CreateDelegate<QueryCursorCloseDelegate>(ProcQryCursorClose); ACQUIRE = CreateDelegate<AcquireDelegate>(ProcAcquire); RELEASE = CreateDelegate<ReleaseDelegate>(ProcRelease); TxStart = CreateDelegate<TransactionsStartDelegate>(ProcTxStart); TxCommit = CreateDelegate<TransactionsCommitDelegate>(ProcTxCommit); TxCommitAsync = CreateDelegate<TransactionsCommitAsyncDelegate>(ProcTxCommitAsync); TxRollback = CreateDelegate<TransactionsRollbackDelegate>(ProcTxRollback); TxRollbackAsync = CreateDelegate<TransactionsRollbackAsyncDelegate>(ProcTxRollbackAsync); TxClose = CreateDelegate<TransactionsCloseDelegate>(ProcTxClose); TxState = CreateDelegate<TransactionsStateDelegate>(ProcTxState); TxSetRollbackOnly = CreateDelegate<TransactionsSetRollbackOnlyDelegate>(ProcTxSetRollbackOnly); TxResetMetrics = CreateDelegate<TransactionsResetMetricsDelegate>(ProcTxResetMetrics); THROW_TO_JAVA = CreateDelegate<ThrowToJavaDelegate>(ProcThrowToJava); HANDLERS_SIZE = CreateDelegate<HandlersSizeDelegate>(ProcHandlersSize); CREATE_CONTEXT = CreateDelegate<CreateContextDelegate>(ProcCreateContext); DELETE_CONTEXT = CreateDelegate<DeleteContextDelegate>(ProcDeleteContext); DESTROY_JVM = CreateDelegate<DestroyJvmDelegate>(ProcDestroyJvm); EVENTS_WITH_ASYNC = CreateDelegate<EventsWithAsyncDelegate>(ProcEventsWithAsync); EVENTS_STOP_LOCAL_LISTEN = CreateDelegate<EventsStopLocalListenDelegate>(ProcEventsStopLocalListen); EVENTS_LOCAL_LISTEN = CreateDelegate<EventsLocalListenDelegate>(ProcEventsLocalListen); EVENTS_IS_ENABLED = CreateDelegate<EventsIsEnabledDelegate>(ProcEventsIsEnabled); SERVICES_WITH_ASYNC = CreateDelegate<ServicesWithAsyncDelegate>(ProcServicesWithAsync); SERVICES_WITH_SERVER_KEEP_PORTABLE = CreateDelegate<ServicesWithServerKeepPortableDelegate>(ProcServicesWithServerKeepPortable); SERVICES_CANCEL = CreateDelegate<ServicesCancelDelegate>(ProcServicesCancel); SERVICES_CANCEL_ALL = CreateDelegate<ServicesCancelAllDelegate>(ProcServicesCancelAll); SERVICES_GET_SERVICE_PROXY = CreateDelegate<ServicesGetServiceProxyDelegate>(ProcServicesGetServiceProxy); } #region NATIVE METHODS: PROCESSOR internal static IUnmanagedTarget IgnitionStart(UnmanagedContext ctx, string cfgPath, string gridName, bool clientMode) { using (var mem = IgniteManager.Memory.Allocate().Stream()) { mem.WriteBool(clientMode); sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfgPath); sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName); try { void* res = IGNITION_START(ctx.NativeContext, cfgPath0, gridName0, InteropFactoryId, mem.SynchronizeOutput()); return new UnmanagedTarget(ctx, res); } finally { Marshal.FreeHGlobal(new IntPtr(cfgPath0)); Marshal.FreeHGlobal(new IntPtr(gridName0)); } } } internal static bool IgnitionStop(void* ctx, string gridName, bool cancel) { sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName); try { return IGNITION_STOP(ctx, gridName0, cancel); } finally { Marshal.FreeHGlobal(new IntPtr(gridName0)); } } internal static void IgnitionStopAll(void* ctx, bool cancel) { IGNITION_STOP_ALL(ctx, cancel); } internal static void ProcessorReleaseStart(IUnmanagedTarget target) { PROCESSOR_RELEASE_START(target.Context, target.Target); } internal static IUnmanagedTarget ProcessorProjection(IUnmanagedTarget target) { void* res = PROCESSOR_PROJECTION(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_CACHE(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_CREATE_CACHE(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_GET_OR_CREATE_CACHE(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorAffinity(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_AFFINITY(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorDataStreamer(IUnmanagedTarget target, string name, bool keepPortable) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_DATA_STREAMER(target.Context, target.Target, name0, keepPortable); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorTransactions(IUnmanagedTarget target) { void* res = PROCESSOR_TRANSACTIONS(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCompute(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_COMPUTE(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorMessage(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_MESSAGE(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorEvents(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_EVENTS(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorServices(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_SERVICES(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorExtensions(IUnmanagedTarget target) { void* res = PROCESSOR_EXTENSIONS(target.Context, target.Target); return target.ChangeTarget(res); } #endregion #region NATIVE METHODS: TARGET internal static long TargetInStreamOutLong(IUnmanagedTarget target, int opType, long memPtr) { return TARGET_IN_STREAM_OUT_LONG(target.Context, target.Target, opType, memPtr); } internal static void TargetInStreamOutStream(IUnmanagedTarget target, int opType, long inMemPtr, long outMemPtr) { TARGET_IN_STREAM_OUT_STREAM(target.Context, target.Target, opType, inMemPtr, outMemPtr); } internal static IUnmanagedTarget TargetInStreamOutObject(IUnmanagedTarget target, int opType, long inMemPtr) { void* res = TARGET_IN_STREAM_OUT_OBJECT(target.Context, target.Target, opType, inMemPtr); return target.ChangeTarget(res); } internal static void TargetInObjectStreamOutStream(IUnmanagedTarget target, int opType, void* arg, long inMemPtr, long outMemPtr) { TARGET_IN_OBJECT_STREAM_OUT_STREAM(target.Context, target.Target, opType, arg, inMemPtr, outMemPtr); } internal static long TargetOutLong(IUnmanagedTarget target, int opType) { return TARGET_OUT_LONG(target.Context, target.Target, opType); } internal static void TargetOutStream(IUnmanagedTarget target, int opType, long memPtr) { TARGET_OUT_STREAM(target.Context, target.Target, opType, memPtr); } internal static IUnmanagedTarget TargetOutObject(IUnmanagedTarget target, int opType) { void* res = TARGET_OUT_OBJECT(target.Context, target.Target, opType); return target.ChangeTarget(res); } internal static void TargetListenFuture(IUnmanagedTarget target, long futId, int typ) { TargetListenFut(target.Context, target.Target, futId, typ); } internal static void TargetListenFutureForOperation(IUnmanagedTarget target, long futId, int typ, int opId) { TargetListenFutForOp(target.Context, target.Target, futId, typ, opId); } #endregion #region NATIVE METHODS: AFFINITY internal static int AffinityPartitions(IUnmanagedTarget target) { return AffinityParts(target.Context, target.Target); } #endregion #region NATIVE METHODS: CACHE internal static IUnmanagedTarget CacheWithSkipStore(IUnmanagedTarget target) { void* res = CACHE_WITH_SKIP_STORE(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithNoRetries(IUnmanagedTarget target) { void* res = CACHE_WITH_NO_RETRIES(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithExpiryPolicy(IUnmanagedTarget target, long create, long update, long access) { void* res = CACHE_WITH_EXPIRY_POLICY(target.Context, target.Target, create, update, access); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithAsync(IUnmanagedTarget target) { void* res = CACHE_WITH_ASYNC(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithKeepPortable(IUnmanagedTarget target) { void* res = CACHE_WITH_KEEP_PORTABLE(target.Context, target.Target); return target.ChangeTarget(res); } internal static void CacheClear(IUnmanagedTarget target) { CACHE_CLEAR(target.Context, target.Target); } internal static void CacheRemoveAll(IUnmanagedTarget target) { CACHE_REMOVE_ALL(target.Context, target.Target); } internal static IUnmanagedTarget CacheOutOpQueryCursor(IUnmanagedTarget target, int type, long memPtr) { void* res = CACHE_OUT_OP_QUERY_CURSOR(target.Context, target.Target, type, memPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheOutOpContinuousQuery(IUnmanagedTarget target, int type, long memPtr) { void* res = CACHE_OUT_OP_CONTINUOUS_QUERY(target.Context, target.Target, type, memPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheIterator(IUnmanagedTarget target) { void* res = CACHE_ITERATOR(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheLocalIterator(IUnmanagedTarget target, int peekModes) { void* res = CACHE_LOCAL_ITERATOR(target.Context, target.Target, peekModes); return target.ChangeTarget(res); } internal static void CacheEnterLock(IUnmanagedTarget target, long id) { CACHE_ENTER_LOCK(target.Context, target.Target, id); } internal static void CacheExitLock(IUnmanagedTarget target, long id) { CACHE_EXIT_LOCK(target.Context, target.Target, id); } internal static bool CacheTryEnterLock(IUnmanagedTarget target, long id, long timeout) { return CACHE_TRY_ENTER_LOCK(target.Context, target.Target, id, timeout); } internal static void CacheCloseLock(IUnmanagedTarget target, long id) { CACHE_CLOSE_LOCK(target.Context, target.Target, id); } internal static void CacheRebalance(IUnmanagedTarget target, long futId) { CACHE_REBALANCE(target.Context, target.Target, futId); } internal static void CacheStoreCallbackInvoke(IUnmanagedTarget target, long memPtr) { CACHE_STORE_CALLBACK_INVOKE(target.Context, target.Target, memPtr); } internal static int CacheSize(IUnmanagedTarget target, int modes, bool loc) { return CACHE_SIZE(target.Context, target.Target, modes, loc); } #endregion #region NATIVE METHODS: COMPUTE internal static void ComputeWithNoFailover(IUnmanagedTarget target) { COMPUTE_WITH_NO_FAILOVER(target.Context, target.Target); } internal static void ComputeWithTimeout(IUnmanagedTarget target, long timeout) { COMPUTE_WITH_TIMEOUT(target.Context, target.Target, timeout); } internal static void ComputeExecuteNative(IUnmanagedTarget target, long taskPtr, long topVer) { COMPUTE_EXECUTE_NATIVE(target.Context, target.Target, taskPtr, topVer); } #endregion #region NATIVE METHODS: CONTINUOUS QUERY internal static void ContinuousQueryClose(IUnmanagedTarget target) { ContinuousQryClose(target.Context, target.Target); } internal static IUnmanagedTarget ContinuousQueryGetInitialQueryCursor(IUnmanagedTarget target) { void* res = ContinuousQryGetInitialQueryCursor(target.Context, target.Target); return res == null ? null : target.ChangeTarget(res); } #endregion #region NATIVE METHODS: DATA STREAMER internal static void DataStreamerListenTopology(IUnmanagedTarget target, long ptr) { DataStreamerListenTop(target.Context, target.Target, ptr); } internal static bool DataStreamerAllowOverwriteGet(IUnmanagedTarget target) { return DATA_STREAMER_ALLOW_OVERWRITE_GET(target.Context, target.Target); } internal static void DataStreamerAllowOverwriteSet(IUnmanagedTarget target, bool val) { DATA_STREAMER_ALLOW_OVERWRITE_SET(target.Context, target.Target, val); } internal static bool DataStreamerSkipStoreGet(IUnmanagedTarget target) { return DATA_STREAMER_SKIP_STORE_GET(target.Context, target.Target); } internal static void DataStreamerSkipStoreSet(IUnmanagedTarget target, bool val) { DATA_STREAMER_SKIP_STORE_SET(target.Context, target.Target, val); } internal static int DataStreamerPerNodeBufferSizeGet(IUnmanagedTarget target) { return DATA_STREAMER_PER_NODE_BUFFER_SIZE_GET(target.Context, target.Target); } internal static void DataStreamerPerNodeBufferSizeSet(IUnmanagedTarget target, int val) { DATA_STREAMER_PER_NODE_BUFFER_SIZE_SET(target.Context, target.Target, val); } internal static int DataStreamerPerNodeParallelOperationsGet(IUnmanagedTarget target) { return DataStreamerPerNodeParallelOpsGet(target.Context, target.Target); } internal static void DataStreamerPerNodeParallelOperationsSet(IUnmanagedTarget target, int val) { DataStreamerPerNodeParallelOpsSet(target.Context, target.Target, val); } #endregion #region NATIVE METHODS: MESSAGING internal static IUnmanagedTarget MessagingWithASync(IUnmanagedTarget target) { void* res = MessagingWithAsync(target.Context, target.Target); return target.ChangeTarget(res); } #endregion #region NATIVE METHODS: PROJECTION internal static IUnmanagedTarget ProjectionForOthers(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROJECTION_FOR_OTHERS(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForRemotes(IUnmanagedTarget target) { void* res = PROJECTION_FOR_REMOTES(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForDaemons(IUnmanagedTarget target) { void* res = PROJECTION_FOR_DAEMONS(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForRandom(IUnmanagedTarget target) { void* res = PROJECTION_FOR_RANDOM(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForOldest(IUnmanagedTarget target) { void* res = PROJECTION_FOR_OLDEST(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForYoungest(IUnmanagedTarget target) { void* res = PROJECTION_FOR_YOUNGEST(target.Context, target.Target); return target.ChangeTarget(res); } internal static void ProjectionResetMetrics(IUnmanagedTarget target) { PROJECTION_RESET_METRICS(target.Context, target.Target); } internal static IUnmanagedTarget ProjectionOutOpRet(IUnmanagedTarget target, int type, long memPtr) { void* res = PROJECTION_OUT_OP_RET(target.Context, target.Target, type, memPtr); return target.ChangeTarget(res); } #endregion #region NATIVE METHODS: QUERY CURSOR internal static void QueryCursorIterator(IUnmanagedTarget target) { QryCursorIterator(target.Context, target.Target); } internal static void QueryCursorClose(IUnmanagedTarget target) { QryCursorClose(target.Context, target.Target); } #endregion #region NATIVE METHODS: TRANSACTIONS internal static long TransactionsStart(IUnmanagedTarget target, int concurrency, int isolation, long timeout, int txSize) { return TxStart(target.Context, target.Target, concurrency, isolation, timeout, txSize); } internal static int TransactionsCommit(IUnmanagedTarget target, long id) { return TxCommit(target.Context, target.Target, id); } internal static void TransactionsCommitAsync(IUnmanagedTarget target, long id, long futId) { TxCommitAsync(target.Context, target.Target, id, futId); } internal static int TransactionsRollback(IUnmanagedTarget target, long id) { return TxRollback(target.Context, target.Target, id); } internal static void TransactionsRollbackAsync(IUnmanagedTarget target, long id, long futId) { TxRollbackAsync(target.Context, target.Target, id, futId); } internal static int TransactionsClose(IUnmanagedTarget target, long id) { return TxClose(target.Context, target.Target, id); } internal static int TransactionsState(IUnmanagedTarget target, long id) { return TxState(target.Context, target.Target, id); } internal static bool TransactionsSetRollbackOnly(IUnmanagedTarget target, long id) { return TxSetRollbackOnly(target.Context, target.Target, id); } internal static void TransactionsResetMetrics(IUnmanagedTarget target) { TxResetMetrics(target.Context, target.Target); } #endregion #region NATIVE METHODS: MISCELANNEOUS internal static void Reallocate(long memPtr, int cap) { int res = REALLOCATE(memPtr, cap); if (res != 0) throw new IgniteException("Failed to reallocate external memory [ptr=" + memPtr + ", capacity=" + cap + ']'); } internal static IUnmanagedTarget Acquire(UnmanagedContext ctx, void* target) { void* target0 = ACQUIRE(ctx.NativeContext, target); return new UnmanagedTarget(ctx, target0); } internal static void Release(IUnmanagedTarget target) { RELEASE(target.Target); } internal static void ThrowToJava(void* ctx, Exception e) { char* msgChars = (char*)IgniteUtils.StringToUtf8Unmanaged(e.Message); try { THROW_TO_JAVA(ctx, msgChars); } finally { Marshal.FreeHGlobal(new IntPtr(msgChars)); } } internal static int HandlersSize() { return HANDLERS_SIZE(); } internal static void* CreateContext(void* opts, int optsLen, void* cbs) { return CREATE_CONTEXT(opts, optsLen, cbs); } internal static void DeleteContext(void* ctx) { DELETE_CONTEXT(ctx); } internal static void DestroyJvm(void* ctx) { DESTROY_JVM(ctx); } #endregion #region NATIVE METHODS: EVENTS internal static IUnmanagedTarget EventsWithAsync(IUnmanagedTarget target) { return target.ChangeTarget(EVENTS_WITH_ASYNC(target.Context, target.Target)); } internal static bool EventsStopLocalListen(IUnmanagedTarget target, long handle) { return EVENTS_STOP_LOCAL_LISTEN(target.Context, target.Target, handle); } internal static bool EventsIsEnabled(IUnmanagedTarget target, int type) { return EVENTS_IS_ENABLED(target.Context, target.Target, type); } internal static void EventsLocalListen(IUnmanagedTarget target, long handle, int type) { EVENTS_LOCAL_LISTEN(target.Context, target.Target, handle, type); } #endregion #region NATIVE METHODS: SERVICES internal static IUnmanagedTarget ServicesWithAsync(IUnmanagedTarget target) { return target.ChangeTarget(SERVICES_WITH_ASYNC(target.Context, target.Target)); } internal static IUnmanagedTarget ServicesWithServerKeepPortable(IUnmanagedTarget target) { return target.ChangeTarget(SERVICES_WITH_SERVER_KEEP_PORTABLE(target.Context, target.Target)); } internal static void ServicesCancel(IUnmanagedTarget target, string name) { var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name); try { SERVICES_CANCEL(target.Context, target.Target, nameChars); } finally { Marshal.FreeHGlobal(new IntPtr(nameChars)); } } internal static void ServicesCancelAll(IUnmanagedTarget target) { SERVICES_CANCEL_ALL(target.Context, target.Target); } internal static IUnmanagedTarget ServicesGetServiceProxy(IUnmanagedTarget target, string name, bool sticky) { var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name); try { return target.ChangeTarget( SERVICES_GET_SERVICE_PROXY(target.Context, target.Target, nameChars, sticky)); } finally { Marshal.FreeHGlobal(new IntPtr(nameChars)); } } #endregion /// <summary> /// No-op initializer used to force type loading and static constructor call. /// </summary> internal static void Initialize() { // No-op. } /// <summary> /// Create delegate for the given procedure. /// </summary> /// <typeparam name="T">Delegate type.</typeparam> /// <param name="procName">Procedure name.</param> /// <returns></returns> private static T CreateDelegate<T>(string procName) { var procPtr = NativeMethods.GetProcAddress(Ptr, procName); if (procPtr == IntPtr.Zero) throw new IgniteException(string.Format("Unable to find native function: {0} (Error code: {1}). " + "Make sure that module.def is up to date", procName, Marshal.GetLastWin32Error())); return TypeCaster<T>.Cast(Marshal.GetDelegateForFunctionPointer(procPtr, typeof (T))); } } }
// ========================================================================== // This software is subject to the provisions of the Zope Public License, // Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED // WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS // FOR A PARTICULAR PURPOSE. // ========================================================================== using System; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections; using System.Reflection; using System.Reflection.Emit; namespace Python.Runtime { /// <summary> /// The DelegateManager class manages the creation of true managed /// delegate instances that dispatch calls to Python methods. /// </summary> internal class DelegateManager { Hashtable cache; Type basetype; Type listtype; Type voidtype; Type typetype; Type ptrtype; CodeGenerator codeGenerator; public DelegateManager() { basetype = typeof(Dispatcher); listtype = typeof(ArrayList); voidtype = typeof(void); typetype = typeof(Type); ptrtype = typeof(IntPtr); cache = new Hashtable(); codeGenerator = new CodeGenerator(); } //==================================================================== // Given a true delegate instance, return the PyObject handle of the // Python object implementing the delegate (or IntPtr.Zero if the // delegate is not implemented in Python code. //==================================================================== public IntPtr GetPythonHandle(Delegate d) { if ((d != null) && (d.Target is Dispatcher)) { Dispatcher disp = d.Target as Dispatcher; return disp.target; } return IntPtr.Zero; } //==================================================================== // GetDispatcher is responsible for creating a class that provides // an appropriate managed callback method for a given delegate type. //==================================================================== private Type GetDispatcher(Type dtype) { // If a dispatcher type for the given delegate type has already // been generated, get it from the cache. The cache maps delegate // types to generated dispatcher types. A possible optimization // for the future would be to generate dispatcher types based on // unique signatures rather than delegate types, since multiple // delegate types with the same sig could use the same dispatcher. Object item = cache[dtype]; if (item != null) { return (Type)item; } string name = "__" + dtype.FullName + "Dispatcher"; name = name.Replace('.', '_'); name = name.Replace('+', '_'); TypeBuilder tb = codeGenerator.DefineType(name, basetype); // Generate a constructor for the generated type that calls the // appropriate constructor of the Dispatcher base type. MethodAttributes ma = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; CallingConventions cc = CallingConventions.Standard; Type[] args = {ptrtype, typetype}; ConstructorBuilder cb = tb.DefineConstructor(ma, cc, args); ConstructorInfo ci = basetype.GetConstructor(args); ILGenerator il = cb.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Call, ci); il.Emit(OpCodes.Ret); // Method generation: we generate a method named "Invoke" on the // dispatcher type, whose signature matches the delegate type for // which it is generated. The method body simply packages the // arguments and hands them to the Dispatch() method, which deals // with converting the arguments, calling the Python method and // converting the result of the call. MethodInfo method = dtype.GetMethod("Invoke"); ParameterInfo[] pi = method.GetParameters(); Type[] signature = new Type[pi.Length]; for (int i = 0; i < pi.Length; i++) { signature[i] = pi[i].ParameterType; } MethodBuilder mb = tb.DefineMethod( "Invoke", MethodAttributes.Public, method.ReturnType, signature ); ConstructorInfo ctor = listtype.GetConstructor(Type.EmptyTypes); MethodInfo dispatch = basetype.GetMethod("Dispatch"); MethodInfo add = listtype.GetMethod("Add"); il = mb.GetILGenerator(); il.DeclareLocal(listtype); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Stloc_0); for (int c = 0; c < signature.Length; c++) { Type t = signature[c]; il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldarg_S, (byte)(c + 1)); if (t.IsValueType) { il.Emit(OpCodes.Box, t); } il.Emit(OpCodes.Callvirt, add); il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Call, dispatch); if (method.ReturnType == voidtype) { il.Emit(OpCodes.Pop); } else if (method.ReturnType.IsValueType) { il.Emit(OpCodes.Unbox_Any, method.ReturnType); } il.Emit(OpCodes.Ret); Type disp = tb.CreateType(); cache[dtype] = disp; return disp; } //==================================================================== // Given a delegate type and a callable Python object, GetDelegate // returns an instance of the delegate type. The delegate instance // returned will dispatch calls to the given Python object. //==================================================================== internal Delegate GetDelegate(Type dtype, IntPtr callable) { Type dispatcher = GetDispatcher(dtype); object[] args = {callable, dtype}; object o = Activator.CreateInstance(dispatcher, args); return Delegate.CreateDelegate(dtype, o, "Invoke"); } } /* When a delegate instance is created that has a Python implementation, the delegate manager generates a custom subclass of Dispatcher and instantiates it, passing the IntPtr of the Python callable. The "real" delegate is created using CreateDelegate, passing the instance of the generated type and the name of the (generated) implementing method (Invoke). The true delegate instance holds the only reference to the dispatcher instance, which ensures that when the delegate dies, the finalizer of the referenced instance will be able to decref the Python callable. A possible alternate strategy would be to create custom subclasses of the required delegate type, storing the IntPtr in it directly. This would be slightly cleaner, but I'm not sure if delegates are too "special" for this to work. It would be more work, so for now the 80/20 rule applies :) */ public class Dispatcher { public IntPtr target; public Type dtype; public Dispatcher(IntPtr target, Type dtype) { Runtime.Incref(target); this.target = target; this.dtype = dtype; } ~Dispatcher() { // Note: the managed GC thread can run and try to free one of // these *after* the Python runtime has been finalized! if (Runtime.Py_IsInitialized() > 0) { IntPtr gs = PythonEngine.AcquireLock(); Runtime.Decref(target); PythonEngine.ReleaseLock(gs); } } public object Dispatch(ArrayList args) { IntPtr gs = PythonEngine.AcquireLock(); object ob = null; try { ob = TrueDispatch(args); } catch (Exception e) { PythonEngine.ReleaseLock(gs); throw e; } PythonEngine.ReleaseLock(gs); return ob; } public object TrueDispatch(ArrayList args) { MethodInfo method = dtype.GetMethod("Invoke"); ParameterInfo[] pi = method.GetParameters(); IntPtr pyargs = Runtime.PyTuple_New(pi.Length); Type rtype = method.ReturnType; for (int i = 0; i < pi.Length; i++) { // Here we own the reference to the Python value, and we // give the ownership to the arg tuple. IntPtr arg = Converter.ToPython(args[i], pi[i].ParameterType); Runtime.PyTuple_SetItem(pyargs, i, arg); } IntPtr op = Runtime.PyObject_Call(target, pyargs, IntPtr.Zero); Runtime.Decref(pyargs); if (op == IntPtr.Zero) { PythonException e = new PythonException(); throw e; } if (rtype == typeof(void)) { return null; } Object result = null; if (!Converter.ToManaged(op, rtype, out result, false)) { string s = "could not convert Python result to " + rtype.ToString(); Runtime.Decref(op); throw new ConversionException(s); } Runtime.Decref(op); return result; } } public class ConversionException : System.Exception { public ConversionException() : base() {} public ConversionException(string msg) : base(msg) {} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Permissions { using System; using SecurityElement = System.Security.SecurityElement; using System.Security.AccessControl; using System.Security.Util; using System.IO; using System.Globalization; using System.Runtime.Serialization; [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum RegistryPermissionAccess { NoAccess = 0x00, Read = 0x01, Write = 0x02, Create = 0x04, AllAccess = 0x07, } [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class RegistryPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { private StringExpressionSet m_read; private StringExpressionSet m_write; private StringExpressionSet m_create; [OptionalField(VersionAdded = 2)] private StringExpressionSet m_viewAcl; [OptionalField(VersionAdded = 2)] private StringExpressionSet m_changeAcl; private bool m_unrestricted; public RegistryPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { m_unrestricted = true; } else if (state == PermissionState.None) { m_unrestricted = false; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } public RegistryPermission( RegistryPermissionAccess access, String pathList ) { SetPathList( access, pathList ); } public void SetPathList( RegistryPermissionAccess access, String pathList ) { VerifyAccess( access ); m_unrestricted = false; if ((access & RegistryPermissionAccess.Read) != 0) m_read = null; if ((access & RegistryPermissionAccess.Write) != 0) m_write = null; if ((access & RegistryPermissionAccess.Create) != 0) m_create = null; AddPathList( access, pathList ); } public void AddPathList( RegistryPermissionAccess access, String pathList ) { AddPathList( access, AccessControlActions.None, pathList ); } public void AddPathList( RegistryPermissionAccess access, AccessControlActions control, String pathList ) { VerifyAccess( access ); if ((access & RegistryPermissionAccess.Read) != 0) { if (m_read == null) m_read = new StringExpressionSet(); m_read.AddExpressions( pathList ); } if ((access & RegistryPermissionAccess.Write) != 0) { if (m_write == null) m_write = new StringExpressionSet(); m_write.AddExpressions( pathList ); } if ((access & RegistryPermissionAccess.Create) != 0) { if (m_create == null) m_create = new StringExpressionSet(); m_create.AddExpressions( pathList ); } } public String GetPathList( RegistryPermissionAccess access ) { // SafeCritical: these are registry paths, which means we're not leaking file system information here VerifyAccess( access ); ExclusiveAccess( access ); if ((access & RegistryPermissionAccess.Read) != 0) { if (m_read == null) { return ""; } return m_read.UnsafeToString(); } if ((access & RegistryPermissionAccess.Write) != 0) { if (m_write == null) { return ""; } return m_write.UnsafeToString(); } if ((access & RegistryPermissionAccess.Create) != 0) { if (m_create == null) { return ""; } return m_create.UnsafeToString(); } /* not reached */ return ""; } private void VerifyAccess( RegistryPermissionAccess access ) { if ((access & ~RegistryPermissionAccess.AllAccess) != 0) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access)); } private void ExclusiveAccess( RegistryPermissionAccess access ) { if (access == RegistryPermissionAccess.NoAccess) { throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); } if (((int) access & ((int)access-1)) != 0) { throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); } } private bool IsEmpty() { return (!m_unrestricted && (this.m_read == null || this.m_read.IsEmpty()) && (this.m_write == null || this.m_write.IsEmpty()) && (this.m_create == null || this.m_create.IsEmpty()) && (this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) && (this.m_changeAcl == null || this.m_changeAcl.IsEmpty())); } //------------------------------------------------------ // // CODEACCESSPERMISSION IMPLEMENTATION // //------------------------------------------------------ public bool IsUnrestricted() { return m_unrestricted; } //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public override bool IsSubsetOf(IPermission target) { if (target == null) { return this.IsEmpty(); } RegistryPermission operand = target as RegistryPermission; if (operand == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if (operand.IsUnrestricted()) return true; else if (this.IsUnrestricted()) return false; else return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) && (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) && (this.m_create == null || this.m_create.IsSubsetOf( operand.m_create )) && (this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) && (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl ))); } public override IPermission Intersect(IPermission target) { if (target == null) { return null; } else if (!VerifyType(target)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } else if (this.IsUnrestricted()) { return target.Copy(); } RegistryPermission operand = (RegistryPermission)target; if (operand.IsUnrestricted()) { return this.Copy(); } StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read ); StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write ); StringExpressionSet intersectCreate = this.m_create == null ? null : this.m_create.Intersect( operand.m_create ); StringExpressionSet intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl ); StringExpressionSet intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl ); if ((intersectRead == null || intersectRead.IsEmpty()) && (intersectWrite == null || intersectWrite.IsEmpty()) && (intersectCreate == null || intersectCreate.IsEmpty()) && (intersectViewAcl == null || intersectViewAcl.IsEmpty()) && (intersectChangeAcl == null || intersectChangeAcl.IsEmpty())) { return null; } RegistryPermission intersectPermission = new RegistryPermission(PermissionState.None); intersectPermission.m_unrestricted = false; intersectPermission.m_read = intersectRead; intersectPermission.m_write = intersectWrite; intersectPermission.m_create = intersectCreate; intersectPermission.m_viewAcl = intersectViewAcl; intersectPermission.m_changeAcl = intersectChangeAcl; return intersectPermission; } public override IPermission Union(IPermission other) { if (other == null) { return this.Copy(); } else if (!VerifyType(other)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } RegistryPermission operand = (RegistryPermission)other; if (this.IsUnrestricted() || operand.IsUnrestricted()) { return new RegistryPermission( PermissionState.Unrestricted ); } StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read ); StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write ); StringExpressionSet unionCreate = this.m_create == null ? operand.m_create : this.m_create.Union( operand.m_create ); StringExpressionSet unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl ); StringExpressionSet unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl ); if ((unionRead == null || unionRead.IsEmpty()) && (unionWrite == null || unionWrite.IsEmpty()) && (unionCreate == null || unionCreate.IsEmpty()) && (unionViewAcl == null || unionViewAcl.IsEmpty()) && (unionChangeAcl == null || unionChangeAcl.IsEmpty())) { return null; } RegistryPermission unionPermission = new RegistryPermission(PermissionState.None); unionPermission.m_unrestricted = false; unionPermission.m_read = unionRead; unionPermission.m_write = unionWrite; unionPermission.m_create = unionCreate; unionPermission.m_viewAcl = unionViewAcl; unionPermission.m_changeAcl = unionChangeAcl; return unionPermission; } public override IPermission Copy() { RegistryPermission copy = new RegistryPermission(PermissionState.None); if (this.m_unrestricted) { copy.m_unrestricted = true; } else { copy.m_unrestricted = false; if (this.m_read != null) { copy.m_read = this.m_read.Copy(); } if (this.m_write != null) { copy.m_write = this.m_write.Copy(); } if (this.m_create != null) { copy.m_create = this.m_create.Copy(); } if (this.m_viewAcl != null) { copy.m_viewAcl = this.m_viewAcl.Copy(); } if (this.m_changeAcl != null) { copy.m_changeAcl = this.m_changeAcl.Copy(); } } return copy; } /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return RegistryPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.RegistryPermissionIndex; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using Flurl; using Flurl.Http; using NBitcoin; using Newtonsoft.Json; using Stratis.Bitcoin.Features.Wallet.Models; using Stratis.Bitcoin.IntegrationTests.Common; using Stratis.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers; using Stratis.Bitcoin.Networks; using Stratis.Features.FederatedPeg.Models; using Stratis.Sidechains.Networks; namespace Stratis.Features.FederatedPeg.IntegrationTests.Utils { public class SidechainTestContext : IDisposable { private const string WalletName = "mywallet"; private const string WalletPassword = "password"; private const string WalletPassphrase = "passphrase"; private const string WalletAccount = "account 0"; private const string ConfigSideChain = "sidechain"; private const string ConfigMainChain = "mainchain"; private const string ConfigAgentPrefix = "agentprefix"; // TODO: Make these private, or move to public immutable properties. Will happen naturally over time. public readonly IList<Mnemonic> mnemonics; public readonly Dictionary<Mnemonic, PubKey> pubKeysByMnemonic; public readonly (Script payToMultiSig, BitcoinAddress sidechainMultisigAddress, BitcoinAddress mainchainMultisigAddress) scriptAndAddresses; public readonly List<string> chains; private readonly SidechainNodeBuilder nodeBuilder; public Network MainChainNetwork { get; } public FederatedPegRegTest SideChainNetwork { get; } // TODO: HashSets / Readonly public IReadOnlyList<CoreNode> MainChainNodes { get; } public IReadOnlyList<CoreNode> SideChainNodes { get; } public IReadOnlyList<CoreNode> MainChainFedNodes { get; } public IReadOnlyList<CoreNode> SideChainFedNodes { get; } public CoreNode MainUser{ get; } public CoreNode FedMain1 { get; } public CoreNode FedMain2 { get; } public CoreNode FedMain3 { get; } public CoreNode SideUser { get; } public CoreNode FedSide1 { get; } public CoreNode FedSide2 { get; } public CoreNode FedSide3 { get; } public SidechainTestContext() { this.MainChainNetwork = Networks.Stratis.Regtest(); this.SideChainNetwork = (FederatedPegRegTest)FederatedPegNetwork.NetworksSelector.Regtest(); this.mnemonics = this.SideChainNetwork.FederationMnemonics; this.pubKeysByMnemonic = this.mnemonics.ToDictionary(m => m, m => m.DeriveExtKey().PrivateKey.PubKey); this.scriptAndAddresses = FederatedPegTestHelper.GenerateScriptAndAddresses(this.MainChainNetwork, this.SideChainNetwork, 2, this.pubKeysByMnemonic); this.chains = new[] { "mainchain", "sidechain" }.ToList(); this.nodeBuilder = SidechainNodeBuilder.CreateSidechainNodeBuilder(this); this.MainUser = this.nodeBuilder.CreateStratisPosNode(this.MainChainNetwork, nameof(this.MainUser)).WithWallet(); this.FedMain1 = this.nodeBuilder.CreateMainChainFederationNode(this.MainChainNetwork, this.SideChainNetwork).WithWallet(); this.FedMain2 = this.nodeBuilder.CreateMainChainFederationNode(this.MainChainNetwork, this.SideChainNetwork); this.FedMain3 = this.nodeBuilder.CreateMainChainFederationNode(this.MainChainNetwork, this.SideChainNetwork); this.SideUser = this.nodeBuilder.CreateSidechainNode(this.SideChainNetwork).WithWallet(); this.FedSide1 = this.nodeBuilder.CreateSidechainFederationNode(this.SideChainNetwork, this.MainChainNetwork, this.SideChainNetwork.FederationKeys[0]); this.FedSide2 = this.nodeBuilder.CreateSidechainFederationNode(this.SideChainNetwork, this.MainChainNetwork, this.SideChainNetwork.FederationKeys[1]); this.FedSide3 = this.nodeBuilder.CreateSidechainFederationNode(this.SideChainNetwork, this.MainChainNetwork, this.SideChainNetwork.FederationKeys[2]); this.SideChainNodes = new List<CoreNode>() { this.SideUser, this.FedSide1, this.FedSide2, this.FedSide3 }; this.MainChainNodes = new List<CoreNode>() { this.MainUser, this.FedMain1, this.FedMain2, this.FedMain3, }; this.SideChainFedNodes = new List<CoreNode>() { this.FedSide1, this.FedSide2, this.FedSide3 }; this.MainChainFedNodes = new List<CoreNode>() { this.FedMain1, this.FedMain2, this.FedMain3 }; this.ApplyConfigParametersToNodes(); } public void StartAndConnectNodes() { this.StartMainNodes(); this.StartSideNodes(); TestHelper.WaitLoop(() => this.FedMain3.State == CoreNodeState.Running && this.FedSide3.State == CoreNodeState.Running); this.ConnectMainChainNodes(); this.ConnectSideChainNodes(); } public void StartMainNodes() { foreach (CoreNode node in this.MainChainNodes) { node.Start(); } } public void StartSideNodes() { foreach (CoreNode node in this.SideChainNodes) { node.Start(); } } public void ConnectMainChainNodes() { TestHelper.Connect(this.MainUser, this.FedMain1); TestHelper.Connect(this.MainUser, this.FedMain2); TestHelper.Connect(this.MainUser, this.FedMain3); TestHelper.Connect(this.FedMain1, this.MainUser); TestHelper.Connect(this.FedMain1, this.FedMain2); TestHelper.Connect(this.FedMain1, this.FedMain3); TestHelper.Connect(this.FedMain2, this.MainUser); TestHelper.Connect(this.FedMain2, this.FedMain1); TestHelper.Connect(this.FedMain2, this.FedMain3); TestHelper.Connect(this.FedMain3, this.MainUser); TestHelper.Connect(this.FedMain3, this.FedMain1); TestHelper.Connect(this.FedMain3, this.FedMain2); } public void ConnectSideChainNodes() { TestHelper.Connect(this.SideUser, this.FedSide1); TestHelper.Connect(this.SideUser, this.FedSide2); TestHelper.Connect(this.SideUser, this.FedSide3); TestHelper.Connect(this.FedSide1, this.SideUser); TestHelper.Connect(this.FedSide1, this.FedSide2); TestHelper.Connect(this.FedSide1, this.FedSide3); TestHelper.Connect(this.FedSide2, this.SideUser); TestHelper.Connect(this.FedSide2, this.FedSide1); TestHelper.Connect(this.FedSide2, this.FedSide3); TestHelper.Connect(this.FedSide3, this.SideUser); TestHelper.Connect(this.FedSide3, this.FedSide1); TestHelper.Connect(this.FedSide3, this.FedSide2); } public void EnableMainFedWallets() { EnableFederationWallets(this.MainChainFedNodes); } public void EnableSideFedWallets() { EnableFederationWallets(this.SideChainFedNodes); } private void EnableFederationWallets(IReadOnlyList<CoreNode> nodes) { for (int i = 0; i < nodes.Count; i++) { CoreNode node = nodes[i]; $"http://localhost:{node.ApiPort}/api".AppendPathSegment("FederationWallet/enable-federation").PostJsonAsync(new EnableFederationRequest { Password = "password", Mnemonic = this.mnemonics[i].ToString() }).Result.StatusCode.Should().Be(HttpStatusCode.OK); } } /// <summary> /// Helper method to build and send a deposit transaction to the federation on the main chain. /// </summary> public async Task DepositToSideChain(CoreNode node, decimal amount, string sidechainDepositAddress) { HttpResponseMessage depositTransaction = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/build-transaction") .PostJsonAsync(new { walletName = WalletName, accountName = WalletAccount, password = WalletPassword, opReturnData = sidechainDepositAddress, feeAmount = "0.01", allowUnconfirmed = true, recipients = new[] { new { destinationAddress = this.scriptAndAddresses.mainchainMultisigAddress.ToString(), amount = amount } } }); string result = await depositTransaction.Content.ReadAsStringAsync(); WalletBuildTransactionModel walletBuildTxModel = JsonConvert.DeserializeObject<WalletBuildTransactionModel>(result); HttpResponseMessage sendTransactionResponse = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/send-transaction") .PostJsonAsync(new { hex = walletBuildTxModel.Hex }); } public async Task WithdrawToMainChain(CoreNode node, decimal amount, string mainchainWithdrawAddress) { HttpResponseMessage withdrawTransaction = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/build-transaction") .PostJsonAsync(new { walletName = WalletName, accountName = WalletAccount, password = WalletPassword, opReturnData = mainchainWithdrawAddress, feeAmount = "0.01", recipients = new[] { new { destinationAddress = this.scriptAndAddresses.sidechainMultisigAddress.ToString(), amount = amount } } }); string result = await withdrawTransaction.Content.ReadAsStringAsync(); WalletBuildTransactionModel walletBuildTxModel = JsonConvert.DeserializeObject<WalletBuildTransactionModel>(result); HttpResponseMessage sendTransactionResponse = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/send-transaction") .PostJsonAsync(new { hex = walletBuildTxModel.Hex }); } private void ApplyFederationIPs(CoreNode fed1, CoreNode fed2, CoreNode fed3) { string fedIps = $"{fed1.Endpoint},{fed2.Endpoint},{fed3.Endpoint}"; fed1.AppendToConfig($"{FederationGatewaySettings.FederationIpsParam}={fedIps}"); fed2.AppendToConfig($"{FederationGatewaySettings.FederationIpsParam}={fedIps}"); fed3.AppendToConfig($"{FederationGatewaySettings.FederationIpsParam}={fedIps}"); } private void ApplyCounterChainAPIPort(CoreNode fromNode, CoreNode toNode) { fromNode.AppendToConfig($"{FederationGatewaySettings.CounterChainApiPortParam}={toNode.ApiPort.ToString()}"); toNode.AppendToConfig($"{FederationGatewaySettings.CounterChainApiPortParam}={fromNode.ApiPort.ToString()}"); } private void ApplyConfigParametersToNodes() { this.FedSide1.AppendToConfig($"{ConfigSideChain}=1"); this.FedSide2.AppendToConfig($"{ConfigSideChain}=1"); this.FedSide3.AppendToConfig($"{ConfigSideChain}=1"); this.FedMain1.AppendToConfig($"{ConfigMainChain}=1"); this.FedMain2.AppendToConfig($"{ConfigMainChain}=1"); this.FedMain3.AppendToConfig($"{ConfigMainChain}=1"); this.FedSide1.AppendToConfig($"mindepositconfirmations=5"); this.FedSide2.AppendToConfig($"mindepositconfirmations=5"); this.FedSide3.AppendToConfig($"mindepositconfirmations=5"); this.FedMain1.AppendToConfig($"mindepositconfirmations=5"); this.FedMain2.AppendToConfig($"mindepositconfirmations=5"); this.FedMain3.AppendToConfig($"mindepositconfirmations=5"); // To look for deposits from the beginning on our sidechain. this.FedSide1.AppendToConfig($"{FederationGatewaySettings.CounterChainDepositBlock}=1"); this.FedSide2.AppendToConfig($"{FederationGatewaySettings.CounterChainDepositBlock}=1"); this.FedSide3.AppendToConfig($"{FederationGatewaySettings.CounterChainDepositBlock}=1"); this.FedSide1.AppendToConfig($"{FederationGatewaySettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedSide2.AppendToConfig($"{FederationGatewaySettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedSide3.AppendToConfig($"{FederationGatewaySettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedMain1.AppendToConfig($"{FederationGatewaySettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedMain2.AppendToConfig($"{FederationGatewaySettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedMain3.AppendToConfig($"{FederationGatewaySettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedSide1.AppendToConfig($"{FederationGatewaySettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[0]].ToString()}"); this.FedSide2.AppendToConfig($"{FederationGatewaySettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[1]].ToString()}"); this.FedSide3.AppendToConfig($"{FederationGatewaySettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[2]].ToString()}"); this.FedMain1.AppendToConfig($"{FederationGatewaySettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[0]].ToString()}"); this.FedMain2.AppendToConfig($"{FederationGatewaySettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[1]].ToString()}"); this.FedMain3.AppendToConfig($"{FederationGatewaySettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[2]].ToString()}"); this.ApplyFederationIPs(this.FedMain1, this.FedMain2, this.FedMain3); this.ApplyFederationIPs(this.FedSide1, this.FedSide2, this.FedSide3); this.ApplyCounterChainAPIPort(this.FedMain1, this.FedSide1); this.ApplyCounterChainAPIPort(this.FedMain2, this.FedSide2); this.ApplyCounterChainAPIPort(this.FedMain3, this.FedSide3); this.ApplyAgentPrefixToNodes(); } private void ApplyAgentPrefixToNodes() { // name assigning a little gross here - fix later. string[] names = new string[] {"SideUser", "FedSide1", "FedSide2", "FedSide3", "MainUser", "FedMain1", "FedMain2", "FedMain3"}; int index = 0; foreach (CoreNode n in this.SideChainNodes.Concat(this.MainChainNodes)) { string text = File.ReadAllText(n.Config); text = text.Replace($"{ConfigAgentPrefix}=node{n.Endpoint.Port}", $"{ConfigAgentPrefix}={names[index]}"); File.WriteAllText(n.Config, text); index++; } } public void Dispose() { this.nodeBuilder?.Dispose(); } } }
// // 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 Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// A virtual machine disk associated with your subscription. /// </summary> public partial class VirtualMachineDiskGetResponse : AzureOperationResponse { private string _affinityGroup; /// <summary> /// Optional. The affinity group in which the disk is located. The /// AffinityGroup value is derived from storage account that contains /// the blob in which the media is located. If the storage account /// does not belong to an affinity group the value is NULL. /// </summary> public string AffinityGroup { get { return this._affinityGroup; } set { this._affinityGroup = value; } } private string _iOType; /// <summary> /// Optional. Gets or sets the IO type. /// </summary> public string IOType { get { return this._iOType; } set { this._iOType = value; } } private bool? _isCorrupted; /// <summary> /// Optional. Specifies whether the disk is known to be corrupt. /// </summary> public bool? IsCorrupted { get { return this._isCorrupted; } set { this._isCorrupted = value; } } private bool? _isPremium; /// <summary> /// Optional. Specifies whether or not the disk contains a premium /// virtual machine image. /// </summary> public bool? IsPremium { get { return this._isPremium; } set { this._isPremium = value; } } private string _label; /// <summary> /// Optional. The friendly name of the disk. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _location; /// <summary> /// Optional. The geo-location in which the disk is located. The /// Location value is derived from storage account that contains the /// blob in which the disk is located. If the storage account belongs /// to an affinity group the value is NULL. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private int _logicalSizeInGB; /// <summary> /// Optional. The size, in GB, of the disk. /// </summary> public int LogicalSizeInGB { get { return this._logicalSizeInGB; } set { this._logicalSizeInGB = value; } } private Uri _mediaLinkUri; /// <summary> /// Optional. The location of the blob in the blob store in which the /// media for the disk is located. The blob location belongs to a /// storage account in the subscription specified by the /// SubscriptionId value in the operation call. Example: /// http://example.blob.core.windows.net/disks/mydisk.vhd. /// </summary> public Uri MediaLinkUri { get { return this._mediaLinkUri; } set { this._mediaLinkUri = value; } } private string _name; /// <summary> /// Optional. The name of the disk. This is the name that is used when /// creating one or more virtual machines using the disk. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _operatingSystemType; /// <summary> /// Optional. The operating system type of the OS image. Possible /// Values are: Linux, Windows, or NULL. /// </summary> public string OperatingSystemType { get { return this._operatingSystemType; } set { this._operatingSystemType = value; } } private string _sourceImageName; /// <summary> /// Optional. The name of the OS Image from which the disk was created. /// This property is populated automatically when a disk is created /// from an OS image by calling the Add Role, Create Deployment, or /// Provision Disk operations. /// </summary> public string SourceImageName { get { return this._sourceImageName; } set { this._sourceImageName = value; } } private VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails _usageDetails; /// <summary> /// Optional. Contains properties that specify a virtual machine that /// is currently using the disk. A disk cannot be deleted as long as /// it is attached to a virtual machine. /// </summary> public VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails UsageDetails { get { return this._usageDetails; } set { this._usageDetails = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineDiskGetResponse /// class. /// </summary> public VirtualMachineDiskGetResponse() { } /// <summary> /// Contains properties that specify a virtual machine that currently /// using the disk. A disk cannot be deleted as long as it is attached /// to a virtual machine. /// </summary> public partial class VirtualMachineDiskUsageDetails { private string _deploymentName; /// <summary> /// Optional. The deployment in which the disk is being used. /// </summary> public string DeploymentName { get { return this._deploymentName; } set { this._deploymentName = value; } } private string _hostedServiceName; /// <summary> /// Optional. The hosted service in which the disk is being used. /// </summary> public string HostedServiceName { get { return this._hostedServiceName; } set { this._hostedServiceName = value; } } private string _roleName; /// <summary> /// Optional. The virtual machine that the disk is attached to. /// </summary> public string RoleName { get { return this._roleName; } set { this._roleName = value; } } /// <summary> /// Initializes a new instance of the /// VirtualMachineDiskUsageDetails class. /// </summary> public VirtualMachineDiskUsageDetails() { } } } }
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Firebase.Crashlytics.Editor { using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using UnityEditor.iOS.Xcode; /// <summary> /// Container for reflection-based method calls to add a Run Script Build Phase for the generated /// Xcode project to call the run script and upload symbols. /// </summary> public class iOSBuildPhaseMethodCall { public string MethodName; public Type [] ArgumentTypes; public object [] Arguments; } /// <summary> /// Editor script that generates a Run Script Build Phase for the Xcode project with the /// Crashlytics run script, and sets the Debug Information Format to Dwarf with DSYM to make it /// easier for customers to onboard. /// </summary> public class iOSPostBuild { private const string CRASHLYTICS_UNITY_VERSION_KEY = "CrashlyticsUnityVersion"; // In Unity 2019.3 - PODS_ROOT is no longer an environment variable that is exposed. // Use ${PROJECT_DIR}/Pods. private const string RunScriptBody = "chmod u+x \"${PROJECT_DIR}/Pods/FirebaseCrashlytics/run\"\n" + "chmod u+x \"${PROJECT_DIR}/Pods/FirebaseCrashlytics/upload-symbols\"\n" + "\"${PROJECT_DIR}/Pods/FirebaseCrashlytics/run\""; private const string GooglePlistPath = "${PROJECT_DIR}/GoogleService-Info.plist"; private const string RunScriptName = "Crashlytics Run Script"; private const string ShellPath = "/bin/sh -x"; /// <summary> /// When building out to iOS, write Firebase specific values to the appropriate Plist files. /// </summary> /// <param name="buildTarget"> /// The platform that we are targeting to build /// </param> /// <param name="buildPath"> /// The path to which we are building out /// </param> [PostProcessBuild(100)] public static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath) { // BuiltTarget.iOS is not defined in Unity 4, so we just use strings here if (buildTarget.ToString() == "iOS" || buildTarget.ToString() == "iPhone") { string projectPath = Path.Combine(buildPath, "Unity-iPhone.xcodeproj/project.pbxproj"); string plistPath = Path.Combine(buildPath, "Info.plist"); IFirebaseConfigurationStorage configurationStorage = StorageProvider.ConfigurationStorage; PrepareProject(projectPath, configurationStorage); AddCrashlyticsDevelopmentPlatformToPlist(plistPath); } } private static void PrepareProject(string projectPath, IFirebaseConfigurationStorage configurationStorage) { // Return if we have already added the script var xcodeProjectLines = File.ReadAllLines(projectPath); foreach (var line in xcodeProjectLines) { if (line.Contains("FirebaseCrashlytics/run")) { return; } } Debug.Log("Adding Crashlytics Run Script to the Xcode project's Build Phases"); var pbxProject = new UnityEditor.iOS.Xcode.PBXProject(); pbxProject.ReadFromFile(projectPath); string completeRunScriptBody = GetRunScriptBody(configurationStorage); string appGUID = iOSPostBuild.GetMainUnityProjectTargetGuid(pbxProject); SetupGUIDForSymbolUploads(pbxProject, completeRunScriptBody, appGUID); // In older versions of Unity there is no separate framework GUID, so this can // be empty or null. string frameworkGUID = iOSPostBuild.GetUnityFrameworkTargetGuid(pbxProject); if (!String.IsNullOrEmpty(frameworkGUID)) { SetupGUIDForSymbolUploads(pbxProject, completeRunScriptBody, frameworkGUID); } pbxProject.WriteToFile(projectPath); } private static void SetupGUIDForSymbolUploads(UnityEditor.iOS.Xcode.PBXProject pbxProject, string completeRunScriptBody, string targetGuid) { try { // Use reflection to append a Crashlytics Run Script BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public; CallingConventions callingConventions = CallingConventions.Any; ParameterModifier [] paramModifiers = new ParameterModifier [] { }; iOSBuildPhaseMethodCall methodCall = GetBuildPhaseMethodCall(Application.unityVersion, targetGuid, completeRunScriptBody); MethodInfo appendMethod = pbxProject.GetType().GetMethod( methodCall.MethodName, bindingFlags, null, callingConventions, methodCall.ArgumentTypes, paramModifiers); appendMethod.Invoke(pbxProject, methodCall.Arguments); } catch (Exception e) { Debug.LogWarning("Failed to add Crashlytics Run Script: '" + e.Message + "'. " + "You can manually fix this by adding a Run Script Build Phase to your Xcode " + "project with the following script:\n" + completeRunScriptBody); } finally { // Set debug information format to DWARF with DSYM pbxProject.SetBuildProperty(targetGuid, "DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym"); } } internal static iOSBuildPhaseMethodCall GetBuildPhaseMethodCall(string unityVersion, string targetGuid, string completeRunScriptBody) { if (VersionInfo.GetUnityMajorVersion(unityVersion) >= 2019) { Debug.Log("Using AddShellScriptBuildPhase to add the Crashlytics Run Script"); return new iOSBuildPhaseMethodCall { MethodName = "AddShellScriptBuildPhase", ArgumentTypes = new [] { typeof(string), typeof(string), typeof(string), typeof(string) }, Arguments = new object [] { targetGuid, RunScriptName, ShellPath, completeRunScriptBody }, }; } else { Debug.Log("Using AppendShellScriptBuildPhase to add the Crashlytics Run Script"); return new iOSBuildPhaseMethodCall { MethodName = "AppendShellScriptBuildPhase", ArgumentTypes = new [] { typeof(IEnumerable<string>), typeof(string), typeof(string), typeof(string) }, Arguments = new object [] { new [] { targetGuid }, RunScriptName, ShellPath, completeRunScriptBody }, }; } } private static string GetUnityFrameworkTargetGuid(UnityEditor.iOS.Xcode.PBXProject project) { // var project = (UnityEditor.iOS.Xcode.PBXProject)projectObj; MethodInfo getUnityFrameworkTargetGuid = project.GetType().GetMethod("GetUnityFrameworkTargetGuid"); // Starting in Unity 2019.3, TargetGuidByName is deprecated // Use reflection to call the GetUnityFrameworkTargetGuid method if it exists (it was added // ub 2019.3). if (getUnityFrameworkTargetGuid != null) { return (string)getUnityFrameworkTargetGuid.Invoke(project, new object[] {}); } else { // Hardcode the main target name "UnityFramework" because there isn't a way to get the // Unity Framework target name. string targetName = "UnityFramework"; MethodInfo targetGuidByName = project.GetType().GetMethod("TargetGuidByName"); if (targetGuidByName != null) { return (string)targetGuidByName.Invoke(project, new object[] { (object)targetName }); } else { return ""; } } } /// <summary> /// Get the main Unity project's target GUID /// The GUID is needed to manipulate the target, for example to add the run script build phase. /// </summary> /// <param name="projectObj">The project where the main target GUID will be read from</param> /// <returns>The main target GUID</returns> private static string GetMainUnityProjectTargetGuid(object projectObj) { var project = (UnityEditor.iOS.Xcode.PBXProject)projectObj; MethodInfo getUnityMainTargetGuid = project.GetType().GetMethod("GetUnityMainTargetGuid"); // Starting in Unity 2019.3, TargetGuidByName is deprecated // Use reflection to call the GetUnityMainTargetGuid method if it exists if (getUnityMainTargetGuid != null) { return (string)getUnityMainTargetGuid.Invoke(project, new object[] {}); } else { // Hardcode the main target name "Unity-iPhone" by default, just in case // GetUnityTargetName() is not available. string targetName = "Unity-iPhone"; MethodInfo getUnityTargetName = project.GetType().GetMethod("GetUnityTargetName"); if (getUnityTargetName != null) { targetName = (string) getUnityTargetName.Invoke(null, new object[] {}); } MethodInfo targetGuidByName = project.GetType().GetMethod("TargetGuidByName"); if (targetGuidByName != null) { return (string)targetGuidByName.Invoke(project, new object[] { (object)targetName }); } } return ""; } /// <summary> /// Generate the body of the iOS post build run script used to upload symbols /// </summary> /// <returns>Body of the iOS post build run script</returns> public static string GetRunScriptBody(IFirebaseConfigurationStorage configurationStorage) { string completeRunScriptBody = RunScriptBody; completeRunScriptBody = String.Format("{0} -gsp \"{1}\"", RunScriptBody, GooglePlistPath); return completeRunScriptBody; } private static void AddCrashlyticsDevelopmentPlatformToPlist(string plistPath) { string unityVersion = Application.unityVersion; Debug.Log(String.Format("Adding Unity Editor Version ({0}) to the Xcode project's Info.plist", unityVersion)); PlistDocument plist = new PlistDocument(); plist.ReadFromFile(plistPath); plist.root.SetString(CRASHLYTICS_UNITY_VERSION_KEY, unityVersion); plist.WriteToFile(plistPath); } } }
// 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.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { public sealed partial class ClientWebSocket : WebSocket { private enum InternalState { Created = 0, Connecting = 1, Connected = 2, Disposed = 3 } private readonly ClientWebSocketOptions _options; private WebSocketHandle _innerWebSocket; // may be mutable struct; do not make readonly // NOTE: this is really an InternalState value, but Interlocked doesn't support // operations on values of enum types. private int _state; public ClientWebSocket() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); WebSocketHandle.CheckPlatformSupport(); _state = (int)InternalState.Created; _options = new ClientWebSocketOptions(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } #region Properties public ClientWebSocketOptions Options { get { return _options; } } public override WebSocketCloseStatus? CloseStatus { get { if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.CloseStatus; } return null; } } public override string CloseStatusDescription { get { if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.CloseStatusDescription; } return null; } } public override string SubProtocol { get { if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.SubProtocol; } return null; } } public override WebSocketState State { get { // state == Connected or Disposed if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.State; } switch ((InternalState)_state) { case InternalState.Created: return WebSocketState.None; case InternalState.Connecting: return WebSocketState.Connecting; default: // We only get here if disposed before connecting Debug.Assert((InternalState)_state == InternalState.Disposed); return WebSocketState.Closed; } } } #endregion Properties public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri) { throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri)); } if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss) { throw new ArgumentException(SR.net_WebSockets_Scheme, nameof(uri)); } // Check that we have not started already var priorState = (InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created); if (priorState == InternalState.Disposed) { throw new ObjectDisposedException(GetType().FullName); } else if (priorState != InternalState.Created) { throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted); } _options.SetToReadOnly(); return ConnectAsyncCore(uri, cancellationToken); } private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken) { _innerWebSocket = WebSocketHandle.Create(); try { // Change internal state to 'connected' to enable the other methods if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting) { // Aborted/Disposed during connect. throw new ObjectDisposedException(GetType().FullName); } await _innerWebSocket.ConnectAsyncCore(uri, cancellationToken, _options).ConfigureAwait(false); } catch (Exception ex) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, ex); throw; } } public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); } public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.ReceiveAsync(buffer, cancellationToken); } public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); } public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); } public override void Abort() { if ((InternalState)_state == InternalState.Disposed) { return; } if (WebSocketHandle.IsValid(_innerWebSocket)) { _innerWebSocket.Abort(); } Dispose(); } public override void Dispose() { var priorState = (InternalState)Interlocked.Exchange(ref _state, (int)InternalState.Disposed); if (priorState == InternalState.Disposed) { // No cleanup required. return; } if (WebSocketHandle.IsValid(_innerWebSocket)) { _innerWebSocket.Dispose(); } } private void ThrowIfNotConnected() { if ((InternalState)_state == InternalState.Disposed) { throw new ObjectDisposedException(GetType().FullName); } else if ((InternalState)_state != InternalState.Connected) { throw new InvalidOperationException(SR.net_WebSockets_NotConnected); } } } }
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; namespace MaterialDesignThemes.Wpf.Transitions { /// <summary> /// The transitioner provides an easy way to move between content with a default in-place circular transition. /// </summary> public class Transitioner : Selector, IZIndexController { private Point? _nextTransitionOrigin; static Transitioner() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Transitioner), new FrameworkPropertyMetadata(typeof(Transitioner))); } /// <summary> /// Causes the the next slide to be displayed (affectively increments <see cref="Selector.SelectedIndex"/>). /// </summary> public static RoutedCommand MoveNextCommand = new RoutedCommand(); /// <summary> /// Causes the the previous slide to be displayed (affectively decrements <see cref="Selector.SelectedIndex"/>). /// </summary> public static RoutedCommand MovePreviousCommand = new RoutedCommand(); /// <summary> /// Moves to the first slide. /// </summary> public static RoutedCommand MoveFirstCommand = new RoutedCommand(); /// <summary> /// Moves to the last slide. /// </summary> public static RoutedCommand MoveLastCommand = new RoutedCommand(); public static readonly DependencyProperty AutoApplyTransitionOriginsProperty = DependencyProperty.Register( "AutoApplyTransitionOrigins", typeof(bool), typeof(Transitioner), new PropertyMetadata(default(bool))); /// <summary> /// If enabled, transition origins will be applied to wipes, according to where a transition was triggered from. For example, the mouse point where a user clicks a button. /// </summary> public bool AutoApplyTransitionOrigins { get => (bool)GetValue(AutoApplyTransitionOriginsProperty); set => SetValue(AutoApplyTransitionOriginsProperty, value); } public static readonly DependencyProperty DefaultTransitionOriginProperty = DependencyProperty.Register( "DefaultTransitionOrigin", typeof(Point), typeof(Transitioner), new PropertyMetadata(new Point(0.5, 0.5))); public Point DefaultTransitionOrigin { get => (Point)GetValue(DefaultTransitionOriginProperty); set => SetValue(DefaultTransitionOriginProperty, value); } public Transitioner() { CommandBindings.Add(new CommandBinding(MoveNextCommand, MoveNextHandler)); CommandBindings.Add(new CommandBinding(MovePreviousCommand, MovePreviousHandler)); CommandBindings.Add(new CommandBinding(MoveFirstCommand, MoveFirstHandler)); CommandBindings.Add(new CommandBinding(MoveLastCommand, MoveLastHandler)); AddHandler(TransitionerSlide.InTransitionFinished, new RoutedEventHandler(IsTransitionFinishedHandler)); Loaded += (sender, args) => { if (SelectedIndex != -1) ActivateFrame(SelectedIndex, -1); }; } protected override bool IsItemItsOwnContainerOverride(object item) { return item is TransitionerSlide; } protected override DependencyObject GetContainerForItemOverride() { return new TransitionerSlide(); } protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) { if (AutoApplyTransitionOrigins) _nextTransitionOrigin = GetNavigationSourcePoint(e); base.OnPreviewMouseLeftButtonDown(e); } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { var unselectedIndex = -1; if (e.RemovedItems.Count == 1) { unselectedIndex = Items.IndexOf(e.RemovedItems[0]); } var selectedIndex = 1; if (e.AddedItems.Count == 1) { selectedIndex = Items.IndexOf(e.AddedItems[0]); } ActivateFrame(selectedIndex, unselectedIndex); base.OnSelectionChanged(e); } private void IsTransitionFinishedHandler(object sender, RoutedEventArgs routedEventArgs) { foreach (var slide in Items.OfType<object>().Select(GetSlide).Where(s => s.State == TransitionerSlideState.Previous)) { slide.SetCurrentValue(TransitionerSlide.StateProperty, TransitionerSlideState.None); } } private void MoveNextHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) { if (AutoApplyTransitionOrigins) _nextTransitionOrigin = GetNavigationSourcePoint(executedRoutedEventArgs); SetCurrentValue(SelectedIndexProperty, Math.Min(Items.Count - 1, SelectedIndex + 1)); } private void MovePreviousHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) { if (AutoApplyTransitionOrigins) _nextTransitionOrigin = GetNavigationSourcePoint(executedRoutedEventArgs); SetCurrentValue(SelectedIndexProperty, Math.Max(0, SelectedIndex - 1)); } private void MoveFirstHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) { if (AutoApplyTransitionOrigins) _nextTransitionOrigin = GetNavigationSourcePoint(executedRoutedEventArgs); SetCurrentValue(SelectedIndexProperty, 0); } private void MoveLastHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) { if (AutoApplyTransitionOrigins) _nextTransitionOrigin = GetNavigationSourcePoint(executedRoutedEventArgs); SetCurrentValue(SelectedIndexProperty, Items.Count - 1); } private Point? GetNavigationSourcePoint(RoutedEventArgs executedRoutedEventArgs) { var sourceElement = executedRoutedEventArgs.OriginalSource as FrameworkElement; if (sourceElement == null || !IsAncestorOf(sourceElement) || !IsSafePositive(ActualWidth) || !IsSafePositive(ActualHeight) || !IsSafePositive(sourceElement.ActualWidth) || !IsSafePositive(sourceElement.ActualHeight)) return null; var transitionOrigin = sourceElement.TranslatePoint(new Point(sourceElement.ActualWidth / 2, sourceElement.ActualHeight), this); transitionOrigin = new Point(transitionOrigin.X / ActualWidth, transitionOrigin.Y / ActualHeight); return transitionOrigin; } private static bool IsSafePositive(double dubz) { return !double.IsNaN(dubz) && !double.IsInfinity(dubz) && dubz > 0.0; } private TransitionerSlide GetSlide(object item) { if (IsItemItsOwnContainer(item)) return (TransitionerSlide)item; return (TransitionerSlide)ItemContainerGenerator.ContainerFromItem(item); } private void ActivateFrame(int selectedIndex, int unselectedIndex) { if (!IsLoaded) return; TransitionerSlide oldSlide = null, newSlide = null; for (var index = 0; index < Items.Count; index++) { var slide = GetSlide(Items[index]); if (index == selectedIndex) { newSlide = slide; slide.SetCurrentValue(TransitionerSlide.StateProperty, TransitionerSlideState.Current); } else if (index == unselectedIndex) { oldSlide = slide; slide.SetCurrentValue(TransitionerSlide.StateProperty, TransitionerSlideState.Previous); } else { slide.SetCurrentValue(TransitionerSlide.StateProperty, TransitionerSlideState.None); } Panel.SetZIndex(slide, 0); } if (newSlide != null) { newSlide.Opacity = 1; } if (oldSlide != null && newSlide != null) { var wipe = selectedIndex > unselectedIndex ? oldSlide.ForwardWipe : oldSlide.BackwardWipe; if (wipe != null) { wipe.Wipe(oldSlide, newSlide, GetTransitionOrigin(newSlide), this); } else { DoStack(newSlide, oldSlide); } oldSlide.Opacity = 0; } else if (oldSlide != null || newSlide != null) { DoStack(oldSlide ?? newSlide); if (oldSlide != null) { oldSlide.Opacity = 0; } } _nextTransitionOrigin = null; } private Point GetTransitionOrigin(TransitionerSlide slide) { if (_nextTransitionOrigin != null) { return _nextTransitionOrigin.Value; } if (slide.ReadLocalValue(TransitionerSlide.TransitionOriginProperty) != DependencyProperty.UnsetValue) { return slide.TransitionOrigin; } return DefaultTransitionOrigin; } void IZIndexController.Stack(params TransitionerSlide[] highestToLowest) { DoStack(highestToLowest); } private static void DoStack(params TransitionerSlide[] highestToLowest) { if (highestToLowest == null) return; var pos = highestToLowest.Length; foreach (var slide in highestToLowest.Where(s => s != null)) { Panel.SetZIndex(slide, pos--); } } } }
// 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.Concurrent; using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { [OuterLoop] public static partial class ParallelQueryCombinationTests { private const int DefaultStart = 8; private const int DefaultSize = 16; private const int CountFactor = 8; private const int GroupFactor = 8; private static readonly Operation DefaultSource = (start, count, ignore) => ParallelEnumerable.Range(start, count); private static readonly Labeled<Operation> LabeledDefaultSource = Label("Default", DefaultSource); private static readonly Labeled<Operation> Failing = Label("ThrowOnFirstEnumeration", (start, count, source) => Enumerables<int>.ThrowOnEnumeration().AsParallel()); private static IEnumerable<Labeled<Operation>> UnorderedRangeSources() { // The difference between this and the existing sources is more control is needed over the range creation. // Specifically, start/count won't be known until the nesting level is resolved at runtime. yield return Label("ParallelEnumerable.Range", (start, count, ignore) => ParallelEnumerable.Range(start, count)); yield return Label("Enumerable.Range", (start, count, ignore) => Enumerable.Range(start, count).AsParallel()); yield return Label("Array", (start, count, ignore) => Enumerable.Range(start, count).ToArray().AsParallel()); yield return Label("List", (start, count, ignore) => Enumerable.Range(start, count).ToList().AsParallel()); yield return Label("Partitioner", (start, count, ignore) => Partitioner.Create(Enumerable.Range(start, count).ToArray()).AsParallel()); // PLINQ doesn't currently have any special code paths for readonly collections. If it ever does, this should be uncommented. // yield return Label("ReadOnlyCollection", (start, count, ignore) => new System.Collections.ReadOnlyCollection<int>(Enumerable.Range(start, count).ToList()).AsParallel()); } private static IEnumerable<Labeled<Operation>> RangeSources() { foreach (Labeled<Operation> source in UnorderedRangeSources()) { yield return source.AsOrdered(); foreach (Labeled<Operation> ordering in OrderOperators()) { yield return source.Append(ordering); } } } private static IEnumerable<Labeled<Operation>> OrderOperators() { yield return Label("OrderBy", (start, count, source) => source(start, count).OrderBy(x => x)); yield return Label("OrderByDescending", (start, count, source) => source(start, count).OrderByDescending(x => -x)); yield return Label("ThenBy", (start, count, source) => source(start, count).OrderBy(x => 0).ThenBy(x => x)); yield return Label("ThenByDescending", (start, count, source) => source(start, count).OrderBy(x => 0).ThenByDescending(x => -x)); } private static IEnumerable<Labeled<Operation>> ReverseOrderOperators() { yield return Label("OrderBy-Reversed", (start, count, source) => source(start, count).OrderBy(x => x, ReverseComparer.Instance)); yield return Label("OrderByDescending-Reversed", (start, count, source) => source(start, count).OrderByDescending(x => -x, ReverseComparer.Instance)); yield return Label("ThenBy-Reversed", (start, count, source) => source(start, count).OrderBy(x => 0).ThenBy(x => x, ReverseComparer.Instance)); yield return Label("ThenByDescending-Reversed", (start, count, source) => source(start, count).OrderBy(x => 0).ThenByDescending(x => -x, ReverseComparer.Instance)); } public static IEnumerable<object[]> OrderFailingOperators() { foreach (Labeled<Operation> operation in new[] { Label("OrderBy", (start, count, s) => s(start, count).OrderBy<int, int>(x => {throw new DeliberateTestException(); })), Label("OrderBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => x, new FailingComparer())), Label("OrderByDescending", (start, count, s) => s(start, count).OrderByDescending<int, int>(x => {throw new DeliberateTestException(); })), Label("OrderByDescending-Comparer", (start, count, s) => s(start, count).OrderByDescending(x => x, new FailingComparer())), Label("ThenBy", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy<int, int>(x => {throw new DeliberateTestException(); })), Label("ThenBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy(x => x, new FailingComparer())), Label("ThenByDescending", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending<int, int>(x => {throw new DeliberateTestException(); })), Label("ThenByDescending-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending(x => x, new FailingComparer())), }) { yield return new object[] { LabeledDefaultSource, operation }; } foreach (Labeled<Operation> operation in OrderOperators()) { yield return new object[] { Failing, operation }; } } public static IEnumerable<object[]> OrderCancelingOperators() { yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("OrderBy-Comparer", (source, cancel) => source.OrderBy(x => x, new CancelingComparer(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("OrderByDescending-Comparer", (source, cancel) => source.OrderByDescending(x => x, new CancelingComparer(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("ThenBy-Comparer", (source, cancel) => source.OrderBy(x => 0).ThenBy(x => x, new CancelingComparer(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("ThenByDescending-Comparer", (source, cancel) => source.OrderBy(x => 0).ThenByDescending(x => x, new CancelingComparer(cancel))) }; } public static IEnumerable<object[]> UnaryOperations() { yield return new object[] { Label("Cast", (start, count, source) => source(start, count).Cast<int>()) }; yield return new object[] { Label("DefaultIfEmpty", (start, count, source) => source(start, count).DefaultIfEmpty()) }; yield return new object[] { Label("Distinct", (start, count, source) => source(start * 2, count * 2).Select(x => x / 2).Distinct(new ModularCongruenceComparer(count))) }; yield return new object[] { Label("OfType", (start, count, source) => source(start, count).OfType<int>()) }; yield return new object[] { Label("Reverse", (start, count, source) => source(start, count).Reverse()) }; yield return new object[] { Label("GroupBy", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, new ModularCongruenceComparer(count)).Select(g => g.Key + start)) }; yield return new object[] { Label("GroupBy-ElementSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, new ModularCongruenceComparer(count)).Select(g => g.Min() - 1)) }; yield return new object[] { Label("GroupBy-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, (key, g) => key + start, new ModularCongruenceComparer(count))) }; yield return new object[] { Label("GroupBy-ElementSelector-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, (key, g) => g.Min() - 1, new ModularCongruenceComparer(count))) }; yield return new object[] { Label("Select", (start, count, source) => source(start - count, count).Select(x => x + count)) }; yield return new object[] { Label("Select-Index", (start, count, source) => source(start - count, count).Select((x, index) => x + count)) }; yield return new object[] { Label("SelectMany", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor)))) }; yield return new object[] { Label("SelectMany-Index", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor)))) }; yield return new object[] { Label("SelectMany-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element)) }; yield return new object[] { Label("SelectMany-Index-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element)) }; yield return new object[] { Label("Where", (start, count, source) => source(start - count / 2, count * 2).Where(x => x >= start && x < start + count)) }; yield return new object[] { Label("Where-Index", (start, count, source) => source(start - count / 2, count * 2).Where((x, index) => x >= start && x < start + count)) }; yield return new object[] { Label("WithCancellation", (start, count, source) => source(start, count).WithCancellation(CancellationToken.None)) }; yield return new object[] { Label("WithDegreesOfParallelism", (start, count, source) => source(start, count).WithDegreeOfParallelism(Environment.ProcessorCount)) }; yield return new object[] { Label("WithExecutionMode", (start, count, source) => source(start, count).WithExecutionMode(ParallelExecutionMode.Default)) }; yield return new object[] { Label("WithMergeOptions", (start, count, source) => source(start, count).WithMergeOptions(ParallelMergeOptions.Default)) }; } public static IEnumerable<object[]> UnaryUnorderedOperators() { foreach (Labeled<Operation> source in UnorderedRangeSources()) { foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0])) { yield return new object[] { source, operation }; } } } private static IEnumerable<Labeled<Operation>> SkipTakeOperations() { // Take/Skip-based operations require ordered input, or will disobey // the [start, start + count) convention expected in tests. yield return Label("Skip", (start, count, source) => source(start - count, count * 2).Skip(count)); yield return Label("SkipWhile", (start, count, source) => source(start - count, count * 2).SkipWhile(x => x < start)); yield return Label("SkipWhile-Index", (start, count, source) => source(start - count, count * 2).SkipWhile((x, index) => x < start)); yield return Label("Take", (start, count, source) => source(start, count * 2).Take(count)); yield return Label("TakeWhile", (start, count, source) => source(start, count * 2).TakeWhile(x => x < start + count)); yield return Label("TakeWhile-Index", (start, count, source) => source(start, count * 2).TakeWhile((x, index) => x < start + count)); } public static IEnumerable<object[]> SkipTakeOperators() { foreach (Labeled<Operation> source in RangeSources()) { foreach (Labeled<Operation> operation in SkipTakeOperations()) { yield return new object[] { source, operation }; } } } public static IEnumerable<object[]> UnaryOperators() { // Apply an ordered source to each operation foreach (Labeled<Operation> source in RangeSources()) { foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0]).Where(op => !op.ToString().Contains("Reverse"))) { yield return new object[] { source, operation }; } } Labeled<Operation> reverse = UnaryOperations().Select(i => (Labeled<Operation>)i[0]).Where(op => op.ToString().Contains("Reverse")).Single(); foreach (Labeled<Operation> source in UnorderedRangeSources()) { foreach (Labeled<Operation> ordering in ReverseOrderOperators()) { yield return new object[] { source.Append(ordering), reverse }; } } // Apply ordering to the output of each operation foreach (Labeled<Operation> source in UnorderedRangeSources()) { foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0])) { foreach (Labeled<Operation> ordering in OrderOperators()) { yield return new object[] { source, operation.Append(ordering) }; } } } foreach (object[] parms in SkipTakeOperators()) { yield return parms; } } public static IEnumerable<object[]> UnaryFailingOperators() { foreach (Labeled<Operation> operation in new[] { Label("Distinct", (start, count, s) => s(start, count).Distinct(new FailingEqualityComparer<int>())), Label("GroupBy", (start, count, s) => s(start, count).GroupBy<int, int>(x => {throw new DeliberateTestException(); }).Select(g => g.Key)), Label("GroupBy-Comparer", (start, count, s) => s(start, count).GroupBy(x => x, new FailingEqualityComparer<int>()).Select(g => g.Key)), Label("GroupBy-ElementSelector", (start, count, s) => s(start, count).GroupBy<int, int, int>(x => x, x => { throw new DeliberateTestException(); }).Select(g => g.Key)), Label("GroupBy-ResultSelector", (start, count, s) => s(start, count).GroupBy<int, int, int, int>(x => x, x => x, (x, g) => { throw new DeliberateTestException(); })), Label("Select", (start, count, s) => s(start, count).Select<int, int>(x => {throw new DeliberateTestException(); })), Label("Select-Index", (start, count, s) => s(start, count).Select<int, int>((x, index) => {throw new DeliberateTestException(); })), Label("SelectMany", (start, count, s) => s(start, count).SelectMany<int, int>(x => {throw new DeliberateTestException(); })), Label("SelectMany-Index", (start, count, s) => s(start, count).SelectMany<int, int>((x, index) => {throw new DeliberateTestException(); })), Label("SelectMany-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>(x => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })), Label("SelectMany-Index-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>((x, index) => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })), Label("SkipWhile", (start, count, s) => s(start, count).SkipWhile(x => {throw new DeliberateTestException(); })), Label("SkipWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })), Label("TakeWhile", (start, count, s) => s(start, count).TakeWhile(x => {throw new DeliberateTestException(); })), Label("TakeWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })), Label("Where", (start, count, s) => s(start, count).Where(x => {throw new DeliberateTestException(); })), Label("Where-Index", (start, count, s) => s(start, count).Where((x, index) => {throw new DeliberateTestException(); })), }) { yield return new object[] { LabeledDefaultSource, operation }; } foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0]).Cast<Labeled<Operation>>().Concat(SkipTakeOperations())) { yield return new object[] { Failing, operation }; } } public static IEnumerable<object[]> UnaryCancelingOperators() { yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Distinct", (source, cancel) => source.Distinct(new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupBy-Comparer", (source, cancel) => source.GroupBy(x => x, new CancelingEqualityComparer<int>(cancel)).Select(g => g.Key)) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany", (source, cancel) => source.SelectMany(x => { cancel(); return new[] { x }; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-Index", (source, cancel) => source.SelectMany((x, index) => { cancel(); return new[] { x }; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-ResultSelector", (source, cancel) => source.SelectMany(x => new[] { x }, (group, elem) => { cancel(); return elem; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-Index-ResultSelector", (source, cancel) => source.SelectMany((x, index) => new[] { x }, (group, elem) => { cancel(); return elem; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SkipWhile", (source, cancel) => source.SkipWhile(x => { cancel(); return true; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SkipWhile-Index", (source, cancel) => source.SkipWhile((x, index) => { cancel(); return true; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("TakeWhile", (source, cancel) => source.TakeWhile(x => { cancel(); return true; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("TakeWhile-Index", (source, cancel) => source.TakeWhile((x, index) => { cancel(); return true; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Where", (source, cancel) => source.Where(x => { cancel(); return true; })) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Where-Index", (source, cancel) => source.Where((x, index) => { cancel(); return true; })) }; } private static IEnumerable<Labeled<Operation>> BinaryOperations(Labeled<Operation> otherSource) { string label = otherSource.ToString(); Operation other = otherSource.Item; yield return Label("Concat-Right:" + label, (start, count, source) => source(start, count / 2).Concat(other(start + count / 2, count / 2 + count % 2))); yield return Label("Concat-Left:" + label, (start, count, source) => other(start, count / 2).Concat(source(start + count / 2, count / 2 + count % 2))); // Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined for unordered collections. yield return Label("Except-Right:" + label, (start, count, source) => source(start, count + count / 2).Except(other(start + count, count), new ModularCongruenceComparer(count * 2))); yield return Label("Except-Left:" + label, (start, count, source) => other(start, count + count / 2).Except(source(start + count, count), new ModularCongruenceComparer(count * 2))); yield return Label("GroupJoin-Right:" + label, (start, count, source) => source(start, count).GroupJoin(other(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count))); yield return Label("GroupJoin-Left:" + label, (start, count, source) => other(start, count).GroupJoin(source(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count))); // Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined. yield return Label("Intersect-Right:" + label, (start, count, source) => source(start, count + count / 2).Intersect(other(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2))); yield return Label("Intersect-Left:" + label, (start, count, source) => other(start, count + count / 2).Intersect(source(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2))); yield return Label("Join-Right:" + label, (start, count, source) => source(0, count).Join(other(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count))); yield return Label("Join-Left:" + label, (start, count, source) => other(0, count).Join(source(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count))); yield return Label("Union-Right:" + label, (start, count, source) => source(start, count * 3 / 4).Union(other(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count))); yield return Label("Union-Left:" + label, (start, count, source) => other(start, count * 3 / 4).Union(source(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count))); // When both sources are unordered any element can be matched to any other, so a different check is required. yield return Label("Zip-Unordered-Right:" + label, (start, count, source) => source(0, count).Zip(other(start * 2, count), (x, y) => x + start)); yield return Label("Zip-Unordered-Left:" + label, (start, count, source) => other(start * 2, count).Zip(source(0, count), (x, y) => y + start)); } public static IEnumerable<object[]> BinaryOperations() { return BinaryOperations(LabeledDefaultSource).Select(op => new object[] { op }); } public static IEnumerable<object[]> BinaryUnorderedOperators() { foreach (Labeled<Operation> source in UnorderedRangeSources()) { // Operations having multiple paths to check. foreach (Labeled<Operation> operation in BinaryOperations(LabeledDefaultSource)) { yield return new object[] { source, operation }; } } } public static IEnumerable<object[]> BinaryOperators() { foreach (Labeled<Operation> source in RangeSources()) { // Each binary can work differently, depending on which of the two source queries (or both) is ordered. // For most, only the ordering of the first query is important foreach (Labeled<Operation> operation in BinaryOperations(LabeledDefaultSource).Where(op => !(op.ToString().StartsWith("Union") || op.ToString().StartsWith("Zip") || op.ToString().StartsWith("Concat")) && op.ToString().Contains("Right"))) { yield return new object[] { source, operation }; } // For Concat and Union, both sources must be ordered foreach (var operation in BinaryOperations(RangeSources().First()).Where(op => op.ToString().StartsWith("Concat") || op.ToString().StartsWith("Union"))) { yield return new object[] { source, operation }; } // Zip is the same as Concat, but has a special check for matching indices (as compared to unordered) foreach (Labeled<Operation> operation in new[] { Label("Zip-Ordered-Right", (start, count, s) => s(0, count).Zip(DefaultSource(start * 2, count).AsOrdered(), (x, y) => (x + y) / 2)), Label("Zip-Ordered-Left", (start, count, s) => DefaultSource(start * 2, count).AsOrdered().Zip(s(0, count), (x, y) => (x + y) / 2)) }) { yield return new object[] { source, operation }; } } // Ordering the output should always be safe foreach (object[] parameters in BinaryUnorderedOperators()) { foreach (Labeled<Operation> ordering in OrderOperators()) { yield return new[] { parameters[0], ((Labeled<Operation>)parameters[1]).Append(ordering) }; } } } public static IEnumerable<object[]> BinaryFailingOperators() { Labeled<Operation> failing = Label("Failing", (start, count, s) => s(start, count).Select<int, int>(x => { throw new DeliberateTestException(); })); foreach (Labeled<Operation> operation in BinaryOperations(LabeledDefaultSource)) { yield return new object[] { LabeledDefaultSource.Append(failing), operation }; yield return new object[] { Failing, operation }; } foreach (Labeled<Operation> operation in new[] { Label("Except-Fail", (start, count, s) => s(start, count).Except(DefaultSource(start, count), new FailingEqualityComparer<int>())), Label("GroupJoin-Fail", (start, count, s) => s(start, count).GroupJoin(DefaultSource(start, count), x => x, y => y, (x, g) => x, new FailingEqualityComparer<int>())), Label("Intersect-Fail", (start, count, s) => s(start, count).Intersect(DefaultSource(start, count), new FailingEqualityComparer<int>())), Label("Join-Fail", (start, count, s) => s(start, count).Join(DefaultSource(start, count), x => x, y => y, (x, y) => x, new FailingEqualityComparer<int>())), Label("Union-Fail", (start, count, s) => s(start, count).Union(DefaultSource(start, count), new FailingEqualityComparer<int>())), Label("Zip-Fail", (start, count, s) => s(start, count).Zip<int, int, int>(DefaultSource(start, count), (x, y) => { throw new DeliberateTestException(); })), }) { yield return new object[] { LabeledDefaultSource, operation }; } } public static IEnumerable<object[]> BinaryCancelingOperators() { yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Except", (source, cancel) => source.Except(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Except-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Except(source, new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupJoin", (source, cancel) => source.GroupJoin(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, g) => x, new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupJoin-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).GroupJoin(source, x => x, y => y, (x, g) => x, new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Intersect", (source, cancel) => source.Intersect(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Intersect-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Intersect(source, new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Join", (source, cancel) => source.Join(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, y) => x, new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Join-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Join(source, x => x, y => y, (x, y) => x, new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Union", (source, cancel) => source.Union(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))) }; yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Union-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Union(source, new CancelingEqualityComparer<int>(cancel))) }; } public delegate ParallelQuery<int> Operation(int start, int count, Operation source = null); public static Labeled<Operation> Label(string label, Operation item) { return Labeled.Label(label, item); } public static Labeled<Operation> Append(this Labeled<Operation> item, Labeled<Operation> next) { Operation op = item.Item; Operation nxt = next.Item; return Label(item.ToString() + "|" + next.ToString(), (start, count, source) => nxt(start, count, (s, c, ignore) => op(s, c, source))); } public static Labeled<Operation> AsOrdered(this Labeled<Operation> query) { return query.Append(Label("AsOrdered", (start, count, source) => source(start, count).AsOrdered())); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using Microsoft.Test.ModuleCore; namespace XLinqTests { public class TreeManipulationTests : TestModule { [Fact] [OuterLoop] public static void ConstructorXDocument() { RunTestCase(new ParamsObjectsCreation { Attribute = new TestCaseAttribute { Name = "Constructors with params - XDocument" } }); } [Fact] [OuterLoop] public static void ConstructorXElementArray() { RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - array", Param = 0 } }); //Param = InputParamStyle.Array } [Fact] [OuterLoop] public static void ConstructorXElementIEnumerable() { RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - IEnumerable", Param = 2 } }); //InputParamStyle.IEnumerable } [Fact] [OuterLoop] public static void ConstructorXElementNodeArray() { RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - node + array", Param = 1 } }); //InputParamStyle.SingleAndArray } [Fact] [OuterLoop] public static void IEnumerableOfXAttributeRemove() { RunTestCase(new XAttributeEnumRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XAttribute>.Remove()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void IEnumerableOfXAttributeRemoveWithRemove() { RunTestCase(new XAttributeEnumRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XAttribute>.Remove() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void IEnumerableOfXNodeRemove() { RunTestCase(new XNodeSequenceRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XNode>.Remove()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void IEnumerableOfXNodeRemoveWithEvents() { RunTestCase(new XNodeSequenceRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XNode>.Remove() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void LoadFromReader() { RunTestCase(new LoadFromReader { Attribute = new TestCaseAttribute { Name = "Load from Reader" } }); } [Fact] [OuterLoop] public static void LoadFromStreamSanity() { RunTestCase(new LoadFromStream { Attribute = new TestCaseAttribute { Name = "Load from Stream - sanity" } }); } [Fact] [OuterLoop] public static void SaveWithWriter() { RunTestCase(new SaveWithWriter { Attribute = new TestCaseAttribute { Name = "Save with Writer" } }); } [Fact] [OuterLoop] public static void SimpleConstructors() { RunTestCase(new SimpleObjectsCreation { Attribute = new TestCaseAttribute { Name = "Simple constructors" } }); } [Fact] [OuterLoop] public static void XAttributeRemove() { RunTestCase(new XAttributeRemove { Attribute = new TestCaseAttribute { Name = "XAttribute.Remove", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XAttributeRemoveWithEvents() { RunTestCase(new XAttributeRemove { Attribute = new TestCaseAttribute { Name = "XAttribute.Remove with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerAddIntoElement() { RunTestCase(new XContainerAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.Add1", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerAddIntoDocument() { RunTestCase(new XContainerAddIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.Add2", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerAddFirstInvalidIntoXDocument() { RunTestCase(new AddFirstInvalidIntoXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirst", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerAddFirstInvalidIntoXDocumentWithEvents() { RunTestCase(new AddFirstInvalidIntoXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirst with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void AddFirstSingeNodeAddIntoElement() { RunTestCase(new AddFirstSingeNodeAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstSingeNodeAddIntoElement", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void AddFirstSingeNodeAddIntoElementWithEvents() { RunTestCase(new AddFirstSingeNodeAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstSingeNodeAddIntoElement with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void AddFirstAddFirstIntoDocument() { RunTestCase(new AddFirstAddFirstIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstAddFirstIntoDocument", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void AddFirstAddFirstIntoDocumentWithEvents() { RunTestCase(new AddFirstAddFirstIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstAddFirstIntoDocument with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerAddIntoElementWithEvents() { RunTestCase(new XContainerAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.Add with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerAddIntoDocumentWithEvents() { RunTestCase(new XContainerAddIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.Add with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerFirstNode() { RunTestCase(new FirstNode { Attribute = new TestCaseAttribute { Name = "XContainer.FirstNode", Param = true } }); } [Fact] [OuterLoop] public static void XContainerLastNode() { RunTestCase(new FirstNode { Attribute = new TestCaseAttribute { Name = "XContainer.LastNode", Param = false } }); } [Fact] [OuterLoop] public static void XContainerNextPreviousNode() { RunTestCase(new NextNode { Attribute = new TestCaseAttribute { Name = "XContainer.Next/PreviousNode" } }); } [Fact] [OuterLoop] public static void XContainerRemoveNodesOnXElement() { RunTestCase(new XContainerRemoveNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerRemoveNodesOnXElementWithEvents() { RunTestCase(new XContainerRemoveNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerRemoveNodesOnXDocument() { RunTestCase(new XContainerRemoveNodesOnXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerRemoveNodesOnXDocumentWithEvents() { RunTestCase(new XContainerRemoveNodesOnXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerReplaceNodesOnDocument() { RunTestCase(new XContainerReplaceNodesOnDocument { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXDocument()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerReplaceNodesOnDocumentWithEvents() { RunTestCase(new XContainerReplaceNodesOnDocument { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXDocument() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XContainerReplaceNodesOnXElement() { RunTestCase(new XContainerReplaceNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXElement()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XContainerReplaceNodesOnXElementWithEvents() { RunTestCase(new XContainerReplaceNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXElement() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XElementRemoveAttributes() { RunTestCase(new RemoveAttributes { Attribute = new TestCaseAttribute { Name = "XElement.RemoveAttributes", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XElementRemoveAttributesWithEvents() { RunTestCase(new RemoveAttributes { Attribute = new TestCaseAttribute { Name = "XElement.RemoveAttributes with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XElementSetAttributeValue() { RunTestCase(new XElement_SetAttributeValue { Attribute = new TestCaseAttribute { Name = "XElement.SetAttributeValue()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XElementSetAttributeValueWithEvents() { RunTestCase(new XElement_SetAttributeValue { Attribute = new TestCaseAttribute { Name = "XElement.SetAttributeValue() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XElementSetElementValue() { RunTestCase(new XElement_SetElementValue { Attribute = new TestCaseAttribute { Name = "XElement.SetElementValue()", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XElementSetElementValueWithEvents() { RunTestCase(new XElement_SetElementValue { Attribute = new TestCaseAttribute { Name = "XElement.SetElementValue() with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeAddAfter() { RunTestCase(new AddNodeAfter { Attribute = new TestCaseAttribute { Name = "XNode.AddAfter", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeAddAfterWithEvents() { RunTestCase(new AddNodeAfter { Attribute = new TestCaseAttribute { Name = "XNode.AddAfter with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeAddBefore() { RunTestCase(new AddNodeBefore { Attribute = new TestCaseAttribute { Name = "XNode.AddBefore", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeAddBeforeWithEvents() { RunTestCase(new AddNodeBefore { Attribute = new TestCaseAttribute { Name = "XNode.AddBefore with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeRemoveNodeMisc() { RunTestCase(new XNodeRemoveNodeMisc { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeRemoveNodeMiscWithEvents() { RunTestCase(new XNodeRemoveNodeMisc { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeRemoveOnDocument() { RunTestCase(new XNodeRemoveOnDocument { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeRemoveOnDocumentWithEvents() { RunTestCase(new XNodeRemoveOnDocument { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeRemoveOnElement() { RunTestCase(new XNodeRemoveOnElement { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeRemoveOnElementWithEvents() { RunTestCase(new XNodeRemoveOnElement { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnDocument1() { RunTestCase(new XNodeReplaceOnDocument1 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnDocument1WithEvents() { RunTestCase(new XNodeReplaceOnDocument1 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnDocument2() { RunTestCase(new XNodeReplaceOnDocument2 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnDocument2WithEvents() { RunTestCase(new XNodeReplaceOnDocument2 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnDocument3() { RunTestCase(new XNodeReplaceOnDocument3 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnDocument3WithEvents() { RunTestCase(new XNodeReplaceOnDocument3 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnElement() { RunTestCase(new XNodeReplaceOnElement { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } }); } [Fact] [OuterLoop] public static void XNodeReplaceOnElementWithEvents() { RunTestCase(new XNodeReplaceOnElement { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } }); } private static void RunTestCase(TestItem testCase) { var module = new TreeManipulationTests(); module.Init(); module.AddChild(testCase); module.Execute(); Assert.Equal(0, module.FailCount); } } }
using System; using System.IO; using System.Collections; using Server; using Server.Accounting; namespace Knives.Chat3 { public enum OnlineStatus { Online, Away, Busy, Hidden } public enum Skin { Three, Two, One } public class Data { #region Statics public static void Save() { try { SaveGlobalOptions(); } catch (Exception e) { Errors.Report(General.Local(175), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { SavePlayerOptions(); } catch (Exception e) { Errors.Report(General.Local(228), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { SaveFriends(); } catch (Exception e) { Errors.Report(General.Local(230), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { SaveIgnores(); } catch (Exception e) { Errors.Report(General.Local(232), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { SaveGlobalListens(); } catch (Exception e) { Errors.Report(General.Local(234), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { SaveMsgs(); } catch (Exception e) { Errors.Report(General.Local(236), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } } public static void Load() { try { LoadGlobalOptions(); } catch (Exception e) { Errors.Report(General.Local(174), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { LoadPlayerOptions(); } catch (Exception e) { Errors.Report(General.Local(227), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { LoadFriends(); } catch (Exception e) { Errors.Report(General.Local(229), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { LoadIgnores(); } catch (Exception e) { Errors.Report(General.Local(231), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { LoadGlobalListens(); } catch (Exception e) { Errors.Report(General.Local(233), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } try { LoadMsgs(); } catch (Exception e) { Errors.Report(General.Local(235), e); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } } public static void SaveGlobalOptions() { CleanUpData(); if (!Directory.Exists(General.SavePath)) Directory.CreateDirectory(General.SavePath); GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "GlobalOptions.bin"), true); writer.Write(2); // version writer.Write(s_MultiPort); writer.Write(s_MultiServer); writer.Write(s_Notifications.Count); foreach (Notification not in s_Notifications) not.Save(writer); writer.Write(s_Filters.Count); foreach (string str in s_Filters) writer.Write(str); writer.Write((int)s_FilterPenalty); writer.Write((int)s_MacroPenalty); writer.Write(s_MaxMsgs); writer.Write(s_ChatSpam); writer.Write(s_MsgSpam); writer.Write(s_RequestSpam); writer.Write(s_FilterBanLength); writer.Write(s_FilterWarnings); writer.Write(s_AntiMacroDelay); writer.Write(s_IrcPort); writer.Write(s_IrcMaxAttempts); writer.Write(s_IrcEnabled); writer.Write(s_IrcAutoConnect); writer.Write(s_IrcAutoReconnect); writer.Write(s_FilterSpeech); writer.Write(s_FilterMsg); writer.Write(s_Debug); writer.Write(s_LogChat); writer.Write(s_LogPms); writer.Write((int)s_IrcStaffColor); writer.Write(s_IrcServer); writer.Write(s_IrcRoom); writer.Write(s_IrcNick); writer.Write(s_TotalChats+1); writer.Close(); } public static void SavePlayerOptions() { if (!Directory.Exists(General.SavePath)) Directory.CreateDirectory(General.SavePath); GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "PlayerOptions.bin"), true); writer.Write(0); // version writer.Write(s_Datas.Count); foreach (Data data in s_Datas.Values) { writer.Write(data.Mobile); data.SaveOptions(writer); } writer.Close(); } public static void SaveFriends() { if (!Directory.Exists(General.SavePath)) Directory.CreateDirectory(General.SavePath); GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Friends.bin"), true); writer.Write(0); // version writer.Write(s_Datas.Count); foreach (Data data in s_Datas.Values) { writer.Write(data.Mobile); data.SaveFriends(writer); } writer.Close(); } public static void SaveIgnores() { if (!Directory.Exists(General.SavePath)) Directory.CreateDirectory(General.SavePath); GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Ignores.bin"), true); writer.Write(0); // version writer.Write(s_Datas.Count); foreach (Data data in s_Datas.Values) { writer.Write(data.Mobile); data.SaveIgnores(writer); } writer.Close(); } public static void SaveGlobalListens() { if (!Directory.Exists(General.SavePath)) Directory.CreateDirectory(General.SavePath); GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "GlobalListens.bin"), true); writer.Write(0); // version writer.Write(s_Datas.Count); foreach (Data data in s_Datas.Values) { writer.Write(data.Mobile); data.SaveGlobalListens(writer); } writer.Close(); } public static void SaveMsgs() { if (!Directory.Exists(General.SavePath)) Directory.CreateDirectory(General.SavePath); GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Pms.bin"), true); writer.Write(0); // version writer.Write(s_Datas.Count); foreach (Data data in s_Datas.Values) { writer.Write(data.Mobile); data.SaveMsgs(writer); } writer.Close(); } public static void LoadGlobalOptions() { if (!File.Exists(Path.Combine(General.SavePath, "GlobalOptions.bin"))) return; using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "GlobalOptions.bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); int version = reader.ReadInt(); if (version >= 2) s_MultiPort = reader.ReadInt(); if (version >= 2) s_MultiServer = reader.ReadString(); int count = 0; if (version >= 1) { count = reader.ReadInt(); Notification not = null; for (int i = 0; i < count; ++i) { not = new Notification(); not.Load(reader); } } count = reader.ReadInt(); string txt = ""; for (int i = 0; i < count; ++i) { txt = reader.ReadString(); if(!s_Filters.Contains(txt)) s_Filters.Add(txt); } s_FilterPenalty = (FilterPenalty)reader.ReadInt(); if(version >= 1) s_MacroPenalty = (MacroPenalty)reader.ReadInt(); s_MaxMsgs = reader.ReadInt(); s_ChatSpam = reader.ReadInt(); s_MsgSpam = reader.ReadInt(); s_RequestSpam = reader.ReadInt(); s_FilterBanLength = reader.ReadInt(); s_FilterWarnings = reader.ReadInt(); if (version >= 1) s_AntiMacroDelay = reader.ReadInt(); s_IrcPort = reader.ReadInt(); s_IrcMaxAttempts = reader.ReadInt(); s_IrcEnabled = reader.ReadBool(); s_IrcAutoConnect = reader.ReadBool(); s_IrcAutoReconnect = reader.ReadBool(); s_FilterSpeech = reader.ReadBool(); s_FilterMsg = reader.ReadBool(); s_Debug = reader.ReadBool(); s_LogChat = reader.ReadBool(); s_LogPms = reader.ReadBool(); s_IrcStaffColor = (IrcColor)reader.ReadInt(); s_IrcServer = reader.ReadString(); s_IrcRoom = reader.ReadString(); s_IrcNick = reader.ReadString(); s_TotalChats = reader.ReadULong() - 1; } } public static void LoadPlayerOptions() { if (!File.Exists(Path.Combine(General.SavePath, "PlayerOptions.bin"))) return; using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "PlayerOptions.bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); int version = reader.ReadInt(); Mobile m = null; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m = reader.ReadMobile(); if (m != null) GetData(m).LoadOptions(reader); else (new Data()).LoadOptions(reader); } } } public static void LoadFriends() { if (!File.Exists(Path.Combine(General.SavePath, "Friends.bin"))) return; using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "Friends.bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); int version = reader.ReadInt(); Mobile m = null; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m = reader.ReadMobile(); if (m != null) GetData(m).LoadFriends(reader); else (new Data()).LoadFriends(reader); } } } public static void LoadIgnores() { if (!File.Exists(Path.Combine(General.SavePath, "Ignores.bin"))) return; using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "Ignores.bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); int version = reader.ReadInt(); Mobile m = null; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m = reader.ReadMobile(); if (m != null) GetData(m).LoadIgnores(reader); else (new Data()).LoadIgnores(reader); } } } public static void LoadGlobalListens() { if (!File.Exists(Path.Combine(General.SavePath, "GlobalListens.bin"))) return; using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "GlobalListens.bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); int version = reader.ReadInt(); Mobile m = null; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m = reader.ReadMobile(); if (m != null) GetData(m).LoadGlobalListens(reader); else (new Data()).LoadGlobalListens(reader); } } } public static void LoadMsgs() { if (!File.Exists(Path.Combine(General.SavePath, "Pms.bin"))) return; using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "Pms.bin"), FileMode.Open, FileAccess.Read, FileShare.Read)) { GenericReader reader = new BinaryFileReader(new BinaryReader(bin)); int version = reader.ReadInt(); Mobile m = null; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m = reader.ReadMobile(); if (m != null) GetData(m).LoadMsgs(reader); else (new Data()).LoadMsgs(reader); } } } private static void CleanUpData() { Data data = null; foreach (Mobile m in new ArrayList(s_Datas.Keys)) { data = (Data)s_Datas[m]; if (m.Deleted || data.Mobile == null || data.Mobile.Deleted) s_Datas.Remove(data.Mobile); else if (data.Mobile.Player && data.Mobile.Account != null && ((Account)data.Mobile.Account).LastLogin < DateTime.Now - TimeSpan.FromDays(30)) s_Datas.Remove(data.Mobile); } } #endregion #region Static Definitions private static Hashtable s_Datas = new Hashtable(); private static ArrayList s_Notifications = new ArrayList(); private static ArrayList s_MultiBlocks = new ArrayList(); private static ArrayList s_Filters = new ArrayList(); private static ArrayList s_IrcList = new ArrayList(); private static FilterPenalty s_FilterPenalty; private static MacroPenalty s_MacroPenalty; private static int s_MaxMsgs = 50; private static int s_ChatSpam = 2; private static int s_MsgSpam = 5; private static int s_RequestSpam = 24; private static int s_FilterBanLength = 5; private static int s_FilterWarnings = 3; private static int s_AntiMacroDelay = 60; private static int s_IrcPort = 6667; private static int s_IrcMaxAttempts = 3; private static int s_MultiPort = 8112; private static ulong s_TotalChats; private static bool s_IrcEnabled = false; private static bool s_IrcAutoConnect = false; private static bool s_IrcAutoReconnect = false; private static bool s_MultiMaster = false; private static bool s_FilterSpeech = false; private static bool s_FilterMsg = false; private static bool s_Debug = false; private static bool s_LogChat = false; private static bool s_LogPms = false; private static IrcColor s_IrcStaffColor = IrcColor.Black; private static string s_IrcServer = ""; private static string s_IrcRoom = ""; private static string s_IrcNick = Server.Misc.ServerList.ServerName; private static string s_MultiServer = "127.0.0.1"; public static Hashtable Datas { get { return s_Datas; } } public static ArrayList Notifications { get { return s_Notifications; } } public static ArrayList MultiBlocks { get { return s_MultiBlocks; } } public static ArrayList Filters { get { return s_Filters; } } public static ArrayList IrcList { get { return s_IrcList; } } public static FilterPenalty FilterPenalty { get { return s_FilterPenalty; } set { s_FilterPenalty = value; } } public static MacroPenalty MacroPenalty { get { return s_MacroPenalty; } set { s_MacroPenalty = value; } } public static int MaxMsgs { get { return s_MaxMsgs; } set { s_MaxMsgs = value; } } public static int ChatSpam { get { return s_ChatSpam; } set { s_ChatSpam = value; } } public static int MsgSpam { get { return s_MsgSpam; } set { s_MsgSpam = value; } } public static int RequestSpam { get { return s_RequestSpam; } set { s_RequestSpam = value; } } public static int FilterBanLength { get { return s_FilterBanLength; } set { s_FilterBanLength = value; } } public static int FilterWarnings { get { return s_FilterWarnings; } set { s_FilterWarnings = value; } } public static int AntiMacroDelay { get { return s_AntiMacroDelay; } set { s_AntiMacroDelay = value; } } public static int IrcPort { get { return s_IrcPort; } set { s_IrcPort = value; } } public static int IrcMaxAttempts { get { return s_IrcMaxAttempts; } set { s_IrcMaxAttempts = value; } } public static int MultiPort { get { return s_MultiPort; } set { s_MultiPort = value; } } public static ulong TotalChats { get { return s_TotalChats; } set { s_TotalChats = value; } } public static bool IrcAutoConnect { get { return s_IrcAutoConnect; } set { s_IrcAutoConnect = value; } } public static bool IrcAutoReconnect { get { return s_IrcAutoReconnect; } set { s_IrcAutoReconnect = value; } } public static bool FilterSpeech { get { return s_FilterSpeech; } set { s_FilterSpeech = value; } } public static bool FilterMsg { get { return s_FilterMsg; } set { s_FilterMsg = value; } } public static bool Debug { get { return s_Debug; } set { s_Debug = value; } } public static bool LogChat { get { return s_LogChat; } set { s_LogChat = value; } } public static bool LogPms { get { return s_LogPms; } set { s_LogPms = value; } } public static string IrcServer { get { return s_IrcServer; } set { s_IrcServer = value; } } public static string IrcNick { get { return s_IrcNick; } set { s_IrcNick = value; } } public static string MultiServer { get { return s_MultiServer; } set { s_MultiServer = value; } } public static bool IrcEnabled { get { return s_IrcEnabled; } set { s_IrcEnabled = value; if (!value) { IrcConnection.Connection.CancelConnect(); IrcConnection.Connection.Disconnect(false); } } } public static bool MultiMaster { get { return s_MultiMaster; } set { s_MultiMaster = value; if (!value) { MultiConnection.Connection.CloseMaster(); MultiConnection.Connection.CloseSlave(); } } } public static IrcColor IrcStaffColor { get { return s_IrcStaffColor; } set { if ((int)value > 15) value = (IrcColor)0; if ((int)value < 0) value = (IrcColor)15; s_IrcStaffColor = value; } } public static Data GetData(Mobile m) { if (s_Datas[m] == null) return new Data(m); return (Data)s_Datas[m]; } public static string IrcRoom { get { return s_IrcRoom; } set { s_IrcRoom = value; if (s_IrcRoom.IndexOf("#") != 0) s_IrcRoom = "#" + s_IrcRoom; } } #endregion #region Class Definitions private Mobile c_Mobile; private Channel c_CurrentChannel; private OnlineStatus c_Status; private Skin c_MenuSkin; private object c_Recording; private ArrayList c_Friends, c_Ignores, c_Messages, c_GIgnores, c_GListens, c_IrcIgnores; private Hashtable c_Sounds; private int c_GlobalMC, c_GlobalCC, c_GlobalGC, c_GlobalFC, c_GlobalWC, c_SystemC, c_MultiC, c_MsgC, c_PerPage, c_DefaultSound, c_StaffC, c_Avatar, c_Karma, c_Warnings; private bool c_GlobalAccess, c_Global, c_GlobalM, c_GlobalC, c_GlobalG, c_GlobalF, c_GlobalW, c_Banned, c_FriendsOnly, c_MsgSound, c_ByRequest, c_FriendAlert, c_SevenDays, c_WhenFull, c_ReadReceipt, c_IrcRaw, c_QuickBar, c_ExtraPm; private string c_AwayMsg, c_Signature; private DateTime c_BannedUntil, c_LastKarma; public Mobile Mobile { get { return c_Mobile; } } public Channel CurrentChannel { get { return c_CurrentChannel; } set { c_CurrentChannel = value; } } public OnlineStatus Status { get { return c_Status; } set { c_Status = value; } } public Skin MenuSkin { get { return c_MenuSkin; } set { c_MenuSkin = value; } } public object Recording{ get{ return c_Recording; } set{ c_Recording = value; } } public ArrayList Friends { get { return c_Friends; } } public ArrayList Ignores { get { return c_Ignores; } } public ArrayList Messages { get { return c_Messages; } } public ArrayList GIgnores { get { return c_GIgnores; } } public ArrayList GListens { get { return c_GListens; } } public ArrayList IrcIgnores { get { return c_IrcIgnores; } } public bool Global { get { return c_Global; } set { c_Global = value; } } public bool GlobalM { get { return c_GlobalM && c_Global; } set { c_GlobalM = value; } } public bool GlobalC { get { return c_GlobalC && c_Global; } set { c_GlobalC = value; } } public bool GlobalG { get { return c_GlobalG && c_Global; } set { c_GlobalG = value; } } public bool GlobalF { get { return c_GlobalF && c_Global; } set { c_GlobalF = value; } } public bool GlobalW { get { return c_GlobalW && c_Global; } set { c_GlobalW = value; } } public bool FriendsOnly { get { return c_FriendsOnly; } set { c_FriendsOnly = value; } } public bool MsgSound { get { return c_MsgSound; } set { c_MsgSound = value; } } public bool ByRequest { get { return c_ByRequest; } set { c_ByRequest = value; } } public bool FriendAlert { get { return c_FriendAlert; } set { c_FriendAlert = value; } } public bool SevenDays { get { return c_SevenDays; } set { c_SevenDays = value; } } public bool WhenFull { get { return c_WhenFull; } set { c_WhenFull = value; } } public bool ReadReceipt { get { return c_ReadReceipt; } set { c_ReadReceipt = value; } } public bool IrcRaw { get { return c_IrcRaw; } set { c_IrcRaw = value; } } public bool QuickBar { get { return c_QuickBar; } set { c_QuickBar = value; } } public bool ExtraPm { get { return c_ExtraPm; } set { c_ExtraPm = value; } } public int GlobalMC { get { return c_GlobalMC; } set { c_GlobalMC = value; } } public int GlobalCC { get { return c_GlobalCC; } set { c_GlobalCC = value; } } public int GlobalGC { get { return c_GlobalGC; } set { c_GlobalGC = value; } } public int GlobalFC { get { return c_GlobalFC; } set { c_GlobalFC = value; } } public int GlobalWC { get { return c_GlobalWC; } set { c_GlobalWC = value; } } public int SystemC { get { return c_SystemC; } set { c_SystemC = value; } } public int MultiC { get { return c_MultiC; } set { c_MultiC = value; } } public int MsgC { get { return c_MsgC; } set { c_MsgC = value; } } public int StaffC { get { return c_StaffC; } set { c_StaffC = value; } } public int Avatar { get { return c_Avatar; } set { c_Avatar = value; } } public int Warnings { get { return c_Warnings; } set { c_Warnings = value; } } public string AwayMsg { get { return c_AwayMsg; } set { c_AwayMsg = value; } } public string Signature { get { return c_Signature; } set { c_Signature = value; c_Mobile.SendMessage(c_SystemC, General.Local(246));} } public int Karma { get { return c_Karma; } set { if (c_LastKarma + TimeSpan.FromHours(24) > DateTime.Now) return; c_Karma = value; c_LastKarma = DateTime.Now; } } public int PerPage { get { return c_PerPage; } set { c_PerPage = value; if (c_PerPage < 5) c_PerPage = 5; if (c_PerPage > 15) c_PerPage = 15; } } public int DefaultSound { get { return c_DefaultSound; } set { foreach (Mobile m in c_Sounds.Keys) if ((int)c_Sounds[m] == c_DefaultSound) c_Sounds[m] = value; c_DefaultSound = value; if (c_DefaultSound < 0) c_DefaultSound = 0; } } public bool GlobalAccess { get { return c_GlobalAccess || c_Mobile.AccessLevel >= AccessLevel.Administrator; } set { c_GlobalAccess = value; if (value) c_Mobile.SendMessage(c_SystemC, General.Local(92)); else c_Mobile.SendMessage(c_SystemC, General.Local(93)); } } public bool Banned { get{ return c_Banned; } set { c_Banned = value; if (value) c_Mobile.SendMessage(c_SystemC, General.Local(90)); else c_Mobile.SendMessage(c_SystemC, General.Local(91)); } } public int DefaultBack { get { switch (c_MenuSkin) { case Skin.Three: return 0x1400; case Skin.Two: return 0x13BE; default: return 0xE10; } } } #endregion #region Constructors public Data(Mobile m) { c_Mobile = m; c_Friends = new ArrayList(); c_Ignores = new ArrayList(); c_Messages = new ArrayList(); c_GIgnores = new ArrayList(); c_GListens = new ArrayList(); c_IrcIgnores = new ArrayList(); c_Sounds = new Hashtable(); c_PerPage = 10; c_SystemC = 0x161; c_GlobalMC = 0x26; c_GlobalCC = 0x47E; c_GlobalGC = 0x44; c_GlobalFC = 0x17; c_GlobalWC = 0x3; c_StaffC = 0x3B4; c_MsgC = 0x480; c_AwayMsg = ""; c_Signature = ""; c_BannedUntil = DateTime.Now; if (m.AccessLevel >= AccessLevel.Administrator) c_GlobalAccess = true; s_Datas[m] = this; foreach (Channel c in Channel.Channels) if (c.NewChars) c.Join(m); } public Data() { c_Friends = new ArrayList(); c_Ignores = new ArrayList(); c_Messages = new ArrayList(); c_GIgnores = new ArrayList(); c_GListens = new ArrayList(); c_IrcIgnores = new ArrayList(); c_Sounds = new Hashtable(); c_PerPage = 10; c_SystemC = 0x161; c_GlobalMC = 0x26; c_GlobalCC = 0x47E; c_GlobalGC = 0x44; c_GlobalFC = 0x17; c_GlobalWC = 0x3; c_StaffC = 0x3B4; c_MsgC = 0x480; c_AwayMsg = ""; c_Signature = ""; c_BannedUntil = DateTime.Now; } #endregion #region Methods public bool NewMsg() { foreach (Message msg in c_Messages) if (!msg.Read) return true; return false; } public bool NewMsgFrom(Mobile m) { foreach (Message msg in c_Messages) if (!msg.Read && msg.From == m) return true; return false; } public Message GetNewMsgFrom(Mobile m) { foreach (Message msg in c_Messages) if (!msg.Read && msg.From == m) return msg; return null; } public void CheckMsg() { foreach( Message msg in c_Messages ) if (!msg.Read) { new MessageGump(c_Mobile, msg); return; } } public Message GetMsg() { if (c_Messages.Count == 0) return null; return (Message)c_Messages[c_Messages.Count - 1]; } public void CheckMsgFrom(Mobile m) { foreach(Message msg in c_Messages) if (!msg.Read && msg.From == m) { new MessageGump(c_Mobile, msg); return; } } public int GetSound(Mobile m) { if (c_Sounds[m] == null) c_Sounds[m] = c_DefaultSound; return (int)c_Sounds[m]; } public void SetSound(Mobile m, int num) { if (num < 0) num = 0; c_Sounds[m] = num; } public void AddFriend(Mobile m) { if (c_Friends.Contains(m) || m == c_Mobile) return; c_Friends.Add(m); c_Mobile.SendMessage(c_SystemC, m.Name + " " + General.Local(73)); } public void RemoveFriend(Mobile m) { if (!c_Friends.Contains(m)) return; c_Friends.Remove(m); c_Mobile.SendMessage(c_SystemC, m.Name + " " + General.Local(72)); } public void AddIgnore(Mobile m) { if (c_Mobile == m) return; if (c_Ignores.Contains(m) || m == c_Mobile) return; c_Ignores.Add(m); c_Mobile.SendMessage(c_SystemC, General.Local(68) + " " + m.Name); } public void RemoveIgnore(Mobile m) { if (!c_Ignores.Contains(m)) return; c_Ignores.Remove(m); c_Mobile.SendMessage(c_SystemC, General.Local(74) + " " + m.Name); } public void AddGIgnore(Mobile m) { if (c_GIgnores.Contains(m)) return; c_GIgnores.Add(m); c_Mobile.SendMessage(c_SystemC, General.Local(80) + " " + m.Name); } public void RemoveGIgnore(Mobile m) { if (!c_GIgnores.Contains(m)) return; c_GIgnores.Remove(m); c_Mobile.SendMessage(c_SystemC, General.Local(79) + " " + m.Name); } public void AddGListen(Mobile m) { if (c_GListens.Contains(m)) return; c_GListens.Add(m); c_Mobile.SendMessage(c_SystemC, General.Local(82) + " " + m.Name); } public void RemoveGListen(Mobile m) { if (!c_GListens.Contains(m)) return; c_GListens.Remove(m); c_Mobile.SendMessage(c_SystemC, General.Local(81) + " " + m.Name); } public void AddIrcIgnore(string str) { if (c_IrcIgnores.Contains(str)) return; c_IrcIgnores.Add(str); c_Mobile.SendMessage(c_SystemC, General.Local(68) + " " + str); } public void RemoveIrcIgnore(string str) { if (!c_IrcIgnores.Contains(str)) return; c_IrcIgnores.Remove(str); c_Mobile.SendMessage(c_SystemC, General.Local(74) + " " + str); } public void AddMessage(Message msg) { c_Messages.Add(msg); if(c_MsgSound) c_Mobile.SendSound(GetSound(msg.From)); if (c_WhenFull && c_Messages.Count > s_MaxMsgs) c_Messages.RemoveAt(0); } public void DeleteMessage(Message msg) { c_Messages.Remove(msg); c_Mobile.SendMessage(c_SystemC, General.Local(69)); } public void Ban(TimeSpan ts) { c_BannedUntil = DateTime.Now + ts; c_Banned = true; Mobile.SendMessage(c_SystemC, General.Local(90)); Timer.DelayCall(ts, new TimerCallback(RemoveBan)); } public void RemoveBan() { c_BannedUntil = DateTime.Now; c_Banned = false; if(Mobile != null) Mobile.SendMessage(c_SystemC, General.Local(91)); } public void AvatarUp() { if (c_Avatar == 0) { c_Avatar = (int)Chat3.Avatar.AvaKeys[0]; return; } ArrayList list = new ArrayList(Chat3.Avatar.AvaKeys); for (int i = 0; i < list.Count; ++i) if (c_Avatar == (int)list[i]) { if (i == list.Count - 1) { c_Avatar = (int)list[0]; return; } c_Avatar = (int)list[i + 1]; return; } } public void AvatarDown() { if (c_Avatar == 0) { c_Avatar = (int)Chat3.Avatar.AvaKeys[0]; return; } ArrayList list = new ArrayList(Chat3.Avatar.AvaKeys); for (int i = 0; i < list.Count; ++i) if (c_Avatar == (int)list[i]) { if (i == 0) { c_Avatar = (int)list[list.Count - 1]; return; } c_Avatar = (int)list[i - 1]; return; } } public void SaveOptions(GenericWriter writer) { writer.Write(3); // Version writer.Write(c_MultiC); writer.Write(c_Karma); writer.Write(c_ReadReceipt); writer.Write(c_QuickBar); writer.Write(c_ExtraPm); writer.Write((int)c_Status); foreach (Mobile m in new ArrayList(c_Sounds.Keys)) if (m.Deleted) c_Sounds.Remove(m); writer.Write(c_Sounds.Count); foreach (Mobile m in c_Sounds.Keys) { writer.Write(m); writer.Write((int)c_Sounds[m]); } writer.Write(c_GlobalMC); writer.Write(c_GlobalCC); writer.Write(c_GlobalGC); writer.Write(c_GlobalFC); writer.Write(c_GlobalWC); writer.Write(c_SystemC); writer.Write(c_MsgC); writer.Write(c_PerPage); writer.Write(c_DefaultSound); writer.Write(c_StaffC); writer.Write(c_Avatar); writer.Write((int)c_MenuSkin); writer.Write(c_GlobalAccess); writer.Write(c_Global); writer.Write(c_GlobalM); writer.Write(c_GlobalC); writer.Write(c_GlobalG); writer.Write(c_GlobalF); writer.Write(c_GlobalW); writer.Write(c_Banned); writer.Write(c_FriendsOnly); writer.Write(c_MsgSound); writer.Write(c_ByRequest); writer.Write(c_FriendAlert); writer.Write(c_SevenDays); writer.Write(c_WhenFull); writer.Write(c_IrcRaw); writer.Write(c_AwayMsg); writer.Write(c_Signature); writer.Write(c_BannedUntil); } public void SaveFriends(GenericWriter writer) { writer.Write(1); // Version writer.WriteMobileList(c_Friends, true); } public void SaveIgnores(GenericWriter writer) { writer.Write(1); // Version writer.WriteMobileList(c_Ignores, true); } public void SaveMsgs(GenericWriter writer) { writer.Write(1); // Version foreach (Message msg in new ArrayList(c_Messages)) if (msg.From.Deleted ) c_Messages.Remove(msg); writer.Write(c_Messages.Count); foreach (Message msg in c_Messages) msg.Save(writer); } public void SaveGlobalListens(GenericWriter writer) { writer.Write(1); // Version writer.WriteMobileList(c_GIgnores, true); writer.WriteMobileList(c_GListens, true); } public void LoadOptions(GenericReader reader) { int version = reader.ReadInt(); if (version >= 3) c_MultiC = reader.ReadInt(); if (version >= 2) c_Karma = reader.ReadInt(); c_ReadReceipt = reader.ReadBool(); c_QuickBar = reader.ReadBool(); c_ExtraPm = reader.ReadBool(); c_Status = (OnlineStatus)reader.ReadInt(); Mobile m; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m = reader.ReadMobile(); if (m != null) c_Sounds[m] = reader.ReadInt(); else reader.ReadInt(); } c_GlobalMC = reader.ReadInt(); c_GlobalCC = reader.ReadInt(); c_GlobalGC = reader.ReadInt(); c_GlobalFC = reader.ReadInt(); c_GlobalWC = reader.ReadInt(); c_SystemC = reader.ReadInt(); c_MsgC = reader.ReadInt(); c_PerPage = reader.ReadInt(); c_DefaultSound = reader.ReadInt(); c_StaffC = reader.ReadInt(); c_Avatar = reader.ReadInt(); c_MenuSkin = (Skin)reader.ReadInt(); c_GlobalAccess = reader.ReadBool(); c_Global = reader.ReadBool(); c_GlobalM = reader.ReadBool(); c_GlobalC = reader.ReadBool(); c_GlobalG = reader.ReadBool(); c_GlobalF = reader.ReadBool(); c_GlobalW = reader.ReadBool(); c_Banned = reader.ReadBool(); c_FriendsOnly = reader.ReadBool(); c_MsgSound = reader.ReadBool(); c_ByRequest = reader.ReadBool(); c_FriendAlert = reader.ReadBool(); c_SevenDays = reader.ReadBool(); c_WhenFull = reader.ReadBool(); c_IrcRaw = reader.ReadBool(); c_AwayMsg = reader.ReadString(); c_Signature = reader.ReadString(); c_BannedUntil = reader.ReadDateTime(); if (c_BannedUntil > DateTime.Now) Ban(c_BannedUntil - DateTime.Now); else RemoveBan(); } public void LoadFriends(GenericReader reader) { int version = reader.ReadInt(); c_Friends = reader.ReadMobileList(); } public void LoadIgnores(GenericReader reader) { int version = reader.ReadInt(); c_Ignores = reader.ReadMobileList(); } public void LoadMsgs(GenericReader reader) { int version = reader.ReadInt(); Message msg; int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { msg = new Message(); msg.Load(reader); if (msg.From != null ) c_Messages.Add(msg); } } public void LoadGlobalListens(GenericReader reader) { int version = reader.ReadInt(); c_GIgnores = reader.ReadMobileList(); c_GListens = reader.ReadMobileList(); } #endregion } }
using System; using System.Runtime.CompilerServices; using QUnit; #pragma warning disable 184, 458, 1720 namespace CoreLib.TestScript.Reflection { [TestFixture] public class TypeSystemLanguageSupportTests { public class C1 {} [IncludeGenericArguments] public class C2<T> {} public interface I1 {} [IncludeGenericArguments] public interface I2<T1> {} public interface I3 : I1 {} public interface I4 {} [IncludeGenericArguments] public interface I5<T1> : I2<T1> {} [IncludeGenericArguments] public interface I6<out T> {} [IncludeGenericArguments] public interface I7<in T> {} [IncludeGenericArguments] public interface I8<out T1, in T2> : I6<T1>, I7<T2> {} [IncludeGenericArguments] public interface I9<T1, out T2> {} [IncludeGenericArguments] public interface I10<out T1, in T2> : I8<T1,T2> {} public class D1 : C1, I1 { } [IncludeGenericArguments] public class D2<T> : C2<T>, I2<T>, I1 { } public class D3 : C2<int>, I2<string> { } public class D4 : I3, I4 { } public class X1 : I1 { } public class X2 : X1 { } [IncludeGenericArguments] public class Y1<T> : I6<T> {} public class Y1X1 : Y1<X1> {} public class Y1X2 : Y1<X2> {} [IncludeGenericArguments] public class Y2<T> : I7<T> {} public class Y2X1 : Y2<X1> {} public class Y2X2 : Y2<X2> {} [IncludeGenericArguments] public class Y3<T1, T2> : I8<T1, T2> {} public class Y3X1X1 : Y3<X1, X1> {} public class Y3X1X2 : Y3<X1, X2> {} public class Y3X2X1 : Y3<X2, X1> {} public class Y3X2X2 : Y3<X2, X2> {} [IncludeGenericArguments] public class Y4<T1, T2> : I9<T1, T2> {} public class Y5<T1, T2> : I6<I8<T1, T2>> {} public class Y6<T1, T2> : I7<I8<T1, T2>> {} public enum E1 {} public enum E2 {} [Serializable] public class BS { public int X; public BS(int x) { X = x; } } [Serializable(TypeCheckCode = "{$System.Script}.isValue({this}.y)")] public class DS : BS { public DS() : base(0) {} } [Imported(TypeCheckCode = "{$System.Script}.isValue({this}.y)")] public class CI { } [IncludeGenericArguments] private static bool CanConvert<T>(object arg) { try { #pragma warning disable 219 // The variable `x' is assigned but its value is never used var x = (T)arg; #pragma warning restore 219 return true; } catch { return false; } } [Test] public void TypeIsWorksForReferenceTypes() { Assert.IsFalse((object)new object() is C1, "#1"); Assert.IsTrue ((object)new C1() is object, "#2"); Assert.IsFalse((object)new object() is I1, "#3"); Assert.IsFalse((object)new C1() is D1, "#4"); Assert.IsTrue ((object)new D1() is C1, "#5"); Assert.IsTrue ((object)new D1() is I1, "#6"); Assert.IsTrue ((object)new D2<int>() is C2<int>, "#7"); Assert.IsFalse((object)new D2<int>() is C2<string>, "#8"); Assert.IsTrue ((object)new D2<int>() is I2<int>, "#9"); Assert.IsFalse((object)new D2<int>() is I2<string>, "#10"); Assert.IsTrue ((object)new D2<int>() is I1, "#11"); Assert.IsFalse((object)new D3() is C2<string>, "#12"); Assert.IsTrue ((object)new D3() is C2<int>, "#13"); Assert.IsFalse((object)new D3() is I2<int>, "#14"); Assert.IsTrue ((object)new D3() is I2<string>, "#15"); Assert.IsTrue ((object)new D4() is I1, "#16"); Assert.IsTrue ((object)new D4() is I3, "#17"); Assert.IsTrue ((object)new D4() is I4, "#18"); Assert.IsTrue ((object)new X2() is I1, "#19"); Assert.IsTrue ((object)new E2() is E1, "#20"); Assert.IsTrue ((object)new E1() is int, "#21"); Assert.IsTrue ((object)new E1() is object, "#22"); Assert.IsFalse((object)new Y1<X1>() is I7<X1>, "#23"); Assert.IsTrue ((object)new Y1<X1>() is I6<X1>, "#24"); Assert.IsTrue ((object)new Y1X1() is I6<X1>, "#25"); Assert.IsFalse((object)new Y1<X1>() is I6<X2>, "#26"); Assert.IsFalse((object)new Y1X1() is I6<X2>, "#27"); Assert.IsTrue ((object)new Y1<X2>() is I6<X1>, "#28"); Assert.IsTrue ((object)new Y1X2() is I6<X1>, "#29"); Assert.IsTrue ((object)new Y1<X2>() is I6<X2>, "#30"); Assert.IsTrue ((object)new Y1X2() is I6<X2>, "#31"); Assert.IsFalse((object)new Y2<X1>() is I6<X1>, "#32"); Assert.IsTrue ((object)new Y2<X1>() is I7<X1>, "#33"); Assert.IsTrue ((object)new Y2X1() is I7<X1>, "#34"); Assert.IsTrue ((object)new Y2<X1>() is I7<X2>, "#35"); Assert.IsTrue ((object)new Y2X1() is I7<X2>, "#36"); Assert.IsFalse((object)new Y2<X2>() is I7<X1>, "#37"); Assert.IsFalse((object)new Y2X2() is I7<X1>, "#38"); Assert.IsTrue ((object)new Y2<X2>() is I7<X2>, "#39"); Assert.IsTrue ((object)new Y2X2() is I7<X2>, "#40"); Assert.IsFalse((object)new Y3<X1, X1>() is I1, "#41"); Assert.IsTrue ((object)new Y3<X1, X1>() is I8<X1, X1>, "#42"); Assert.IsTrue ((object)new Y3X1X1() is I8<X1, X1>, "#43"); Assert.IsFalse((object)new Y3<X1, X2>() is I8<X1, X1>, "#44"); Assert.IsFalse((object)new Y3X1X2() is I8<X1, X1>, "#45"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X1, X1>, "#46"); Assert.IsTrue ((object)new Y3X2X1() is I8<X1, X1>, "#47"); Assert.IsFalse((object)new Y3<X2, X2>() is I8<X1, X1>, "#48"); Assert.IsFalse((object)new Y3X2X2() is I8<X1, X1>, "#49"); Assert.IsTrue ((object)new Y3<X1, X1>() is I8<X1, X2>, "#50"); Assert.IsTrue ((object)new Y3X1X1() is I8<X1, X2>, "#51"); Assert.IsTrue ((object)new Y3<X1, X2>() is I8<X1, X2>, "#52"); Assert.IsTrue ((object)new Y3X1X2() is I8<X1, X2>, "#53"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X1, X2>, "#54"); Assert.IsTrue ((object)new Y3X2X1() is I8<X1, X2>, "#55"); Assert.IsTrue ((object)new Y3<X2, X2>() is I8<X1, X2>, "#56"); Assert.IsTrue ((object)new Y3X2X2() is I8<X1, X2>, "#57"); Assert.IsFalse((object)new Y3<X1, X1>() is I8<X2, X1>, "#58"); Assert.IsFalse((object)new Y3X1X1() is I8<X2, X1>, "#59"); Assert.IsFalse((object)new Y3<X1, X2>() is I8<X2, X1>, "#60"); Assert.IsFalse((object)new Y3X1X2() is I8<X2, X1>, "#61"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X2, X1>, "#62"); Assert.IsTrue ((object)new Y3X2X1() is I8<X2, X1>, "#63"); Assert.IsFalse((object)new Y3<X2, X2>() is I8<X2, X1>, "#64"); Assert.IsFalse((object)new Y3X2X2() is I8<X2, X1>, "#65"); Assert.IsFalse((object)new Y3<X1, X1>() is I8<X2, X2>, "#66"); Assert.IsFalse((object)new Y3X1X1() is I8<X2, X2>, "#67"); Assert.IsFalse((object)new Y3<X1, X2>() is I8<X2, X2>, "#68"); Assert.IsFalse((object)new Y3X1X2() is I8<X2, X2>, "#69"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X2, X2>, "#70"); Assert.IsTrue ((object)new Y3X2X1() is I8<X2, X2>, "#71"); Assert.IsTrue ((object)new Y3<X2, X2>() is I8<X2, X2>, "#72"); Assert.IsTrue ((object)new Y3X2X2() is I8<X2, X2>, "#73"); Assert.IsTrue ((object)new Y4<string, X1>() is I9<string, X1>, "#74"); Assert.IsFalse((object)new Y4<string, X1>() is I9<object, X1>, "#75"); Assert.IsFalse((object)new Y4<object, X1>() is I9<string, X1>, "#76"); Assert.IsTrue ((object)new Y4<object, X1>() is I9<object, X1>, "#77"); Assert.IsFalse((object)new Y4<string, X1>() is I9<string, X2>, "#78"); Assert.IsFalse((object)new Y4<string, X1>() is I9<object, X2>, "#79"); Assert.IsFalse((object)new Y4<object, X1>() is I9<string, X2>, "#80"); Assert.IsFalse((object)new Y4<object, X1>() is I9<object, X2>, "#81"); Assert.IsTrue ((object)new Y4<string, X2>() is I9<string, X1>, "#82"); Assert.IsFalse((object)new Y4<string, X2>() is I9<object, X1>, "#83"); Assert.IsFalse((object)new Y4<object, X2>() is I9<string, X1>, "#84"); Assert.IsTrue ((object)new Y4<object, X2>() is I9<object, X1>, "#85"); Assert.IsTrue ((object)new Y4<string, X2>() is I9<string, X2>, "#86"); Assert.IsFalse((object)new Y4<string, X2>() is I9<object, X2>, "#87"); Assert.IsFalse((object)new Y4<object, X2>() is I9<string, X2>, "#88"); Assert.IsTrue ((object)new Y4<object, X2>() is I9<object, X2>, "#89"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I6<X1>>, "#90"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I7<X1>>, "#91"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I6<X2>>, "#92"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I7<X2>>, "#93"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I8<X1, X1>>, "#94"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I8<X1, X2>>, "#95"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I8<X2, X1>>, "#96"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I8<X2, X2>>, "#97"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X1, X1>>, "#98"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X1, X2>>, "#99"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X2, X1>>, "#100"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X2, X2>>, "#101"); Assert.IsTrue((object)new Y5<X2, X2>() is I6<I6<X1>>, "#102"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I7<X1>>, "#103"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I6<X2>>, "#104"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I7<X2>>, "#105"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I8<X1, X1>>, "#106"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I8<X1, X2>>, "#107"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I8<X2, X1>>, "#108"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I8<X2, X2>>, "#109"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X1, X1>>, "#110"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X1, X2>>, "#111"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X2, X1>>, "#112"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X2, X2>>, "#113"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I6<X1>>, "#114"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I7<X1>>, "#115"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I6<X2>>, "#116"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I7<X2>>, "#117"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I8<X1, X1>>, "#118"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I8<X1, X2>>, "#119"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I8<X2, X1>>, "#120"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I8<X2, X2>>, "#121"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I10<X1, X1>>, "#122"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I10<X1, X2>>, "#123"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I10<X2, X1>>, "#124"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I10<X2, X2>>, "#125"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I6<X1>>, "#126"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I7<X1>>, "#127"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I6<X2>>, "#128"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I7<X2>>, "#129"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I8<X1, X1>>, "#130"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I8<X1, X2>>, "#131"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I8<X2, X1>>, "#132"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I8<X2, X2>>, "#133"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I10<X1, X1>>, "#134"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I10<X1, X2>>, "#135"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I10<X2, X1>>, "#136"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I10<X2, X2>>, "#137"); Assert.IsFalse((object)null is object, "#138"); } [Test] public void TypeAsWorksForReferenceTypes() { Assert.IsFalse(((object)new object() as C1) != null, "#1"); Assert.IsTrue (((object)new C1() as object) != null, "#2"); Assert.IsFalse(((object)new object() as I1) != null, "#3"); Assert.IsFalse(((object)new C1() as D1) != null, "#4"); Assert.IsTrue (((object)new D1() as C1) != null, "#5"); Assert.IsTrue (((object)new D1() as I1) != null, "#6"); Assert.IsTrue (((object)new D2<int>() as C2<int>) != null, "#7"); Assert.IsFalse(((object)new D2<int>() as C2<string>) != null, "#8"); Assert.IsTrue (((object)new D2<int>() as I2<int>) != null, "#9"); Assert.IsFalse(((object)new D2<int>() as I2<string>) != null, "#10"); Assert.IsTrue (((object)new D2<int>() as I1) != null, "#11"); Assert.IsFalse(((object)new D3() as C2<string>) != null, "#12"); Assert.IsTrue (((object)new D3() as C2<int>) != null, "#13"); Assert.IsFalse(((object)new D3() as I2<int>) != null, "#14"); Assert.IsTrue (((object)new D3() as I2<string>) != null, "#15"); Assert.IsTrue (((object)new D4() as I1) != null, "#16"); Assert.IsTrue (((object)new D4() as I3) != null, "#17"); Assert.IsTrue (((object)new D4() as I4) != null, "#18"); Assert.IsTrue (((object)new X2() as I1) != null, "#19"); Assert.IsTrue (((object)new E2() as E1?) != null, "#20"); Assert.IsTrue (((object)new E1() as int?) != null, "#21"); Assert.IsTrue (((object)new E1() as object) != null, "#22"); Assert.IsFalse(((object)new Y1<X1>() as I7<X1>) != null, "#23"); Assert.IsTrue (((object)new Y1<X1>() as I6<X1>) != null, "#24"); Assert.IsTrue (((object)new Y1X1() as I6<X1>) != null, "#25"); Assert.IsFalse(((object)new Y1<X1>() as I6<X2>) != null, "#26"); Assert.IsFalse(((object)new Y1X1() as I6<X2>) != null, "#27"); Assert.IsTrue (((object)new Y1<X2>() as I6<X1>) != null, "#28"); Assert.IsTrue (((object)new Y1X2() as I6<X1>) != null, "#29"); Assert.IsTrue (((object)new Y1<X2>() as I6<X2>) != null, "#30"); Assert.IsTrue (((object)new Y1X2() as I6<X2>) != null, "#31"); Assert.IsFalse(((object)new Y2<X1>() as I6<X1>) != null, "#32"); Assert.IsTrue (((object)new Y2<X1>() as I7<X1>) != null, "#33"); Assert.IsTrue (((object)new Y2X1() as I7<X1>) != null, "#34"); Assert.IsTrue (((object)new Y2<X1>() as I7<X2>) != null, "#35"); Assert.IsTrue (((object)new Y2X1() as I7<X2>) != null, "#36"); Assert.IsFalse(((object)new Y2<X2>() as I7<X1>) != null, "#37"); Assert.IsFalse(((object)new Y2X2() as I7<X1>) != null, "#38"); Assert.IsTrue (((object)new Y2<X2>() as I7<X2>) != null, "#39"); Assert.IsTrue (((object)new Y2X2() as I7<X2>) != null, "#40"); Assert.IsFalse(((object)new Y3<X1, X1>() as I1) != null, "#41"); Assert.IsTrue (((object)new Y3<X1, X1>() as I8<X1, X1>) != null, "#42"); Assert.IsTrue (((object)new Y3X1X1() as I8<X1, X1>) != null, "#43"); Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X1, X1>) != null, "#44"); Assert.IsFalse(((object)new Y3X1X2() as I8<X1, X1>) != null, "#45"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X1, X1>) != null, "#46"); Assert.IsTrue (((object)new Y3X2X1() as I8<X1, X1>) != null, "#47"); Assert.IsFalse(((object)new Y3<X2, X2>() as I8<X1, X1>) != null, "#48"); Assert.IsFalse(((object)new Y3X2X2() as I8<X1, X1>) != null, "#49"); Assert.IsTrue (((object)new Y3<X1, X1>() as I8<X1, X2>) != null, "#50"); Assert.IsTrue (((object)new Y3X1X1() as I8<X1, X2>) != null, "#51"); Assert.IsTrue (((object)new Y3<X1, X2>() as I8<X1, X2>) != null, "#52"); Assert.IsTrue (((object)new Y3X1X2() as I8<X1, X2>) != null, "#53"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X1, X2>) != null, "#54"); Assert.IsTrue (((object)new Y3X2X1() as I8<X1, X2>) != null, "#55"); Assert.IsTrue (((object)new Y3<X2, X2>() as I8<X1, X2>) != null, "#56"); Assert.IsTrue (((object)new Y3X2X2() as I8<X1, X2>) != null, "#57"); Assert.IsFalse(((object)new Y3<X1, X1>() as I8<X2, X1>) != null, "#58"); Assert.IsFalse(((object)new Y3X1X1() as I8<X2, X1>) != null, "#59"); Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X2, X1>) != null, "#60"); Assert.IsFalse(((object)new Y3X1X2() as I8<X2, X1>) != null, "#61"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X2, X1>) != null, "#62"); Assert.IsTrue (((object)new Y3X2X1() as I8<X2, X1>) != null, "#63"); Assert.IsFalse(((object)new Y3<X2, X2>() as I8<X2, X1>) != null, "#64"); Assert.IsFalse(((object)new Y3X2X2() as I8<X2, X1>) != null, "#65"); Assert.IsFalse(((object)new Y3<X1, X1>() as I8<X2, X2>) != null, "#66"); Assert.IsFalse(((object)new Y3X1X1() as I8<X2, X2>) != null, "#67"); Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X2, X2>) != null, "#68"); Assert.IsFalse(((object)new Y3X1X2() as I8<X2, X2>) != null, "#69"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X2, X2>) != null, "#70"); Assert.IsTrue (((object)new Y3X2X1() as I8<X2, X2>) != null, "#71"); Assert.IsTrue (((object)new Y3<X2, X2>() as I8<X2, X2>) != null, "#72"); Assert.IsTrue (((object)new Y3X2X2() as I8<X2, X2>) != null, "#73"); Assert.IsTrue (((object)new Y4<string, X1>() as I9<string, X1>) != null, "#74"); Assert.IsFalse(((object)new Y4<string, X1>() as I9<object, X1>) != null, "#75"); Assert.IsFalse(((object)new Y4<object, X1>() as I9<string, X1>) != null, "#76"); Assert.IsTrue (((object)new Y4<object, X1>() as I9<object, X1>) != null, "#77"); Assert.IsFalse(((object)new Y4<string, X1>() as I9<string, X2>) != null, "#78"); Assert.IsFalse(((object)new Y4<string, X1>() as I9<object, X2>) != null, "#79"); Assert.IsFalse(((object)new Y4<object, X1>() as I9<string, X2>) != null, "#80"); Assert.IsFalse(((object)new Y4<object, X1>() as I9<object, X2>) != null, "#81"); Assert.IsTrue (((object)new Y4<string, X2>() as I9<string, X1>) != null, "#82"); Assert.IsFalse(((object)new Y4<string, X2>() as I9<object, X1>) != null, "#83"); Assert.IsFalse(((object)new Y4<object, X2>() as I9<string, X1>) != null, "#84"); Assert.IsTrue (((object)new Y4<object, X2>() as I9<object, X1>) != null, "#85"); Assert.IsTrue (((object)new Y4<string, X2>() as I9<string, X2>) != null, "#86"); Assert.IsFalse(((object)new Y4<string, X2>() as I9<object, X2>) != null, "#87"); Assert.IsFalse(((object)new Y4<object, X2>() as I9<string, X2>) != null, "#88"); Assert.IsTrue (((object)new Y4<object, X2>() as I9<object, X2>) != null, "#89"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I6<X1>>) != null, "#90"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I7<X1>>) != null, "#91"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I6<X2>>) != null, "#92"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I7<X2>>) != null, "#93"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I8<X1, X1>>) != null, "#94"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I8<X1, X2>>) != null, "#95"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I8<X2, X1>>) != null, "#96"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I8<X2, X2>>) != null, "#97"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X1, X1>>) != null, "#98"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X1, X2>>) != null, "#99"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X2, X1>>) != null, "#100"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X2, X2>>) != null, "#101"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I6<X1>>) != null, "#102"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I7<X1>>) != null, "#103"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I6<X2>>) != null, "#104"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I7<X2>>) != null, "#105"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I8<X1, X1>>) != null, "#106"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I8<X1, X2>>) != null, "#107"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I8<X2, X1>>) != null, "#108"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I8<X2, X2>>) != null, "#109"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X1, X1>>) != null, "#110"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X1, X2>>) != null, "#111"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X2, X1>>) != null, "#112"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X2, X2>>) != null, "#113"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I6<X1>>) != null, "#114"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I7<X1>>) != null, "#115"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I6<X2>>) != null, "#116"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I7<X2>>) != null, "#117"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I8<X1, X1>>) != null, "#118"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I8<X1, X2>>) != null, "#119"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I8<X2, X1>>) != null, "#120"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I8<X2, X2>>) != null, "#121"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I10<X1, X1>>) != null, "#122"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I10<X1, X2>>) != null, "#123"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I10<X2, X1>>) != null, "#124"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I10<X2, X2>>) != null, "#125"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I6<X1>>) != null, "#126"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I7<X1>>) != null, "#127"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I6<X2>>) != null, "#128"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I7<X2>>) != null, "#129"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I8<X1, X1>>) != null, "#130"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I8<X1, X2>>) != null, "#131"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I8<X2, X1>>) != null, "#132"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I8<X2, X2>>) != null, "#133"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I10<X1, X1>>) != null, "#134"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I10<X1, X2>>) != null, "#135"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I10<X2, X1>>) != null, "#136"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I10<X2, X2>>) != null, "#137"); Assert.IsFalse(((object)null as object) != null, "#138"); } [Test] public void CastWorksForReferenceTypes() { Assert.IsFalse(CanConvert<C1>(new object()), "#1"); Assert.IsTrue (CanConvert<object>(new C1()), "#2"); Assert.IsFalse(CanConvert<I1>(new object()), "#3"); Assert.IsFalse(CanConvert<D1>(new C1()), "#4"); Assert.IsTrue (CanConvert<C1>(new D1()), "#5"); Assert.IsTrue (CanConvert<I1>(new D1()), "#6"); Assert.IsTrue (CanConvert<C2<int>>(new D2<int>()), "#7"); Assert.IsFalse(CanConvert<C2<string>>(new D2<int>()), "#8"); Assert.IsTrue (CanConvert<I2<int>>(new D2<int>()), "#9"); Assert.IsFalse(CanConvert<I2<string>>(new D2<int>()), "#10"); Assert.IsTrue (CanConvert<I1>(new D2<int>()), "#11"); Assert.IsFalse(CanConvert<C2<string>>(new D3()), "#12"); Assert.IsTrue (CanConvert<C2<int>>(new D3()), "#13"); Assert.IsFalse(CanConvert<I2<int>>(new D3()), "#14"); Assert.IsTrue (CanConvert<I2<string>>(new D3()), "#15"); Assert.IsTrue (CanConvert<I1>(new D4()), "#16"); Assert.IsTrue (CanConvert<I3>(new D4()), "#17"); Assert.IsTrue (CanConvert<I4>(new D4()), "#18"); Assert.IsTrue (CanConvert<I1>(new X2()), "#19"); Assert.IsTrue (CanConvert<E1>(new E2()), "#20"); Assert.IsTrue (CanConvert<int>(new E1()), "#21"); Assert.IsTrue (CanConvert<object>(new E1()), "#22"); Assert.IsFalse(CanConvert<I7<X1>>(new Y1<X1>()), "#23"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1<X1>()), "#24"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1X1()), "#25"); Assert.IsFalse(CanConvert<I6<X2>>(new Y1<X1>()), "#26"); Assert.IsFalse(CanConvert<I6<X2>>(new Y1X1()), "#27"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1<X2>()), "#28"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1X2()), "#29"); Assert.IsTrue (CanConvert<I6<X2>>(new Y1<X2>()), "#30"); Assert.IsTrue (CanConvert<I6<X2>>(new Y1X2()), "#31"); Assert.IsFalse(CanConvert<I6<X1>>(new Y2<X1>()), "#32"); Assert.IsTrue (CanConvert<I7<X1>>(new Y2<X1>()), "#33"); Assert.IsTrue (CanConvert<I7<X1>>(new Y2X1()), "#34"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2<X1>()), "#35"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2X1()), "#36"); Assert.IsFalse(CanConvert<I7<X1>>(new Y2<X2>()), "#37"); Assert.IsFalse(CanConvert<I7<X1>>(new Y2X2()), "#38"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2<X2>()), "#39"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2X2()), "#40"); Assert.IsFalse(CanConvert<I1>(new Y3<X1, X1>()), "#41"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3<X1, X1>()), "#42"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3X1X1()), "#43"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3<X1, X2>()), "#44"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3X1X2()), "#45"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3<X2, X1>()), "#46"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3X2X1()), "#47"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3<X2, X2>()), "#48"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3X2X2()), "#49"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X1, X1>()), "#50"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X1X1()), "#51"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X1, X2>()), "#52"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X1X2()), "#53"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X2, X1>()), "#54"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X2X1()), "#55"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X2, X2>()), "#56"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X2X2()), "#57"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X1, X1>()), "#58"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X1X1()), "#59"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X1, X2>()), "#60"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X1X2()), "#61"); Assert.IsTrue (CanConvert<I8<X2, X1>>(new Y3<X2, X1>()), "#62"); Assert.IsTrue (CanConvert<I8<X2, X1>>(new Y3X2X1()), "#63"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X2, X2>()), "#64"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X2X2()), "#65"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3<X1, X1>()), "#66"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3X1X1()), "#67"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3<X1, X2>()), "#68"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3X1X2()), "#69"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3<X2, X1>()), "#70"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3X2X1()), "#71"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3<X2, X2>()), "#72"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3X2X2()), "#73"); Assert.IsTrue (CanConvert<I9<string, X1>>(new Y4<string, X1>()), "#74"); Assert.IsFalse(CanConvert<I9<object, X1>>(new Y4<string, X1>()), "#75"); Assert.IsFalse(CanConvert<I9<string, X1>>(new Y4<object, X1>()), "#76"); Assert.IsTrue (CanConvert<I9<object, X1>>(new Y4<object, X1>()), "#77"); Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<string, X1>()), "#78"); Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<string, X1>()), "#79"); Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<object, X1>()), "#80"); Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<object, X1>()), "#81"); Assert.IsTrue (CanConvert<I9<string, X1>>(new Y4<string, X2>()), "#82"); Assert.IsFalse(CanConvert<I9<object, X1>>(new Y4<string, X2>()), "#83"); Assert.IsFalse(CanConvert<I9<string, X1>>(new Y4<object, X2>()), "#84"); Assert.IsTrue (CanConvert<I9<object, X1>>(new Y4<object, X2>()), "#85"); Assert.IsTrue (CanConvert<I9<string, X2>>(new Y4<string, X2>()), "#86"); Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<string, X2>()), "#87"); Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<object, X2>()), "#88"); Assert.IsTrue (CanConvert<I9<object, X2>>(new Y4<object, X2>()), "#89"); Assert.IsTrue (CanConvert<I6<I6<X1>>>(new Y5<X1, X1>()), "#90"); Assert.IsTrue (CanConvert<I6<I7<X1>>>(new Y5<X1, X1>()), "#91"); Assert.IsFalse(CanConvert<I6<I6<X2>>>(new Y5<X1, X1>()), "#92"); Assert.IsTrue (CanConvert<I6<I7<X2>>>(new Y5<X1, X1>()), "#93"); Assert.IsTrue (CanConvert<I6<I8<X1, X1>>>(new Y5<X1, X1>()), "#94"); Assert.IsTrue (CanConvert<I6<I8<X1, X2>>>(new Y5<X1, X1>()), "#95"); Assert.IsFalse(CanConvert<I6<I8<X2, X1>>>(new Y5<X1, X1>()), "#96"); Assert.IsFalse(CanConvert<I6<I8<X2, X2>>>(new Y5<X1, X1>()), "#97"); Assert.IsFalse(CanConvert<I6<I10<X1, X1>>>(new Y5<X1, X1>()), "#98"); Assert.IsFalse(CanConvert<I6<I10<X1, X2>>>(new Y5<X1, X1>()), "#99"); Assert.IsFalse(CanConvert<I6<I10<X2, X1>>>(new Y5<X1, X1>()), "#100"); Assert.IsFalse(CanConvert<I6<I10<X2, X2>>>(new Y5<X1, X1>()), "#101"); Assert.IsTrue (CanConvert<I6<I6<X1>>>(new Y5<X2, X2>()), "#102"); Assert.IsFalse(CanConvert<I6<I7<X1>>>(new Y5<X2, X2>()), "#103"); Assert.IsTrue (CanConvert<I6<I6<X2>>>(new Y5<X2, X2>()), "#104"); Assert.IsTrue (CanConvert<I6<I7<X2>>>(new Y5<X2, X2>()), "#105"); Assert.IsFalse(CanConvert<I6<I8<X1, X1>>>(new Y5<X2, X2>()), "#106"); Assert.IsTrue (CanConvert<I6<I8<X1, X2>>>(new Y5<X2, X2>()), "#107"); Assert.IsFalse(CanConvert<I6<I8<X2, X1>>>(new Y5<X2, X2>()), "#108"); Assert.IsTrue (CanConvert<I6<I8<X2, X2>>>(new Y5<X2, X2>()), "#109"); Assert.IsFalse(CanConvert<I6<I10<X1, X1>>>(new Y5<X2, X2>()), "#110"); Assert.IsFalse(CanConvert<I6<I10<X1, X2>>>(new Y5<X2, X2>()), "#111"); Assert.IsFalse(CanConvert<I6<I10<X2, X1>>>(new Y5<X2, X2>()), "#112"); Assert.IsFalse(CanConvert<I6<I10<X2, X2>>>(new Y5<X2, X2>()), "#113"); Assert.IsFalse(CanConvert<I7<I6<X1>>>(new Y6<X1, X1>()), "#114"); Assert.IsFalse(CanConvert<I7<I7<X1>>>(new Y6<X1, X1>()), "#115"); Assert.IsFalse(CanConvert<I7<I6<X2>>>(new Y6<X1, X1>()), "#116"); Assert.IsFalse(CanConvert<I7<I7<X2>>>(new Y6<X1, X1>()), "#117"); Assert.IsTrue (CanConvert<I7<I8<X1, X1>>>(new Y6<X1, X1>()), "#118"); Assert.IsFalse(CanConvert<I7<I8<X1, X2>>>(new Y6<X1, X1>()), "#119"); Assert.IsTrue (CanConvert<I7<I8<X2, X1>>>(new Y6<X1, X1>()), "#120"); Assert.IsFalse(CanConvert<I7<I8<X2, X2>>>(new Y6<X1, X1>()), "#121"); Assert.IsTrue (CanConvert<I7<I10<X1, X1>>>(new Y6<X1, X1>()), "#122"); Assert.IsFalse(CanConvert<I7<I10<X1, X2>>>(new Y6<X1, X1>()), "#123"); Assert.IsTrue (CanConvert<I7<I10<X2, X1>>>(new Y6<X1, X1>()), "#124"); Assert.IsFalse(CanConvert<I7<I10<X2, X2>>>(new Y6<X1, X1>()), "#125"); Assert.IsFalse(CanConvert<I7<I6<X1>>>(new Y6<X2, X2>()), "#126"); Assert.IsFalse(CanConvert<I7<I7<X1>>>(new Y6<X2, X2>()), "#127"); Assert.IsFalse(CanConvert<I7<I6<X2>>>(new Y6<X2, X2>()), "#128"); Assert.IsFalse(CanConvert<I7<I7<X2>>>(new Y6<X2, X2>()), "#129"); Assert.IsFalse(CanConvert<I7<I8<X1, X1>>>(new Y6<X2, X2>()), "#130"); Assert.IsFalse(CanConvert<I7<I8<X1, X2>>>(new Y6<X2, X2>()), "#131"); Assert.IsTrue (CanConvert<I7<I8<X2, X1>>>(new Y6<X2, X2>()), "#132"); Assert.IsTrue (CanConvert<I7<I8<X2, X2>>>(new Y6<X2, X2>()), "#133"); Assert.IsFalse(CanConvert<I7<I10<X1, X1>>>(new Y6<X2, X2>()), "#134"); Assert.IsFalse(CanConvert<I7<I10<X1, X2>>>(new Y6<X2, X2>()), "#135"); Assert.IsTrue (CanConvert<I7<I10<X2, X1>>>(new Y6<X2, X2>()), "#136"); Assert.IsTrue (CanConvert<I7<I10<X2, X2>>>(new Y6<X2, X2>()), "#137"); Assert.IsFalse((object)null is object, "#138"); } [Test] public void GetTypeWorksOnObjects() { Action a = () => {}; Assert.AreEqual(new C1().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C1"); Assert.AreEqual(new C2<int>().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C2$1[ss.Int32]"); Assert.AreEqual(new C2<string>().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C2$1[String]"); Assert.AreEqual((1).GetType().FullName, "Number"); Assert.AreEqual("X".GetType().FullName, "String"); Assert.AreEqual(a.GetType().FullName, "Function"); Assert.AreEqual(new object().GetType().FullName, "Object"); Assert.AreEqual(new[] { 1, 2 }.GetType().FullName, "Array"); } [Test] public void GetTypeOnNullInstanceThrowsException() { Assert.Throws(() => ((object)null).GetType()); } #pragma warning disable 219 [Test] public void CastOperatorsWorkForSerializableTypesWithCustomTypeCheckCode() { object o1 = new { x = 1 }; object o2 = new { x = 1, y = 2 }; Assert.IsFalse(o1 is DS, "o1 should not be of type"); Assert.IsTrue (o2 is DS, "o2 should be of type"); Assert.AreStrictEqual(o1 as DS, null, "Try cast o1 to type should be null"); Assert.IsTrue((o2 as DS) == o2, "Try cast o2 to type should return o2"); Assert.Throws(() => { object x = (DS)o1; }, "Cast o1 to type should throw"); Assert.IsTrue((DS)o2 == o2, "Cast o2 to type should return o2"); } [Test] public void CastOperatorsWorkForImportedTypesWithCustomTypeCheckCode() { object o1 = new { x = 1 }; object o2 = new { x = 1, y = 2 }; Assert.IsFalse(o1 is CI, "o1 should not be of type"); Assert.IsTrue (o2 is CI, "o2 should be of type"); Assert.AreStrictEqual(o1 as CI, null, "Try cast o1 to type should be null"); Assert.IsTrue((o2 as CI) == o2, "Try cast o2 to type should return o2"); Assert.Throws(() => { object x = (DS)o1; }, "Cast o1 to type should throw"); Assert.IsTrue((CI)o2 == o2, "Cast o2 to type should return o2"); } #pragma warning restore 219 } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using Avalonia.Data; using Avalonia.Reactive; namespace Avalonia { /// <summary> /// Provides extension methods for <see cref="AvaloniaObject"/> and related classes. /// </summary> public static class AvaloniaObjectExtensions { public static IBinding AsBinding<T>(this IObservable<T> source) { return new BindingAdaptor(source.Select(x => (object)x)); } /// <summary> /// Gets an observable for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The property.</param> /// <returns> /// An observable which fires immediately with the current value of the property on the /// object and subsequently each time the property value changes. /// </returns> public static IObservable<object> GetObservable(this IAvaloniaObject o, AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(o != null); Contract.Requires<ArgumentNullException>(property != null); return new AvaloniaObservable<object>( observer => { EventHandler<AvaloniaPropertyChangedEventArgs> handler = (s, e) => { if (e.Property == property) { observer.OnNext(e.NewValue); } }; observer.OnNext(o.GetValue(property)); o.PropertyChanged += handler; return Disposable.Create(() => { o.PropertyChanged -= handler; }); }, GetDescription(o, property)); } /// <summary> /// Gets an observable for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="o">The object.</param> /// <typeparam name="T">The property type.</typeparam> /// <param name="property">The property.</param> /// <returns> /// An observable which fires immediately with the current value of the property on the /// object and subsequently each time the property value changes. /// </returns> public static IObservable<T> GetObservable<T>(this IAvaloniaObject o, AvaloniaProperty<T> property) { Contract.Requires<ArgumentNullException>(o != null); Contract.Requires<ArgumentNullException>(property != null); return o.GetObservable((AvaloniaProperty)property).Cast<T>(); } /// <summary> /// Gets an observable for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="o">The object.</param> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="property">The property.</param> /// <returns> /// An observable which when subscribed pushes the old and new values of the property each /// time it is changed. Note that the observable returned from this method does not fire /// with the current value of the property immediately. /// </returns> public static IObservable<Tuple<T, T>> GetObservableWithHistory<T>( this IAvaloniaObject o, AvaloniaProperty<T> property) { Contract.Requires<ArgumentNullException>(o != null); Contract.Requires<ArgumentNullException>(property != null); return new AvaloniaObservable<Tuple<T, T>>( observer => { EventHandler<AvaloniaPropertyChangedEventArgs> handler = (s, e) => { if (e.Property == property) { observer.OnNext(Tuple.Create((T)e.OldValue, (T)e.NewValue)); } }; o.PropertyChanged += handler; return Disposable.Create(() => { o.PropertyChanged -= handler; }); }, GetDescription(o, property)); } /// <summary> /// Gets a subject for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The property.</param> /// <param name="priority"> /// The priority with which binding values are written to the object. /// </param> /// <returns> /// An <see cref="ISubject{Object}"/> which can be used for two-way binding to/from the /// property. /// </returns> public static ISubject<object> GetSubject( this IAvaloniaObject o, AvaloniaProperty property, BindingPriority priority = BindingPriority.LocalValue) { // TODO: Subject.Create<T> is not yet in stable Rx : once it is, remove the // AnonymousSubject classes and use Subject.Create<T>. var output = new Subject<object>(); var result = new AnonymousSubject<object>( Observer.Create<object>( x => output.OnNext(x), e => output.OnError(e), () => output.OnCompleted()), o.GetObservable(property)); o.Bind(property, output, priority); return result; } /// <summary> /// Gets a subject for a <see cref="AvaloniaProperty"/>. /// </summary> /// <typeparam name="T">The property type.</typeparam> /// <param name="o">The object.</param> /// <param name="property">The property.</param> /// <param name="priority"> /// The priority with which binding values are written to the object. /// </param> /// <returns> /// An <see cref="ISubject{T}"/> which can be used for two-way binding to/from the /// property. /// </returns> public static ISubject<T> GetSubject<T>( this IAvaloniaObject o, AvaloniaProperty<T> property, BindingPriority priority = BindingPriority.LocalValue) { // TODO: Subject.Create<T> is not yet in stable Rx : once it is, remove the // AnonymousSubject classes from this file and use Subject.Create<T>. var output = new Subject<T>(); var result = new AnonymousSubject<T>( Observer.Create<T>( x => output.OnNext(x), e => output.OnError(e), () => output.OnCompleted()), o.GetObservable(property)); o.Bind(property, output, priority); return result; } /// <summary> /// Gets a weak observable for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The property.</param> /// <returns>An observable.</returns> public static IObservable<object> GetWeakObservable(this IAvaloniaObject o, AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(o != null); Contract.Requires<ArgumentNullException>(property != null); return new WeakPropertyChangedObservable( new WeakReference<IAvaloniaObject>(o), property, GetDescription(o, property)); } /// <summary> /// Binds a property on an <see cref="IAvaloniaObject"/> to an <see cref="IBinding"/>. /// </summary> /// <param name="target">The object.</param> /// <param name="property">The property to bind.</param> /// <param name="binding">The binding.</param> /// <param name="anchor"> /// An optional anchor from which to locate required context. When binding to objects that /// are not in the logical tree, certain types of binding need an anchor into the tree in /// order to locate named controls or resources. The <paramref name="anchor"/> parameter /// can be used to provice this context. /// </param> /// <returns>An <see cref="IDisposable"/> which can be used to cancel the binding.</returns> public static IDisposable Bind( this IAvaloniaObject target, AvaloniaProperty property, IBinding binding, object anchor = null) { Contract.Requires<ArgumentNullException>(target != null); Contract.Requires<ArgumentNullException>(property != null); Contract.Requires<ArgumentNullException>(binding != null); var metadata = property.GetMetadata(target.GetType()) as IDirectPropertyMetadata; var result = binding.Initiate( target, property, anchor, metadata?.EnableDataValidation ?? false); if (result != null) { return BindingOperations.Apply(target, property, result, anchor); } else { return Disposable.Empty; } } /// <summary> /// Subscribes to a property changed notifications for changes that originate from a /// <typeparamref name="TTarget"/>. /// </summary> /// <typeparam name="TTarget">The type of the property change sender.</typeparam> /// <param name="observable">The property changed observable.</param> /// <param name="action"> /// The method to call. The parameters are the sender and the event args. /// </param> /// <returns>A disposable that can be used to terminate the subscription.</returns> public static IDisposable AddClassHandler<TTarget>( this IObservable<AvaloniaPropertyChangedEventArgs> observable, Action<TTarget, AvaloniaPropertyChangedEventArgs> action) where TTarget : AvaloniaObject { return observable.Subscribe(e => { if (e.Sender is TTarget) { action((TTarget)e.Sender, e); } }); } /// <summary> /// Subscribes to a property changed notifications for changes that originate from a /// <typeparamref name="TTarget"/>. /// </summary> /// <typeparam name="TTarget">The type of the property change sender.</typeparam> /// <param name="observable">The property changed observable.</param> /// <param name="handler">Given a TTarget, returns the handler.</param> /// <returns>A disposable that can be used to terminate the subscription.</returns> public static IDisposable AddClassHandler<TTarget>( this IObservable<AvaloniaPropertyChangedEventArgs> observable, Func<TTarget, Action<AvaloniaPropertyChangedEventArgs>> handler) where TTarget : class { return observable.Subscribe(e => SubscribeAdapter(e, handler)); } /// <summary> /// Gets a description of a property that van be used in observables. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The property</param> /// <returns>The description.</returns> private static string GetDescription(IAvaloniaObject o, AvaloniaProperty property) { return $"{o.GetType().Name}.{property.Name}"; } /// <summary> /// Observer method for <see cref="AddClassHandler{TTarget}(IObservable{AvaloniaPropertyChangedEventArgs}, /// Func{TTarget, Action{AvaloniaPropertyChangedEventArgs}})"/>. /// </summary> /// <typeparam name="TTarget">The sender type to accept.</typeparam> /// <param name="e">The event args.</param> /// <param name="handler">Given a TTarget, returns the handler.</param> private static void SubscribeAdapter<TTarget>( AvaloniaPropertyChangedEventArgs e, Func<TTarget, Action<AvaloniaPropertyChangedEventArgs>> handler) where TTarget : class { var target = e.Sender as TTarget; if (target != null) { handler(target)(e); } } private class BindingAdaptor : IBinding { private IObservable<object> _source; public BindingAdaptor(IObservable<object> source) { this._source = source; } public InstancedBinding Initiate( IAvaloniaObject target, AvaloniaProperty targetProperty, object anchor = null, bool enableDataValidation = false) { return new InstancedBinding(_source); } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Services { using System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Linq; using Adxstudio.Xrm.Configuration; using Adxstudio.Xrm.Core.Telemetry.EventSources; using Adxstudio.Xrm.Diagnostics.Trace; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Query; [EventSource(Guid = "76032881-E1AD-481D-80C9-3157C0E5B8BC", Name = InternalName)] internal sealed class ServicesEventSource : EventSourceBase { /// <summary> /// The EventSource name. /// </summary> private const string InternalName = "PortalServices"; /// <summary> /// The internal TraceSource. /// </summary> private static readonly TraceSource InternalTrace = new TraceSource(InternalName); /// <summary> /// The variable for lazy initialization of <see cref="ServicesEventSource"/>. /// </summary> private static readonly Lazy<ServicesEventSource> _instance = new Lazy<ServicesEventSource>(); public static ServicesEventSource Log { get { return _instance.Value; } } private enum EventName { /// <summary> /// Application has failed to connect to CRM. /// </summary> UnableToConnect = 1, /// <summary> /// <see cref="Microsoft.Xrm.Sdk.OrganizationRequest"/> to be executed. /// </summary> OrganizationRequest = 2, /// <summary> /// Request to create a record. /// </summary> Create = 3, /// <summary> /// Request to read a record. /// </summary> Retrieve = 4, /// <summary> /// Request to update a record. /// </summary> Update = 5, /// <summary> /// Request to delete a record. /// </summary> Delete = 6, /// <summary> /// Request to read one or more records. /// </summary> RetrieveMultiple = 7, /// <summary> /// Request to associate a record to another. /// </summary> Associate = 8, /// <summary> /// Request to disassociate a record from another. /// </summary> Disassociate = 9 } /// <summary> /// Log execution of an associate of an <see cref="Microsoft.Xrm.Sdk.Entity"/> record to other record(s). /// </summary> /// <param name="entityLogicalName">Logical name of the entity record.</param> /// <param name="entityId">Uniqued ID of the record.</param> /// <param name="relationship"><see cref="Microsoft.Xrm.Sdk.Relationship"/></param> /// <param name="relatedEntities"><see cref="Microsoft.Xrm.Sdk.EntityReferenceCollection"/></param> /// <param name="duration">The duration in milliseconds.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string Associate(string entityLogicalName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, long duration) { if (relationship == null || relatedEntities == null || relatedEntities.Count <= 0) { return GetActivityId(); } var relatedEntitiesString = string.Join(";", relatedEntities.ToArray().Select(o => string.Format("{0}:{1}", o.LogicalName, o.Id))); WriteEventAssociate( entityLogicalName, entityId.ToString(), relationship.SchemaName, relatedEntitiesString, duration, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); return GetActivityId(); } [Event((int)EventName.Associate, Message = "Entity Logical Name : {0} Entity ID : {1} Relationship Name : {2} Related Entities : {3} Duration : {4} PortalUrl : {5} PortalVersion : {6} PortalProductionOrTrialType : {7} SessionId : {8} ElapsedTime : {9}", Level = EventLevel.Informational, Version = 4)] private void WriteEventAssociate(string entityLogicalName, string entityId, string relationshipName, string relatedEntities, long duration, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.Associate, "Entity Logical Name : {0} Entity ID : {1} Relationship Name : {2} Related Entities : {3} Duration : {4}", entityLogicalName ?? string.Empty, entityId ?? string.Empty, relationshipName ?? string.Empty, relatedEntities ?? string.Empty, duration); WriteEvent( EventName.Associate, entityLogicalName ?? string.Empty, entityId ?? string.Empty, relationshipName ?? string.Empty, relatedEntities ?? string.Empty, duration, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log execution of create of an <see cref="Microsoft.Xrm.Sdk.Entity"/> record. /// </summary> /// <param name="entity"><see cref="Microsoft.Xrm.Sdk.Entity"/> record to create.</param> /// <param name="duration">The duration in milliseconds.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string Create(Entity entity, long duration) { if (entity == null) { return GetActivityId(); } WriteEventCreate( entity.LogicalName, duration, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); return GetActivityId(); } [Event((int)EventName.Create, Message = "Entity Logical Name : {0} Duration : {1} PortalUrl : {2} PortalVersion : {3} PortalProductionOrTrialType : {4} SessionId : {8} ElapsedTime : {9}", Level = EventLevel.Informational, Version = 4)] private void WriteEventCreate(string entityLogicalName, long duration, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.Create, "Entity Logical Name : {0} Duration : {1}", entityLogicalName ?? string.Empty, duration); WriteEvent(EventName.Create, entityLogicalName ?? string.Empty, duration, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log execution of a delete of an <see cref="Microsoft.Xrm.Sdk.Entity"/> record. /// </summary> /// <param name="entityLogicalName">Logical name of the entity record.</param> /// <param name="entityId">Uniqued ID of the record.</param> /// <param name="duration">The duration in milliseconds.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string Delete(string entityLogicalName, Guid entityId, long duration) { WriteEventDelete( entityLogicalName, entityId.ToString(), duration, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); return GetActivityId(); } [Event((int)EventName.Delete, Message = "Entity Logical Name : {0} Entity ID : {1} Duration : {2} PortalUrl : {3} PortalVersion : {4} PortalProductionOrTrialType : {5} SessionId : {6} ElapsedTime : {7}", Level = EventLevel.Informational, Version = 4)] private void WriteEventDelete(string entityLogicalName, string entityId, long duration, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.Delete, "Entity Logical Name : {0} Entity ID : {1} Duration : {2}", entityLogicalName ?? string.Empty, entityId ?? string.Empty, duration); WriteEvent(EventName.Delete, entityLogicalName ?? string.Empty, entityId ?? string.Empty, duration, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log execution of disassociate of an <see cref="Microsoft.Xrm.Sdk.Entity"/> record from other record(s). /// </summary> /// <param name="entityLogicalName">Logical name of the entity record.</param> /// <param name="entityId">Uniqued ID of the record.</param> /// <param name="relationship"><see cref="Microsoft.Xrm.Sdk.Relationship"/></param> /// <param name="relatedEntities"><see cref="Microsoft.Xrm.Sdk.EntityReferenceCollection"/></param> /// <param name="duration">The duration in milliseconds.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string Disassociate(string entityLogicalName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, long duration) { if (relationship == null || relatedEntities == null || relatedEntities.Count <= 0) { return GetActivityId(); } var relatedEntitiesString = string.Join(";", relatedEntities.ToArray().Select(o => string.Format("{0}:{1}", o.LogicalName, o.Id))); WriteEventDisassociate( entityLogicalName, entityId.ToString(), relationship.SchemaName, relatedEntitiesString, duration, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); return GetActivityId(); } [Event((int)EventName.Disassociate, Message = "Entity Logical Name : {0} Entity ID : {1} Relationship Name : {2} Related Entities : {3} Duration : {4} PortalUrl : {5} PortalVersion : {6} PortalProductionOrTrialType : {7} SessionId : {8} ElapsedTime : {9}", Level = EventLevel.Informational, Version = 4)] private void WriteEventDisassociate(string entityLogicalName, string entityId, string relationshipName, string relatedEntities, long duration, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.Disassociate, "Entity Logical Name : {0} Entity ID : {1} Relationship Name : {2} Related Entities : {3} Duration : {4}", entityLogicalName ?? string.Empty, entityId ?? string.Empty, relationshipName ?? string.Empty, relatedEntities ?? string.Empty, duration); WriteEvent(EventName.Disassociate, entityLogicalName ?? string.Empty, entityId ?? string.Empty, relationshipName ?? string.Empty, relatedEntities ?? string.Empty, duration, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log execution of an <see cref="Microsoft.Xrm.Sdk.OrganizationRequest"/>. /// </summary> /// <param name="request"><see cref="Microsoft.Xrm.Sdk.OrganizationRequest"/> to be executed.</param> /// <param name="duration">The duration in milliseconds.</param> /// <param name="cached">Indicates a cached request.</param> /// <param name="telemetry">Additional telemetry.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string OrganizationRequest(OrganizationRequest request, long duration, bool cached, CacheItemTelemetry telemetry = null) { if (request == null) { return GetActivityId(); } var cachedRequest = request as CachedOrganizationRequest; if (cachedRequest != null) { return this.OrganizationRequest(cachedRequest.Request, duration, cached, cachedRequest.Telemetry); } var retrieveMultiple = request as RetrieveMultipleRequest; if (retrieveMultiple != null) { return RetrieveMultiple(retrieveMultiple.Query, duration, cached, telemetry); } var fetchMultiple = request as FetchMultipleRequest; if (fetchMultiple != null) { return RetrieveMultiple(fetchMultiple.Query, duration, cached, telemetry); } var retrieveSingle = request as RetrieveSingleRequest; if (retrieveSingle != null) { return RetrieveMultiple(retrieveSingle.Query, duration, cached, telemetry); } var retrieve = request as RetrieveRequest; if (retrieve != null && retrieve.Target != null) { return Retrieve(retrieve.Target.LogicalName, retrieve.Target.Id, retrieve.ColumnSet, duration, cached, telemetry); } var create = request as CreateRequest; if (create != null && create.Target != null) { return Create(new Entity(create.Target.LogicalName) { Id = create.Target.Id }, duration); } var update = request as UpdateRequest; if (update != null && update.Target != null) { return Update(new Entity(update.Target.LogicalName) { Id = update.Target.Id }, duration); } var delete = request as DeleteRequest; if (delete != null && delete.Target != null) { return Delete(delete.Target.LogicalName, delete.Target.Id, duration); } var associate = request as AssociateRequest; if (associate != null && associate.Target != null) { return Associate(associate.Target.LogicalName, associate.Target.Id, associate.Relationship, associate.RelatedEntities, duration); } var disassociate = request as DisassociateRequest; if (disassociate != null && disassociate.Target != null) { return Disassociate(disassociate.Target.LogicalName, disassociate.Target.Id, disassociate.Relationship, disassociate.RelatedEntities, duration); } WriteEventOrganizationRequest( request.RequestName, request.RequestId.HasValue ? request.RequestId.Value.ToString() : null, duration, cached, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime(), telemetry?.Caller.MemberName, telemetry?.Caller.SourceFilePath, telemetry?.Caller.SourceLineNumber ?? 0); return GetActivityId(); } [Event((int)EventName.OrganizationRequest, Message = "Request Name : {0} Request ID : {1} Duration : {2} Cached : {3} PortalUrl : {4} PortalVersion : {5} PortalProductionOrTrialType : {6} SessionId : {7} ElapsedTime : {8} MemberName : {9} SourceFilePath : {10} SourceLineNumber : {11}", Level = EventLevel.Informational, Version = 5)] private void WriteEventOrganizationRequest(string requestName, string requestId, long duration, bool cached, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime, string memberName, string sourceFilePath, int sourceLineNumber) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.OrganizationRequest, "Request Name : {0} Request ID : {1} Duration : {2} Cached : {3} MemberName: {4} SourceFilePath : {5} SourceLineNumber : {6}", requestName ?? string.Empty, requestId ?? string.Empty, duration, cached, memberName, sourceFilePath, sourceLineNumber); WriteEvent(EventName.OrganizationRequest, requestName ?? string.Empty, requestId ?? string.Empty, duration, cached, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime, memberName, sourceFilePath, sourceLineNumber); } /// <summary> /// Log execution of a retrieve of an <see cref="Microsoft.Xrm.Sdk.Entity"/> record. /// </summary> /// <param name="entityLogicalName">Logical name of the entity record.</param> /// <param name="entityId">Uniqued ID of the record.</param> /// <param name="columnSet"><see cref="Microsoft.Xrm.Sdk.Query.ColumnSet"/></param> /// <param name="duration">The duration in milliseconds.</param> /// <param name="cached">Indicates a cached request.</param> /// <param name="telemetry">Additional telemetry.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string Retrieve(string entityLogicalName, Guid entityId, ColumnSet columnSet, long duration, bool cached, CacheItemTelemetry telemetry) { var columns = string.Empty; if (columnSet != null && columnSet.Columns != null && columnSet.Columns.Count > 0) { columns = string.Join(";", columnSet.Columns.ToArray()); } WriteEventRetrieve( entityLogicalName, entityId.ToString(), columns, duration, cached, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime(), telemetry?.IsAllColumns ?? false, telemetry?.Caller.MemberName, telemetry?.Caller.SourceFilePath, telemetry?.Caller.SourceLineNumber ?? 0); return GetActivityId(); } [Event((int)EventName.Retrieve, Message = "Entity Logical Name : {0} Entity ID : {1} ColumnSet : {2} Duration : {3} Cached : {4} PortalUrl : {5} PortalVersion : {6} PortalProductionOrTrialType : {7} SessionId : {8} ElapsedTime : {9} AllColumns : {10} MemberName : {11} SourceFilePath : {12} SourceLineNumber : {13}", Level = EventLevel.Informational, Version = 6)] private void WriteEventRetrieve(string entityLogicalName, string entityId, string columnSet, long duration, bool cached, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime, bool allColumns, string memberName, string sourceFilePath, int sourceLineNumber) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.Retrieve, "Entity Logical Name : {0} Entity ID : {1} ColumnSet : {2} Duration : {3} Cached : {4} AllColumns : {5} MemberName: {6} SourceFilePath : {7} SourceLineNumber : {8}", entityLogicalName ?? string.Empty, entityId ?? string.Empty, columnSet ?? string.Empty, duration, cached, allColumns, memberName, sourceFilePath, sourceLineNumber); WriteEvent(EventName.Retrieve, entityLogicalName ?? string.Empty, entityId ?? string.Empty, columnSet ?? string.Empty, duration, cached, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime, allColumns, memberName, sourceFilePath, sourceLineNumber); } /// <summary> /// Log execution of a retrieve multiple of <see cref="Microsoft.Xrm.Sdk.Entity"/> records. /// </summary> /// <param name="query"><see cref="Microsoft.Xrm.Sdk.Query.QueryBase"/> query to be executed.</param> /// <param name="duration">The duration in milliseconds.</param> /// <param name="cached">Indicates a cached request.</param> /// <param name="telemetry">Additional telemetry.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string RetrieveMultiple(QueryBase query, long duration, bool cached, CacheItemTelemetry telemetry) { if (query == null) { return GetActivityId(); } var queryInfo = string.Empty; var fetchExpression = query as FetchExpression; var queryExpression = query as QueryExpression; var queryByAttribute = query as QueryByAttribute; if (fetchExpression != null && fetchExpression.Query != null) { queryInfo = fetchExpression.Query; } if (queryExpression != null) { queryInfo = queryExpression.EntityName; } if (queryByAttribute != null) { queryInfo = queryByAttribute.EntityName; } WriteEventRetrieveMultiple( queryInfo, duration, cached, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime(), telemetry?.IsAllColumns ?? false, telemetry?.Caller.MemberName, telemetry?.Caller.SourceFilePath, telemetry?.Caller.SourceLineNumber ?? 0); return GetActivityId(); } [Event((int)EventName.RetrieveMultiple, Message = "Query Info : {0} Duration : {1} Cached : {2} PortalUrl : {3} PortalVersion : {4} PortalProductionOrTrialType : {5} SessionId : {6} ElapsedTime : {7} AllColumns : {8} MemberName : {9} SourceFilePath : {10} SourceLineNumber : {11}", Level = EventLevel.Informational, Version = 6)] private void WriteEventRetrieveMultiple(string queryInfo, long duration, bool cached, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime, bool allColumns, string memberName, string sourceFilePath, int sourceLineNumber) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.RetrieveMultiple, "Query Info : {0} Duration : {1} Cached : {2} Allcolumns : {3} MemberName: {4} SourceFilePath : {5} SourceLineNumber : {6}", queryInfo ?? string.Empty, duration, cached, allColumns, memberName, sourceFilePath, sourceLineNumber); WriteEvent(EventName.RetrieveMultiple, queryInfo ?? string.Empty, duration, cached, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime, allColumns, memberName, sourceFilePath, sourceLineNumber); } /// <summary> /// Log execution of an update of <see cref="Microsoft.Xrm.Sdk.Entity"/> record. /// </summary> /// <param name="entity"><see cref="Microsoft.Xrm.Sdk.Entity"/> record to update.</param> /// <param name="duration">The duration in milliseconds.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string Update(Entity entity, long duration) { if (entity == null) { return GetActivityId(); } WriteEventUpdate( entity.LogicalName, entity.Id, duration, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); return GetActivityId(); } [Event((int)EventName.Update, Message = "Entity Logical Name : {0} Entity ID : {1} Duration : {2} PortalUrl : {3} PortalVersion : {4} PortalProductionOrTrialType : {5} SessionId : {6} ElapsedTime : {7}", Level = EventLevel.Informational, Version = 4)] private void WriteEventUpdate(string entityLogicalName, Guid entityId, long duration, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { InternalTrace.TraceEvent( PortalSettings.Instance, TraceEventType.Information, (int)EventName.Update, "Entity Logical Name : {0} Entity ID : {1} Duration : {2}", entityLogicalName ?? string.Empty, entityId, duration); WriteEvent(EventName.Update, entityLogicalName ?? string.Empty, entityId, duration, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TakeOrSkipQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Parallel { /// <summary> /// Take and Skip either take or skip a specified number of elements, captured in the /// count argument. These will work a little bit like TakeWhile and SkipWhile: there /// are two phases, (1) Search and (2) Yield. In the search phase, our goal is to /// find the 'count'th index from the input. We do this in parallel by sharing a count- /// sized array. Each thread races to populate the array with indices in ascending /// order. This requires synchronization for inserts. We use a simple heap, for decent /// worst case performance. After a thread has scanned 'count' elements, or its current /// index is greater than or equal to the maximum index in the array (and the array is /// fully populated), the thread can stop searching. All threads issue a barrier before /// moving to the Yield phase. When the Yield phase is entered, the count-1th element /// of the array contains: in the case of Take, the maximum index (exclusive) to be /// returned; or in the case of Skip, the minimum index (inclusive) to be returned. The /// Yield phase simply consists of yielding these elements as output. /// </summary> /// <typeparam name="TResult"></typeparam> internal sealed class TakeOrSkipQueryOperator<TResult> : UnaryQueryOperator<TResult, TResult> { private readonly int _count; // The number of elements to take or skip. private readonly bool _take; // Whether to take (true) or skip (false). private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. //--------------------------------------------------------------------------------------- // Initializes a new take-while operator. // // Arguments: // child - the child data source to enumerate // count - the number of elements to take or skip // take - whether this is a Take (true) or Skip (false) // internal TakeOrSkipQueryOperator(IEnumerable<TResult> child, int count, bool take) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); _count = count; _take = take; SetOrdinalIndexState(OutputOrdinalIndexState()); } /// <summary> /// Determines the order index state for the output operator /// </summary> private OrdinalIndexState OutputOrdinalIndexState() { OrdinalIndexState indexState = Child.OrdinalIndexState; if (indexState == OrdinalIndexState.Indexable) { return OrdinalIndexState.Indexable; } if (indexState.IsWorseThan(OrdinalIndexState.Increasing)) { _prematureMerge = true; indexState = OrdinalIndexState.Correct; } // If the operator is skip and the index was correct, now it is only increasing. if (!_take && indexState == OrdinalIndexState.Correct) { indexState = OrdinalIndexState.Increasing; } return indexState; } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, bool preferStriping, QuerySettings settings) { Debug.Assert(Child.OrdinalIndexState != OrdinalIndexState.Indexable, "Don't take this code path if the child is indexable."); // If the index is not at least increasing, we need to reindex. if (_prematureMerge) { ListQueryResults<TResult> results = ExecuteAndCollectResults( inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings); PartitionedStream<TResult, int> inputIntStream = results.GetPartitionedStream(); WrapHelper<int>(inputIntStream, recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>(PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; FixedMaxHeap<TKey> sharedIndices = new FixedMaxHeap<TKey>(_count, inputStream.KeyComparer); // an array used to track the sequence of indices leading up to the Nth index CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); // a barrier to synchronize before yielding PartitionedStream<TResult, TKey> outputStream = new PartitionedStream<TResult, TKey>(partitionCount, inputStream.KeyComparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new TakeOrSkipQueryOperatorEnumerator<TKey>( inputStream[i], _take, sharedIndices, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TResult> Open(QuerySettings settings, bool preferStriping) { QueryResults<TResult> childQueryResults = Child.Open(settings, true); return TakeOrSkipQueryOperatorResults.NewResults(childQueryResults, this, settings, preferStriping); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the Take or Skip. // private class TakeOrSkipQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TResult, TKey> { private readonly QueryOperatorEnumerator<TResult, TKey> _source; // The data source to enumerate. private readonly int _count; // The number of elements to take or skip. private readonly bool _take; // Whether to execute a Take (true) or Skip (false). private readonly IComparer<TKey> _keyComparer; // Comparer for the order keys. // These fields are all shared among partitions. private readonly FixedMaxHeap<TKey> _sharedIndices; // The indices shared among partitions. private readonly CountdownEvent _sharedBarrier; // To separate the search/yield phases. private readonly CancellationToken _cancellationToken; // Indicates that cancellation has occurred. private List<Pair<TResult, TKey>>? _buffer; // Our buffer. private Shared<int>? _bufferIndex; // Our current index within the buffer. [allocate in moveNext to avoid false-sharing] //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal TakeOrSkipQueryOperatorEnumerator( QueryOperatorEnumerator<TResult, TKey> source, bool take, FixedMaxHeap<TKey> sharedIndices, CountdownEvent sharedBarrier, CancellationToken cancellationToken, IComparer<TKey> keyComparer) { Debug.Assert(source != null); Debug.Assert(sharedIndices != null); Debug.Assert(sharedBarrier != null); Debug.Assert(keyComparer != null); _source = source; _count = sharedIndices.Size; _take = take; _sharedIndices = sharedIndices; _sharedBarrier = sharedBarrier; _cancellationToken = cancellationToken; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TResult currentElement, ref TKey currentKey) { Debug.Assert(_sharedIndices != null); // If the buffer has not been created, we will populate it lazily on demand. if (_buffer == null && _count > 0) { // Create a buffer, but don't publish it yet (in case of exception). List<Pair<TResult, TKey>> buffer = new List<Pair<TResult, TKey>>(); // Enter the search phase. In this phase, all partitions race to populate // the shared indices with their first 'count' contiguous elements. TResult current = default(TResult)!; TKey index = default(TKey)!; int i = 0; //counter to help with cancellation while (buffer.Count < _count && _source.MoveNext(ref current!, ref index)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Add the current element to our buffer. buffer.Add(new Pair<TResult, TKey>(current, index)); // Now we will try to insert our index into the shared indices list, quitting if // our index is greater than all of the indices already inside it. lock (_sharedIndices) { if (!_sharedIndices.Insert(index)) { // We have read past the maximum index. We can move to the barrier now. break; } } } // Before exiting the search phase, we will synchronize with others. This is a barrier. _sharedBarrier.Signal(); _sharedBarrier.Wait(_cancellationToken); // Publish the buffer and set the index to just before the 1st element. _buffer = buffer; _bufferIndex = new Shared<int>(-1); } // Now either enter (or continue) the yielding phase. As soon as we reach this, we know the // index of the 'count'-th input element. if (_take) { Debug.Assert(_buffer != null && _bufferIndex != null); // In the case of a Take, we will yield each element from our buffer for which // the element is lesser than the 'count'-th index found. if (_count == 0 || _bufferIndex.Value >= _buffer.Count - 1) { return false; } // Increment the index, and remember the values. ++_bufferIndex.Value; currentElement = _buffer[_bufferIndex.Value].First; currentKey = _buffer[_bufferIndex.Value].Second; // Only yield the element if its index is less than or equal to the max index. return _sharedIndices.Count == 0 || _keyComparer.Compare(_buffer[_bufferIndex.Value].Second, _sharedIndices.MaxValue) <= 0; } else { TKey minKey = default(TKey)!; // If the count to skip was greater than 0, look at the buffer. if (_count > 0) { // If there wasn't enough input to skip, return right away. if (_sharedIndices.Count < _count) { return false; } minKey = _sharedIndices.MaxValue; Debug.Assert(_buffer != null && _bufferIndex != null); // In the case of a skip, we must skip over elements whose index is lesser than the // 'count'-th index found. Once we've exhausted the buffer, we must go back and continue // enumerating the data source until it is empty. if (_bufferIndex.Value < _buffer.Count - 1) { for (_bufferIndex.Value++; _bufferIndex.Value < _buffer.Count; _bufferIndex.Value++) { // If the current buffered element's index is greater than the 'count'-th index, // we will yield it as a result. if (_keyComparer.Compare(_buffer[_bufferIndex.Value].Second, minKey) > 0) { currentElement = _buffer[_bufferIndex.Value].First; currentKey = _buffer[_bufferIndex.Value].Second; return true; } } } } // Lastly, so long as our input still has elements, they will be yieldable. if (_source.MoveNext(ref currentElement!, ref currentKey)) { Debug.Assert(_count <= 0 || _keyComparer.Compare(currentKey, minKey) > 0, "expected remaining element indices to be greater than smallest"); return true; } } return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TResult> AsSequentialQuery(CancellationToken token) { if (_take) { return Child.AsSequentialQuery(token).Take(_count); } IEnumerable<TResult> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.Skip(_count); } //----------------------------------------------------------------------------------- // Query results for a Take or a Skip operator. The results are indexable if the child // results were indexable. // private class TakeOrSkipQueryOperatorResults : UnaryQueryOperatorResults { private readonly TakeOrSkipQueryOperator<TResult> _takeOrSkipOp; // The operator that generated the results private readonly int _childCount; // The number of elements in child results public static QueryResults<TResult> NewResults( QueryResults<TResult> childQueryResults, TakeOrSkipQueryOperator<TResult> op, QuerySettings settings, bool preferStriping) { if (childQueryResults.IsIndexible) { return new TakeOrSkipQueryOperatorResults( childQueryResults, op, settings, preferStriping); } else { return new UnaryQueryOperatorResults( childQueryResults, op, settings, preferStriping); } } private TakeOrSkipQueryOperatorResults( QueryResults<TResult> childQueryResults, TakeOrSkipQueryOperator<TResult> takeOrSkipOp, QuerySettings settings, bool preferStriping) : base(childQueryResults, takeOrSkipOp, settings, preferStriping) { _takeOrSkipOp = takeOrSkipOp; Debug.Assert(_childQueryResults.IsIndexible); _childCount = _childQueryResults.ElementsCount; } internal override bool IsIndexible { get { return _childCount >= 0; } } internal override int ElementsCount { get { Debug.Assert(_childCount >= 0); if (_takeOrSkipOp._take) { return Math.Min(_childCount, _takeOrSkipOp._count); } else { return Math.Max(_childCount - _takeOrSkipOp._count, 0); } } } internal override TResult GetElement(int index) { Debug.Assert(_childCount >= 0); Debug.Assert(index >= 0); Debug.Assert(index < ElementsCount); if (_takeOrSkipOp._take) { return _childQueryResults.GetElement(index); } else { return _childQueryResults.GetElement(_takeOrSkipOp._count + index); } } } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class RemoteViews : java.lang.Object, android.os.Parcelable, android.view.LayoutInflater.Filter { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RemoteViews() { InitJNI(); } protected RemoteViews(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class ActionException : java.lang.RuntimeException { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ActionException() { InitJNI(); } protected ActionException(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _ActionException11777; public ActionException(java.lang.Exception arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.ActionException.staticClass, global::android.widget.RemoteViews.ActionException._ActionException11777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _ActionException11778; public ActionException(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.ActionException.staticClass, global::android.widget.RemoteViews.ActionException._ActionException11778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RemoteViews.ActionException.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RemoteViews$ActionException")); global::android.widget.RemoteViews.ActionException._ActionException11777 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.ActionException.staticClass, "<init>", "(Ljava/lang/Exception;)V"); global::android.widget.RemoteViews.ActionException._ActionException11778 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.ActionException.staticClass, "<init>", "(Ljava/lang/String;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.RemoteViews.RemoteView_))] public interface RemoteView : java.lang.annotation.Annotation { } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.RemoteViews.RemoteView))] public sealed partial class RemoteView_ : java.lang.Object, RemoteView { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RemoteView_() { InitJNI(); } internal RemoteView_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _equals11779; bool java.lang.annotation.Annotation.equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_._equals11779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_.staticClass, global::android.widget.RemoteViews.RemoteView_._equals11779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString11780; global::java.lang.String java.lang.annotation.Annotation.toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_._toString11780)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_.staticClass, global::android.widget.RemoteViews.RemoteView_._toString11780)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode11781; int java.lang.annotation.Annotation.hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_._hashCode11781); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_.staticClass, global::android.widget.RemoteViews.RemoteView_._hashCode11781); } internal static global::MonoJavaBridge.MethodId _annotationType11782; global::java.lang.Class java.lang.annotation.Annotation.annotationType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_._annotationType11782)) as java.lang.Class; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RemoteViews.RemoteView_.staticClass, global::android.widget.RemoteViews.RemoteView_._annotationType11782)) as java.lang.Class; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RemoteViews.RemoteView_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RemoteViews$RemoteView")); global::android.widget.RemoteViews.RemoteView_._equals11779 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.RemoteView_.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.widget.RemoteViews.RemoteView_._toString11780 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.RemoteView_.staticClass, "toString", "()Ljava/lang/String;"); global::android.widget.RemoteViews.RemoteView_._hashCode11781 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.RemoteView_.staticClass, "hashCode", "()I"); global::android.widget.RemoteViews.RemoteView_._annotationType11782 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.RemoteView_.staticClass, "annotationType", "()Ljava/lang/Class;"); } } internal static global::MonoJavaBridge.MethodId _getPackage11783; public virtual global::java.lang.String getPackage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RemoteViews._getPackage11783)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._getPackage11783)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _setBoolean11784; public virtual void setBoolean(int arg0, java.lang.String arg1, bool arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setBoolean11784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setBoolean11784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setByte11785; public virtual void setByte(int arg0, java.lang.String arg1, byte arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setByte11785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setByte11785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setChar11786; public virtual void setChar(int arg0, java.lang.String arg1, char arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setChar11786, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setChar11786, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setShort11787; public virtual void setShort(int arg0, java.lang.String arg1, short arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setShort11787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setShort11787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setInt11788; public virtual void setInt(int arg0, java.lang.String arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setInt11788, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setInt11788, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setLong11789; public virtual void setLong(int arg0, java.lang.String arg1, long arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setLong11789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setLong11789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setFloat11790; public virtual void setFloat(int arg0, java.lang.String arg1, float arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setFloat11790, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setFloat11790, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setDouble11791; public virtual void setDouble(int arg0, java.lang.String arg1, double arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setDouble11791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setDouble11791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _writeToParcel11792; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._writeToParcel11792, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._writeToParcel11792, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents11793; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.RemoteViews._describeContents11793); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._describeContents11793); } internal static global::MonoJavaBridge.MethodId _addView11794; public virtual void addView(int arg0, android.widget.RemoteViews arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._addView11794, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._addView11794, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setBitmap11795; public virtual void setBitmap(int arg0, java.lang.String arg1, android.graphics.Bitmap arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setBitmap11795, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setBitmap11795, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _removeAllViews11796; public virtual void removeAllViews(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._removeAllViews11796, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._removeAllViews11796, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setTextColor11797; public virtual void setTextColor(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setTextColor11797, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setTextColor11797, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getLayoutId11798; public virtual int getLayoutId() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.RemoteViews._getLayoutId11798); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._getLayoutId11798); } internal static global::MonoJavaBridge.MethodId _setViewVisibility11799; public virtual void setViewVisibility(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setViewVisibility11799, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setViewVisibility11799, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setTextViewText11800; public virtual void setTextViewText(int arg0, java.lang.CharSequence arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setTextViewText11800, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setTextViewText11800, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void setTextViewText(int arg0, string arg1) { setTextViewText(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1); } internal static global::MonoJavaBridge.MethodId _setImageViewResource11801; public virtual void setImageViewResource(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setImageViewResource11801, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setImageViewResource11801, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setImageViewUri11802; public virtual void setImageViewUri(int arg0, android.net.Uri arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setImageViewUri11802, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setImageViewUri11802, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setImageViewBitmap11803; public virtual void setImageViewBitmap(int arg0, android.graphics.Bitmap arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setImageViewBitmap11803, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setImageViewBitmap11803, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setChronometer11804; public virtual void setChronometer(int arg0, long arg1, java.lang.String arg2, bool arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setChronometer11804, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setChronometer11804, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _setProgressBar11805; public virtual void setProgressBar(int arg0, int arg1, int arg2, bool arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setProgressBar11805, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setProgressBar11805, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _setOnClickPendingIntent11806; public virtual void setOnClickPendingIntent(int arg0, android.app.PendingIntent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setOnClickPendingIntent11806, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setOnClickPendingIntent11806, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setString11807; public virtual void setString(int arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setString11807, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setString11807, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setCharSequence11808; public virtual void setCharSequence(int arg0, java.lang.String arg1, java.lang.CharSequence arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setCharSequence11808, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setCharSequence11808, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public void setCharSequence(int arg0, java.lang.String arg1, string arg2) { setCharSequence(arg0, arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2); } internal static global::MonoJavaBridge.MethodId _setUri11809; public virtual void setUri(int arg0, java.lang.String arg1, android.net.Uri arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setUri11809, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setUri11809, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setBundle11810; public virtual void setBundle(int arg0, java.lang.String arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._setBundle11810, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._setBundle11810, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _apply11811; public virtual global::android.view.View apply(android.content.Context arg0, android.view.ViewGroup arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RemoteViews._apply11811, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._apply11811, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _reapply11812; public virtual void reapply(android.content.Context arg0, android.view.View arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RemoteViews._reapply11812, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._reapply11812, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onLoadClass11813; public virtual bool onLoadClass(java.lang.Class arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.RemoteViews._onLoadClass11813, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._onLoadClass11813, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _RemoteViews11814; public RemoteViews(java.lang.String arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._RemoteViews11814, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _RemoteViews11815; public RemoteViews(android.os.Parcel arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._RemoteViews11815, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _CREATOR11816; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RemoteViews.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RemoteViews")); global::android.widget.RemoteViews._getPackage11783 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "getPackage", "()Ljava/lang/String;"); global::android.widget.RemoteViews._setBoolean11784 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setBoolean", "(ILjava/lang/String;Z)V"); global::android.widget.RemoteViews._setByte11785 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setByte", "(ILjava/lang/String;B)V"); global::android.widget.RemoteViews._setChar11786 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setChar", "(ILjava/lang/String;C)V"); global::android.widget.RemoteViews._setShort11787 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setShort", "(ILjava/lang/String;S)V"); global::android.widget.RemoteViews._setInt11788 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setInt", "(ILjava/lang/String;I)V"); global::android.widget.RemoteViews._setLong11789 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setLong", "(ILjava/lang/String;J)V"); global::android.widget.RemoteViews._setFloat11790 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setFloat", "(ILjava/lang/String;F)V"); global::android.widget.RemoteViews._setDouble11791 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setDouble", "(ILjava/lang/String;D)V"); global::android.widget.RemoteViews._writeToParcel11792 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.widget.RemoteViews._describeContents11793 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "describeContents", "()I"); global::android.widget.RemoteViews._addView11794 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "addView", "(ILandroid/widget/RemoteViews;)V"); global::android.widget.RemoteViews._setBitmap11795 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setBitmap", "(ILjava/lang/String;Landroid/graphics/Bitmap;)V"); global::android.widget.RemoteViews._removeAllViews11796 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "removeAllViews", "(I)V"); global::android.widget.RemoteViews._setTextColor11797 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setTextColor", "(II)V"); global::android.widget.RemoteViews._getLayoutId11798 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "getLayoutId", "()I"); global::android.widget.RemoteViews._setViewVisibility11799 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setViewVisibility", "(II)V"); global::android.widget.RemoteViews._setTextViewText11800 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setTextViewText", "(ILjava/lang/CharSequence;)V"); global::android.widget.RemoteViews._setImageViewResource11801 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setImageViewResource", "(II)V"); global::android.widget.RemoteViews._setImageViewUri11802 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setImageViewUri", "(ILandroid/net/Uri;)V"); global::android.widget.RemoteViews._setImageViewBitmap11803 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setImageViewBitmap", "(ILandroid/graphics/Bitmap;)V"); global::android.widget.RemoteViews._setChronometer11804 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setChronometer", "(IJLjava/lang/String;Z)V"); global::android.widget.RemoteViews._setProgressBar11805 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setProgressBar", "(IIIZ)V"); global::android.widget.RemoteViews._setOnClickPendingIntent11806 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setOnClickPendingIntent", "(ILandroid/app/PendingIntent;)V"); global::android.widget.RemoteViews._setString11807 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setString", "(ILjava/lang/String;Ljava/lang/String;)V"); global::android.widget.RemoteViews._setCharSequence11808 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setCharSequence", "(ILjava/lang/String;Ljava/lang/CharSequence;)V"); global::android.widget.RemoteViews._setUri11809 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setUri", "(ILjava/lang/String;Landroid/net/Uri;)V"); global::android.widget.RemoteViews._setBundle11810 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "setBundle", "(ILjava/lang/String;Landroid/os/Bundle;)V"); global::android.widget.RemoteViews._apply11811 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "apply", "(Landroid/content/Context;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.RemoteViews._reapply11812 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "reapply", "(Landroid/content/Context;Landroid/view/View;)V"); global::android.widget.RemoteViews._onLoadClass11813 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "onLoadClass", "(Ljava/lang/Class;)Z"); global::android.widget.RemoteViews._RemoteViews11814 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "<init>", "(Ljava/lang/String;I)V"); global::android.widget.RemoteViews._RemoteViews11815 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "<init>", "(Landroid/os/Parcel;)V"); } } }
// 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. // Enable CHECK_ACCURATE_ENSURE to ensure that the AsnWriter is not ever // abusing the normal EnsureWriteCapacity + ArrayPool behaviors of rounding up. //#define CHECK_ACCURATE_ENSURE using System.Buffers; using System.Buffers.Text; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using System.Runtime.InteropServices; namespace System.Security.Cryptography.Asn1 { internal sealed class AsnWriter : IDisposable { private byte[] _buffer; private int _offset; private Stack<(Asn1Tag,int)> _nestingStack; public AsnEncodingRules RuleSet { get; } public AsnWriter(AsnEncodingRules ruleSet) { if (ruleSet != AsnEncodingRules.BER && ruleSet != AsnEncodingRules.CER && ruleSet != AsnEncodingRules.DER) { throw new ArgumentOutOfRangeException(nameof(ruleSet)); } RuleSet = ruleSet; } public void Dispose() { _nestingStack = null; if (_buffer != null) { Array.Clear(_buffer, 0, _offset); ArrayPool<byte>.Shared.Return(_buffer); _buffer = null; _offset = 0; } } private void EnsureWriteCapacity(int pendingCount) { if (pendingCount < 0) { throw new OverflowException(); } if (_buffer == null || _buffer.Length - _offset < pendingCount) { #if CHECK_ACCURATE_ENSURE // A debug paradigm to make sure that throughout the execution nothing ever writes // past where the buffer was "allocated". This causes quite a number of reallocs // and copies, so it's a #define opt-in. byte[] newBytes = new byte[_offset + pendingCount]; if (_buffer != null) { Buffer.BlockCopy(_buffer, 0, newBytes, 0, _offset); } #else const int BlockSize = 1024; // While the ArrayPool may have similar logic, make sure we don't run into a lot of // "grow a little" by asking in 1k steps. int blocks = checked(_offset + pendingCount + (BlockSize - 1)) / BlockSize; byte[] newBytes = ArrayPool<byte>.Shared.Rent(BlockSize * blocks); if (_buffer != null) { Buffer.BlockCopy(_buffer, 0, newBytes, 0, _offset); Array.Clear(_buffer, 0, _offset); ArrayPool<byte>.Shared.Return(_buffer); } #endif #if DEBUG // Ensure no "implicit 0" is happening for (int i = _offset; i < newBytes.Length; i++) { newBytes[i] ^= 0xFF; } #endif _buffer = newBytes; } } private void WriteTag(Asn1Tag tag) { int spaceRequired = tag.CalculateEncodedSize(); EnsureWriteCapacity(spaceRequired); if (!tag.TryWrite(_buffer.AsSpan().Slice(_offset, spaceRequired), out int written) || written != spaceRequired) { Debug.Fail($"TryWrite failed or written was wrong value ({written} vs {spaceRequired})"); throw new CryptographicException(); } _offset += spaceRequired; } // T-REC-X.690-201508 sec 8.1.3 private void WriteLength(int length) { const byte MultiByteMarker = 0x80; Debug.Assert(length >= -1); // If the indefinite form has been requested. // T-REC-X.690-201508 sec 8.1.3.6 if (length == -1) { EnsureWriteCapacity(1); _buffer[_offset] = MultiByteMarker; _offset++; return; } Debug.Assert(length >= 0); // T-REC-X.690-201508 sec 8.1.3.3, 8.1.3.4 if (length < MultiByteMarker) { // Pre-allocate the pending data since we know how much. EnsureWriteCapacity(1 + length); _buffer[_offset] = (byte)length; _offset++; return; } // The rest of the method implements T-REC-X.680-201508 sec 8.1.3.5 int lengthLength = GetEncodedLengthSubsequentByteCount(length); // Pre-allocate the pending data since we know how much. EnsureWriteCapacity(lengthLength + 1 + length); _buffer[_offset] = (byte)(MultiByteMarker | lengthLength); // No minus one because offset didn't get incremented yet. int idx = _offset + lengthLength; int remaining = length; do { _buffer[idx] = (byte)remaining; remaining >>= 8; idx--; } while (remaining > 0); Debug.Assert(idx == _offset); _offset += lengthLength + 1; } // T-REC-X.690-201508 sec 8.1.3.5 private static int GetEncodedLengthSubsequentByteCount(int length) { if (length <= 0x7F) return 0; if (length <= byte.MaxValue) return 1; if (length <= ushort.MaxValue) return 2; if (length <= 0x00FFFFFF) return 3; return 4; } public void WriteEncodedValue(ReadOnlyMemory<byte> preEncodedValue) { AsnReader reader = new AsnReader(preEncodedValue, RuleSet); // Is it legal under the current rules? ReadOnlyMemory<byte> parsedBack = reader.GetEncodedValue(); if (reader.HasData) { throw new ArgumentException(SR.Cryptography_WriteEncodedValue_OneValueAtATime, nameof(preEncodedValue)); } Debug.Assert(parsedBack.Length == preEncodedValue.Length); EnsureWriteCapacity(preEncodedValue.Length); preEncodedValue.Span.CopyTo(_buffer.AsSpan().Slice(_offset)); _offset += preEncodedValue.Length; } // T-REC-X.690-201508 sec 8.1.5 private void WriteEndOfContents() { EnsureWriteCapacity(2); _buffer[_offset++] = 0; _buffer[_offset++] = 0; } public void WriteBoolean(bool value) { WriteBooleanCore(Asn1Tag.Boolean, value); } public void WriteBoolean(Asn1Tag tag, bool value) { CheckUniversalTag(tag, UniversalTagNumber.Boolean); WriteBooleanCore(tag.AsPrimitive(), value); } // T-REC-X.690-201508 sec 11.1, 8.2 private void WriteBooleanCore(Asn1Tag tag, bool value) { Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(1); // Ensured by WriteLength Debug.Assert(_offset < _buffer.Length); _buffer[_offset] = (byte)(value ? 0xFF : 0x00); _offset++; } public void WriteInteger(long value) { WriteIntegerCore(Asn1Tag.Integer, value); } public void WriteInteger(ulong value) { WriteNonNegativeIntegerCore(Asn1Tag.Integer, value); } public void WriteInteger(BigInteger value) { WriteIntegerCore(Asn1Tag.Integer, value); } public void WriteInteger(Asn1Tag tag, long value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); WriteIntegerCore(tag.AsPrimitive(), value); } // T-REC-X.690-201508 sec 8.3 private void WriteIntegerCore(Asn1Tag tag, long value) { if (value >= 0) { WriteNonNegativeIntegerCore(tag, (ulong)value); return; } int valueLength; if (value >= sbyte.MinValue) valueLength = 1; else if (value >= short.MinValue) valueLength = 2; else if (value >= unchecked((long)0xFFFFFFFF_FF800000)) valueLength = 3; else if (value >= int.MinValue) valueLength = 4; else if (value >= unchecked((long)0xFFFFFF80_00000000)) valueLength = 5; else if (value >= unchecked((long)0xFFFF8000_00000000)) valueLength = 6; else if (value >= unchecked((long)0xFF800000_00000000)) valueLength = 7; else valueLength = 8; Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(valueLength); long remaining = value; int idx = _offset + valueLength - 1; do { _buffer[idx] = (byte)remaining; remaining >>= 8; idx--; } while (idx >= _offset); #if DEBUG if (valueLength > 1) { // T-REC-X.690-201508 sec 8.3.2 // Cannot start with 9 bits of 1 (or 9 bits of 0, but that's not this method). Debug.Assert(_buffer[_offset] != 0xFF || _buffer[_offset + 1] < 0x80); } #endif _offset += valueLength; } public void WriteInteger(Asn1Tag tag, ulong value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); WriteNonNegativeIntegerCore(tag.AsPrimitive(), value); } // T-REC-X.690-201508 sec 8.3 private void WriteNonNegativeIntegerCore(Asn1Tag tag, ulong value) { int valueLength; // 0x80 needs two bytes: 0x00 0x80 if (value < 0x80) valueLength = 1; else if (value < 0x8000) valueLength = 2; else if (value < 0x800000) valueLength = 3; else if (value < 0x80000000) valueLength = 4; else if (value < 0x80_00000000) valueLength = 5; else if (value < 0x8000_00000000) valueLength = 6; else if (value < 0x800000_00000000) valueLength = 7; else if (value < 0x80000000_00000000) valueLength = 8; else valueLength = 9; // Clear the constructed bit, if it was set. Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(valueLength); ulong remaining = value; int idx = _offset + valueLength - 1; do { _buffer[idx] = (byte)remaining; remaining >>= 8; idx--; } while (idx >= _offset); #if DEBUG if (valueLength > 1) { // T-REC-X.690-201508 sec 8.3.2 // Cannot start with 9 bits of 0 (or 9 bits of 1, but that's not this method). Debug.Assert(_buffer[_offset] != 0 || _buffer[_offset + 1] > 0x7F); } #endif _offset += valueLength; } public void WriteInteger(Asn1Tag tag, BigInteger value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); WriteIntegerCore(tag.AsPrimitive(), value); } // T-REC-X.690-201508 sec 8.3 private void WriteIntegerCore(Asn1Tag tag, BigInteger value) { // TODO: Split this for netstandard vs netcoreapp for span-perf?. byte[] encoded = value.ToByteArray(); Array.Reverse(encoded); Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(encoded.Length); Buffer.BlockCopy(encoded, 0, _buffer, _offset, encoded.Length); _offset += encoded.Length; } public void WriteBitString(ReadOnlySpan<byte> bitString, int unusedBitCount=0) { WriteBitStringCore(Asn1Tag.PrimitiveBitString, bitString, unusedBitCount); } public void WriteBitString(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount=0) { CheckUniversalTag(tag, UniversalTagNumber.BitString); // Primitive or constructed, doesn't matter. WriteBitStringCore(tag, bitString, unusedBitCount); } // T-REC-X.690-201508 sec 8.6 private void WriteBitStringCore(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount) { // T-REC-X.690-201508 sec 8.6.2.2 if (unusedBitCount < 0 || unusedBitCount > 7) { throw new ArgumentOutOfRangeException( nameof(unusedBitCount), unusedBitCount, SR.Cryptography_Asn_UnusedBitCountRange); } // T-REC-X.690-201508 sec 8.6.2.3 if (bitString.Length == 0 && unusedBitCount != 0) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } // If 3 bits are "unused" then build a mask for them to check for 0. // 1 << 3 => 0b0000_1000 // subtract 1 => 0b000_0111 int mask = (1 << unusedBitCount) - 1; byte lastByte = bitString.IsEmpty ? (byte)0 : bitString[bitString.Length - 1]; if ((lastByte & mask) != 0) { // T-REC-X.690-201508 sec 11.2 // // This could be ignored for BER, but since DER is more common and // it likely suggests a program error on the caller, leave it enabled for // BER for now. // TODO: Probably warrants a distinct message. throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } if (RuleSet == AsnEncodingRules.CER) { // T-REC-X.690-201508 sec 9.2 // // If it's not within a primitive segment, use the constructed encoding. // (>= instead of > because of the unused bit count byte) if (bitString.Length >= AsnReader.MaxCERSegmentSize) { WriteConstructedCerBitString(tag, bitString, unusedBitCount); return; } } // Clear the constructed flag, if present. WriteTag(tag.AsPrimitive()); // The unused bits byte requires +1. WriteLength(bitString.Length + 1); _buffer[_offset] = (byte)unusedBitCount; _offset++; bitString.CopyTo(_buffer.AsSpan().Slice(_offset)); _offset += bitString.Length; } // T-REC-X.690-201508 sec 9.2, 8.6 private void WriteConstructedCerBitString(Asn1Tag tag, ReadOnlySpan<byte> payload, int unusedBitCount) { const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize; // Every segment has an "unused bit count" byte. const int MaxCERContentSize = MaxCERSegmentSize - 1; Debug.Assert(payload.Length > MaxCERContentSize); WriteTag(tag.AsConstructed()); // T-REC-X.690-201508 sec 9.1 // Constructed CER uses the indefinite form. WriteLength(-1); int fullSegments = Math.DivRem(payload.Length, MaxCERContentSize, out int lastContentSize); // The tag size is 1 byte. // The length will always be encoded as 82 03 E8 (3 bytes) // And 1000 content octets (by T-REC-X.690-201508 sec 9.2) const int FullSegmentEncodedSize = 1004; Debug.Assert( FullSegmentEncodedSize == 1 + 1 + MaxCERSegmentSize + GetEncodedLengthSubsequentByteCount(MaxCERSegmentSize)); int remainingEncodedSize; if (lastContentSize == 0) { remainingEncodedSize = 0; } else { // One byte of tag, minimum one byte of length, and one byte of unused bit count. remainingEncodedSize = 3 + lastContentSize + GetEncodedLengthSubsequentByteCount(lastContentSize); } // Reduce the number of copies by pre-calculating the size. // +2 for End-Of-Contents int expectedSize = fullSegments * FullSegmentEncodedSize + remainingEncodedSize + 2; EnsureWriteCapacity(expectedSize); byte[] ensureNoExtraCopy = _buffer; int savedOffset = _offset; ReadOnlySpan<byte> remainingData = payload; Span<byte> dest; Asn1Tag primitiveBitString = Asn1Tag.PrimitiveBitString; while (remainingData.Length > MaxCERContentSize) { // T-REC-X.690-201508 sec 8.6.4.1 WriteTag(primitiveBitString); WriteLength(MaxCERSegmentSize); // 0 unused bits in this segment. _buffer[_offset] = 0; _offset++; dest = _buffer.AsSpan().Slice(_offset); remainingData.Slice(0, MaxCERContentSize).CopyTo(dest); remainingData = remainingData.Slice(MaxCERContentSize); _offset += MaxCERContentSize; } WriteTag(primitiveBitString); WriteLength(remainingData.Length + 1); _buffer[_offset] = (byte)unusedBitCount; _offset++; dest = _buffer.AsSpan().Slice(_offset); remainingData.CopyTo(dest); _offset += remainingData.Length; WriteEndOfContents(); Debug.Assert(_offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {_offset - savedOffset}"); Debug.Assert(_buffer == ensureNoExtraCopy, $"_buffer was replaced during {nameof(WriteConstructedCerBitString)}"); } public void WriteNamedBitList(object enumValue) { if (enumValue == null) throw new ArgumentNullException(nameof(enumValue)); WriteNamedBitList(Asn1Tag.PrimitiveBitString, enumValue); } public void WriteNamedBitList<TEnum>(TEnum enumValue) where TEnum : struct { WriteNamedBitList(Asn1Tag.PrimitiveBitString, enumValue); } public void WriteNamedBitList(Asn1Tag tag, object enumValue) { if (enumValue == null) throw new ArgumentNullException(nameof(enumValue)); WriteNamedBitList(tag, enumValue.GetType(), enumValue); } public void WriteNamedBitList<TEnum>(Asn1Tag tag, TEnum enumValue) where TEnum : struct { WriteNamedBitList(tag, typeof(TEnum), enumValue); } private void WriteNamedBitList(Asn1Tag tag, Type tEnum, object enumValue) { Type backingType = tEnum.GetEnumUnderlyingType(); if (!tEnum.IsDefined(typeof(FlagsAttribute), false)) { throw new ArgumentException(SR.Cryptography_Asn_NamedBitListRequiresFlagsEnum, nameof(tEnum)); } ulong integralValue; if (backingType == typeof(ulong)) { integralValue = Convert.ToUInt64(enumValue); } else { // All other types fit in a (signed) long. long numericValue = Convert.ToInt64(enumValue); integralValue = unchecked((ulong)numericValue); } WriteNamedBitList(tag, integralValue); } // T-REC-X.680-201508 sec 22 // T-REC-X.690-201508 sec 8.6, 11.2.2 private void WriteNamedBitList(Asn1Tag tag, ulong integralValue) { Span<byte> temp = stackalloc byte[sizeof(ulong)]; // Reset to all zeros, since we're just going to or-in bits we need. temp.Clear(); int indexOfHighestSetBit = -1; for (int i = 0; integralValue != 0; integralValue >>= 1, i++) { if ((integralValue & 1) != 0) { temp[i / 8] |= (byte)(0x80 >> (i % 8)); indexOfHighestSetBit = i; } } if (indexOfHighestSetBit < 0) { // No bits were set; this is an empty bit string. // T-REC-X.690-201508 sec 11.2.2-note2 WriteBitString(tag, ReadOnlySpan<byte>.Empty); } else { // At least one bit was set. // Determine the shortest length necessary to represent the bit string. // Since "bit 0" gets written down 0 => 1. // Since "bit 8" is in the second byte 8 => 2. // That makes the formula ((bit / 8) + 1) instead of ((bit + 7) / 8). int byteLen = (indexOfHighestSetBit / 8) + 1; int unusedBitCount = 7 - (indexOfHighestSetBit % 8); WriteBitString( tag, temp.Slice(0, byteLen), unusedBitCount); } } public void WriteOctetString(ReadOnlySpan<byte> octetString) { WriteOctetString(Asn1Tag.PrimitiveOctetString, octetString); } public void WriteOctetString(Asn1Tag tag, ReadOnlySpan<byte> octetString) { CheckUniversalTag(tag, UniversalTagNumber.OctetString); // Primitive or constructed, doesn't matter. WriteOctetStringCore(tag, octetString); } // T-REC-X.690-201508 sec 8.7 private void WriteOctetStringCore(Asn1Tag tag, ReadOnlySpan<byte> octetString) { if (RuleSet == AsnEncodingRules.CER) { // If it's bigger than a primitive segment, use the constructed encoding // T-REC-X.690-201508 sec 9.2 if (octetString.Length > AsnReader.MaxCERSegmentSize) { WriteConstructedCerOctetString(tag, octetString); return; } } // Clear the constructed flag, if present. WriteTag(tag.AsPrimitive()); WriteLength(octetString.Length); octetString.CopyTo(_buffer.AsSpan().Slice(_offset)); _offset += octetString.Length; } // T-REC-X.690-201508 sec 9.2, 8.7 private void WriteConstructedCerOctetString(Asn1Tag tag, ReadOnlySpan<byte> payload) { const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize; Debug.Assert(payload.Length > MaxCERSegmentSize); WriteTag(tag.AsConstructed()); WriteLength(-1); int fullSegments = Math.DivRem(payload.Length, MaxCERSegmentSize, out int lastSegmentSize); // The tag size is 1 byte. // The length will always be encoded as 82 03 E8 (3 bytes) // And 1000 content octets (by T-REC-X.690-201508 sec 9.2) const int FullSegmentEncodedSize = 1004; Debug.Assert( FullSegmentEncodedSize == 1 + 1 + MaxCERSegmentSize + GetEncodedLengthSubsequentByteCount(MaxCERSegmentSize)); int remainingEncodedSize; if (lastSegmentSize == 0) { remainingEncodedSize = 0; } else { // One byte of tag, and minimum one byte of length. remainingEncodedSize = 2 + lastSegmentSize + GetEncodedLengthSubsequentByteCount(lastSegmentSize); } // Reduce the number of copies by pre-calculating the size. // +2 for End-Of-Contents int expectedSize = fullSegments * FullSegmentEncodedSize + remainingEncodedSize + 2; EnsureWriteCapacity(expectedSize); byte[] ensureNoExtraCopy = _buffer; int savedOffset = _offset; ReadOnlySpan<byte> remainingData = payload; Span<byte> dest; Asn1Tag primitiveOctetString = Asn1Tag.PrimitiveOctetString; while (remainingData.Length > MaxCERSegmentSize) { // T-REC-X.690-201508 sec 8.7.3.2-note2 WriteTag(primitiveOctetString); WriteLength(MaxCERSegmentSize); dest = _buffer.AsSpan().Slice(_offset); remainingData.Slice(0, MaxCERSegmentSize).CopyTo(dest); _offset += MaxCERSegmentSize; remainingData = remainingData.Slice(MaxCERSegmentSize); } WriteTag(primitiveOctetString); WriteLength(remainingData.Length); dest = _buffer.AsSpan().Slice(_offset); remainingData.CopyTo(dest); _offset += remainingData.Length; WriteEndOfContents(); Debug.Assert(_offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {_offset - savedOffset}"); Debug.Assert(_buffer == ensureNoExtraCopy, $"_buffer was replaced during {nameof(WriteConstructedCerOctetString)}"); } public void WriteNull() { WriteNullCore(Asn1Tag.Null); } public void WriteNull(Asn1Tag tag) { CheckUniversalTag(tag, UniversalTagNumber.Null); WriteNullCore(tag.AsPrimitive()); } // T-REC-X.690-201508 sec 8.8 private void WriteNullCore(Asn1Tag tag) { Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(0); } public void WriteObjectIdentifier(Oid oid) { if (oid == null) throw new ArgumentNullException(nameof(oid)); WriteObjectIdentifier(oid.Value); } public void WriteObjectIdentifier(string oidValue) { if (oidValue == null) throw new ArgumentNullException(nameof(oidValue)); WriteObjectIdentifier(oidValue.AsReadOnlySpan()); } public void WriteObjectIdentifier(ReadOnlySpan<char> oidValue) { WriteObjectIdentifierCore(Asn1Tag.ObjectIdentifier, oidValue); } public void WriteObjectIdentifier(Asn1Tag tag, Oid oid) { if (oid == null) throw new ArgumentNullException(nameof(oid)); WriteObjectIdentifier(tag, oid.Value); } public void WriteObjectIdentifier(Asn1Tag tag, string oidValue) { if (oidValue == null) throw new ArgumentNullException(nameof(oidValue)); WriteObjectIdentifier(tag, oidValue.AsReadOnlySpan()); } public void WriteObjectIdentifier(Asn1Tag tag, ReadOnlySpan<char> oidValue) { CheckUniversalTag(tag, UniversalTagNumber.ObjectIdentifier); WriteObjectIdentifierCore(tag.AsPrimitive(), oidValue); } // T-REC-X.690-201508 sec 8.19 private void WriteObjectIdentifierCore(Asn1Tag tag, ReadOnlySpan<char> oidValue) { // T-REC-X.690-201508 sec 8.19.4 // The first character is in { 0, 1, 2 }, the second will be a '.', and a third (digit) // will also exist. if (oidValue.Length < 3) throw new CryptographicException(SR.Argument_InvalidOidValue); if (oidValue[1] != '.') throw new CryptographicException(SR.Argument_InvalidOidValue); // The worst case is "1.1.1.1.1", which takes 4 bytes (5 components, with the first two condensed) // Longer numbers get smaller: "2.1.127" is only 2 bytes. (81d (0x51) and 127 (0x7F)) // So length / 2 should prevent any reallocations. byte[] tmp = ArrayPool<byte>.Shared.Rent(oidValue.Length / 2); int tmpOffset = 0; try { int firstComponent; switch (oidValue[0]) { case '0': firstComponent = 0; break; case '1': firstComponent = 1; break; case '2': firstComponent = 2; break; default: throw new CryptographicException(SR.Argument_InvalidOidValue); } // The first two components are special: // ITU X.690 8.19.4: // The numerical value of the first subidentifier is derived from the values of the first two // object identifier components in the object identifier value being encoded, using the formula: // (X*40) + Y // where X is the value of the first object identifier component and Y is the value of the // second object identifier component. // NOTE - This packing of the first two object identifier components recognizes that only // three values are allocated from the root node, and at most 39 subsequent values from // nodes reached by X = 0 and X = 1. // skip firstComponent and the trailing . ReadOnlySpan<char> remaining = oidValue.Slice(2); BigInteger subIdentifier = ParseSubIdentifier(ref remaining); subIdentifier += 40 * firstComponent; int localLen = EncodeSubIdentifier(tmp.AsSpan().Slice(tmpOffset), ref subIdentifier); tmpOffset += localLen; while (!remaining.IsEmpty) { subIdentifier = ParseSubIdentifier(ref remaining); localLen = EncodeSubIdentifier(tmp.AsSpan().Slice(tmpOffset), ref subIdentifier); tmpOffset += localLen; } Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(tmpOffset); Buffer.BlockCopy(tmp, 0, _buffer, _offset, tmpOffset); _offset += tmpOffset; } finally { Array.Clear(tmp, 0, tmpOffset); ArrayPool<byte>.Shared.Return(tmp); } } private static BigInteger ParseSubIdentifier(ref ReadOnlySpan<char> oidValue) { int endIndex = oidValue.IndexOf('.'); if (endIndex == -1) { endIndex = oidValue.Length; } else if (endIndex == oidValue.Length - 1) { throw new CryptographicException(SR.Argument_InvalidOidValue); } // The following code is equivalent to // BigInteger.TryParse(temp, NumberStyles.None, CultureInfo.InvariantCulture, out value) // TODO: Split this for netstandard vs netcoreapp for span-perf?. BigInteger value = BigInteger.Zero; for (int position = 0; position < endIndex; position++) { if (position > 0 && value == 0) { // T-REC X.680-201508 sec 12.26 throw new CryptographicException(SR.Argument_InvalidOidValue); } value *= 10; value += AtoI(oidValue[position]); } oidValue = oidValue.Slice(Math.Min(oidValue.Length, endIndex + 1)); return value; } private static int AtoI(char c) { if (c >= '0' && c <= '9') { return c - '0'; } throw new CryptographicException(SR.Argument_InvalidOidValue); } // ITU-T-X.690-201508 sec 8.19.5 private static int EncodeSubIdentifier(Span<byte> dest, ref BigInteger subIdentifier) { Debug.Assert(dest.Length > 0); if (subIdentifier.IsZero) { dest[0] = 0; return 1; } BigInteger unencoded = subIdentifier; int idx = 0; do { BigInteger cur = unencoded & 0x7F; byte curByte = (byte)cur; if (subIdentifier != unencoded) { curByte |= 0x80; } unencoded >>= 7; dest[idx] = curByte; idx++; } while (unencoded != BigInteger.Zero); Reverse(dest.Slice(0, idx)); return idx; } public void WriteEnumeratedValue(object enumValue) { if (enumValue == null) throw new ArgumentNullException(nameof(enumValue)); WriteEnumeratedValue(Asn1Tag.Enumerated, enumValue); } public void WriteEnumeratedValue<TEnum>(TEnum value) where TEnum : struct { WriteEnumeratedValue(Asn1Tag.Enumerated, value); } public void WriteEnumeratedValue(Asn1Tag tag, object enumValue) { if (enumValue == null) throw new ArgumentNullException(nameof(enumValue)); WriteEnumeratedValue(tag.AsPrimitive(), enumValue.GetType(), enumValue); } public void WriteEnumeratedValue<TEnum>(Asn1Tag tag, TEnum value) where TEnum : struct { WriteEnumeratedValue(tag.AsPrimitive(), typeof(TEnum), value); } // T-REC-X.690-201508 sec 8.4 private void WriteEnumeratedValue(Asn1Tag tag, Type tEnum, object enumValue) { CheckUniversalTag(tag, UniversalTagNumber.Enumerated); Type backingType = tEnum.GetEnumUnderlyingType(); if (tEnum.IsDefined(typeof(FlagsAttribute), false)) { throw new ArgumentException( SR.Cryptography_Asn_EnumeratedValueRequiresNonFlagsEnum, nameof(tEnum)); } if (backingType == typeof(ulong)) { ulong numericValue = Convert.ToUInt64(enumValue); // T-REC-X.690-201508 sec 8.4 WriteNonNegativeIntegerCore(tag, numericValue); } else { // All other types fit in a (signed) long. long numericValue = Convert.ToInt64(enumValue); // T-REC-X.690-201508 sec 8.4 WriteIntegerCore(tag, numericValue); } } public void PushSequence() { PushSequenceCore(Asn1Tag.Sequence); } public void PushSequence(Asn1Tag tag) { CheckUniversalTag(tag, UniversalTagNumber.Sequence); // Assert the constructed flag, in case it wasn't. PushSequenceCore(tag.AsConstructed()); } // T-REC-X.690-201508 sec 8.9, 8.10 private void PushSequenceCore(Asn1Tag tag) { PushTag(tag.AsConstructed()); } public void PopSequence() { PopSequence(Asn1Tag.Sequence); } public void PopSequence(Asn1Tag tag) { // PopSequence shouldn't be used to pop a SetOf. CheckUniversalTag(tag, UniversalTagNumber.Sequence); // Assert the constructed flag, in case it wasn't. PopSequenceCore(tag.AsConstructed()); } // T-REC-X.690-201508 sec 8.9, 8.10 private void PopSequenceCore(Asn1Tag tag) { PopTag(tag); } public void PushSetOf() { PushSetOf(Asn1Tag.SetOf); } public void PushSetOf(Asn1Tag tag) { CheckUniversalTag(tag, UniversalTagNumber.SetOf); // Assert the constructed flag, in case it wasn't. PushSetOfCore(tag.AsConstructed()); } // T-REC-X.690-201508 sec 8.12 // The writer claims SetOf, and not Set, so as to avoid the field // ordering clause of T-REC-X.690-201508 sec 9.3 private void PushSetOfCore(Asn1Tag tag) { PushTag(tag); } public void PopSetOf() { PopSetOfCore(Asn1Tag.SetOf); } public void PopSetOf(Asn1Tag tag) { CheckUniversalTag(tag, UniversalTagNumber.SetOf); // Assert the constructed flag, in case it wasn't. PopSetOfCore(tag.AsConstructed()); } // T-REC-X.690-201508 sec 8.12 private void PopSetOfCore(Asn1Tag tag) { // T-REC-X.690-201508 sec 11.6 bool sortContents = RuleSet == AsnEncodingRules.CER || RuleSet == AsnEncodingRules.DER; PopTag(tag, sortContents); } public void WriteUtcTime(DateTimeOffset value) { WriteUtcTimeCore(Asn1Tag.UtcTime, value); } public void WriteUtcTime(Asn1Tag tag, DateTimeOffset value) { CheckUniversalTag(tag, UniversalTagNumber.UtcTime); // Clear the constructed flag, if present. WriteUtcTimeCore(tag.AsPrimitive(), value); } // T-REC-X.680-201508 sec 47 // T-REC-X.690-201508 sec 11.8 private void WriteUtcTimeCore(Asn1Tag tag, DateTimeOffset value) { // Because UtcTime is IMPLICIT VisibleString it technically can have // a constructed form. // DER says character strings must be primitive. // CER says character strings <= 1000 encoded bytes must be primitive. // So we'll just make BER be primitive, too. Debug.Assert(!tag.IsConstructed); WriteTag(tag); // BER allows for omitting the seconds, but that's not an option we need to expose. // BER allows for non-UTC values, but that's also not an option we need to expose. // So the format is always yyMMddHHmmssZ (13) const int UtcTimeValueLength = 13; WriteLength(UtcTimeValueLength); DateTimeOffset normalized = value.ToUniversalTime(); int year = normalized.Year; int month = normalized.Month; int day = normalized.Day; int hour = normalized.Hour; int minute = normalized.Minute; int second = normalized.Second; Span<byte> baseSpan = _buffer.AsSpan().Slice(_offset); StandardFormat format = new StandardFormat('D', 2); if (!Utf8Formatter.TryFormat(year % 100, baseSpan.Slice(0, 2), out _, format) || !Utf8Formatter.TryFormat(month, baseSpan.Slice(2, 2), out _, format) || !Utf8Formatter.TryFormat(day, baseSpan.Slice(4, 2), out _, format) || !Utf8Formatter.TryFormat(hour, baseSpan.Slice(6, 2), out _, format) || !Utf8Formatter.TryFormat(minute, baseSpan.Slice(8, 2), out _, format) || !Utf8Formatter.TryFormat(second, baseSpan.Slice(10, 2), out _, format)) { Debug.Fail($"Utf8Formatter.TryFormat failed to build components of {normalized:O}"); throw new CryptographicException(); } _buffer[_offset + 12] = (byte)'Z'; _offset += UtcTimeValueLength; } public void WriteGeneralizedTime(DateTimeOffset value, bool omitFractionalSeconds = false) { WriteGeneralizedTimeCore(Asn1Tag.GeneralizedTime, value, omitFractionalSeconds); } public void WriteGeneralizedTime(Asn1Tag tag, DateTimeOffset value, bool omitFractionalSeconds = false) { CheckUniversalTag(tag, UniversalTagNumber.GeneralizedTime); // Clear the constructed flag, if present. WriteGeneralizedTimeCore(tag.AsPrimitive(), value, omitFractionalSeconds); } // T-REC-X.680-201508 sec 46 // T-REC-X.690-201508 sec 11.7 private void WriteGeneralizedTimeCore(Asn1Tag tag, DateTimeOffset value, bool omitFractionalSeconds) { // GeneralizedTime under BER allows many different options: // * (HHmmss), (HHmm), (HH) // * "(value).frac", "(value),frac" // * frac == 0 may be omitted or emitted // non-UTC offset in various formats // // We're not allowing any of them. // Just encode as the CER/DER common restrictions. // // This results in the following formats: // yyyyMMddHHmmssZ // yyyyMMddHHmmss.f?Z // // where "f?" is anything from "f" to "fffffff" (tenth of a second down to 100ns/1-tick) // with no trailing zeros. DateTimeOffset normalized = value.ToUniversalTime(); if (normalized.Year > 9999) { // This is unreachable since DateTimeOffset guards against this internally. throw new ArgumentOutOfRangeException(nameof(value)); } // We're only loading in sub-second ticks. // Ticks are defined as 1e-7 seconds, so their printed form // is at the longest "0.1234567", or 9 bytes. Span<byte> fraction = stackalloc byte[0]; if (!omitFractionalSeconds) { long floatingTicks = normalized.Ticks % TimeSpan.TicksPerSecond; if (floatingTicks != 0) { // We're only loading in sub-second ticks. // Ticks are defined as 1e-7 seconds, so their printed form // is at the longest "0.1234567", or 9 bytes. fraction = stackalloc byte[9]; decimal decimalTicks = floatingTicks; decimalTicks /= TimeSpan.TicksPerSecond; if (!Utf8Formatter.TryFormat(decimalTicks, fraction, out int bytesWritten, new StandardFormat('G'))) { Debug.Fail($"Utf8Formatter.TryFormat could not format {floatingTicks} / TicksPerSecond"); throw new CryptographicException(); } Debug.Assert(bytesWritten > 2, $"{bytesWritten} should be > 2"); Debug.Assert(fraction[0] == (byte)'0'); Debug.Assert(fraction[1] == (byte)'.'); fraction = fraction.Slice(1, bytesWritten - 1); } } // yyyy, MM, dd, hh, mm, ss const int IntegerPortionLength = 4 + 2 + 2 + 2 + 2 + 2; // Z, and the optional fraction. int totalLength = IntegerPortionLength + 1 + fraction.Length; // Because GeneralizedTime is IMPLICIT VisibleString it technically can have // a constructed form. // DER says character strings must be primitive. // CER says character strings <= 1000 encoded bytes must be primitive. // So we'll just make BER be primitive, too. Debug.Assert(!tag.IsConstructed); WriteTag(tag); WriteLength(totalLength); int year = normalized.Year; int month = normalized.Month; int day = normalized.Day; int hour = normalized.Hour; int minute = normalized.Minute; int second = normalized.Second; Span<byte> baseSpan = _buffer.AsSpan().Slice(_offset); StandardFormat d4 = new StandardFormat('D', 4); StandardFormat d2 = new StandardFormat('D', 2); if (!Utf8Formatter.TryFormat(year, baseSpan.Slice(0, 4), out _, d4) || !Utf8Formatter.TryFormat(month, baseSpan.Slice(4, 2), out _, d2) || !Utf8Formatter.TryFormat(day, baseSpan.Slice(6, 2), out _, d2) || !Utf8Formatter.TryFormat(hour, baseSpan.Slice(8, 2), out _, d2) || !Utf8Formatter.TryFormat(minute, baseSpan.Slice(10, 2), out _, d2) || !Utf8Formatter.TryFormat(second, baseSpan.Slice(12, 2), out _, d2)) { Debug.Fail($"Utf8Formatter.TryFormat failed to build components of {normalized:O}"); throw new CryptographicException(); } _offset += IntegerPortionLength; fraction.CopyTo(baseSpan.Slice(IntegerPortionLength)); _offset += fraction.Length; _buffer[_offset] = (byte)'Z'; _offset++; } /// <summary> /// Transfer the encoded representation of the data to <paramref name="dest"/>. /// </summary> /// <param name="dest">Write destination.</param> /// <param name="bytesWritten">The number of bytes which were written to <paramref name="dest"/>.</param> /// <returns><c>true</c> if the encode succeeded, <c>false</c> if <paramref name="dest"/> is too small.</returns> /// <exception cref="InvalidOperationException"> /// A <see cref="PushSequence()"/> or <see cref="PushSetOf()"/> has not been closed via /// <see cref="PopSequence()"/> or <see cref="PopSetOf()"/>. /// </exception> public bool TryEncode(Span<byte> dest, out int bytesWritten) { if ((_nestingStack?.Count ?? 0) != 0) throw new InvalidOperationException(SR.Cryptography_AsnWriter_EncodeUnbalancedStack); // If the stack is closed out then everything is a definite encoding (BER, DER) or a // required indefinite encoding (CER). So we're correctly sized up, and ready to copy. if (dest.Length < _offset) { bytesWritten = 0; return false; } if (_offset == 0) { bytesWritten = 0; return true; } bytesWritten = _offset; _buffer.AsSpan().Slice(0, _offset).CopyTo(dest); return true; } public byte[] Encode() { if ((_nestingStack?.Count ?? 0) != 0) { throw new InvalidOperationException(SR.Cryptography_AsnWriter_EncodeUnbalancedStack); } if (_offset == 0) { return Array.Empty<byte>(); } // If the stack is closed out then everything is a definite encoding (BER, DER) or a // required indefinite encoding (CER). So we're correctly sized up, and ready to copy. return _buffer.AsSpan().Slice(0, _offset).ToArray(); } public ReadOnlySpan<byte> EncodeAsSpan() { if ((_nestingStack?.Count ?? 0) != 0) { throw new InvalidOperationException(SR.Cryptography_AsnWriter_EncodeUnbalancedStack); } if (_offset == 0) { return ReadOnlySpan<byte>.Empty; } // If the stack is closed out then everything is a definite encoding (BER, DER) or a // required indefinite encoding (CER). So we're correctly sized up, and ready to copy. return new ReadOnlySpan<byte>(_buffer, 0, _offset); } private void PushTag(Asn1Tag tag) { if (_nestingStack == null) { _nestingStack = new Stack<(Asn1Tag,int)>(); } Debug.Assert(tag.IsConstructed); WriteTag(tag); _nestingStack.Push((tag, _offset)); // Indicate that the length is indefinite. // We'll come back and clean this up (as appropriate) in PopTag. WriteLength(-1); } private void PopTag(Asn1Tag tag, bool sortContents=false) { if (_nestingStack == null || _nestingStack.Count == 0) { throw new ArgumentException(SR.Cryptography_AsnWriter_PopWrongTag, nameof(tag)); } (Asn1Tag stackTag, int lenOffset) = _nestingStack.Peek(); Debug.Assert(tag.IsConstructed); if (stackTag != tag) { throw new ArgumentException(SR.Cryptography_AsnWriter_PopWrongTag, nameof(tag)); } _nestingStack.Pop(); if (sortContents) { SortContents(_buffer, lenOffset + 1, _offset); } // BER could use the indefinite encoding that CER does. // But since the definite encoding form is easier to read (doesn't require a contextual // parser to find the end-of-contents marker) some ASN.1 readers (including the previous // incarnation of AsnReader) may choose not to support it. // // So, BER will use the DER rules here, in the interest of broader compatibility. // T-REC-X.690-201508 sec 9.1 (constructed CER => indefinite length) // T-REC-X.690-201508 sec 8.1.3.6 if (RuleSet == AsnEncodingRules.CER) { WriteEndOfContents(); return; } int containedLength = _offset - 1 - lenOffset; Debug.Assert(containedLength >= 0); int shiftSize = GetEncodedLengthSubsequentByteCount(containedLength); // Best case, length fits in the compact byte if (shiftSize == 0) { _buffer[lenOffset] = (byte)containedLength; return; } // We're currently at the end, so ensure we have room for N more bytes. EnsureWriteCapacity(shiftSize); // Buffer.BlockCopy correctly does forward-overlapped, so use it. int start = lenOffset + 1; Buffer.BlockCopy(_buffer, start, _buffer, start + shiftSize, containedLength); int tmp = _offset; _offset = lenOffset; WriteLength(containedLength); Debug.Assert(_offset - lenOffset - 1 == shiftSize); _offset = tmp + shiftSize; } public void WriteCharacterString(UniversalTagNumber encodingType, string str) { if (str == null) throw new ArgumentNullException(nameof(str)); WriteCharacterString(encodingType, str.AsReadOnlySpan()); } public void WriteCharacterString(UniversalTagNumber encodingType, ReadOnlySpan<char> str) { Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType); WriteCharacterStringCore(new Asn1Tag(encodingType), encoding, str); } public void WriteCharacterString(Asn1Tag tag, UniversalTagNumber encodingType, string str) { if (str == null) throw new ArgumentNullException(nameof(str)); WriteCharacterString(tag, encodingType, str.AsReadOnlySpan()); } public void WriteCharacterString(Asn1Tag tag, UniversalTagNumber encodingType, ReadOnlySpan<char> str) { CheckUniversalTag(tag, encodingType); Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType); WriteCharacterStringCore(tag, encoding, str); } // T-REC-X.690-201508 sec 8.23 private void WriteCharacterStringCore(Asn1Tag tag, Text.Encoding encoding, ReadOnlySpan<char> str) { int size = -1; // T-REC-X.690-201508 sec 9.2 if (RuleSet == AsnEncodingRules.CER) { // TODO: Split this for netstandard vs netcoreapp for span?. unsafe { fixed (char* strPtr = &MemoryMarshal.GetReference(str)) { size = encoding.GetByteCount(strPtr, str.Length); // If it exceeds the primitive segment size, use the constructed encoding. if (size > AsnReader.MaxCERSegmentSize) { WriteConstructedCerCharacterString(tag, encoding, str, size); return; } } } } // TODO: Split this for netstandard vs netcoreapp for span?. unsafe { fixed (char* strPtr = &MemoryMarshal.GetReference(str)) { if (size < 0) { size = encoding.GetByteCount(strPtr, str.Length); } // Clear the constructed tag, if present. WriteTag(tag.AsPrimitive()); WriteLength(size); Span<byte> dest = _buffer.AsSpan().Slice(_offset, size); fixed (byte* destPtr = &MemoryMarshal.GetReference(dest)) { int written = encoding.GetBytes(strPtr, str.Length, destPtr, dest.Length); if (written != size) { Debug.Fail($"Encoding produced different answer for GetByteCount ({size}) and GetBytes ({written})"); throw new InvalidOperationException(); } } _offset += size; } } } private void WriteConstructedCerCharacterString(Asn1Tag tag, Text.Encoding encoding, ReadOnlySpan<char> str, int size) { Debug.Assert(size > AsnReader.MaxCERSegmentSize); byte[] tmp; // TODO: Split this for netstandard vs netcoreapp for span?. unsafe { fixed (char* strPtr = &MemoryMarshal.GetReference(str)) { tmp = ArrayPool<byte>.Shared.Rent(size); fixed (byte* destPtr = tmp) { int written = encoding.GetBytes(strPtr, str.Length, destPtr, tmp.Length); if (written != size) { Debug.Fail( $"Encoding produced different answer for GetByteCount ({size}) and GetBytes ({written})"); throw new InvalidOperationException(); } } } } WriteConstructedCerOctetString(tag, tmp.AsSpan().Slice(0, size)); Array.Clear(tmp, 0, size); ArrayPool<byte>.Shared.Return(tmp); } private static void SortContents(byte[] buffer, int start, int end) { Debug.Assert(buffer != null); Debug.Assert(end >= start); int len = end - start; if (len == 0) { return; } // Since BER can read everything and the reader does not mutate data // just use a BER reader for identifying the positions of the values // within this memory segment. // // Since it's not mutating, any restrictions imposed by CER or DER will // still be maintained. var reader = new AsnReader(new ReadOnlyMemory<byte>(buffer, start, len), AsnEncodingRules.BER); List<(int, int)> positions = new List<(int, int)>(); int pos = start; while (reader.HasData) { ReadOnlyMemory<byte> encoded = reader.GetEncodedValue(); positions.Add((pos, encoded.Length)); pos += encoded.Length; } Debug.Assert(pos == end); var comparer = new ArrayIndexSetOfValueComparer(buffer); positions.Sort(comparer); byte[] tmp = ArrayPool<byte>.Shared.Rent(len); pos = 0; foreach ((int offset, int length) in positions) { Buffer.BlockCopy(buffer, offset, tmp, pos, length); pos += length; } Debug.Assert(pos == len); Buffer.BlockCopy(tmp, 0, buffer, start, len); Array.Clear(tmp, 0, len); ArrayPool<byte>.Shared.Return(tmp); } internal static void Reverse(Span<byte> span) { int i = 0; int j = span.Length - 1; while (i < j) { byte tmp = span[i]; span[i] = span[j]; span[j] = tmp; i++; j--; } } private static void CheckUniversalTag(Asn1Tag tag, UniversalTagNumber universalTagNumber) { if (tag.TagClass == TagClass.Universal && tag.TagValue != (int)universalTagNumber) { throw new ArgumentException( SR.Cryptography_Asn_UniversalValueIsFixed, nameof(tag)); } } private class ArrayIndexSetOfValueComparer : IComparer<(int, int)> { private readonly byte[] _data; public ArrayIndexSetOfValueComparer(byte[] data) { _data = data; } public int Compare((int, int) x, (int, int) y) { (int xOffset, int xLength) = x; (int yOffset, int yLength) = y; int value = SetOfValueComparer.Instance.Compare( new ReadOnlyMemory<byte>(_data, xOffset, xLength), new ReadOnlyMemory<byte>(_data, yOffset, yLength)); if (value == 0) { // Whichever had the lowest index wins (once sorted, stay sorted) return xOffset - yOffset; } return value; } } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class ProductionLot : IEquatable<ProductionLot> { /// <summary> /// Initializes a new instance of the <see cref="ProductionLot" /> class. /// Initializes a new instance of the <see cref="ProductionLot" />class. /// </summary> /// <param name="ProductionLot">ProductionLot (required).</param> /// <param name="Quantity">Quantity (required).</param> /// <param name="CustomFields">CustomFields.</param> /// <param name="Sku">Sku.</param> public ProductionLot(string ProductionLot = null, int? Quantity = null, Dictionary<string, Object> CustomFields = null, string Sku = null) { // to ensure "ProductionLot" is required (not null) if (ProductionLot == null) { throw new InvalidDataException("ProductionLot is a required property for ProductionLot and cannot be null"); } else { this.ProductionLot = ProductionLot; } // to ensure "Quantity" is required (not null) if (Quantity == null) { throw new InvalidDataException("Quantity is a required property for ProductionLot and cannot be null"); } else { this.Quantity = Quantity; } this.CustomFields = CustomFields; this.Sku = Sku; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; private set; } /// <summary> /// Gets or Sets ProductionLot /// </summary> [DataMember(Name="productionLot", EmitDefaultValue=false)] public string ProductionLot { get; set; } /// <summary> /// Gets or Sets Quantity /// </summary> [DataMember(Name="quantity", EmitDefaultValue=false)] public int? Quantity { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { get; set; } /// <summary> /// Gets or Sets Sku /// </summary> [DataMember(Name="sku", EmitDefaultValue=false)] public string Sku { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ProductionLot {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" ProductionLot: ").Append(ProductionLot).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ProductionLot); } /// <summary> /// Returns true if ProductionLot instances are equal /// </summary> /// <param name="other">Instance of ProductionLot to be compared</param> /// <returns>Boolean</returns> public bool Equals(ProductionLot other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.ProductionLot == other.ProductionLot || this.ProductionLot != null && this.ProductionLot.Equals(other.ProductionLot) ) && ( this.Quantity == other.Quantity || this.Quantity != null && this.Quantity.Equals(other.Quantity) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ) && ( this.Sku == other.Sku || this.Sku != null && this.Sku.Equals(other.Sku) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.ProductionLot != null) hash = hash * 59 + this.ProductionLot.GetHashCode(); if (this.Quantity != null) hash = hash * 59 + this.Quantity.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); if (this.Sku != null) hash = hash * 59 + this.Sku.GetHashCode(); return hash; } } } }
/* * Copyright 2016 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Firebase.Editor { using Google; using GooglePlayServices; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using UnityEditor; using UnityEditor.Callbacks; using UnityEngine; [InitializeOnLoad] internal class XcodeProjectPatcher : AssetPostprocessor { // When in the build process the project should be patched. private const int BUILD_ORDER_ADD_CONFIG = 1; private const int BUILD_ORDER_PATCH_PROJECT = 2; // Firebase configuration filename. private const string GOOGLE_SERVICES_INFO_PLIST_BASENAME = "GoogleService-Info"; private const string GOOGLE_SERVICES_INFO_PLIST_FILE = "GoogleService-Info.plist"; // Keys this module needs from the config file. private static string[] PROJECT_KEYS = new string[] { "CLIENT_ID", "REVERSED_CLIENT_ID", "BUNDLE_ID", "PROJECT_ID", "STORAGE_BUCKET", "DATABASE_URL", }; // Configuration values of PROJECT_KEYS read from the config file. private static Dictionary<string, string> configValues = new Dictionary<string, string>(); // Developers can have multiple plist config files each containing a different bundleid. // Any one of them could be valid, so when we show a list to select one, it needs to come from parsing // every plist file. Fortunately, we already do this in our scan to find the "correct" config. private static HashSet<string> allBundleIds = new HashSet<string>(); // Path to the previously read config file. private static string configFile = null; // Flag for avoiding dialog spam private static bool spamguard; // Whether this component is enabled. private static bool Enabled { get { return (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS) && Google.IOSResolver.Enabled; } } static XcodeProjectPatcher() { // Delay initialization until the build target is iOS and the editor is not in play // mode. EditorInitializer.InitializeOnMainThread( condition: () => { return EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS && !EditorApplication.isPlayingOrWillChangePlaymode; }, initializer: () => { // We attempt to read the config even when the target platform isn't // iOS as the project settings are surfaced in the settings window. Google.IOSResolver.RemapXcodeExtension(); ReadConfigOnUpdate(); PlayServicesResolver.BundleIdChanged -= OnBundleIdChanged; if (Enabled) { PlayServicesResolver.BundleIdChanged += OnBundleIdChanged; CheckConfiguration(); } return true; }, name: "XcodeProjectPatcher"); } // Some versions of Unity 4.x crash when you to try to read the asset database from static // class constructors. internal static void ReadConfigOnUpdate() { ReadConfig(errorOnNoConfig: false); } // Get the iOS bundle / application ID. private static string GetIOSApplicationId() { return UnityCompat.GetApplicationId(BuildTarget.iOS); } // Check the editor environment on the first update after loading this // module. private static void CheckConfiguration() { CheckBundleId(GetIOSApplicationId()); CheckBuildEnvironment(); } // Read the configuration file, storing the filename in configFile and // values of keys specified by PROJECT_KEYS in configValues. internal static void ReadConfig(bool errorOnNoConfig = true, string filename = null) { try { ReadConfigInternal(errorOnNoConfig, filename: filename); } catch (Exception exception) { // FileNotFoundException and TypeInitializationException can be // thrown *before* ReadConfigInternal is entered if the iOS Xcode // assembly can't be loaded so we catch them here and only report // a warning if this module is enabled and iOS is the selected // platform. if (exception is FileNotFoundException || exception is TypeInitializationException) { if (Enabled) { // It's likely we failed to load the iOS Xcode extension. Debug.LogWarning(DocRef.FailedToLoadIOSExtensions); } } else { throw exception; } } } // Implementation of ReadConfig(). // NOTE: This is separate from ReadConfig() so it's possible to catch // a missing UnityEditor.iOS.Xcode assembly exception. internal static void ReadConfigInternal(bool errorOnNoConfig, string filename = null) { configValues = new Dictionary<string, string>(); configFile = filename ?? FindConfig(errorOnNoConfig: errorOnNoConfig); if (configFile == null) { return; } var plist = new UnityEditor.iOS.Xcode.PlistDocument(); plist.ReadFromString(File.ReadAllText(configFile)); var rootDict = plist.root; foreach (var key in PROJECT_KEYS) { var item = rootDict[key]; if (item == null) continue; configValues[key] = item.AsString(); if (Equals(key, "BUNDLE_ID")) { allBundleIds.Add(item.AsString()); } } } // Get all fields in PROJECT_KEYS previously read from the config file. internal static Dictionary<string, string> GetConfig() { return configValues; } // Verify that the build environment *really* supports iOS. private static void CheckBuildEnvironment() { // If iOS is the selected build target but we're not on a OSX machine // report an error as pod installation will fail among other things. if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS && Application.platform == RuntimePlatform.WindowsEditor) { Debug.LogError(DocRef.IOSNotSupportedOnWindows); } } // Called when the bundle ID is updated. private static void OnBundleIdChanged( object sender, PlayServicesResolver.BundleIdChangedEventArgs args) { ReadConfig(errorOnNoConfig: false); CheckBundleId(GetIOSApplicationId()); } // Check the bundle ID private static string CheckBundleId(string bundleId, bool promptUpdate = true, bool logErrorOnMissingBundleId = true) { if (configFile == null) { return null; } var configDict = GetConfig(); string configBundleId; if (!configDict.TryGetValue("BUNDLE_ID", out configBundleId)) { return null; } if (!configBundleId.Equals(bundleId) && logErrorOnMissingBundleId && allBundleIds.Count > 0) { // Report an error, prompt user to use the bundle ID // from the plist. string[] bundleIds = allBundleIds.ToArray(); string errorMessage = String.Format(DocRef.GoogleServicesFileBundleIdMissing, bundleId, "GoogleServices-Info.plist", String.Join(", ", bundleIds), Link.IOSAddApp); if (promptUpdate && !spamguard) { ChooserDialog.Show( "Please fix your Bundle ID", "Select a valid Bundle ID from your Firebase " + "configuration.", String.Format("Your bundle ID {0} is not present in your " + "Firebase configuration. A mismatched bundle ID " + "will result in your application to fail to " + "initialize.\n\n" + "New Bundle ID:", bundleId), bundleIds, 0, "Apply", "Cancel", selectedBundleId => { if (!String.IsNullOrEmpty(selectedBundleId)) { // If we have a valid value, the user hit apply. UnityCompat.SetApplicationId(BuildTarget.iOS, selectedBundleId); Measurement.ReportWithBuildTarget("bundleidmismatch/apply", null, "Mismatched Bundle ID: Apply"); } else { Measurement.ReportWithBuildTarget("bundleidmismatch/cancel", null, "Mismatched Bundle ID: Cancel"); // If the user hits cancel, we disable the dialog to // avoid spamming the user. spamguard = true; Debug.LogError(errorMessage); } ReadConfig(); }); } else { Debug.LogError(errorMessage); } } return configBundleId; } // Called when any asset is imported, deleted, or moved. private static void OnPostprocessAllAssets( string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) { // We track the config file state even when the target isn't iOS // as the project settings are surfaced in the settings window. if (!Enabled) return; bool configFilePresent = false; foreach (string asset in importedAssets) { if (Path.GetFileName(asset) == GOOGLE_SERVICES_INFO_PLIST_FILE) { configFilePresent = true; break; } } if (configFilePresent) { spamguard = false; // Reset our spamguard to show a dialog. ReadConfig(errorOnNoConfig: false); CheckBundleId(GetIOSApplicationId()); } } /// <summary> /// Search for the Firebase config file. /// </summary> /// <returns>String with a path to the file if found, null if not /// found or more than one config file is present in the project.</returns> internal static string FindConfig(bool errorOnNoConfig = true) { string previousConfigFile = configFile; var plists = new SortedDictionary<string, string>(); allBundleIds.Clear(); foreach (var guid in AssetDatabase.FindAssets( String.Format("{0}", GOOGLE_SERVICES_INFO_PLIST_BASENAME), new [] { "Assets"})) { string path = AssetDatabase.GUIDToAssetPath(guid); if (Path.GetFileName(path) == GOOGLE_SERVICES_INFO_PLIST_FILE) { plists[path] = path; } } string[] files = new string[plists.Keys.Count]; plists.Keys.CopyTo(files, 0); string selectedFile = files.Length >= 1 ? files[0] : null; if (files.Length == 0) { if (errorOnNoConfig && Enabled) { Debug.LogError( String.Format(DocRef.GoogleServicesIOSFileMissing, GOOGLE_SERVICES_INFO_PLIST_FILE, Link.IOSAddApp)); } } else if (files.Length > 1) { var bundleId = GetIOSApplicationId(); string selectedBundleId = null; // Search files for the first file matching the project's bundle identifier. foreach (var filename in files) { ReadConfig(filename: filename); var currentBundleId = CheckBundleId(bundleId, logErrorOnMissingBundleId: false); selectedBundleId = selectedBundleId ?? currentBundleId; if (currentBundleId == bundleId) { selectedFile = filename; selectedBundleId = bundleId; } } // If the config file changed, warn the user about the selected file. if (String.IsNullOrEmpty(previousConfigFile) || !selectedFile.Equals(previousConfigFile)) { Debug.LogWarning( String.Format(DocRef.GoogleServicesFileMultipleFiles, GOOGLE_SERVICES_INFO_PLIST_FILE, selectedFile, selectedBundleId, String.Join("\n", files))); } } return selectedFile; } /// <summary> /// Add the Firebase config file to the generated Xcode project. /// </summary> [PostProcessBuildAttribute(BUILD_ORDER_ADD_CONFIG)] internal static void OnPostProcessAddGoogleServicePlist( BuildTarget buildTarget, string pathToBuiltProject) { if (!Enabled) return; Measurement.analytics.Report("ios/xcodepatch", "iOS Xcode Project Patcher: Start"); AddGoogleServicePlist(buildTarget, pathToBuiltProject); } // Implementation of OnPostProcessAddGoogleServicePlist(). // NOTE: This is separate from the post-processing method to prevent the // Mono runtime from loading the Xcode API before calling the post // processing step. internal static void AddGoogleServicePlist( BuildTarget buildTarget, string pathToBuiltProject) { ReadConfig(); if (configFile == null) { Measurement.analytics.Report("ios/xcodepatch/config/failed", "Add Firebase Configuration File Failure"); return; } CheckBundleId(GetIOSApplicationId(), promptUpdate: false); // Copy the config file to the Xcode project folder. string configFileBasename = Path.GetFileName(configFile); File.Copy(configFile, Path.Combine(pathToBuiltProject, configFileBasename), true); // Add the config file to the Xcode project. string pbxprojPath = Google.IOSResolver.GetProjectPath(pathToBuiltProject); var project = new UnityEditor.iOS.Xcode.PBXProject(); project.ReadFromString(File.ReadAllText(pbxprojPath)); foreach (var targetGuid in Google.IOSResolver.GetXcodeTargetGuids(project, includeAllTargets: true)) { project.AddFileToBuild( targetGuid, project.AddFile(configFileBasename, configFileBasename, UnityEditor.iOS.Xcode.PBXSourceTree.Source)); } File.WriteAllText(pbxprojPath, project.WriteToString()); Measurement.analytics.Report("ios/xcodepatch/config/success", "Add Firebase Configuration File Successful"); } /// <summary> /// Patch the Xcode project with Firebase settings and workarounds. /// </summary> [PostProcessBuildAttribute(BUILD_ORDER_PATCH_PROJECT)] internal static void OnPostProcessPatchProject( BuildTarget buildTarget, string pathToBuiltProject) { if (!Enabled) return; ReadAndApplyFirebaseConfig(buildTarget, pathToBuiltProject); ApplyNsUrlSessionWorkaround(buildTarget, pathToBuiltProject); } // Apply the Firebase configuration to the Xcode project. // NOTE: This is separate from the post-processing method to prevent the // Mono runtime from loading the Xcode API before calling the post // processing step. internal static void ReadAndApplyFirebaseConfig( BuildTarget buildTarget, string pathToBuiltProject) { // DLLs that trigger post processing by this method. // We use the DLL names here as: // * Pod dependencies may not be present if frameworks are manually // being included. // * DLLs may not be loaded in the Unity Editor App domain so we can't // detect the module using reflection. var invitesDll = "Firebase.Invites.dll"; var dllsThatRequireReversedClientId = new HashSet<string> { "Firebase.Auth.dll", "Firebase.DynamicLinks.dll", invitesDll }; bool reversedClientIdRequired = false; bool invitesPresent = false; // Search the asset database for the DLLs to handle projects where // users move files around. foreach (var assetGuid in AssetDatabase.FindAssets("t:Object")) { var filename = Path.GetFileName( AssetDatabase.GUIDToAssetPath(assetGuid)); if (dllsThatRequireReversedClientId.Contains(filename)) { reversedClientIdRequired = true; invitesPresent = filename == invitesDll; } } if (!(invitesPresent || reversedClientIdRequired)) { return; } ReadConfig(); // Read required data from the config file. var configDict = GetConfig(); if (configDict.Count == 0) return; string reversedClientId = null; string bundleId = null; if (!configDict.TryGetValue("REVERSED_CLIENT_ID", out reversedClientId)) { Measurement.analytics.Report("ios/xcodepatch/reversedclientid/failed", "Add Reversed Client ID Failed"); Debug.LogError( String.Format(DocRef.PropertyMissingForGoogleSignIn, GOOGLE_SERVICES_INFO_PLIST_FILE, "REVERSED_CLIENT_ID", Link.IOSAddApp)); } if (!configDict.TryGetValue("BUNDLE_ID", out bundleId)) { Debug.LogError( String.Format(DocRef.PropertyMissingForGoogleSignIn, GOOGLE_SERVICES_INFO_PLIST_FILE, "BUNDLE_ID", Link.IOSAddApp)); } // Update the Xcode project's Info.plist. string plistPath = Path.Combine(pathToBuiltProject, "Info.plist"); var plist = new UnityEditor.iOS.Xcode.PlistDocument(); plist.ReadFromString(File.ReadAllText(plistPath)); var rootDict = plist.root; UnityEditor.iOS.Xcode.PlistElementArray urlTypes = null; if (rootDict.values.ContainsKey("CFBundleURLTypes")) { urlTypes = rootDict["CFBundleURLTypes"].AsArray(); } if (urlTypes == null) { urlTypes = rootDict.CreateArray("CFBundleURLTypes"); } if (reversedClientId != null) { var googleType = urlTypes.AddDict(); googleType.SetString("CFBundleTypeRole", "Editor"); googleType.SetString("CFBundleURLName", "google"); googleType.CreateArray("CFBundleURLSchemes").AddString( reversedClientId); Measurement.analytics.Report("ios/xcodepatch/reversedclientid/success", "Add Reversed Client ID Successful"); } if (bundleId != null) { var bundleType = urlTypes.AddDict(); bundleType.SetString("CFBundleTypeRole", "Editor"); bundleType.SetString("CFBundleURLName", bundleId); bundleType.CreateArray("CFBundleURLSchemes").AddString(bundleId); } // Invites needs usage permission to access Contacts. if (invitesPresent) { if (!rootDict.values.ContainsKey("NSContactsUsageDescription")) { rootDict.SetString("NSContactsUsageDescription", "Invite others to use the app."); } } // Finished, Write to File File.WriteAllText(plistPath, plist.WriteToString()); } // Patch the Xcode project to workaround a bug in NSURLSession in some iOS versions. internal static void ApplyNsUrlSessionWorkaround( BuildTarget buildTarget, string pathToBuiltProject) { const string WorkaroundNotAppliedMessage = "Unable to apply NSURLSession workaround. If " + "NSAllowsArbitraryLoads is set to a different value than " + "NSAllowsArbitraryLoadsInWebContent in your Info.plist " + "network operations will randomly fail on some versions of iOS"; string plistPath = Path.Combine(pathToBuiltProject, "Info.plist"); var plist = new UnityEditor.iOS.Xcode.PlistDocument(); plist.ReadFromString(File.ReadAllText(plistPath)); var rootDict = plist.root; // Some versions of iOS exhibit buggy behavior when using NSURLSession if // NSAppTransportSecurity is present and NSAllowsArbitraryLoadsInWebContent is not // set. This manifests as connections being closed with error // "Domain=kCFErrorDomainCFNetwork Code=-1005". The theory is that when // NSAllowsArbitraryLoadsInWebContent isn't initialized the framework is reading // uninitialized memory which sporadically blocks encrypted connections opened with // NSURLSession. if (rootDict.values.ContainsKey("NSAppTransportSecurity")) { UnityEditor.iOS.Xcode.PlistElementDict transportSecurity; try { transportSecurity = rootDict["NSAppTransportSecurity"].AsDict(); } catch (InvalidCastException e) { Debug.LogWarning(String.Format( "Unable to parse NSAppTransportSecurity as a dictionary. ({0})\n{1}\n" + "To fix this issue make sure NSAppTransportSecurity is a dictionary in your " + "Info.plist", e, WorkaroundNotAppliedMessage)); Measurement.analytics.Report("ios/xcodepatch/nsurlsessionworkaround/failed", "NSURLSession workaround Failed"); return; } if (transportSecurity.values.ContainsKey("NSAllowsArbitraryLoads") && !transportSecurity.values.ContainsKey("NSAllowsArbitraryLoadsInWebContent")) { try { transportSecurity.SetBoolean( "NSAllowsArbitraryLoadsInWebContent", transportSecurity["NSAllowsArbitraryLoads"].AsBoolean()); } catch (InvalidCastException e) { Debug.LogWarning(String.Format( "Unable to parse NSAllowsArbitraryLoads as a boolean value. ({0})\n{1}\n" + "To fix this problem make sure NSAllowsArbitraryLoads is YES or NO in " + "your Info.plist or NSAllowsArbitraryLoadsInWebContent is set.", e, WorkaroundNotAppliedMessage)); Measurement.analytics.Report("ios/xcodepatch/nsurlsessionworkaround/failed", "NSURLSession workaround Failed"); return; } Measurement.analytics.Report("ios/xcodepatch/nsurlsessionworkaround/success", "NSURLSession workaround Successful"); } } File.WriteAllText(plistPath, plist.WriteToString()); } } } // namespace Firebase.Editor
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using ASC.Common.Data.Sql.Expressions; using ASC.Core; using ASC.Files.Core; using ASC.Web.Studio.Core; namespace ASC.Files.Thirdparty.Dropbox { internal class DropboxFolderDao : DropboxDaoBase, IFolderDao { public DropboxFolderDao(DropboxDaoSelector.DropboxInfo dropboxInfo, DropboxDaoSelector dropboxDaoSelector) : base(dropboxInfo, dropboxDaoSelector) { } public Folder GetFolder(object folderId) { return ToFolder(GetDropboxFolder(folderId)); } public Folder GetFolder(string title, object parentId) { var metadata = GetDropboxItems(parentId, true) .FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)); return metadata == null ? null : ToFolder(metadata.AsFolder); } public Folder GetRootFolderByFile(object fileId) { return GetRootFolder(fileId); } public List<Folder> GetFolders(object parentId) { return GetDropboxItems(parentId, true).Select(item => ToFolder(item.AsFolder)).ToList(); } public List<Folder> GetFolders(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool withSubfolders = false) { if (filterType == FilterType.FilesOnly || filterType == FilterType.ByExtension || filterType == FilterType.DocumentsOnly || filterType == FilterType.ImagesOnly || filterType == FilterType.PresentationsOnly || filterType == FilterType.SpreadsheetsOnly || filterType == FilterType.ArchiveOnly || filterType == FilterType.MediaOnly) return new List<Folder>(); var folders = GetFolders(parentId).AsEnumerable(); //TODO:!!! if (subjectID != Guid.Empty) { folders = folders.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID) : x.CreateBy == subjectID); } if (!string.IsNullOrEmpty(searchText)) folders = folders.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); if (orderBy == null) orderBy = new OrderBy(SortedByType.DateAndTime, false); switch (orderBy.SortedBy) { case SortedByType.Author: folders = orderBy.IsAsc ? folders.OrderBy(x => x.CreateBy) : folders.OrderByDescending(x => x.CreateBy); break; case SortedByType.AZ: folders = orderBy.IsAsc ? folders.OrderBy(x => x.Title) : folders.OrderByDescending(x => x.Title); break; case SortedByType.DateAndTime: folders = orderBy.IsAsc ? folders.OrderBy(x => x.ModifiedOn) : folders.OrderByDescending(x => x.ModifiedOn); break; case SortedByType.DateAndTimeCreation: folders = orderBy.IsAsc ? folders.OrderBy(x => x.CreateOn) : folders.OrderByDescending(x => x.CreateOn); break; default: folders = orderBy.IsAsc ? folders.OrderBy(x => x.Title) : folders.OrderByDescending(x => x.Title); break; } return folders.ToList(); } public List<Folder> GetFolders(IEnumerable<object> folderIds, FilterType filterType = FilterType.None, bool subjectGroup = false, Guid? subjectID = null, string searchText = "", bool searchSubfolders = false, bool checkShare = true) { if (filterType == FilterType.FilesOnly || filterType == FilterType.ByExtension || filterType == FilterType.DocumentsOnly || filterType == FilterType.ImagesOnly || filterType == FilterType.PresentationsOnly || filterType == FilterType.SpreadsheetsOnly || filterType == FilterType.ArchiveOnly || filterType == FilterType.MediaOnly) return new List<Folder>(); var folders = folderIds.Select(GetFolder); if (subjectID.HasValue && subjectID != Guid.Empty) { folders = folders.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID.Value) : x.CreateBy == subjectID); } if (!string.IsNullOrEmpty(searchText)) folders = folders.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); return folders.ToList(); } public List<Folder> GetParentFolders(object folderId) { var path = new List<Folder>(); while (folderId != null) { var dropboxFolder = GetDropboxFolder(folderId); if (dropboxFolder is ErrorFolder) { folderId = null; } else { path.Add(ToFolder(dropboxFolder)); folderId = GetParentFolderPath(dropboxFolder); } } path.Reverse(); return path; } public object SaveFolder(Folder folder) { if (folder == null) throw new ArgumentNullException("folder"); if (folder.ID != null) { return RenameFolder(folder, folder.Title); } if (folder.ParentFolderID != null) { var dropboxFolderPath = MakeDropboxPath(folder.ParentFolderID); folder.Title = GetAvailableTitle(folder.Title, dropboxFolderPath, IsExist); var dropboxFolder = DropboxProviderInfo.Storage.CreateFolder(folder.Title, dropboxFolderPath); DropboxProviderInfo.CacheReset(dropboxFolder); var parentFolderPath = GetParentFolderPath(dropboxFolder); if (parentFolderPath != null) DropboxProviderInfo.CacheReset(parentFolderPath); return MakeId(dropboxFolder); } return null; } public bool IsExist(string title, string folderId) { return GetDropboxItems(folderId, true) .Any(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)); } public void DeleteFolder(object folderId) { var dropboxFolder = GetDropboxFolder(folderId); var id = MakeId(dropboxFolder); using (var db = GetDb()) using (var tx = db.BeginTransaction()) { var hashIDs = db.ExecuteList(Query("files_thirdparty_id_mapping") .Select("hash_id") .Where(Exp.Like("id", id, SqlLike.StartWith))) .ConvertAll(x => x[0]); db.ExecuteNonQuery(Delete("files_tag_link").Where(Exp.In("entry_id", hashIDs))); db.ExecuteNonQuery(Delete("files_security").Where(Exp.In("entry_id", hashIDs))); db.ExecuteNonQuery(Delete("files_thirdparty_id_mapping").Where(Exp.In("hash_id", hashIDs))); var tagsToRemove = db.ExecuteList( Query("files_tag tbl_ft ") .Select("tbl_ft.id") .LeftOuterJoin("files_tag_link tbl_ftl", Exp.EqColumns("tbl_ft.tenant_id", "tbl_ftl.tenant_id") & Exp.EqColumns("tbl_ft.id", "tbl_ftl.tag_id")) .Where("tbl_ftl.tag_id is null")) .ConvertAll(r => Convert.ToInt32(r[0])); db.ExecuteNonQuery(Delete("files_tag").Where(Exp.In("id", tagsToRemove))); tx.Commit(); } if (!(dropboxFolder is ErrorFolder)) DropboxProviderInfo.Storage.DeleteItem(dropboxFolder); DropboxProviderInfo.CacheReset(MakeDropboxPath(dropboxFolder), true); var parentFolderPath = GetParentFolderPath(dropboxFolder); if (parentFolderPath != null) DropboxProviderInfo.CacheReset(parentFolderPath); } public object MoveFolder(object folderId, object toFolderId, CancellationToken? cancellationToken) { var dropboxFolder = GetDropboxFolder(folderId); if (dropboxFolder is ErrorFolder) throw new Exception(((ErrorFolder)dropboxFolder).Error); var toDropboxFolder = GetDropboxFolder(toFolderId); if (toDropboxFolder is ErrorFolder) throw new Exception(((ErrorFolder)toDropboxFolder).Error); var fromFolderPath = GetParentFolderPath(dropboxFolder); dropboxFolder = DropboxProviderInfo.Storage.MoveFolder(MakeDropboxPath(dropboxFolder), MakeDropboxPath(toDropboxFolder), dropboxFolder.Name); DropboxProviderInfo.CacheReset(MakeDropboxPath(dropboxFolder), false); DropboxProviderInfo.CacheReset(fromFolderPath); DropboxProviderInfo.CacheReset(MakeDropboxPath(toDropboxFolder)); return MakeId(dropboxFolder); } public Folder CopyFolder(object folderId, object toFolderId, CancellationToken? cancellationToken) { var dropboxFolder = GetDropboxFolder(folderId); if (dropboxFolder is ErrorFolder) throw new Exception(((ErrorFolder)dropboxFolder).Error); var toDropboxFolder = GetDropboxFolder(toFolderId); if (toDropboxFolder is ErrorFolder) throw new Exception(((ErrorFolder)toDropboxFolder).Error); var newDropboxFolder = DropboxProviderInfo.Storage.CopyFolder(MakeDropboxPath(dropboxFolder), MakeDropboxPath(toDropboxFolder), dropboxFolder.Name); DropboxProviderInfo.CacheReset(newDropboxFolder); DropboxProviderInfo.CacheReset(MakeDropboxPath(newDropboxFolder), false); DropboxProviderInfo.CacheReset(MakeDropboxPath(toDropboxFolder)); return ToFolder(newDropboxFolder); } public IDictionary<object, string> CanMoveOrCopy(object[] folderIds, object to) { return new Dictionary<object, string>(); } public object RenameFolder(Folder folder, string newTitle) { var dropboxFolder = GetDropboxFolder(folder.ID); var parentFolderPath = GetParentFolderPath(dropboxFolder); if (IsRoot(dropboxFolder)) { //It's root folder DropboxDaoSelector.RenameProvider(DropboxProviderInfo, newTitle); //rename provider customer title } else { newTitle = GetAvailableTitle(newTitle, parentFolderPath, IsExist); //rename folder dropboxFolder = DropboxProviderInfo.Storage.MoveFolder(MakeDropboxPath(dropboxFolder), parentFolderPath, newTitle); } DropboxProviderInfo.CacheReset(dropboxFolder); if (parentFolderPath != null) DropboxProviderInfo.CacheReset(parentFolderPath); return MakeId(dropboxFolder); } public int GetItemsCount(object folderId) { throw new NotImplementedException(); } public bool IsEmpty(object folderId) { var dropboxFolderPath = MakeDropboxPath(folderId); //note: without cache return DropboxProviderInfo.Storage.GetItems(dropboxFolderPath).Count == 0; } public bool UseTrashForRemove(Folder folder) { return false; } public bool UseRecursiveOperation(object folderId, object toRootFolderId) { return false; } public bool CanCalculateSubitems(object entryId) { return false; } public long GetMaxUploadSize(object folderId, bool chunkedUpload) { var storageMaxUploadSize = DropboxProviderInfo.Storage.MaxChunkedUploadFileSize; return chunkedUpload ? storageMaxUploadSize : Math.Min(storageMaxUploadSize, SetupInfo.AvailableFileSize); } #region Only for TMFolderDao public void ReassignFolders(IEnumerable<object> folderIds, Guid newOwnerId) { } public IEnumerable<Folder> Search(string text, bool bunch) { return null; } public object GetFolderID(string module, string bunch, string data, bool createIfNotExists) { return null; } public IEnumerable<object> GetFolderIDs(string module, string bunch, IEnumerable<string> data, bool createIfNotExists) { return new List<object>(); } public object GetFolderIDCommon(bool createIfNotExists) { return null; } public object GetFolderIDUser(bool createIfNotExists, Guid? userId) { return null; } public object GetFolderIDShare(bool createIfNotExists) { return null; } public object GetFolderIDRecent(bool createIfNotExists) { return null; } public object GetFolderIDFavorites(bool createIfNotExists) { return null; } public object GetFolderIDTemplates(bool createIfNotExists) { return null; } public object GetFolderIDPrivacy(bool createIfNotExists, Guid? userId) { return null; } public object GetFolderIDTrash(bool createIfNotExists, Guid? userId) { return null; } public object GetFolderIDPhotos(bool createIfNotExists) { return null; } public object GetFolderIDProjects(bool createIfNotExists) { return null; } public string GetBunchObjectID(object folderID) { return null; } public Dictionary<string, string> GetBunchObjectIDs(IEnumerable<object> folderIDs) { return null; } #endregion } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; using System.Collections.Generic; using System.Windows.Media.Imaging; using Autodesk.Revit; using Autodesk.Revit.UI; using Autodesk.Revit.ApplicationServices; namespace RvtSamples { /// <summary> /// Main external application class. /// A generic menu generator application. /// Read a text file and add entries to the Revit menu. /// Any number and location of entries is supported. /// </summary> public class Application : IExternalApplication { /// <summary> /// Default pulldown menus for samples /// </summary> public enum DefaultPulldownMenus { /// <summary> /// Menu for Basics category /// </summary> Basics, /// <summary> /// Menu for Geometry category /// </summary> Geometry, /// <summary> /// Menu for Parameters category /// </summary> Parameters, /// <summary> /// Menu for Elements category /// </summary> Elements, /// <summary> /// Menu for Families category /// </summary> Families, /// <summary> /// Menu for Materials category /// </summary> Materials, /// <summary> /// Menu for Annotation category /// </summary> Annotation, /// <summary> /// Menu for Views category /// </summary> Views, /// <summary> /// Menu for Rooms/Spaces category /// </summary> RoomsAndSpaces, /// <summary> /// Menu for Data Exchange category /// </summary> DataExchange, /// <summary> /// Menu for MEP category /// </summary> MEP, /// <summary> /// Menu for Structure category /// </summary> Structure } #region Member Data /// <summary> /// Separator of category for samples have more than one category /// </summary> static char[] s_charSeparatorOfCategory = new char[] { ',' }; /// <summary> /// chars which will be trimmed in the file to include extra sample list files /// </summary> static char[] s_trimChars = new char[] {' ', '"', '\'', '<', '>' }; /// <summary> /// The start symbol of lines to include extra sample list files /// </summary> static string s_includeSymbol = "#include"; /// <summary> /// Assembly directory /// </summary> static string s_assemblyDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); /// <summary> /// Name of file which contains information required for menu items /// </summary> public const string m_fileNameStem = "RvtSamples.txt"; /// <summary> /// The controlled application of Revit /// </summary> private UIControlledApplication m_application; /// <summary> /// List contains all pulldown button items contain sample items /// </summary> private SortedList<string, PulldownButton> m_pulldownButtons = new SortedList<string, PulldownButton>(); /// <summary> /// List contains information of samples not belong to default pulldown menus /// </summary> private SortedList<string, List<SampleItem>> m_customizedMenus = new SortedList<string, List<SampleItem>>(); /// <summary> /// List contains information of samples belong to default pulldown menus /// </summary> private SortedList<string, List<SampleItem>> m_defaultMenus = new SortedList<string, List<SampleItem>>(); /// <summary> /// Panel for RvtSamples /// </summary> RibbonPanel m_panelRvtSamples; #endregion // Member Data #region IExternalApplication Members /// <summary> /// Implement this method to implement the external application which should be called when /// Revit starts before a file or default template is actually loaded. /// </summary> /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully started. /// Cancelled can be used to signify that the user cancelled the external operation at /// some point. /// If false is returned then Revit should inform the user that the external application /// failed to load and the release the internal reference.</returns> public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { m_application = application; Autodesk.Revit.UI.Result rc = Autodesk.Revit.UI.Result.Failed; try { // Check whether the file contains samples' list exists // If not, return failure string filename = m_fileNameStem; if (!GetFilepath(ref filename)) { ErrorMsg(m_fileNameStem + " not found."); return rc; } // Read all lines from the file string[] lines = ReadAllLinesWithInclude(filename); // Remove comments lines = RemoveComments(lines); // Add default pulldown menus of samples to Revit m_panelRvtSamples = application.CreateRibbonPanel("RvtSamples"); int i = 0; List<PulldownButtonData> pdData = new List<PulldownButtonData>(3); foreach(string category in Enum.GetNames(typeof(DefaultPulldownMenus))) { if((i + 1) % 3 == 1) { pdData.Clear(); } // // Prepare PulldownButtonData for add stacked buttons operation // string displayName = GetDisplayNameByEnumName(category); List<SampleItem> sampleItems = new List<SampleItem>(); m_defaultMenus.Add(category, sampleItems); PulldownButtonData data = new PulldownButtonData(displayName, displayName); pdData.Add(data); // // Add stacked buttons to RvtSamples panel and set their display names and images // if ((i + 1) % 3 == 0) { IList<RibbonItem> addedButtons = m_panelRvtSamples.AddStackedItems(pdData[0], pdData[1], pdData[2]); foreach (RibbonItem item in addedButtons) { String name = item.ItemText; string enumName = GetEnumNameByDisplayName(name); PulldownButton button = item as PulldownButton; button.Image = new BitmapImage( new Uri(Path.Combine(s_assemblyDirectory, "Icons\\" + enumName + ".ico"), UriKind.Absolute)); button.ToolTip = Properties.Resource.ResourceManager.GetString(enumName); m_pulldownButtons.Add(name, button); } } i++; } // // Add sample items to the pulldown buttons // int n = lines.GetLength(0); int k = 0; while (k < n) { AddSample(lines, n, ref k); } AddSamplesToDefaultPulldownMenus(); AddCustomizedPulldownMenus(); rc = Autodesk.Revit.UI.Result.Succeeded; } catch (Exception e) { ErrorMsg(e.Message); } return rc; } /// <summary> /// Get a button's enum name by its display name /// </summary> /// <param name="name">display name</param> /// <returns>enum name</returns> private string GetEnumNameByDisplayName(string name) { string enumName = null; if (name.Equals("Rooms/Spaces")) { enumName = DefaultPulldownMenus.RoomsAndSpaces.ToString(); } else if (name.Equals("Data Exchange")) { enumName = DefaultPulldownMenus.DataExchange.ToString(); } else { enumName = name; } return enumName; } /// <summary> /// Get a button's display name by its enum name /// </summary> /// <param name="enumName">The button's enum name</param> /// <returns>The button's display name</returns> private string GetDisplayNameByEnumName(string enumName) { string displayName = null; if (enumName.Equals(DefaultPulldownMenus.RoomsAndSpaces.ToString())) { displayName = "Rooms/Spaces"; } else if (enumName.Equals(DefaultPulldownMenus.DataExchange.ToString())) { displayName = "Data Exchange"; } else { displayName = enumName; } return displayName; } /// <summary> /// Implement this method to implement the external application which should be called when /// Revit is about to exit,Any documents must have been closed before this method is called. /// </summary> /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully shutdown. /// Cancelled can be used to signify that the user cancelled the external operation at /// some point. /// If false is returned then the Revit user should be warned of the failure of the external /// application to shut down correctly.</returns> public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application) { return Autodesk.Revit.UI.Result.Succeeded; } #endregion // IExternalApplication Members /// <summary> /// Display error message /// </summary> /// <param name="msg">Message to display</param> public void ErrorMsg(string msg) { MessageBox.Show(msg, "RvtSamples", MessageBoxButtons.OK, MessageBoxIcon.Error); } #region Parser /// <summary> /// Read file contents, including contents of files included in the current file /// </summary> /// <param name="filename">Current file to be read</param> /// <returns>All lines of file contents</returns> private string[] ReadAllLinesWithInclude(string filename) { if (!File.Exists(filename)) { ErrorMsg(filename + " not found."); return new string[] { }; } string[] lines = File.ReadAllLines(filename); int n = lines.GetLength(0); ArrayList all_lines = new ArrayList(n); foreach (string line in lines) { string s = line.TrimStart(); if (s.ToLower().StartsWith(s_includeSymbol)) { string filename2 = s.Substring(s_includeSymbol.Length); filename2 = filename2.Trim(s_trimChars); all_lines.AddRange(ReadAllLinesWithInclude(filename2)); } else { all_lines.Add(line); } } return all_lines.ToArray(typeof(string)) as string[]; } /// <summary> /// Get the input file path. /// Search and return the full path for the given file /// in the current exe directory or one or two directory levels higher. /// </summary> /// <param name="filename">Input filename stem, output full file path</param> /// <returns>True if found, false otherwise.</returns> bool GetFilepath(ref string filename) { string path = Path.Combine(s_assemblyDirectory, filename); bool rc = File.Exists(path); // Get full path of the file if (rc) { filename = Path.GetFullPath(path); } return rc; } /// <summary> /// Remove all comments and empty lines from a given array of lines. /// Comments are delimited by '#' to the end of the line. /// </summary> string[] RemoveComments(string[] lines) { int n = lines.GetLength(0); string[] a = new string[n]; int i = 0; foreach (string line in lines) { string s = line; int j = s.IndexOf('#'); if (0 <= j) { s = s.Substring(0, j); } s = s.Trim(); if (0 < s.Length) { a[i++] = s; } } string[] b = new string[i]; n = i; for (i = 0; i < n; ++i) { b[i] = a[i]; } return b; } #endregion // Parser #region Menu Helpers /// <summary> /// Add a new command to the corresponding pulldown button. /// </summary> /// <param name="lines">Array of lines defining sample's category, display name, description, large image, image, assembly and classname</param> /// <param name="n">Total number of lines in array</param> /// <param name="i">Current index in array</param> void AddSample(string[] lines, int n, ref int i) { if (n < i + 6) { throw new Exception(string.Format("Incomplete record at line {0} of {1}", i, m_fileNameStem)); } string categories = lines[i++].Trim(); string displayName = lines[i++]; string description = lines[i++]; string largeImage = lines[i++].Remove(0, 11).Trim(); string image = lines[i++].Remove(0, 6).Trim(); string assembly = lines[i++]; string className = lines[i++]; // // If sample belongs to default category, add the sample item to the sample list of the default category // If not, store the information for adding to RvtSamples panel later // string[] entries = categories.Split(s_charSeparatorOfCategory, StringSplitOptions.RemoveEmptyEntries); foreach (string value in entries) { string category = value.Trim(); SampleItem item = new SampleItem(category, displayName, description, largeImage, image, assembly, className); if (m_pulldownButtons.ContainsKey(category)) { m_defaultMenus.Values[m_defaultMenus.IndexOfKey(GetEnumNameByDisplayName(category))].Add(item); } else if (m_customizedMenus.ContainsKey(category)) { List<SampleItem> sampleItems = m_customizedMenus.Values[m_customizedMenus.IndexOfKey(category)]; sampleItems.Add(item); } else { List<SampleItem> sampleItems = new List<SampleItem>(); sampleItems.Add(item); m_customizedMenus.Add(category, sampleItems); } } } /// <summary> /// Add sample item to pulldown menu /// </summary> /// <param name="pullDownButton">Pulldown menu</param> /// <param name="item">Sample item to be added</param> private void AddSampleToPulldownMenu(PulldownButton pullDownButton, SampleItem item) { PushButtonData pushButtonData = new PushButtonData(item.DisplayName, item.DisplayName, item.Assembly, item.ClassName); PushButton pushButton = pullDownButton.AddPushButton(pushButtonData); if (!string.IsNullOrEmpty(item.LargeImage)) { BitmapImage largeImageSource = new BitmapImage(new Uri(item.LargeImage, UriKind.Absolute)); pushButton.LargeImage = largeImageSource; } if (!string.IsNullOrEmpty(item.Image)) { BitmapImage imageSource = new BitmapImage(new Uri(item.Image, UriKind.Absolute)); pushButton.Image = imageSource; } pushButton.ToolTip = item.Description; } /// <summary> /// Comparer to sort sample items by their display name /// </summary> /// <param name="s1">sample item 1</param> /// <param name="s2">sample item 2</param> /// <returns>compare result</returns> private static int SortByDisplayName(SampleItem item1, SampleItem item2) { return string.Compare(item1.DisplayName, item2.DisplayName); } /// <summary> /// Sort samples in one category by the sample items' display name /// </summary> /// <param name="menus">samples to be sorted</param> private void SortSampleItemsInOneCategory(SortedList<string, List<SampleItem>> menus) { int iCount = menus.Count; for (int j = 0; j < iCount; j++) { List<SampleItem> sampleItems = menus.Values[j]; sampleItems.Sort(SortByDisplayName); } } /// <summary> /// Add samples of categories in default categories /// </summary> private void AddSamplesToDefaultPulldownMenus() { int iCount = m_defaultMenus.Count; // Sort sample items in every category by display name SortSampleItemsInOneCategory(m_defaultMenus); for (int i = 0; i < iCount; i++) { string category = m_defaultMenus.Keys[i]; List<SampleItem> sampleItems = m_defaultMenus.Values[i]; PulldownButton menuButton = m_pulldownButtons.Values[m_pulldownButtons.IndexOfKey(GetDisplayNameByEnumName(category))]; foreach (SampleItem item in sampleItems) { AddSampleToPulldownMenu(menuButton, item); } } } /// <summary> /// Add samples of categories not in default categories /// </summary> private void AddCustomizedPulldownMenus() { int iCount = m_customizedMenus.Count; // Sort sample items in every category by display name SortSampleItemsInOneCategory(m_customizedMenus); int i = 0; while (iCount >= 3) { string name = m_customizedMenus.Keys[i++]; PulldownButtonData data1 = new PulldownButtonData(name, name); name = m_customizedMenus.Keys[i++]; PulldownButtonData data2 = new PulldownButtonData(name, name); name = m_customizedMenus.Keys[i++]; PulldownButtonData data3 = new PulldownButtonData(name, name); IList<RibbonItem> buttons = m_panelRvtSamples.AddStackedItems(data1, data2, data3); AddSamplesToStackedButtons(buttons); iCount -= 3; } if (iCount == 2) { string name = m_customizedMenus.Keys[i++]; PulldownButtonData data1 = new PulldownButtonData(name, name); name = m_customizedMenus.Keys[i++]; PulldownButtonData data2 = new PulldownButtonData(name, name); IList<RibbonItem> buttons = m_panelRvtSamples.AddStackedItems(data1, data2); AddSamplesToStackedButtons(buttons); } else if (iCount == 1) { string name = m_customizedMenus.Keys[i]; PulldownButtonData pulldownButtonData = new PulldownButtonData(name, name); PulldownButton button = m_panelRvtSamples.AddItem(pulldownButtonData) as PulldownButton; List<SampleItem> sampleItems = m_customizedMenus.Values[m_customizedMenus.IndexOfKey(button.Name)]; foreach (SampleItem item in sampleItems) { AddSampleToPulldownMenu(button, item); } } } /// <summary> /// Add samples to corresponding pulldown button /// </summary> /// <param name="buttons">pulldown buttons</param> private void AddSamplesToStackedButtons(IList<RibbonItem> buttons) { foreach (RibbonItem rItem in buttons) { PulldownButton button = rItem as PulldownButton; List<SampleItem> sampleItems = m_customizedMenus.Values[m_customizedMenus.IndexOfKey(button.Name)]; foreach (SampleItem item in sampleItems) { AddSampleToPulldownMenu(button, item); } } } #endregion // Menu Helpers } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Batch; using Microsoft.Azure.Management.Batch.Models; namespace Microsoft.Azure.Management.Batch { public static partial class AccountOperationsExtensions { /// <summary> /// Begin creating the batch account.To determine whether the operation /// has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the new /// Batch account. /// </param> /// <param name='accountName'> /// Required. A name for the Batch account which must be unique within /// Azure. Batch account names must be between 3 and 24 characters in /// length and must use only numbers and lower-case letters. This name /// is used as part of the DNS name that is used to access the batch /// service in the region in which the account is created. For /// example: http://AccountName.batch.core.windows.net/. /// </param> /// <param name='parameters'> /// Required. Additional parameters for account creation /// </param> /// <returns> /// Values returned by the Create operation. /// </returns> public static BatchAccountCreateResponse BeginCreating(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).BeginCreatingAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin creating the batch account.To determine whether the operation /// has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the new /// Batch account. /// </param> /// <param name='accountName'> /// Required. A name for the Batch account which must be unique within /// Azure. Batch account names must be between 3 and 24 characters in /// length and must use only numbers and lower-case letters. This name /// is used as part of the DNS name that is used to access the batch /// service in the region in which the account is created. For /// example: http://AccountName.batch.core.windows.net/. /// </param> /// <param name='parameters'> /// Required. Additional parameters for account creation /// </param> /// <returns> /// Values returned by the Create operation. /// </returns> public static Task<BatchAccountCreateResponse> BeginCreatingAsync(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters) { return operations.BeginCreatingAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } /// <summary> /// Begin deleting the batch account.To determine whether the operation /// has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account to be deleted. /// </param> /// <param name='accountName'> /// Required. The name of the account to be deleted. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDeleting(this IAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).BeginDeletingAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin deleting the batch account.To determine whether the operation /// has finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account to be deleted. /// </param> /// <param name='accountName'> /// Required. The name of the account to be deleted. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDeletingAsync(this IAccountOperations operations, string resourceGroupName, string accountName) { return operations.BeginDeletingAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// The Create operation creates a new Batch account in the specified /// resource group and datacenter location. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the new /// Batch account. /// </param> /// <param name='accountName'> /// Required. A name for the Batch account which must be unique within /// Azure. Batch account names must be between 3 and 24 characters in /// length and must use only numbers and lower-case letters. This name /// is used as part of the DNS name that is used to access the batch /// service in the region in which the account is created. For /// example: http://AccountName.batch.core.windows.net/. /// </param> /// <param name='parameters'> /// Required. Additional parameters for account creation /// </param> /// <returns> /// Values returned by the Create operation. /// </returns> public static BatchAccountCreateResponse Create(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).CreateAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Create operation creates a new Batch account in the specified /// resource group and datacenter location. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the new /// Batch account. /// </param> /// <param name='accountName'> /// Required. A name for the Batch account which must be unique within /// Azure. Batch account names must be between 3 and 24 characters in /// length and must use only numbers and lower-case letters. This name /// is used as part of the DNS name that is used to access the batch /// service in the region in which the account is created. For /// example: http://AccountName.batch.core.windows.net/. /// </param> /// <param name='parameters'> /// Required. Additional parameters for account creation /// </param> /// <returns> /// Values returned by the Create operation. /// </returns> public static Task<BatchAccountCreateResponse> CreateAsync(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } /// <summary> /// The Delete operation deletes an existing Batch account. The /// operation will return NoContent if the requested account does not /// exist. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account to be deleted. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Delete(this IAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).DeleteAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete operation deletes an existing Batch account. The /// operation will return NoContent if the requested account does not /// exist. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account to be deleted. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> DeleteAsync(this IAccountOperations operations, string resourceGroupName, string accountName) { return operations.DeleteAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// The Get operation gets detailed information about the specified /// Batch account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <returns> /// Values returned by the Get operation. /// </returns> public static BatchAccountGetResponse Get(this IAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).GetAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get operation gets detailed information about the specified /// Batch account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <returns> /// Values returned by the Get operation. /// </returns> public static Task<BatchAccountGetResponse> GetAsync(this IAccountOperations operations, string resourceGroupName, string accountName) { return operations.GetAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// The List operation gets information about the Batch accounts /// associated either with the subscription if no resource group is /// specified or within the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='parameters'> /// Optional. An optional argument which specifies the name of the /// resource group that constrains the set of accounts that are /// returned. /// </param> /// <returns> /// Values returned by the List operation. /// </returns> public static BatchAccountListResponse List(this IAccountOperations operations, AccountListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).ListAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List operation gets information about the Batch accounts /// associated either with the subscription if no resource group is /// specified or within the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='parameters'> /// Optional. An optional argument which specifies the name of the /// resource group that constrains the set of accounts that are /// returned. /// </param> /// <returns> /// Values returned by the List operation. /// </returns> public static Task<BatchAccountListResponse> ListAsync(this IAccountOperations operations, AccountListParameters parameters) { return operations.ListAsync(parameters, CancellationToken.None); } /// <summary> /// The ListActions operation gets information about non-standard /// actions for the provider. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <returns> /// Values returned by the ListActions operation. /// </returns> public static BatchAccountListActionsResponse ListActions(this IAccountOperations operations) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).ListActionsAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The ListActions operation gets information about non-standard /// actions for the provider. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <returns> /// Values returned by the ListActions operation. /// </returns> public static Task<BatchAccountListActionsResponse> ListActionsAsync(this IAccountOperations operations) { return operations.ListActionsAsync(CancellationToken.None); } /// <summary> /// The ListKeys operation gets the account keys for the given Batch /// account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <returns> /// Values returned by the GetKeys operation. /// </returns> public static BatchAccountListKeyResponse ListKeys(this IAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).ListKeysAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The ListKeys operation gets the account keys for the given Batch /// account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <returns> /// Values returned by the GetKeys operation. /// </returns> public static Task<BatchAccountListKeyResponse> ListKeysAsync(this IAccountOperations operations, string resourceGroupName, string accountName) { return operations.ListKeysAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Get the next set of accounts based on the previously returned /// NextLink value. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// Values returned by the List operation. /// </returns> public static BatchAccountListResponse ListNext(this IAccountOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the next set of accounts based on the previously returned /// NextLink value. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// Values returned by the List operation. /// </returns> public static Task<BatchAccountListResponse> ListNextAsync(this IAccountOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// The RegenerateKey operation regenerates the specified account key /// for the given Batch account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <param name='parameters'> /// Required. The type of key to regenerate /// </param> /// <returns> /// Values returned by the RegenerateKey operation. /// </returns> public static BatchAccountRegenerateKeyResponse RegenerateKey(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountRegenerateKeyParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).RegenerateKeyAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The RegenerateKey operation regenerates the specified account key /// for the given Batch account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <param name='parameters'> /// Required. The type of key to regenerate /// </param> /// <returns> /// Values returned by the RegenerateKey operation. /// </returns> public static Task<BatchAccountRegenerateKeyResponse> RegenerateKeyAsync(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountRegenerateKeyParameters parameters) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } /// <summary> /// The SyncAutoStorageKeys operation synchronizes access keys for the /// auto storage account configured for the specified Batch account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the Batch account. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse SyncAutoStorageKeys(this IAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).SyncAutoStorageKeysAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The SyncAutoStorageKeys operation synchronizes access keys for the /// auto storage account configured for the specified Batch account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the Batch account. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> SyncAutoStorageKeysAsync(this IAccountOperations operations, string resourceGroupName, string accountName) { return operations.SyncAutoStorageKeysAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// The Update operation updates the properties of an existing Batch /// account in the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <param name='parameters'> /// Required. Additional parameters for account update /// </param> /// <returns> /// Values returned by the Update operation. /// </returns> public static BatchAccountUpdateResponse Update(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAccountOperations)s).UpdateAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Update operation updates the properties of an existing Batch /// account in the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Batch.IAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group that contains the Batch /// account. /// </param> /// <param name='accountName'> /// Required. The name of the account. /// </param> /// <param name='parameters'> /// Required. Additional parameters for account update /// </param> /// <returns> /// Values returned by the Update operation. /// </returns> public static Task<BatchAccountUpdateResponse> UpdateAsync(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } } }
// ============================================================ // Name: UMADNAToBonePoseWindow // Author: Eli Curtz // Copyright: (c) 2016 Eli Curtz // ============================================================ #if UNITY_EDITOR using UnityEngine; using UnityEditor; using UMA; namespace UMA.PoseTools { public class UMADNAToBonePoseWindow : EditorWindow { public UMAData sourceUMA; public UnityEngine.Object outputFolder; private string folderPath = ""; private GameObject tempAvatarPreDNA; private GameObject tempAvatarPostDNA; private bool avatarDNAisDirty = false; private int selectedDNAIndex = -1; private int selectedDNAHash = 0; private int poseSaveIndex = -1; const string startingPoseName = "StartingPose"; private string poseSaveName = startingPoseName; private static GUIContent sourceGUIContent = new GUIContent( "Source UMA", "UMA character in an active scene to collect DNA poses from."); private static GUIContent converterGUIContent = new GUIContent( "DNA Converter", "DNA Converter Behavior being converted to poses."); private static GUIContent folderGUIContent = new GUIContent( "Output Folder", "Parent folder where the new set of bone poses will be saved."); private static GUIContent saveButtonGUIContent = new GUIContent( "Save Pose Set", "Generate the new poses (may take several seconds)."); void OnGUI() { sourceUMA = EditorGUILayout.ObjectField(sourceGUIContent, sourceUMA, typeof(UMAData), true) as UMAData; EditorGUI.indentLevel++; selectedDNAHash = 0; if (sourceUMA == null) { EditorGUI.BeginDisabledGroup(true); GUIContent[] dnaNames = new GUIContent[1]; dnaNames[0] = new GUIContent(""); EditorGUILayout.Popup(converterGUIContent, selectedDNAIndex, dnaNames); EditorGUI.EndDisabledGroup(); } else { IDNAConverter[] dnaConverters = sourceUMA.umaRecipe.raceData.dnaConverterList; GUIContent[] dnaNames = new GUIContent[dnaConverters.Length]; for (int i = 0; i < dnaConverters.Length; i++) { dnaNames[i] = new GUIContent(dnaConverters[i].name); } selectedDNAIndex = EditorGUILayout.Popup(converterGUIContent, selectedDNAIndex, dnaNames); if ((selectedDNAIndex >= 0) && (selectedDNAIndex < dnaConverters.Length)) { selectedDNAHash = dnaConverters[selectedDNAIndex].DNATypeHash; } } EditorGUI.indentLevel--; EditorGUILayout.Space(); outputFolder = EditorGUILayout.ObjectField(folderGUIContent, outputFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object; EnforceFolder(ref outputFolder); EditorGUI.BeginDisabledGroup((sourceUMA == null) || (selectedDNAHash == 0) || (outputFolder == null)); if (GUILayout.Button(saveButtonGUIContent)) { SavePoseSet(); } EditorGUI.EndDisabledGroup(); } void Update() { if (avatarDNAisDirty) { avatarDNAisDirty = false; UMAData umaPostDNA = tempAvatarPostDNA.GetComponent<UMADynamicAvatar>().umaData; if (umaPostDNA != null) { umaPostDNA.Dirty(true, false, false); } } } // This code is generally the same as used in the DynamicDNAConverterCustomizer // Probably worth breaking it out at some point and having it geenric protected void CreateBonePoseCallback(UMAData umaData) { avatarDNAisDirty = false; UMABonePose bonePose = ScriptableObject.CreateInstance<UMABonePose>(); UMAData umaPreDNA = tempAvatarPreDNA.GetComponent<UMADynamicAvatar>().umaData; UMAData umaPostDNA = tempAvatarPostDNA.GetComponent<UMADynamicAvatar>().umaData; UMADnaBase activeDNA = umaPostDNA.umaRecipe.GetDna(selectedDNAHash); UMASkeleton skeletonPreDNA = umaPreDNA.skeleton; UMASkeleton skeletonPostDNA = umaPostDNA.skeleton; if (poseSaveIndex < 0) { poseSaveName = startingPoseName; // Now that StartingPose has been generated // add the active DNA to the pre DNA avatar // UMA2.8+ Lots of converters can use the same DNA now //UMA2.8+ FixDNAPrefabs raceData.GetConverter(s) now returns IDNAConverter([]) IDNAConverter[] activeConverters = sourceUMA.umaRecipe.raceData.GetConverters(sourceUMA.umaRecipe.GetDna(selectedDNAHash)); //umaPreDNA.umaRecipe.raceData.dnaConverterList = new DnaConverterBehaviour[1]; //umaPreDNA.umaRecipe.raceData.dnaConverterList[0] = activeConverter; umaPreDNA.umaRecipe.raceData.dnaConverterList = activeConverters; umaPreDNA.umaRecipe.raceData.UpdateDictionary(); umaPreDNA.umaRecipe.EnsureAllDNAPresent(); umaPreDNA.Dirty(true, false, true); } Transform transformPreDNA; Transform transformPostDNA; bool transformDirty; int parentHash; foreach (int boneHash in skeletonPreDNA.BoneHashes) { skeletonPreDNA.TryGetBoneTransform(boneHash, out transformPreDNA, out transformDirty, out parentHash); skeletonPostDNA.TryGetBoneTransform(boneHash, out transformPostDNA, out transformDirty, out parentHash); if ((transformPreDNA == null) || (transformPostDNA == null)) { Debug.LogWarning("Bad bone hash in skeleton: " + boneHash); continue; } if (!LocalTransformsMatch(transformPreDNA, transformPostDNA)) { bonePose.AddBone(transformPreDNA, transformPostDNA.localPosition, transformPostDNA.localRotation, transformPostDNA.localScale); } } int activeDNACount = activeDNA.Count; for (int i = 0; i < activeDNACount; i++) { activeDNA.SetValue(i, 0.5f); } AssetDatabase.CreateAsset(bonePose, folderPath + "/" + poseSaveName + ".asset"); EditorUtility.SetDirty(bonePose); AssetDatabase.SaveAssets(); poseSaveIndex++; if (poseSaveIndex < activeDNACount) { poseSaveName = activeDNA.Names[poseSaveIndex] + "_0"; activeDNA.SetValue(poseSaveIndex, 0.0f); avatarDNAisDirty = true; } else if (poseSaveIndex < (activeDNACount * 2)) { int dnaIndex = poseSaveIndex - activeDNACount; poseSaveName = activeDNA.Names[dnaIndex] + "_1"; activeDNA.SetValue(dnaIndex, 1.0f); umaPostDNA.Dirty(); avatarDNAisDirty = true; } else { UMAUtils.DestroySceneObject(tempAvatarPreDNA); UMAUtils.DestroySceneObject(tempAvatarPostDNA); // Build a prefab DNA Converter and populate it with the morph set string assetName = "Morph Set"; string assetPath = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + ".asset"); MorphSetDnaAsset asset = CustomAssetUtility.CreateAsset<MorphSetDnaAsset>(assetPath, false); SerializedObject serializedAsset = new SerializedObject(asset); SerializedProperty startingPose = serializedAsset.FindProperty("startingPose"); startingPose.objectReferenceValue = AssetDatabase.LoadAssetAtPath<UMABonePose>(folderPath + "/" + startingPoseName + ".asset"); SerializedProperty morphSetArray = serializedAsset.FindProperty("dnaMorphs"); morphSetArray.ClearArray(); for (int i = 0; i < activeDNACount; i++) { string posePairName = activeDNA.Names[i]; morphSetArray.InsertArrayElementAtIndex(i); SerializedProperty posePair = morphSetArray.GetArrayElementAtIndex(i); SerializedProperty dnaEntryName = posePair.FindPropertyRelative("dnaEntryName"); dnaEntryName.stringValue = posePairName; SerializedProperty zeroPose = posePair.FindPropertyRelative("poseZero"); zeroPose.objectReferenceValue = AssetDatabase.LoadAssetAtPath<UMABonePose>(folderPath + "/" + posePairName + "_0.asset"); SerializedProperty onePose = posePair.FindPropertyRelative("poseOne"); onePose.objectReferenceValue = AssetDatabase.LoadAssetAtPath<UMABonePose>(folderPath + "/" + posePairName + "_1.asset"); } serializedAsset.ApplyModifiedPropertiesWithoutUndo(); // Build a prefab DNA Converter and populate it with the morph set string prefabName = "Converter Prefab"; string prefabPath = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + prefabName + ".prefab"); GameObject tempConverterPrefab = new GameObject(prefabName); MorphSetDnaConverterBehaviour converter = tempConverterPrefab.AddComponent<MorphSetDnaConverterBehaviour>(); SerializedObject serializedConverter = new SerializedObject(converter); SerializedProperty morphSet = serializedAsset.FindProperty("morphSet"); morphSet.objectReferenceValue = AssetDatabase.LoadAssetAtPath<MorphSetDnaAsset>(assetPath); serializedConverter.ApplyModifiedPropertiesWithoutUndo(); #if UNITY_2018_3_OR_NEWER PrefabUtility.SaveAsPrefabAsset(tempConverterPrefab, prefabPath); #else PrefabUtility.CreatePrefab(prefabPath, tempConverterPrefab); #endif DestroyImmediate(tempConverterPrefab, false); } } protected void SavePoseSet() { // UMA2.8+ Lots of converters can use the same DNA now //UMA2.8+ FixDNAPrefabs raceData.GetConverter(s) now returns IDNAConverter([]) IDNAConverter[] activeConverters = sourceUMA.umaRecipe.raceData.GetConverters(sourceUMA.umaRecipe.GetDna(selectedDNAHash)); //Just use the first result? folderPath = AssetDatabase.GetAssetPath(outputFolder) + "/" + activeConverters[0].name; if (!AssetDatabase.IsValidFolder(folderPath)) { string folderGUID = AssetDatabase.CreateFolder(AssetDatabase.GetAssetPath(outputFolder), activeConverters[0].name); folderPath = AssetDatabase.GUIDToAssetPath(folderGUID); } poseSaveIndex = -1; // Build a temporary version of the Avatar with no DNA to get original state SlotData[] activeSlots = sourceUMA.umaRecipe.GetAllSlots(); int slotIndex; tempAvatarPreDNA = new GameObject("Temp Raw Avatar"); tempAvatarPreDNA.transform.parent = sourceUMA.transform.parent; tempAvatarPreDNA.transform.localPosition = Vector3.zero; tempAvatarPreDNA.transform.localRotation = sourceUMA.transform.localRotation; UMADynamicAvatar tempAvatar = tempAvatarPreDNA.AddComponent<UMADynamicAvatar>(); tempAvatar.umaGenerator = sourceUMA.umaGenerator; tempAvatar.Initialize(); tempAvatar.umaData.umaRecipe = new UMAData.UMARecipe(); tempAvatar.umaData.umaRecipe.raceData = ScriptableObject.CreateInstance<RaceData>(); tempAvatar.umaData.umaRecipe.raceData.raceName = "Temp Raw Race"; tempAvatar.umaData.umaRecipe.raceData.TPose = sourceUMA.umaRecipe.raceData.TPose; tempAvatar.umaData.umaRecipe.raceData.umaTarget = sourceUMA.umaRecipe.raceData.umaTarget; slotIndex = 0; foreach (SlotData slotEntry in activeSlots) { if ((slotEntry == null) || slotEntry.dontSerialize) continue; tempAvatar.umaData.umaRecipe.SetSlot(slotIndex++, slotEntry); } tempAvatar.Show(); tempAvatarPostDNA = new GameObject("Temp DNA Avatar"); tempAvatarPostDNA.transform.parent = sourceUMA.transform.parent; tempAvatarPostDNA.transform.localPosition = Vector3.zero; tempAvatarPostDNA.transform.localRotation = sourceUMA.transform.localRotation; UMADynamicAvatar tempAvatar2 = tempAvatarPostDNA.AddComponent<UMADynamicAvatar>(); tempAvatar2.umaGenerator = sourceUMA.umaGenerator; tempAvatar2.Initialize(); tempAvatar2.umaData.umaRecipe = new UMAData.UMARecipe(); tempAvatar2.umaData.umaRecipe.raceData = ScriptableObject.CreateInstance<RaceData>(); tempAvatar2.umaData.umaRecipe.raceData.raceName = "Temp DNA Race"; tempAvatar2.umaData.umaRecipe.raceData.TPose = sourceUMA.umaRecipe.raceData.TPose; tempAvatar2.umaData.umaRecipe.raceData.umaTarget = sourceUMA.umaRecipe.raceData.umaTarget; //tempAvatar2.umaData.umaRecipe.raceData.dnaConverterList = new DnaConverterBehaviour[1]; //tempAvatar2.umaData.umaRecipe.raceData.dnaConverterList[0] = activeConverter; tempAvatar2.umaData.umaRecipe.raceData.dnaConverterList = activeConverters; tempAvatar2.umaData.umaRecipe.raceData.UpdateDictionary(); slotIndex = 0; foreach (SlotData slotEntry in activeSlots) { if ((slotEntry == null) || slotEntry.dontSerialize) continue; tempAvatar2.umaData.umaRecipe.SetSlot(slotIndex++, slotEntry); } tempAvatar2.umaData.OnCharacterUpdated += CreateBonePoseCallback; tempAvatar2.Show(); } public static void EnforceFolder(ref UnityEngine.Object folderObject) { if (folderObject != null) { string destpath = AssetDatabase.GetAssetPath(folderObject); if (string.IsNullOrEmpty(destpath)) { folderObject = null; } else if (!System.IO.Directory.Exists(destpath)) { destpath = destpath.Substring(0, destpath.LastIndexOf('/')); folderObject = AssetDatabase.LoadMainAssetAtPath(destpath); } } } private const float bonePoseAccuracy = 0.0001f; private static bool LocalTransformsMatch(Transform t1, Transform t2) { if ((t1.localPosition - t2.localPosition).sqrMagnitude > bonePoseAccuracy) return false; if ((t1.localScale - t2.localScale).sqrMagnitude > bonePoseAccuracy) return false; if (t1.localRotation != t2.localRotation) return false; return true; } [MenuItem("UMA/Pose Tools/Bone Pose DNA Extractor", priority = 1)] public static void OpenUMADNAToBonePoseWindow() { EditorWindow win = EditorWindow.GetWindow(typeof(UMADNAToBonePoseWindow)); win.titleContent.text = "Pose Extractor"; } } } #endif
/********************************************************************** * Copyright (c) 2010, j. montgomery * * 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 j. montgomery's employer nor the names of * * its contributors may be used to endorse or promote products * * derived from this software without specific prior written * * permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS* * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,* * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,* * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED* * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Diagnostics; namespace PocketDnDns.Records { /// <summary> /// Handles a basic Dns record /// /// From RFC 1035: /// /// 3.2.1. Format /// /// All RRs have the same top level format shown below: /// /// 1 1 1 1 1 1 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | | /// / / /// / NAME / /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | TYPE | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | CLASS | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | TTL | /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | RDLENGTH | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| /// / RDATA / /// / / /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// /// where: /// /// NAME an owner name, i.e., the name of the node to which this /// resource record pertains. /// /// TYPE two octets containing one of the RR TYPE codes. /// /// CLASS two octets containing one of the RR CLASS codes. /// /// TTL a 32 bit signed integer that specifies the time interval /// that the resource record may be cached before the source /// of the information should again be consulted. Zero /// values are interpreted to mean that the RR can only be /// used for the transaction in progress, and should not be /// cached. For example, SOA records are always distributed /// with a zero TTL to prohibit caching. Zero values can /// also be used for extremely volatile data. /// /// RDLENGTH an unsigned 16 bit integer that specifies the length in /// octets of the RDATA field. /// /// RDATA a variable length string of octets that describes the /// resource. The format of this information varies /// according to the TYPE and CLASS of the resource record. /// </summary> public abstract class DnsRecordBase : IDnsRecord { #region Fields // NAME an owner name, i.e., the name of the node to which this // resource record pertains. //private string _name; // TYPE two octets containing one of the RR TYPE codes. //protected NsType _nsType; // CLASS - two octets containing one of the RR CLASS codes. //private NsClass _nsClass; // TTL - a 32 bit signed integer that specifies the time interval // that the resource record may be cached before the source // of the information should again be consulted. Zero // values are interpreted to mean that the RR can only be // used for the transaction in progress, and should not be // cached. For example, SOA records are always distributed // with a zero TTL to prohibit caching. Zero values can /// also be used for extremely volatile data. //private int _timeToLive; // RDLENGTH - an unsigned 16 bit integer that specifies the length in // octets of the RDATA field. //protected short _dataLength; protected RecordHeader _dnsHeader; protected string _answer; protected string _errorMsg; #endregion #region Properties /// <summary> /// NAME - an owner name, i.e., the name of the node to which this /// resource record pertains. /// </summary> //public string Name //{ // get { return _name; } //} public RecordHeader DnsHeader { get { return _dnsHeader; } } public string Answer { get { return _answer; } } /// <summary> /// TYPE two octets containing one of the RR TYPE codes. /// </summary> //public NsType NsType //{ // get { return _nsType; } //} /// <summary> /// CLASS - two octets containing one of the RR CLASS codes. /// </summary> //public NsClass NsClass //{ // get { return _nsClass; } //} /// <summary> /// TTL - a 32 bit signed integer that specifies the time interval /// that the resource record may be cached before the source /// of the information should again be consulted. Zero /// values are interpreted to mean that the RR can only be /// used for the transaction in progress, and should not be /// cached. For example, SOA records are always distributed /// with a zero TTL to prohibit caching. Zero values can /// also be used for extremely volatile data. /// </summary> //public int TimeToLive //{ // get { return _timeToLive; } //} /// <summary> /// RDLENGTH - an unsigned 16 bit integer that specifies the length in /// octets of the RDATA field. /// </summary> //public short DataLength //{ // get { return _dataLength; } //} public string ErrorMsg { get { return _errorMsg; } } #endregion internal DnsRecordBase() { } public virtual void ParseRecord(ref MemoryStream ms) { // Default implementation - the most common. _answer = DnsRecordBase.ParseName(ref ms); } internal DnsRecordBase(RecordHeader dnsHeader) { _dnsHeader = dnsHeader; } // RFC // 4.1.4. Message compression // // In order to reduce the size of messages, the domain system utilizes a // compression scheme which eliminates the repetition of domain names in a // message. In this scheme, an entire domain name or a list of labels at // the end of a domain name is replaced with a pointer to a prior occurance // of the same name. // // The pointer takes the form of a two octet sequence: // // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // | 1 1| OFFSET | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // // The first two bits are ones. This allows a pointer to be distinguished // from a label, since the label must begin with two zero bits because // labels are restricted to 63 octets or less. (The 10 and 01 combinations // are reserved for future use.) The OFFSET field specifies an offset from // the start of the message (i.e., the first octet of the ID field in the // domain header). A zero offset specifies the first byte of the ID field, // etc. // // The compression scheme allows a domain name in a message to be // represented as either: // // - a sequence of labels ending in a zero octet // - a pointer // - a sequence of labels ending with a pointer // internal static string ParseName(ref MemoryStream ms) { Debug.WriteLine("Reading Name..."); StringBuilder sb = new StringBuilder(); uint next = (uint)ms.ReadByte(); Debug.WriteLine("Next is 0x" + next.ToString("x2")); int bPointer; while ((next != 0x00)) { // Isolate 2 most significat bits -> e.g. 11xx xxxx // if it's 0xc0 (11000000b} then pointer switch (0xc0 & next) { // 0xc0 -> Name is a pointer. case 0xc0: { // Isolate Offset int offsetMASK = ~0xc0; // Example on how to calculate the offset // e.g. // // So if given the following 2 bytes - 0xc1 0x1c (11000001 00011100) // // The pointer takes the form of a two octet sequence: // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // | 1 1| OFFSET | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // | 1 1| 0 0 0 0 0 1 0 0 0 1 1 1 0 0| // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // // A pointer is indicated by the a 1 in the two most significant bits // The Offset is the remaining bits. // // The Pointer = 0xc0 (11000000 00000000) // The offset = 0x11c (00000001 00011100) // Move offset into the proper position int offset = (int)(offsetMASK & next) << 8; // extract the pointer to the data in the stream bPointer = ms.ReadByte() + offset; // store the position so we can resume later long oldPtr = ms.Position; // Move to the specified position in the stream and // parse the name (recursive call) ms.Position = bPointer; sb.Append(DnsRecordBase.ParseName(ref ms)); Debug.WriteLine(sb.ToString()); // Move back to original position, and continue ms.Position = oldPtr; next = 0x00; break; } case 0x00: { Debug.Assert(next < 0xc0, "Offset cannot be greater then 0xc0."); byte[] buffer = new byte[next]; ms.Read(buffer, 0, (int)next); sb.Append(Encoding.ASCII.GetString(buffer, 0, buffer.Length) + "."); next = (uint)ms.ReadByte(); Debug.WriteLine("0x" + next.ToString("x2")); break; } default: throw new InvalidOperationException("There was a problem decompressing the DNS Message."); } } return sb.ToString(); } internal string ParseText(ref MemoryStream ms) { StringBuilder sb = new StringBuilder(); int len = ms.ReadByte(); byte[] buffer = new byte[len]; ms.Read(buffer, 0, len); sb.Append(Encoding.ASCII.GetString(buffer, 0, buffer.Length)); return sb.ToString(); } public override string ToString() { return _answer; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using Shellscape; using Shellscape.Utilities; using System.Diagnostics; namespace GmailNotifierPlus.Forms { public partial class Toast : Form { #region . API [StructLayout(LayoutKind.Sequential)] public struct MARGINS { public int cxLeftWidth; public int cxRightWidth; public int cyTopHeight; public int cyBottomHeight; public MARGINS(int Left, int Right, int Top, int Bottom) { this.cxLeftWidth = Left; this.cxRightWidth = Right; this.cyTopHeight = Top; this.cyBottomHeight = Bottom; } } [StructLayout(LayoutKind.Explicit)] public struct RECT { // Fields [FieldOffset(12)] public int Bottom; [FieldOffset(0)] public int Left; [FieldOffset(8)] public int Right; [FieldOffset(4)] public int Top; // Methods public RECT(Rectangle rect) { this.Left = rect.Left; this.Top = rect.Top; this.Right = rect.Right; this.Bottom = rect.Bottom; } public RECT(int left, int top, int right, int bottom) { this.Left = left; this.Top = top; this.Right = right; this.Bottom = bottom; } public void Set() { this.Left = this.Top = this.Right = this.Bottom = 0; } public void Set(Rectangle rect) { this.Left = rect.Left; this.Top = rect.Top; this.Right = rect.Right; this.Bottom = rect.Bottom; } public void Set(int left, int top, int right, int bottom) { this.Left = left; this.Top = top; this.Right = right; this.Bottom = bottom; } public Rectangle ToRectangle() { return new Rectangle(this.Left, this.Top, this.Right - this.Left, this.Bottom - this.Top); } // Properties public int Height { get { return (this.Bottom - this.Top); } } public Size Size { get { return new Size(this.Width, this.Height); } } public int Width { get { return (this.Right - this.Left); } } } /// <summary> /// The NCCALCSIZE_PARAMS structure contains information that an application can use /// while processing the WM_NCCALCSIZE message to calculate the size, position, and /// valid contents of the client area of a window. /// </summary> [StructLayout(LayoutKind.Sequential)] // This is the default layout for a structure public struct NCCALCSIZE_PARAMS { public RECT rect0, rect1, rect2; // Can't use an array here so simulate one public IntPtr lppos; } [DllImport("dwmapi.dll")] public static extern int DwmExtendFrameIntoClientArea(IntPtr hdc, ref MARGINS marInset); [DllImport("dwmapi.dll")] public static extern int DwmIsCompositionEnabled(ref int pfEnabled); [DllImport("dwmapi.dll")] public static extern int DwmDefWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, out IntPtr result); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags); static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); static readonly IntPtr HWND_TOP = new IntPtr(0); static readonly IntPtr HWND_BOTTOM = new IntPtr(1); [Flags] public enum SetWindowPosFlags : uint { ASYNCWINDOWPOS = 0x4000, DEFERERASE = 0x2000, DRAWFRAME = 0x0020, FRAMECHANGED = 0x0020, HIDEWINDOW = 0x0080, NOACTIVATE = 0x0010, NOCOPYBITS = 0x0100, NOMOVE = 0x0002, NOOWNERZORDER = 0x0200, NOREDRAW = 0x0008, NOREPOSITION = 0x0200, NOSENDCHANGING = 0x0400, NOSIZE = 0x0001, NOZORDER = 0x0004, SHOWWINDOW = 0x0040, } #endregion private class State { public const int Normal = 1; public const int Hot = 2; public const int Pressed = 3; public const int Disabled = 4; } private MARGINS _dwmMargins; private Boolean _setMargins; private Boolean _aeroEnabled; private Size _buttonSize = new Size(26, 22); private Boolean _rectsInitialized = false; private const int LeftControl = 9; private const int CenterControl = 10; private const int RightControl = 11; private Rectangle _rectClose = Rectangle.Empty; private Rectangle _rectNext = Rectangle.Empty; private Rectangle _rectPrev = Rectangle.Empty; private Rectangle _rectInbox = Rectangle.Empty; private Rectangle _rectClient = Rectangle.Empty; private int _stateClose = 1; private int _statePrev = State.Normal; private int _stateInbox = 1; private int _stateNext = State.Disabled; private int _mailIndex = 0; private Timer _closeTimer = new Timer() { Interval = 15000, Enabled = false }; private ToolTip _openTip = null; private VisualStyleElement _elementClose = null; private VisualStyleElement _elementPrev = null; private VisualStyleElement _elementInbox = null; private VisualStyleElement _elementNext = null; private Icon _iconPrev = null; private Icon _iconInbox = null; private Icon _iconNext = null; //private Icon _iconWindow = null; public Toast(Account account) { InitializeComponent(); this.Account = account; this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.UpdateStyles(); int enabled = 0; int response = DwmIsCompositionEnabled(ref enabled); _aeroEnabled = enabled == 1; if(!VisualStyleRenderer.IsSupported || !_aeroEnabled) { this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.ControlBox = true; } this.Opacity = 0; SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, SetWindowPosFlags.NOACTIVATE | SetWindowPosFlags.NOSIZE | SetWindowPosFlags.NOREPOSITION); _closeTimer.Tick += _closeTimer_Tick; _elementClose = VisualStyleElement.Window.SmallCloseButton.Normal; _elementPrev = VisualStyleElement.CreateElement("TaskbandExtendedUI", LeftControl, 1); _elementInbox = VisualStyleElement.CreateElement("TaskbandExtendedUI", CenterControl, 1); _elementNext = VisualStyleElement.CreateElement("TaskbandExtendedUI", RightControl, 1); _iconPrev = Resources.Icons.Previous; _iconInbox = Resources.Icons.Inbox; _iconNext = Resources.Icons.Next; this.Icon = Resources.Icons.Window; ToolTip _openTip = new ToolTip(); _openTip.SetToolTip(_PictureOpen, Localization.Locale.Current.Toast.ViewEmail); _PictureOpen.Cursor = Cursors.Hand; _PictureOpen.Click += OpenEmail; using (Icon icon = Resources.Icons.Open){ //ResourceHelper.GetIcon("Open.ico")) { _PictureOpen.Image = icon.ToBitmap(); } if (this.Account.Emails.Count > 1) { _stateNext = State.Normal; } // show the last (newest) email _mailIndex = 0; //this.Account.Emails.Count - 1; UpdateBody(); } public Account Account { get; set; } protected override bool ShowWithoutActivation { get { return true; } } private void _closeTimer_Tick(object sender, EventArgs e) { this.Close(); } private int _activatedCount = 0; // child controls activate the form automatically. this happens twice. any subsequent activations should stop the timer. protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); if (_activatedCount >= 2) { _closeTimer.Stop(); } _activatedCount++; } protected override void OnMouseUp(MouseEventArgs e) { base.OnClick(e); Point mouse = this.PointToClient(MousePosition); if (_rectClose.Contains(mouse)) { this.Close(); } else if (_rectInbox.Contains(mouse)) { Utilities.UrlHelper.Launch(this.Account, Utilities.UrlHelper.BuildInboxUrl(this.Account)); this.Close(); } // Prev Rect else if (_rectPrev.Contains(mouse) && _statePrev != State.Disabled) { if (_mailIndex > 0) { _mailIndex--; UpdateBody(); if (_statePrev == State.Disabled) { _stateNext = State.Normal; Invalidate(_rectNext); } } else { _statePrev = State.Disabled; Invalidate(_rectPrev); } } // Next Rect else if (_rectNext.Contains(mouse) && _stateNext != State.Disabled) { if (_mailIndex < this.Account.Unread - 1) { _mailIndex++; UpdateBody(); if (_statePrev == State.Disabled) { _statePrev = State.Normal; Invalidate(_rectPrev); } } else { _stateNext = State.Disabled; Invalidate(_rectNext); } } } /// <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(); } _closeTimer.Dispose(); this.Icon.Dispose(); this.Icon = null; _iconPrev.Dispose(); _iconInbox.Dispose(); _iconNext.Dispose(); if(_PictureOpen != null) { _PictureOpen.Image.Dispose(); } if(_openTip != null) { _openTip.Dispose(); } base.Dispose(disposing); } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); _closeTimer.Tick -= _closeTimer_Tick; Timer timer = new Timer() { Interval = 50 }; timer.Tick += delegate(object sender, EventArgs args) { this.Opacity = Math.Max(this.Opacity - 0.1, 0); if (this.Opacity == 0) { timer.Stop(); timer.Dispose(); } }; timer.Start(); } protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); _closeTimer.Start(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (VisualStyleRenderer.IsSupported && _aeroEnabled) { DwmExtendFrameIntoClientArea(this.Handle, ref _dwmMargins); } Timer timer = new Timer() { Interval = 50 }; timer.Tick += delegate(object sender, EventArgs args) { this.Opacity = Math.Min(this.Opacity + 0.1, 1); if (this.Opacity == 1) { timer.Stop(); timer.Dispose(); //this.TopMost = false; } }; timer.Start(); _closeTimer.Start(); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (_rectClose.Contains(e.Location)) { Debug.WriteLine("Mouse Down"); _stateClose = State.Pressed; Invalidate(_rectClose); } else if (_rectPrev.Contains(e.Location) && _statePrev != State.Disabled) { _statePrev = State.Pressed; Invalidate(_rectPrev); } else if (_rectInbox.Contains(e.Location)) { _stateInbox = State.Pressed; Invalidate(_rectInbox); } else if (_rectNext.Contains(e.Location) && _stateNext != State.Disabled) { _stateNext = State.Pressed; Invalidate(_rectNext); } } /// <summary> /// OH LAWD this method is soooo damned fugly. but i'm just not willing to pretty it up. you're an ugly bitch, aintcha? /// </summary> /// <param name="e"></param> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); Boolean pressed = e.Button != System.Windows.Forms.MouseButtons.None; if (_rectClose.Contains(e.Location) && _stateClose != State.Pressed) { SetDefaultState(); _stateClose = pressed ? State.Pressed : State.Hot; } else if (_rectPrev.Contains(e.Location) && _statePrev != State.Disabled) { SetDefaultState(); _statePrev = pressed ? State.Pressed : State.Hot; } else if (_rectInbox.Contains(e.Location)) { SetDefaultState(); _stateInbox = pressed ? State.Pressed : State.Hot; } else if (_rectNext.Contains(e.Location) && _stateNext != State.Disabled) { SetDefaultState(); _stateNext = pressed ? State.Pressed : State.Hot; } else { SetDefaultState(); } Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); _closeTimer.Start(); } private void InitRects(Graphics g) { if (_rectsInitialized) { return; } int totalButtonWidth = _buttonSize.Width * 3; int startX = (((VisualStyleRenderer.IsSupported ? this.Width : this.ClientSize.Width) - totalButtonWidth) / 2); int iconX = (_buttonSize.Width - 16) / 2; int iconY = (_buttonSize.Height - 16) / 2; int buttonY = VisualStyleRenderer.IsSupported ? (this.Height - _buttonSize.Height) : (this.ClientSize.Height - _buttonSize.Height); if (VisualStyleRenderer.IsSupported && _aeroEnabled) { _rectClient = new Rectangle( _dwmMargins.cxLeftWidth, _dwmMargins.cyTopHeight, Width - _dwmMargins.cxRightWidth - _dwmMargins.cxLeftWidth, Height - _dwmMargins.cyBottomHeight - _dwmMargins.cyTopHeight ); } else { _rectClient = this.ClientRectangle; } _Panel.Top = _rectClient.Top; _Panel.Left = _rectClient.Left; _rectPrev = new Rectangle(startX, buttonY, _buttonSize.Width, _buttonSize.Height); startX += _buttonSize.Width; _rectInbox = new Rectangle(startX, buttonY, _buttonSize.Width, _buttonSize.Height); startX += _buttonSize.Width; _rectNext = new Rectangle(startX, buttonY, _buttonSize.Width, _buttonSize.Height); Size closeSize; if (VisualStyleRenderer.IsSupported) { VisualStyleRenderer renderer = new VisualStyleRenderer(_elementClose); closeSize = renderer.GetPartSize(g, ThemeSizeType.True); } else { closeSize = new Size(16, 14); } _rectClose = new Rectangle(Width - _dwmMargins.cxLeftWidth - closeSize.Width, 8, closeSize.Width, closeSize.Height); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); InitRects(e.Graphics); e.Graphics.Clear(_aeroEnabled ? Color.Transparent : SystemColors.Control); e.Graphics.FillRectangle(SystemBrushes.Control, _rectClient); e.Graphics.SmoothingMode = SmoothingMode.HighQuality; if(_aeroEnabled) { e.Graphics.DrawIcon(this.Icon, new Rectangle(_dwmMargins.cxLeftWidth, _dwmMargins.cxLeftWidth, 16, 16)); Rectangle captionLayout = new Rectangle(_dwmMargins.cxLeftWidth + (_dwmMargins.cxLeftWidth / 2) + 16, _dwmMargins.cxLeftWidth, this.Width, _dwmMargins.cyTopHeight); String caption = String.Concat(" ", this.Account.FullAddress); // stupid hack. padding so the glow doesnt get cut off on the left. using(Font font = SystemFonts.CaptionFont) { Utilities.GlassHelper.DrawText(e.Graphics, caption, font, captionLayout, this.ForeColor, TextFormatFlags.Default, Utilities.TextStyle.Glowing); } PaintElement(e.Graphics, _elementClose, _rectClose, _stateClose); } if(VisualStyleRenderer.IsSupported) { PaintElement(e.Graphics, _elementPrev, _rectPrev, _statePrev); PaintElement(e.Graphics, _elementInbox, _rectInbox, _stateInbox); PaintElement(e.Graphics, _elementNext, _rectNext, _stateNext); } PaintIcon(e.Graphics, _iconPrev, _rectPrev, _statePrev); PaintIcon(e.Graphics, _iconInbox, _rectInbox, State.Normal); PaintIcon(e.Graphics, _iconNext, _rectNext, _stateNext); } protected override void WndProc(ref Message m) { if (!VisualStyleRenderer.IsSupported || !_aeroEnabled) { base.WndProc(ref m); return; } int WM_NCCALCSIZE = 0x83; IntPtr result; int dwmHandled = DwmDefWindowProc(m.HWnd, m.Msg, m.WParam, m.LParam, out result); if (dwmHandled == 1) { m.Result = result; return; } if (m.Msg == WM_NCCALCSIZE && (int)m.WParam == 1) { NCCALCSIZE_PARAMS nccsp = (NCCALCSIZE_PARAMS)Marshal.PtrToStructure(m.LParam, typeof(NCCALCSIZE_PARAMS)); // Adjust (shrink) the client rectangle to accommodate the border: nccsp.rect0.Top += 0; nccsp.rect0.Bottom += 0; nccsp.rect0.Left += 0; nccsp.rect0.Right += 0; if (!_setMargins) { //Set what client area would be for passing to DwmExtendIntoClientArea _dwmMargins.cyTopHeight = nccsp.rect2.Top - nccsp.rect1.Top; _dwmMargins.cxLeftWidth = nccsp.rect2.Left - nccsp.rect1.Left; _dwmMargins.cyBottomHeight = _buttonSize.Height + 2; _dwmMargins.cxRightWidth = nccsp.rect1.Right - nccsp.rect2.Right; _setMargins = true; } Marshal.StructureToPtr(nccsp, m.LParam, false); m.Result = IntPtr.Zero; } else { base.WndProc(ref m); } } private void PaintIcon(Graphics g, Icon icon, Rectangle rect, int state) { int x = (rect.Width - icon.Width) / 2; int y = (rect.Height - icon.Height) / 2; Rectangle layout = new Rectangle(x + rect.Left, y + rect.Top, icon.Width, icon.Height); if (state == State.Disabled) { // ControlPaint.DrawImageDisabled sucks ass. ColorMatrix cm = new ColorMatrix(new float[][]{ new float[]{0.3f,0.3f,0.3f,0,0}, new float[]{0.59f,0.59f,0.59f,0,0}, new float[]{0.11f,0.11f,0.11f,0,0}, new float[]{0,0,0,1,0,0}, new float[]{0,0,0,0,1,0}, new float[]{0,0,0,0,0,1} }); using (Bitmap bitmap = icon.ToBitmap()) using (ImageAttributes ia = new ImageAttributes()) { ia.SetColorMatrix(cm); g.DrawImage(bitmap, layout, 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, ia); } } else { g.DrawIcon(icon, layout); } } private void PaintElement(Graphics g, VisualStyleElement element, Rectangle rect, int state) { if (VisualStyleRenderer.IsSupported) { VisualStyleRenderer renderer = new VisualStyleRenderer(element.ClassName, element.Part, state); renderer.DrawBackground(g, rect); } else { ButtonState buttonState = ButtonState.Normal; if (state == State.Disabled) { buttonState = ButtonState.Inactive; } else if (state == State.Pressed) { buttonState = ButtonState.Pushed; } if (element == _elementClose) { ControlPaint.DrawCaptionButton(g, rect, CaptionButton.Close, buttonState); } else { ControlPaint.DrawButton(g, rect, buttonState); } } } private void UpdateBody() { this.Text = this.Account.FullAddress; if (_mailIndex > this.Account.Emails.Count) { _mailIndex = this.Account.Emails.Count - 1; } Email email = this.Account.Emails[_mailIndex]; _LabelDate.Text = email.When; _LabelFrom.Text = email.From; _LabelMessage.Text = email.Message; _LabelTitle.Text = email.Title; String start = (_mailIndex + 1).ToString(); //(this.Account.Unread - _mailIndex).ToString(); String end = this.Account.Unread.ToString(); _LabelIndex.Text = String.Concat(start, " / ", end); //String.Concat((_mailIndex + 1).ToString(), " / ", this.Account.Unread); SetDefaultState(); } private void SetDefaultState() { _stateClose = State.Normal; _stateInbox = State.Normal; if (this.Account.Emails.Count == 1) { _stateNext = _statePrev = State.Disabled; return; } if (_statePrev != State.Disabled) { _statePrev = State.Normal; } if (_stateNext != State.Disabled) { _stateNext = State.Normal; } if (_mailIndex == 0) { _statePrev = State.Disabled; } // gmail's atom feed only sends data for 20 messages else if (_mailIndex >= 19 || _mailIndex >= this.Account.Unread - 1) { _stateNext = State.Disabled; } } private void OpenEmail(object sender, EventArgs e) { String url = this.Account.Emails[_mailIndex].Url; if (!String.IsNullOrEmpty(url)) { Utilities.UrlHelper.Launch(this.Account, url); } this.Close(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using EnvDTE; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio.Resources; namespace NuGet.VisualStudio { public class VsPackageManager : PackageManager, IVsPackageManager { private readonly ISharedPackageRepository _sharedRepository; private readonly IDictionary<string, IProjectManager> _projects; private readonly ISolutionManager _solutionManager; private readonly IFileSystemProvider _fileSystemProvider; private readonly IDeleteOnRestartManager _deleteOnRestartManager; private readonly VsPackageInstallerEvents _packageEvents; private bool _bindingRedirectEnabled = true; private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting; private bool _repositoryOperationPending; public VsPackageManager(ISolutionManager solutionManager, IPackageRepository sourceRepository, IFileSystemProvider fileSystemProvider, IFileSystem fileSystem, ISharedPackageRepository sharedRepository, IDeleteOnRestartManager deleteOnRestartManager, VsPackageInstallerEvents packageEvents, IVsFrameworkMultiTargeting frameworkMultiTargeting = null) : base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository) { _solutionManager = solutionManager; _sharedRepository = sharedRepository; _packageEvents = packageEvents; _fileSystemProvider = fileSystemProvider; _deleteOnRestartManager = deleteOnRestartManager; _frameworkMultiTargeting = frameworkMultiTargeting; _projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase); } public bool BindingRedirectEnabled { get { return _bindingRedirectEnabled; } set { _bindingRedirectEnabled = value; } } internal void EnsureCached(Project project) { string projectUniqueName = project.GetUniqueName(); if (_projects.ContainsKey(projectUniqueName)) { return; } _projects[projectUniqueName] = CreateProjectManager(project); } public virtual IProjectManager GetProjectManager(Project project) { EnsureCached(project); IProjectManager projectManager; bool projectExists = _projects.TryGetValue(project.GetUniqueName(), out projectManager); Debug.Assert(projectExists, "Unknown project"); return projectManager; } private IProjectManager CreateProjectManager(Project project) { // Create the project system IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider); var repository = new PackageReferenceRepository(projectSystem, project.GetProperName(), _sharedRepository); // Ensure the logger is null while registering the repository FileSystem.Logger = null; Logger = null; // Ensure that this repository is registered with the shared repository if it needs to be repository.RegisterIfNecessary(); // The source repository of the project is an aggregate since it might need to look for all // available packages to perform updates on dependent packages var sourceRepository = CreateProjectManagerSourceRepository(); var projectManager = new ProjectManager(sourceRepository, PathResolver, projectSystem, repository); // The package reference repository also provides constraints for packages (via the allowedVersions attribute) projectManager.ConstraintProvider = repository; return projectManager; } public void InstallPackage( IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener packageOperationEventListener) { if (package == null) { throw new ArgumentNullException("package"); } if (operations == null) { throw new ArgumentNullException("operations"); } if (projects == null) { throw new ArgumentNullException("projects"); } using (StartInstallOperation(package.Id, package.Version.ToString())) { ExecuteOperationsWithPackage( projects, package, operations, projectManager => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions), logger, packageOperationEventListener); } } public virtual void InstallPackage( IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions, ILogger logger) { InstallPackage(projectManager, packageId, version, ignoreDependencies, allowPrereleaseVersions, skipAssemblyReferences: false, logger: logger); } public void InstallPackage( IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions, bool skipAssemblyReferences, ILogger logger) { try { InitializeLogger(logger, projectManager); IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions); using (StartInstallOperation(packageId, package.Version.ToString())) { if (skipAssemblyReferences) { package = new SkipAssemblyReferencesPackage(package); } RunSolutionAction(() => { InstallPackage( package, projectManager != null ? projectManager.Project.TargetFramework : null, ignoreDependencies, allowPrereleaseVersions); AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions); }); } } finally { ClearLogger(projectManager); } } public void InstallPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies, bool allowPrereleaseVersions, ILogger logger) { if (package == null) { throw new ArgumentNullException("package"); } if (operations == null) { throw new ArgumentNullException("operations"); } using (StartInstallOperation(package.Id, package.Version.ToString())) { ExecuteOperationsWithPackage( projectManager, package, operations, () => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions), logger); } } public void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies) { UninstallPackage(projectManager, packageId, version, forceRemove, removeDependencies, NullLogger.Instance); } public virtual void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies, ILogger logger) { EventHandler<PackageOperationEventArgs> uninstallingHandler = (sender, e) => _packageEvents.NotifyUninstalling(e); EventHandler<PackageOperationEventArgs> uninstalledHandler = (sender, e) => _packageEvents.NotifyUninstalled(e); try { InitializeLogger(logger, projectManager); bool appliesToProject; IPackage package = FindLocalPackage(projectManager, packageId, version, CreateAmbiguousUninstallException, out appliesToProject); PackageUninstalling += uninstallingHandler; PackageUninstalled += uninstalledHandler; if (appliesToProject) { RemovePackageReference(projectManager, packageId, forceRemove, removeDependencies); } else { UninstallPackage(package, forceRemove, removeDependencies); } } finally { PackageUninstalling -= uninstallingHandler; PackageUninstalled -= uninstalledHandler; ClearLogger(projectManager); } } public void UpdatePackage( IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener packageOperationEventListener) { if (operations == null) { throw new ArgumentNullException("operations"); } if (projects == null) { throw new ArgumentNullException("projects"); } using (StartUpdateOperation(package.Id, package.Version.ToString())) { ExecuteOperationsWithPackage( projects, package, operations, projectManager => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions), logger, packageOperationEventListener); } } public virtual void UpdatePackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackage(projectManager, packageId, () => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger); } private void UpdatePackage(IProjectManager projectManager, string packageId, Action projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { try { InitializeLogger(logger, projectManager); bool appliesToProject; IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject); // Find the package we're going to update to IPackage newPackage = resolvePackage(); if (newPackage != null && package.Version != newPackage.Version) { using (StartUpdateOperation(packageId, newPackage.Version.ToString())) { if (appliesToProject) { RunSolutionAction(projectAction); } else { // We might be updating a solution only package UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions); } } } else { Logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId); } } finally { ClearLogger(projectManager); } } public void UpdatePackages(IProjectManager projectManager, IEnumerable<IPackage> packages, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { if (packages == null) { throw new ArgumentNullException("packages"); } if (operations == null) { throw new ArgumentNullException("operations"); } using (StartUpdateOperation(packageId: null, packageVersion: null)) { ExecuteOperationsWithPackage( projectManager, null, operations, () => { foreach (var package in packages) { UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions); } }, logger); } } public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackage(packageId, projectManager => UpdatePackageReference(projectManager, packageId, versionSpec, updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger, eventListener); } public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackage(packageId, projectManager => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger, eventListener); } public void UpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages(updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } public void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages(projectManager, updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger); } public void UpdateSolutionPackages(IEnumerable<IPackage> packages, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { if (packages == null) { throw new ArgumentNullException("packages"); } if (operations == null) { throw new ArgumentNullException("operations"); } try { InitializeLogger(logger, null); RunSolutionAction(() => { // update all packages in the 'packages' folder foreach (var operation in operations) { Execute(operation); } if (eventListener == null) { eventListener = NullPackageOperationEventListener.Instance; } foreach (Project project in _solutionManager.GetProjects()) { try { eventListener.OnBeforeAddPackageReference(project); IProjectManager projectManager = GetProjectManager(project); InitializeLogger(logger, projectManager); foreach (var package in packages) { // only perform update when the local package exists and has smaller version than the new version var localPackage = projectManager.LocalRepository.FindPackage(package.Id); if (localPackage != null && localPackage.Version < package.Version) { UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies: true, allowPrereleaseVersions: allowPrereleaseVersions); } } ClearLogger(projectManager); } catch (Exception ex) { eventListener.OnAddPackageReferenceError(project, ex); } finally { eventListener.OnAfterAddPackageReference(project); } } }); } finally { ClearLogger(null); } } public void SafeUpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages(projectManager, updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger); } public void SafeUpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackage(packageId, projectManager => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger, eventListener); } public void SafeUpdatePackage(IProjectManager projectManager, string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackage(projectManager, packageId, () => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger); } public void SafeUpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages(updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } // Reinstall all packages in all projects public void ReinstallPackages( bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages( LocalRepository, package => ReinstallPackage( package.Id, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener), logger); } // Reinstall all packages in the specified project public void ReinstallPackages( IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages( projectManager.LocalRepository, package => ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger), logger); } /// <summary> /// Reinstall the specified package in all projects. /// </summary> public void ReinstallPackage( string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { bool appliesToProject; IPackage package = FindLocalPackage(packageId, out appliesToProject); if (appliesToProject) { ReinstallPackageToAllProjects(packageId, updateDependencies, allowPrereleaseVersions, logger, eventListener); } else { ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger); } } /// <summary> /// Reinstall the specified package in the specified project. /// </summary> public void ReinstallPackage( IProjectManager projectManager, string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { bool appliesToProject; IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject); if (appliesToProject) { ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger); } else { ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger); } } /// <summary> /// Reinstall the specified package in the specified project, taking care of logging too. /// </summary> private void ReinstallPackageInProject( IProjectManager projectManager, IPackage package, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { logger = logger ?? NullLogger.Instance; IDisposable disposableAction = StartReinstallOperation(package.Id, package.Version.ToString()); try { InitializeLogger(logger, projectManager); logger.Log(MessageLevel.Info, VsResources.ReinstallProjectPackage, package, projectManager.Project.ProjectName); // Before we start reinstalling, need to make sure the package exists in the source repository. // Otherwise, the package will be uninstalled and can't be reinstalled. if (SourceRepository.Exists(package)) { RunSolutionAction( () => { UninstallPackage( projectManager, package.Id, package.Version, forceRemove: true, removeDependencies: updateDependencies, logger: logger); InstallPackage( projectManager, package.Id, package.Version, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion(), logger: logger); }); } else { logger.Log( MessageLevel.Warning, VsResources.PackageRestoreSkipForProject, package.GetFullName(), projectManager.Project.ProjectName); } } finally { ClearLogger(projectManager); disposableAction.Dispose(); } } // Reinstall one package in all projects. // We need to uninstall the package from all projects BEFORE // reinstalling it back, so that the package will be refreshed from source repository. private void ReinstallPackageToAllProjects( string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { logger = logger ?? NullLogger.Instance; eventListener = eventListener ?? NullPackageOperationEventListener.Instance; var projectsHasPackage = new Dictionary<Project, SemanticVersion>(); var versionsChecked = new Dictionary<SemanticVersion, bool>(); // first uninstall from all projects that has the package installed RunActionOnProjects( _solutionManager.GetProjects(), project => { IProjectManager projectManager = GetProjectManager(project); // find the package version installed in this project IPackage projectPackage = projectManager.LocalRepository.FindPackage(packageId); if (projectPackage != null) { bool packageExistInSource; if (!versionsChecked.TryGetValue(projectPackage.Version, out packageExistInSource)) { // version has not been checked, so check it here packageExistInSource = SourceRepository.Exists(packageId, projectPackage.Version); // mark the version as checked so that we don't have to check again if we // encounter another project with the same version. versionsChecked[projectPackage.Version] = packageExistInSource; } if (packageExistInSource) { // save the version installed in this project so that we can restore the correct version later projectsHasPackage.Add(project, projectPackage.Version); UninstallPackage( projectManager, packageId, version: null, forceRemove: true, removeDependencies: updateDependencies, logger: logger); } else { logger.Log( MessageLevel.Warning, VsResources.PackageRestoreSkipForProject, projectPackage.GetFullName(), project.Name); } } }, logger, eventListener); // now reinstall back to all the affected projects RunActionOnProjects( projectsHasPackage.Keys, project => { var projectManager = GetProjectManager(project); if (!projectManager.LocalRepository.Exists(packageId)) { SemanticVersion oldVersion = projectsHasPackage[project]; using (StartReinstallOperation(packageId, oldVersion.ToString())) { InstallPackage( projectManager, packageId, version: oldVersion, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !String.IsNullOrEmpty(oldVersion.SpecialVersion), logger: logger); } } }, logger, eventListener); } private void ReinstallSolutionPackage( IPackage package, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { logger = logger ?? NullLogger.Instance; var disposableAction = StartReinstallOperation(package.Id, package.Version.ToString()); try { InitializeLogger(logger); logger.Log(MessageLevel.Info, VsResources.ReinstallSolutionPackage, package); if (SourceRepository.Exists(package)) { RunSolutionAction( () => { UninstallPackage(package, forceRemove: true, removeDependencies: !updateDependencies); // Bug 2883: We must NOT use the overload that accepts 'package' object here, // because after the UninstallPackage() call above, the package no longer exists. InstallPackage(package.Id, package.Version, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion()); }); } else { logger.Log( MessageLevel.Warning, VsResources.PackageRestoreSkipForSolution, package.GetFullName()); } } finally { ClearLogger(); disposableAction.Dispose(); } } protected override void ExecuteUninstall(IPackage package) { // Check if the package is in use before removing it if (!_sharedRepository.IsReferenced(package.Id, package.Version)) { base.ExecuteUninstall(package); } } private IPackage FindLocalPackageForUpdate(IProjectManager projectManager, string packageId, out bool appliesToProject) { return FindLocalPackage(projectManager, packageId, null /* version */, CreateAmbiguousUpdateException, out appliesToProject); } private IPackage FindLocalPackage(IProjectManager projectManager, string packageId, SemanticVersion version, Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException, out bool appliesToProject) { IPackage package = null; bool existsInProject = false; appliesToProject = false; if (projectManager != null) { // Try the project repository first package = projectManager.LocalRepository.FindPackage(packageId, version); existsInProject = package != null; } // Fallback to the solution repository (it might be a solution only package) if (package == null) { if (version != null) { // Get the exact package package = LocalRepository.FindPackage(packageId, version); } else { // Get all packages by this name to see if we find an ambiguous match var packages = LocalRepository.FindPackagesById(packageId).ToList(); if (packages.Count > 1) { throw getAmbiguousMatchException(projectManager, packages); } // Pick the only one of default if none match package = packages.SingleOrDefault(); } } // Can't find the package in the solution or in the project then fail if (package == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackage, packageId)); } appliesToProject = IsProjectLevel(package); if (appliesToProject) { if (!existsInProject) { if (_sharedRepository.IsReferenced(package.Id, package.Version)) { // If the package doesn't exist in the project and is referenced by other projects // then fail. if (projectManager != null) { if (version == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackageInProject, package.Id, projectManager.Project.ProjectName)); } throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackageInProject, package.GetFullName(), projectManager.Project.ProjectName)); } } else { // The operation applies to solution level since it's not installed in the current project // but it is installed in some other project appliesToProject = false; } } } // Can't have a project level operation if no project was specified if (appliesToProject && projectManager == null) { throw new InvalidOperationException(VsResources.ProjectNotSpecified); } return package; } internal IPackage FindLocalPackage(string packageId, out bool appliesToProject) { // It doesn't matter if there are multiple versions of the package installed at solution level, // we just want to know that one exists. var packages = LocalRepository.FindPackagesById(packageId).OrderByDescending(p => p.Version).ToList(); // Can't find the package in the solution. if (!packages.Any()) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackage, packageId)); } foreach (IPackage package in packages) { appliesToProject = IsProjectLevel(package); if (!appliesToProject) { if (packages.Count > 1) { throw CreateAmbiguousUpdateException(projectManager: null, packages: packages); } } else if (!_sharedRepository.IsReferenced(package.Id, package.Version)) { Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_PackageNotReferencedByAnyProject, package.Id, package.Version)); // Try next package continue; } // Found a package with package Id as 'packageId' which is installed in at least 1 project return package; } // There are one or more packages with package Id as 'packageId' // BUT, none of them is installed in a project // it's probably a borked install. throw new PackageNotInstalledException( String.Format(CultureInfo.CurrentCulture, VsResources.PackageNotInstalledInAnyProject, packageId)); } /// <summary> /// Check to see if this package applies to a project based on 2 criteria: /// 1. The package has project content (i.e. content that can be applied to a project lib or content files) /// 2. The package is referenced by any other project /// 3. The package has at least one dependecy /// /// This logic will probably fail in one edge case. If there is a meta package that applies to a project /// that ended up not being installed in any of the projects and it only exists at solution level. /// If this happens, then we think that the following operation applies to the solution instead of showing an error. /// To solve that edge case we'd have to walk the graph to find out what the package applies to. /// /// Technically, the third condition is not totally accurate because a solution-level package can depend on another /// solution-level package. However, doing that check here is expensive and we haven't seen such a package. /// This condition here is more geared towards guarding against metadata packages, i.e. we shouldn't treat metadata packages /// as solution-level ones. /// </summary> public bool IsProjectLevel(IPackage package) { return package.HasProjectContent() || package.DependencySets.SelectMany(p => p.Dependencies).Any() || _sharedRepository.IsReferenced(package.Id, package.Version); } private Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages) { if (projectManager != null && packages.Any(IsProjectLevel)) { return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackageInProject, packages[0].Id, projectManager.Project.ProjectName)); } return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.AmbiguousUpdate, packages[0].Id)); } private Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages) { if (projectManager != null && packages.Any(IsProjectLevel)) { return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.AmbiguousProjectLevelUninstal, packages[0].Id, projectManager.Project.ProjectName)); } return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.AmbiguousUninstall, packages[0].Id)); } private void RemovePackageReference(IProjectManager projectManager, string packageId, bool forceRemove, bool removeDependencies) { RunProjectAction(projectManager, () => projectManager.RemovePackageReference(packageId, forceRemove, removeDependencies)); } private void UpdatePackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { string versionString = version == null ? null : version.ToString(); using (StartUpdateOperation(packageId, versionString)) { RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, version, updateDependencies, allowPrereleaseVersions)); } } private void UpdatePackageReference(IProjectManager projectManager, string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { using (StartUpdateOperation(packageId, packageVersion: null)) { RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, versionSpec, updateDependencies, allowPrereleaseVersions)); } } private void AddPackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { RunProjectAction(projectManager, () => projectManager.AddPackageReference(packageId, version, ignoreDependencies, allowPrereleaseVersions)); } private void AddPackageReference(IProjectManager projectManager, IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { RunProjectAction(projectManager, () => projectManager.AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions)); } private void ExecuteOperationsWithPackage(IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, Action<IProjectManager> projectAction, ILogger logger, IPackageOperationEventListener eventListener) { if (eventListener == null) { eventListener = NullPackageOperationEventListener.Instance; } ExecuteOperationsWithPackage( null, package, operations, () => { bool successfulAtLeastOnce = false; foreach (var project in projects) { try { eventListener.OnBeforeAddPackageReference(project); IProjectManager projectManager = GetProjectManager(project); InitializeLogger(logger, projectManager); projectAction(projectManager); successfulAtLeastOnce = true; ClearLogger(projectManager); } catch (Exception ex) { eventListener.OnAddPackageReferenceError(project, ex); } finally { eventListener.OnAfterAddPackageReference(project); } } // Throw an exception only if all the update failed for all projects // so we rollback any solution level operations that might have happened if (projects.Any() && !successfulAtLeastOnce) { throw new InvalidOperationException(VsResources.OperationFailed); } }, logger); } private void ExecuteOperationsWithPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, Action action, ILogger logger) { try { InitializeLogger(logger, projectManager); RunSolutionAction(() => { if (operations.Any()) { foreach (var operation in operations) { Execute(operation); } } else if (package != null && LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, VsResources.Log_PackageAlreadyInstalled, package.GetFullName()); } action(); }); } finally { ClearLogger(projectManager); } } private Project GetProject(IProjectManager projectManager) { // We only support project systems that implement IVsProjectSystem var vsProjectSystem = projectManager.Project as IVsProjectSystem; if (vsProjectSystem == null) { return null; } // Find the project by it's unique name return _solutionManager.GetProject(vsProjectSystem.UniqueName); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")] private void AddBindingRedirects(IProjectManager projectManager) { // Find the project by it's unique name Project project = GetProject(projectManager); // If we can't find the project or it doesn't support binding redirects then don't add any redirects if (project == null || !project.SupportsBindingRedirects()) { return; } try { RuntimeHelpers.AddBindingRedirects(_solutionManager, project, _fileSystemProvider, _frameworkMultiTargeting); } catch (Exception e) { // If there was an error adding binding redirects then print a warning and continue Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message)); } } private void InitializeLogger(ILogger logger, IProjectManager projectManager = null) { // Setup logging on all of our objects Logger = logger; FileSystem.Logger = logger; if (projectManager != null) { projectManager.Logger = logger; projectManager.Project.Logger = logger; } } private void ClearLogger(IProjectManager projectManager = null) { // clear logging on all of our objects Logger = null; FileSystem.Logger = null; if (projectManager != null) { projectManager.Logger = null; projectManager.Project.Logger = null; } } /// <summary> /// Runs the specified action and rolls back any installed packages if on failure. /// </summary> private void RunSolutionAction(Action action) { var packagesAdded = new List<IPackage>(); EventHandler<PackageOperationEventArgs> installHandler = (sender, e) => { // Record packages that we are installing so that if one fails, we can rollback packagesAdded.Add(e.Package); _packageEvents.NotifyInstalling(e); }; EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) => { _packageEvents.NotifyInstalled(e); }; PackageInstalling += installHandler; PackageInstalled += installedHandler; try { // Execute the action action(); } catch { if (packagesAdded.Any()) { // Only print the rollback warning if we have something to rollback Logger.Log(MessageLevel.Warning, VsResources.Warning_RollingBack); } // Don't log anything during the rollback Logger = null; // Rollback the install if it fails Uninstall(packagesAdded); throw; } finally { // Remove the event handler PackageInstalling -= installHandler; PackageInstalled -= installedHandler; } } /// <summary> /// Runs the action on projects and log any error that may occur. /// </summary> private void RunActionOnProjects( IEnumerable<Project> projects, Action<Project> action, ILogger logger, IPackageOperationEventListener eventListener) { foreach (var project in projects) { try { eventListener.OnBeforeAddPackageReference(project); action(project); } catch (Exception exception) { logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(exception).Message); eventListener.OnAddPackageReferenceError(project, exception); } finally { eventListener.OnAfterAddPackageReference(project); } } } /// <summary> /// Runs action on the project manager and rollsback any package installs if it fails. /// </summary> private void RunProjectAction(IProjectManager projectManager, Action action) { if (projectManager == null) { return; } // Keep track of what was added and removed var packagesAdded = new Stack<IPackage>(); var packagesRemoved = new List<IPackage>(); EventHandler<PackageOperationEventArgs> removeHandler = (sender, e) => { packagesRemoved.Add(e.Package); _packageEvents.NotifyReferenceRemoved(e); }; EventHandler<PackageOperationEventArgs> addingHandler = (sender, e) => { packagesAdded.Push(e.Package); _packageEvents.NotifyReferenceAdded(e); // If this package doesn't exist at solution level (it might not be because of leveling) // then we need to install it. if (!LocalRepository.Exists(e.Package)) { ExecuteInstall(e.Package); } }; // Try to get the project for this project manager Project project = GetProject(projectManager); IVsProjectBuildSystem build = null; if (project != null) { build = project.ToVsProjectBuildSystem(); } // Add the handlers projectManager.PackageReferenceRemoved += removeHandler; projectManager.PackageReferenceAdding += addingHandler; try { if (build != null) { // Start a batch edit so there is no background compilation until we're done // processing project actions build.StartBatchEdit(); } action(); if (BindingRedirectEnabled && projectManager.Project.IsBindingRedirectSupported) { // Only add binding redirects if install was successful AddBindingRedirects(projectManager); } } catch { // We need to Remove the handlers here since we're going to attempt // a rollback and we don't want modify the collections while rolling back. projectManager.PackageReferenceRemoved -= removeHandler; projectManager.PackageReferenceAdding -= addingHandler; // When things fail attempt a rollback RollbackProjectActions(projectManager, packagesAdded, packagesRemoved); // Rollback solution packages Uninstall(packagesAdded); // Clear removed packages so we don't try to remove them again (small optimization) packagesRemoved.Clear(); throw; } finally { if (build != null) { // End the batch edit when we are done. build.EndBatchEdit(); } // Remove the handlers projectManager.PackageReferenceRemoved -= removeHandler; projectManager.PackageReferenceAdding -= addingHandler; // Remove any packages that would be removed as a result of updating a dependency or the package itself // We can execute the uninstall directly since we don't need to resolve dependencies again. Uninstall(packagesRemoved); } } private static void RollbackProjectActions(IProjectManager projectManager, IEnumerable<IPackage> packagesAdded, IEnumerable<IPackage> packagesRemoved) { // Disable logging when rolling back project operations projectManager.Logger = null; foreach (var package in packagesAdded) { // Remove each package that was added projectManager.RemovePackageReference(package, forceRemove: false, removeDependencies: false); } foreach (var package in packagesRemoved) { // Add each package that was removed projectManager.AddPackageReference(package, ignoreDependencies: true, allowPrereleaseVersions: true); } } private void Uninstall(IEnumerable<IPackage> packages) { // Packages added to the sequence are added in the order in which they were visited. However for operations on satellite packages to work correctly, // we need to ensure they are always uninstalled prior to the corresponding core package. To address this, we run it by Reduce which reorders it for us and ensures it // returns the minimal set of operations required. var packageOperations = packages.Select(p => new PackageOperation(p, PackageAction.Uninstall)) .Reduce(); foreach (var operation in packageOperations) { ExecuteUninstall(operation.Package); } } private void UpdatePackage( string packageId, Action<IProjectManager> projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { bool appliesToProject; IPackage package = FindLocalPackage(packageId, out appliesToProject); if (appliesToProject) { eventListener = eventListener ?? NullPackageOperationEventListener.Instance; foreach (var project in _solutionManager.GetProjects()) { IProjectManager projectManager = GetProjectManager(project); try { InitializeLogger(logger, projectManager); if (projectManager.LocalRepository.Exists(packageId)) { eventListener.OnBeforeAddPackageReference(project); try { RunSolutionAction(() => projectAction(projectManager)); } catch (Exception e) { logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message); eventListener.OnAddPackageReferenceError(project, e); } finally { eventListener.OnAfterAddPackageReference(project); } } } finally { ClearLogger(projectManager); } } } else { // Find the package we're going to update to IPackage newPackage = resolvePackage(); if (newPackage != null && package.Version != newPackage.Version) { IDisposable operationDisposable = StartUpdateOperation(newPackage.Id, newPackage.Version.ToString()); try { InitializeLogger(logger, projectManager: null); // We might be updating a solution only package UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions); } finally { ClearLogger(projectManager: null); operationDisposable.Dispose(); } } else { logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId); } } } private void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages(projectManager.LocalRepository, package => { if (safeUpdate) { SafeUpdatePackage(projectManager, package.Id, updateDependencies, allowPrereleaseVersions, logger); } else { UpdatePackage(projectManager, package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger); } }, logger); } private void UpdatePackages(bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages(LocalRepository, package => { if (safeUpdate) { SafeUpdatePackage(package.Id, updateDependencies, allowPrereleaseVersions, logger, eventListener); } else { UpdatePackage(package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } }, logger); } private void UpdatePackages(IPackageRepository localRepository, Action<IPackage> updateAction, ILogger logger) { var packageSorter = new PackageSorter(targetFramework: null); // Get the packages in reverse dependency order then run update on each one i.e. if A -> B run Update(A) then Update(B) var packages = packageSorter.GetPackagesByDependencyOrder(localRepository).Reverse(); foreach (var package in packages) { // While updating we might remove packages that were initially in the list. e.g. // A 1.0 -> B 2.0, A 2.0 -> [], since updating to A 2.0 removes B, we end up skipping it. if (localRepository.Exists(package.Id)) { try { updateAction(package); } catch (PackageNotInstalledException e) { logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message); } catch (Exception e) { logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message); } } } } private IPackageRepository CreateProjectManagerSourceRepository() { // The source repo for the project manager is the aggregate of the shared repo and the selected repo. // For dependency resolution, we want VS to look for packages in the selected source and then use the fallback logic var fallbackRepository = SourceRepository as FallbackRepository; if (fallbackRepository != null) { var primaryRepositories = new[] { _sharedRepository, fallbackRepository.SourceRepository.Clone() }; return new FallbackRepository(new AggregateRepository(primaryRepositories), fallbackRepository.DependencyResolver); } return new AggregateRepository(new[] { _sharedRepository, SourceRepository.Clone() }); } private IVersionSpec GetSafeRange(string packageId) { bool appliesToProject; IPackage package = FindLocalPackage(packageId, out appliesToProject); return VersionUtility.GetSafeRange(package.Version); } private IVersionSpec GetSafeRange(IProjectManager projectManager, string packageId) { bool appliesToProject; IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject); return VersionUtility.GetSafeRange(package.Version); } protected override void OnUninstalled(PackageOperationEventArgs e) { base.OnUninstalled(e); _deleteOnRestartManager.MarkPackageDirectoryForDeletion(e.Package); } private IDisposable StartInstallOperation(string packageId, string packageVersion) { return StartOperation(RepositoryOperationNames.Install, packageId, packageVersion); } private IDisposable StartUpdateOperation(string packageId, string packageVersion) { return StartOperation(RepositoryOperationNames.Update, packageId, packageVersion); } private IDisposable StartReinstallOperation(string packageId, string packageVersion) { return StartOperation(RepositoryOperationNames.Reinstall, packageId, packageVersion); } private IDisposable StartOperation(string operation, string packageId, string mainPackageVersion) { // If there's a pending operation, don't allow another one to start. // This is for the Reinstall case. Because Reinstall just means // uninstalling and installing, we don't want the child install operation // to override Reinstall value. if (_repositoryOperationPending) { return DisposableAction.NoOp; } _repositoryOperationPending = true; return DisposableAction.All( SourceRepository.StartOperation(operation, packageId, mainPackageVersion), new DisposableAction(() => _repositoryOperationPending = false)); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Generic; using System; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceDelegateMethodSymbol : SourceMethodSymbol { private ImmutableArray<ParameterSymbol> parameters; private readonly TypeSymbol returnType; protected SourceDelegateMethodSymbol( SourceMemberContainerTypeSymbol delegateType, TypeSymbol returnType, DelegateDeclarationSyntax syntax, MethodKind methodKind, DeclarationModifiers declarationModifiers) : base(delegateType, syntax.GetReference(), bodySyntaxReferenceOpt: null, location: syntax.Identifier.GetLocation()) { this.returnType = returnType; this.MakeFlags(methodKind, declarationModifiers, this.returnType.SpecialType == SpecialType.System_Void, isExtensionMethod: false); } protected void InitializeParameters(ImmutableArray<ParameterSymbol> parameters) { Debug.Assert(this.parameters.IsDefault); this.parameters = parameters; } internal static void AddDelegateMembers( SourceMemberContainerTypeSymbol delegateType, ArrayBuilder<Symbol> symbols, DelegateDeclarationSyntax syntax, DiagnosticBag diagnostics) { Binder binder = delegateType.GetBinder(syntax.ParameterList); TypeSymbol returnType = binder.BindType(syntax.ReturnType, diagnostics); // reuse types to avoid reporting duplicate errors if missing: var voidType = binder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax); var objectType = binder.GetSpecialType(SpecialType.System_Object, diagnostics, syntax); var intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, diagnostics, syntax); if (returnType.IsRestrictedType()) { // Method or delegate cannot return type '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType); } // A delegate has the following members: (see CLI spec 13.6) // (1) a method named Invoke with the specified signature var invoke = new InvokeMethod(delegateType, returnType, syntax, binder, diagnostics); invoke.CheckDelegateVarianceSafety(diagnostics); symbols.Add(invoke); // (2) a constructor with argument types (object, System.IntPtr) symbols.Add(new Constructor(delegateType, voidType, objectType, intPtrType, syntax)); if (binder.Compilation.GetSpecialType(SpecialType.System_IAsyncResult).TypeKind != TypeKind.Error && binder.Compilation.GetSpecialType(SpecialType.System_AsyncCallback).TypeKind != TypeKind.Error && // WinRT delegates don't have Begin/EndInvoke methods !delegateType.IsCompilationOutputWinMdObj()) { var iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, diagnostics, syntax); var asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, diagnostics, syntax); // (3) BeginInvoke symbols.Add(new BeginInvokeMethod(invoke, iAsyncResultType, objectType, asyncCallbackType, syntax)); // and (4) EndInvoke methods symbols.Add(new EndInvokeMethod(invoke, iAsyncResultType, syntax)); } if (delegateType.DeclaredAccessibility <= Accessibility.Private) { return; } HashSet<DiagnosticInfo> useSiteDiagnostics = null; if (!delegateType.IsNoMoreVisibleThan(invoke.ReturnType, ref useSiteDiagnostics)) { // Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateReturn, delegateType.Locations[0], delegateType, invoke.ReturnType); } foreach (var parameter in invoke.Parameters) { if (!parameter.Type.IsAtLeastAsVisibleAs(delegateType, ref useSiteDiagnostics)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateParam, delegateType.Locations[0], delegateType, parameter.Type); } } diagnostics.Add(delegateType.Locations[0], useSiteDiagnostics); } protected override void MethodChecks(DiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } public sealed override bool IsVararg { get { return false; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { return this.parameters; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override TypeSymbol ReturnType { get { return this.returnType; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override bool GenerateDebugInfo { get { return false; } } protected sealed override IAttributeTargetSymbol AttributeOwner { get { return (SourceNamedTypeSymbol)ContainingSymbol; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // TODO: This implementation looks strange. It might make sense for the Invoke method, but // not for constructor and other methods. return OneOrMany.Create(((SourceNamedTypeSymbol)ContainingSymbol).GetAttributeDeclarations()); } internal sealed override System.AttributeTargets GetAttributeTarget() { return System.AttributeTargets.Delegate; } private sealed class Constructor : SourceDelegateMethodSymbol { internal Constructor( SourceMemberContainerTypeSymbol delegateType, TypeSymbol voidType, TypeSymbol objectType, TypeSymbol intPtrType, DelegateDeclarationSyntax syntax) : base(delegateType, voidType, syntax, MethodKind.Constructor, DeclarationModifiers.Public) { InitializeParameters(ImmutableArray.Create<ParameterSymbol>( new SynthesizedParameterSymbol(this, objectType, 0, RefKind.None, "object"), new SynthesizedParameterSymbol(this, intPtrType, 1, RefKind.None, "method"))); } public override string Name { get { return WellKnownMemberNames.InstanceConstructorName; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // Constructors don't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of sythesized methods the same as in Dev12 // Dev12 order is not strictly aphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members inone order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } } private sealed class InvokeMethod : SourceDelegateMethodSymbol { internal InvokeMethod( SourceMemberContainerTypeSymbol delegateType, TypeSymbol returnType, DelegateDeclarationSyntax syntax, Binder binder, DiagnosticBag diagnostics) : base(delegateType, returnType, syntax, MethodKind.DelegateInvoke, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { SyntaxToken arglistToken; var parameters = ParameterHelpers.MakeParameters(binder, this, syntax.ParameterList, true, out arglistToken, diagnostics); if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) { // This is a parse-time error in the native compiler; it is a semantic analysis error in Roslyn. // error CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, new SourceLocation(arglistToken)); } InitializeParameters(parameters); } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of sythesized methods the same as in Dev12 // Dev12 order is not strictly aphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members inone order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } } private sealed class BeginInvokeMethod : SourceDelegateMethodSymbol { internal BeginInvokeMethod( InvokeMethod invoke, TypeSymbol iAsyncResultType, TypeSymbol objectType, TypeSymbol asyncCallbackType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, iAsyncResultType, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (SourceParameterSymbol p in invoke.Parameters) { var synthesizedParam = new SourceClonedParameterSymbol(originalParam: p, newOwner: this, newOrdinal: p.Ordinal, suppressOptional: true); parameters.Add(synthesizedParam); } int paramCount = invoke.ParameterCount; parameters.Add(new SynthesizedParameterSymbol(this, asyncCallbackType, paramCount, RefKind.None, "callback")); parameters.Add(new SynthesizedParameterSymbol(this, objectType, paramCount + 1, RefKind.None, "object")); InitializeParameters(parameters.ToImmutableAndFree()); } public override string Name { get { return WellKnownMemberNames.DelegateBeginInvokeName; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // BeginInvoke method doesn't have return type attributes // because it doesn't inherit Delegate declaration's return type. // It has a special return type: SpecialType.System.IAsyncResult. return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } } private sealed class EndInvokeMethod : SourceDelegateMethodSymbol { internal EndInvokeMethod( InvokeMethod invoke, TypeSymbol iAsyncResultType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, invoke.ReturnType, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); int ordinal = 0; foreach (SourceParameterSymbol p in invoke.Parameters) { if (p.RefKind != RefKind.None) { var synthesizedParam = new SourceClonedParameterSymbol(originalParam: p, newOwner: this, newOrdinal: ordinal++, suppressOptional: true); parameters.Add(synthesizedParam); } } parameters.Add(new SynthesizedParameterSymbol(this, iAsyncResultType, ordinal++, RefKind.None, "__result")); InitializeParameters(parameters.ToImmutableAndFree()); } protected override SourceMethodSymbol BoundAttributesSource { get { // copy return attributes from InvokeMethod return (SourceMethodSymbol)((SourceNamedTypeSymbol)this.ContainingSymbol).DelegateInvokeMethod; } } public override string Name { get { return WellKnownMemberNames.DelegateEndInvokeName; } } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprCondicionIngreso class. /// </summary> [Serializable] public partial class AprCondicionIngresoCollection : ActiveList<AprCondicionIngreso, AprCondicionIngresoCollection> { public AprCondicionIngresoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprCondicionIngresoCollection</returns> public AprCondicionIngresoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprCondicionIngreso o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_CondicionIngreso table. /// </summary> [Serializable] public partial class AprCondicionIngreso : ActiveRecord<AprCondicionIngreso>, IActiveRecord { #region .ctors and Default Settings public AprCondicionIngreso() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprCondicionIngreso(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprCondicionIngreso(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprCondicionIngreso(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_CondicionIngreso", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCondicionAlIngreso = new TableSchema.TableColumn(schema); colvarIdCondicionAlIngreso.ColumnName = "idCondicionAlIngreso"; colvarIdCondicionAlIngreso.DataType = DbType.Int32; colvarIdCondicionAlIngreso.MaxLength = 0; colvarIdCondicionAlIngreso.AutoIncrement = true; colvarIdCondicionAlIngreso.IsNullable = false; colvarIdCondicionAlIngreso.IsPrimaryKey = true; colvarIdCondicionAlIngreso.IsForeignKey = false; colvarIdCondicionAlIngreso.IsReadOnly = false; colvarIdCondicionAlIngreso.DefaultSetting = @""; colvarIdCondicionAlIngreso.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCondicionAlIngreso); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_CondicionIngreso",schema); } } #endregion #region Props [XmlAttribute("IdCondicionAlIngreso")] [Bindable(true)] public int IdCondicionAlIngreso { get { return GetColumnValue<int>(Columns.IdCondicionAlIngreso); } set { SetColumnValue(Columns.IdCondicionAlIngreso, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.AprAbortoCollection colAprAbortoRecords; public DalSic.AprAbortoCollection AprAbortoRecords { get { if(colAprAbortoRecords == null) { colAprAbortoRecords = new DalSic.AprAbortoCollection().Where(AprAborto.Columns.IdCondicionAlIngreso, IdCondicionAlIngreso).Load(); colAprAbortoRecords.ListChanged += new ListChangedEventHandler(colAprAbortoRecords_ListChanged); } return colAprAbortoRecords; } set { colAprAbortoRecords = value; colAprAbortoRecords.ListChanged += new ListChangedEventHandler(colAprAbortoRecords_ListChanged); } } void colAprAbortoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprAbortoRecords[e.NewIndex].IdCondicionAlIngreso = IdCondicionAlIngreso; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { AprCondicionIngreso item = new AprCondicionIngreso(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCondicionAlIngreso,string varNombre) { AprCondicionIngreso item = new AprCondicionIngreso(); item.IdCondicionAlIngreso = varIdCondicionAlIngreso; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCondicionAlIngresoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdCondicionAlIngreso = @"idCondicionAlIngreso"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections public void SetPKValues() { if (colAprAbortoRecords != null) { foreach (DalSic.AprAborto item in colAprAbortoRecords) { if (item.IdCondicionAlIngreso != IdCondicionAlIngreso) { item.IdCondicionAlIngreso = IdCondicionAlIngreso; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colAprAbortoRecords != null) { colAprAbortoRecords.SaveAll(); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Used by the class to hold the underlying socket the stream uses. private Socket _streamSocket; // Used by the class to indicate that the stream is m_Readable. private bool _readable; // Used by the class to indicate that the stream is writable. private bool _writeable; private bool _ownsSocket; // Creates a new instance of the System.Net.Sockets.NetworkStream without initalization. internal NetworkStream() { _ownsSocket = true; } // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket. public NetworkStream(Socket socket) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException("socket"); } InitNetworkStream(socket); #if DEBUG } #endif } public NetworkStream(Socket socket, bool ownsSocket) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException("socket"); } InitNetworkStream(socket); _ownsSocket = ownsSocket; #if DEBUG } #endif } internal NetworkStream(NetworkStream networkStream, bool ownsSocket) { Socket socket = networkStream.Socket; if (socket == null) { throw new ArgumentNullException("networkStream"); } InitNetworkStream(socket); _ownsSocket = ownsSocket; } // Socket - provides access to socket for stream closing protected Socket Socket { get { return _streamSocket; } } internal Socket InternalSocket { get { Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { throw new ObjectDisposedException(this.GetType().FullName); } return chkSocket; } } internal void InternalAbortSocket() { if (!_ownsSocket) { throw new InvalidOperationException(); } Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { return; } try { chkSocket.Dispose(); } catch (ObjectDisposedException) { } } internal void ConvertToNotSocketOwner() { _ownsSocket = false; // Suppress for finialization still allow proceed the requests GC.SuppressFinalize(this); } // Used by the class to indicate that the stream is m_Readable. protected bool Readable { get { return _readable; } set { _readable = value; } } // Used by the class to indicate that the stream is writable. protected bool Writeable { get { return _writeable; } set { _writeable = value; } } // Indicates that data can be read from the stream. // We return the readability of this stream. This is a read only property. public override bool CanRead { get { return _readable; } } // Indicates that the stream can seek a specific location // in the stream. This property always returns false. public override bool CanSeek { get { return false; } } // Indicates that data can be written to the stream. public override bool CanWrite { get { return _writeable; } } // Indicates whether we can timeout public override bool CanTimeout { get { return true; // should we check for Connected state? } } // Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int ReadTimeout { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException("value", SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Receive, value, false); #if DEBUG } #endif } } // Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int WriteTimeout { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException("value", SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Send, value, false); #if DEBUG } #endif } } // Indicates data is available on the stream to be read. // This property checks to see if at least one byte of data is currently available public virtual bool DataAvailable { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } // Ask the socket how many bytes are available. If it's // not zero, return true. return chkStreamSocket.Available != 0; #if DEBUG } #endif } } // The length of data available on the stream. Always throws NotSupportedException. public override long Length { get { throw new NotSupportedException(SR.net_noseek); } } // Gets or sets the position in the stream. Always throws NotSupportedException. public override long Position { get { throw new NotSupportedException(SR.net_noseek); } set { throw new NotSupportedException(SR.net_noseek); } } // Seeks a specific position in the stream. This method is not supported by the // NetworkStream class. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } internal void InitNetworkStream(Socket socket) { if (!socket.Blocking) { throw new IOException(SR.net_sockets_blocking); } if (!socket.Connected) { throw new IOException(SR.net_notconnected); } if (socket.SocketType != SocketType.Stream) { throw new IOException(SR.net_notstream); } _streamSocket = socket; _readable = true; _writeable = true; } internal bool PollRead() { if (_cleanedUp) { return false; } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return false; } return chkStreamSocket.Poll(0, SelectMode.SelectRead); } internal bool Poll(int microSeconds, SelectMode mode) { if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } return chkStreamSocket.Poll(microSeconds, mode); } // Read - provide core Read functionality. // // Provide core read functionality. All we do is call through to the // socket Receive functionality. // // Input: // // Buffer - Buffer to read into. // Offset - Offset into the buffer where we're to read. // Count - Number of bytes to read. // // Returns: // // Number of bytes we read, or 0 if the socket is closed. public override int Read([In, Out] byte[] buffer, int offset, int size) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.Receive(buffer, offset, size, 0); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // Write - provide core Write functionality. // // Provide core write functionality. All we do is call through to the // socket Send method.. // // Input: // // Buffer - Buffer to write from. // Offset - Offset into the buffer from where we'll start writing. // Count - Number of bytes to write. // // Returns: // // Number of bytes written. We'll throw an exception if we // can't write everything. It's brutal, but there's no other // way to indicate an error. public override void Write(byte[] buffer, int offset, int size) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Since the socket is in blocking mode this will always complete // after ALL the requested number of bytes was transferred. chkStreamSocket.Send(buffer, offset, size, SocketFlags.None); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } private volatile bool _cleanedUp = false; protected override void Dispose(bool disposing) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif // Mark this as disposed before changing anything else. bool cleanedUp = _cleanedUp; _cleanedUp = true; if (!cleanedUp && disposing) { // The only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. if (_streamSocket != null) { _readable = false; _writeable = false; if (_ownsSocket) { // If we own the Socket (false by default), close it // ignoring possible exceptions (eg: the user told us // that we own the Socket but it closed at some point of time, // here we would get an ObjectDisposedException) Socket chkStreamSocket = _streamSocket; if (chkStreamSocket != null) { chkStreamSocket.InternalShutdown(SocketShutdown.Both); chkStreamSocket.Dispose(); } } } } #if DEBUG } #endif base.Dispose(disposing); } ~NetworkStream() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Finalization); #endif Dispose(false); } // Indicates whether the stream is still connected internal bool Connected { get { Socket socket = _streamSocket; if (!_cleanedUp && socket != null && socket.Connected) { return true; } else { return false; } } } // BeginRead - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the underlying socket async read. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // // Returns: // // An IASyncResult, representing the read. public IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.BeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } } // EndRead - handle the end of an async read. // // This method is called when an async read is completed. All we // do is call through to the core socket EndReceive functionality. // // Returns: // // The number of bytes read. May throw an exception. public int EndRead(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.EndReceive(asyncResult); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // BeginWrite - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the underlying socket async send. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to written. // // Returns: // // An IASyncResult, representing the write. public IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.BeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // Handle the end of an asynchronous write. // This method is called when an async write is completed. All we // do is call through to the core socket EndSend functionality. // Returns: The number of bytes read. May throw an exception. public void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { chkStreamSocket.EndSend(asyncResult); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // ReadAsync - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the Begin/EndRead methods. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // cancellationtoken - Token used to request cancellation of the operation // // Returns: // // A Task<int> representing the read. public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginRead(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndRead(iar), buffer, offset, size, this); } // WriteAsync - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the Begin/EndWrite methods. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to write. // cancellationtoken - Token used to request cancellation of the operation // // Returns: // // A Task representing the write. public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginWrite(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndWrite(iar), buffer, offset, size, this); } // Flushes data from the stream. This is meaningless for us, so it does nothing. public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } // Sets the length of the stream. Always throws NotSupportedException public override void SetLength(long value) { throw new NotSupportedException(SR.net_noseek); } private int _currentReadTimeout = -1; private int _currentWriteTimeout = -1; internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { if (GlobalLog.IsEnabled) { GlobalLog.Print("NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption() mode:" + mode + " silent:" + silent + " timeout:" + timeout + " m_CurrentReadTimeout:" + _currentReadTimeout + " m_CurrentWriteTimeout:" + _currentWriteTimeout); } GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption"); if (timeout < 0) { timeout = 0; // -1 becomes 0 for the winsock stack } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return; } if (mode == SocketShutdown.Send || mode == SocketShutdown.Both) { if (timeout != _currentWriteTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent); _currentWriteTimeout = timeout; } } if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both) { if (timeout != _currentReadTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent); _currentReadTimeout = timeout; } } } [System.Diagnostics.Conditional("TRACE_VERBOSE")] internal void DebugMembers() { if (_streamSocket != null) { if (GlobalLog.IsEnabled) { GlobalLog.Print("_streamSocket:"); } _streamSocket.DebugMembers(); } } } }